blob: cb0e2a99ca94a9be2028608296811e9483ffd9be [file] [log] [blame]
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001//===- ScopInfo.cpp -------------------------------------------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Tobias Grosser75805372011-04-29 06:27:02 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Create a polyhedral description for a static control flow region.
10//
11// The pass creates a polyhedral description of the Scops detected by the Scop
12// detection derived from their LLVM-IR code.
13//
Tobias Grossera5605d32014-10-29 19:58:28 +000014// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000015// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
16//
17//===----------------------------------------------------------------------===//
18
Tobias Grosser5624d3c2015-12-21 12:38:56 +000019#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Michael Kruse73fa33b2016-06-28 01:37:28 +000022#include "polly/ScopBuilder.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000023#include "polly/ScopDetection.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser77eef902017-07-21 23:07:56 +000025#include "polly/Support/ISLOStream.h"
Michael Krusee3300712018-05-09 16:23:56 +000026#include "polly/Support/ISLTools.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"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000032#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000033#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallSet.h"
Tobias Grosser83628182013-05-07 08:11:54 +000035#include "llvm/ADT/Statistic.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000036#include "llvm/Analysis/AliasAnalysis.h"
Michael Kruse89b1f942017-03-17 13:56:53 +000037#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000038#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "llvm/Analysis/LoopInfo.h"
Adam Nemete0f15412017-10-09 23:49:08 +000040#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000041#include "llvm/Analysis/RegionInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000042#include "llvm/Analysis/RegionIterator.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000043#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosser83628182013-05-07 08:11:54 +000044#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000045#include "llvm/IR/BasicBlock.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000046#include "llvm/IR/ConstantRange.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000047#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/DebugLoc.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000049#include "llvm/IR/Dominators.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Instructions.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000054#include "llvm/IR/Module.h"
55#include "llvm/IR/PassManager.h"
56#include "llvm/IR/Type.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000057#include "llvm/IR/Value.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080058#include "llvm/InitializePasses.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000059#include "llvm/Support/Compiler.h"
Tobias Grosser75805372011-04-29 06:27:02 +000060#include "llvm/Support/Debug.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000061#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000062#include "llvm/Support/raw_ostream.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000063#include "isl/aff.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000064#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000065#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000066#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000067#include "isl/set.h"
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +000068#include <cassert>
Tobias Grosser75805372011-04-29 06:27:02 +000069
70using namespace llvm;
71using namespace polly;
72
Chandler Carruth95fef942014-04-22 03:30:19 +000073#define DEBUG_TYPE "polly-scops"
74
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000075STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
76STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
77STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
78STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
79STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
80STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
81STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
82STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
83STATISTIC(AssumptionsInvariantLoad,
Johannes Doerfertcd195322016-11-17 21:41:08 +000084 "Number of invariant loads assumptions taken.");
Johannes Doerfert81aa6e82016-11-18 14:37:08 +000085STATISTIC(AssumptionsDelinearization,
Johannes Doerfertcd195322016-11-17 21:41:08 +000086 "Number of delinearization assumptions taken.");
87
Michael Kruse06ed5292017-08-23 13:50:30 +000088STATISTIC(NumScops, "Number of feasible SCoPs after ScopInfo");
Tobias Grossercd01a362017-02-17 08:12:36 +000089STATISTIC(NumLoopsInScop, "Number of loops in scops");
Michael Kruse06ed5292017-08-23 13:50:30 +000090STATISTIC(NumBoxedLoops, "Number of boxed loops in SCoPs after ScopInfo");
91STATISTIC(NumAffineLoops, "Number of affine loops in SCoPs after ScopInfo");
92
Tobias Grosserfcc3ad52018-04-18 20:03:36 +000093STATISTIC(NumScopsDepthZero, "Number of scops with maximal loop depth 0");
Tobias Grossercd01a362017-02-17 08:12:36 +000094STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
95STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
96STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
97STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
98STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
99STATISTIC(NumScopsDepthLarger,
100 "Number of scops with maximal loop depth 6 and larger");
101STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
102
Michael Kruse06ed5292017-08-23 13:50:30 +0000103STATISTIC(NumValueWrites, "Number of scalar value writes after ScopInfo");
104STATISTIC(
105 NumValueWritesInLoops,
106 "Number of scalar value writes nested in affine loops after ScopInfo");
107STATISTIC(NumPHIWrites, "Number of scalar phi writes after ScopInfo");
108STATISTIC(NumPHIWritesInLoops,
109 "Number of scalar phi writes nested in affine loops after ScopInfo");
110STATISTIC(NumSingletonWrites, "Number of singleton writes after ScopInfo");
111STATISTIC(NumSingletonWritesInLoops,
112 "Number of singleton writes nested in affine loops after ScopInfo");
113
Michael Krusebb824c62019-06-12 22:40:08 +0000114int const polly::MaxDisjunctsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +0000115
Tobias Grosserc8a82762017-02-16 19:11:25 +0000116// The number of disjunct in the context after which we stop to add more
117// disjuncts. This parameter is there to avoid exponential growth in the
118// number of disjunct when adding non-convex sets to the context.
119static int const MaxDisjunctsInContext = 4;
120
Johannes Doerfert2f705842016-04-12 16:09:44 +0000121static cl::opt<bool> PollyRemarksMinimal(
122 "polly-remarks-minimal",
123 cl::desc("Do not emit remarks about assumptions that are known"),
124 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
125
Tobias Grosser2937b592016-04-29 11:43:20 +0000126static cl::opt<bool>
127 IslOnErrorAbort("polly-on-isl-error-abort",
128 cl::desc("Abort if an isl error is encountered"),
129 cl::init(true), cl::cat(PollyCategory));
130
Tobias Grosserd7c49752017-02-28 09:45:54 +0000131static cl::opt<bool> PollyPreciseInbounds(
132 "polly-precise-inbounds",
133 cl::desc("Take more precise inbounds assumptions (do not scale well)"),
134 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
135
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000136static cl::opt<bool>
137 PollyIgnoreInbounds("polly-ignore-inbounds",
138 cl::desc("Do not take inbounds assumptions at all"),
139 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
140
Tobias Grosser5842dee2017-03-17 13:00:53 +0000141static cl::opt<bool> PollyIgnoreParamBounds(
142 "polly-ignore-parameter-bounds",
143 cl::desc(
144 "Do not add parameter bounds and do no gist simplify sets accordingly"),
145 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
146
Tobias Grosserc2f15102017-03-01 21:11:27 +0000147static cl::opt<bool> PollyPreciseFoldAccesses(
148 "polly-precise-fold-accesses",
Michael Kruse6e7854a2017-04-03 12:03:38 +0000149 cl::desc("Fold memory accesses to model more possible delinearizations "
150 "(does not scale well)"),
Tobias Grosserc2f15102017-03-01 21:11:27 +0000151 cl::Hidden, cl::init(false), cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000152
Michael Kruse5ae08c02017-05-06 14:03:58 +0000153bool polly::UseInstructionNames;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000154
Michael Kruse5ae08c02017-05-06 14:03:58 +0000155static cl::opt<bool, true> XUseInstructionNames(
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000156 "polly-use-llvm-names",
Michael Kruse5ae08c02017-05-06 14:03:58 +0000157 cl::desc("Use LLVM-IR names when deriving statement names"),
158 cl::location(UseInstructionNames), cl::Hidden, cl::init(false),
159 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000160
Tobias Grosserd5fcbef2017-05-27 04:40:18 +0000161static cl::opt<bool> PollyPrintInstructions(
162 "polly-print-instructions", cl::desc("Output instructions per ScopStmt"),
163 cl::Hidden, cl::Optional, cl::init(false), cl::cat(PollyCategory));
164
Michael Kruse7bf39442015-09-10 12:46:52 +0000165//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000166
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000167static isl::set addRangeBoundsToSet(isl::set S, const ConstantRange &Range,
168 int dim, isl::dim type) {
169 isl::val V;
170 isl::ctx Ctx = S.get_ctx();
Johannes Doerferte7044942015-02-24 11:58:30 +0000171
Tobias Grosser3281f602017-02-16 18:39:14 +0000172 // The upper and lower bound for a parameter value is derived either from
173 // the data type of the parameter or from the - possibly more restrictive -
174 // range metadata.
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000175 V = valFromAPInt(Ctx.get(), Range.getSignedMin(), true);
176 S = S.lower_bound_val(type, dim, V);
177 V = valFromAPInt(Ctx.get(), Range.getSignedMax(), true);
178 S = S.upper_bound_val(type, dim, V);
Johannes Doerferte7044942015-02-24 11:58:30 +0000179
Tobias Grosser3281f602017-02-16 18:39:14 +0000180 if (Range.isFullSet())
181 return S;
182
Philip Pfaffe9375d572018-05-16 14:05:03 +0000183 if (S.n_basic_set() > MaxDisjunctsInContext)
Tobias Grosserc8a82762017-02-16 19:11:25 +0000184 return S;
185
Tobias Grosser3281f602017-02-16 18:39:14 +0000186 // In case of signed wrapping, we can refine the set of valid values by
187 // excluding the part not covered by the wrapping range.
188 if (Range.isSignWrappedSet()) {
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000189 V = valFromAPInt(Ctx.get(), Range.getLower(), true);
190 isl::set SLB = S.lower_bound_val(type, dim, V);
Tobias Grosser3281f602017-02-16 18:39:14 +0000191
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000192 V = valFromAPInt(Ctx.get(), Range.getUpper(), true);
193 V = V.sub_ui(1);
194 isl::set SUB = S.upper_bound_val(type, dim, V);
195 S = SLB.unite(SUB);
Tobias Grosser3281f602017-02-16 18:39:14 +0000196 }
Johannes Doerferte7044942015-02-24 11:58:30 +0000197
Tobias Grosser3281f602017-02-16 18:39:14 +0000198 return S;
Johannes Doerferte7044942015-02-24 11:58:30 +0000199}
200
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000201static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
202 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
203 if (!BasePtrLI)
204 return nullptr;
205
Johannes Doerfert952b5302016-05-23 12:40:48 +0000206 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000207 return nullptr;
208
209 ScalarEvolution &SE = *S->getSE();
210
211 auto *OriginBaseSCEV =
212 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
213 if (!OriginBaseSCEV)
214 return nullptr;
215
216 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
217 if (!OriginBaseSCEVUnknown)
218 return nullptr;
219
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000220 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000221 MemoryKind::Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000222}
223
Tobias Grosser27db02b2017-08-06 17:25:05 +0000224ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl::ctx Ctx,
Hongbin Zheng6aded2a2017-01-15 16:47:26 +0000225 ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +0000226 const DataLayout &DL, Scop *S,
227 const char *BaseName)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000228 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000229 std::string BasePtrName =
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000230 BaseName ? BaseName
Tobias Grossere2ccc3f2017-05-03 20:08:52 +0000231 : getIslCompatibleName("MemRef", BasePtr, S->getNextArrayIdx(),
232 Kind == MemoryKind::PHI ? "__phi" : "",
233 UseInstructionNames);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000234 Id = isl::id::alloc(Ctx, BasePtrName, this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000235
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000236 updateSizes(Sizes);
Roman Gareevd7754a12016-07-30 09:25:51 +0000237
Tobias Grosser4d5a9172017-01-14 20:25:44 +0000238 if (!BasePtr || Kind != MemoryKind::Array) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000239 BasePtrOriginSAI = nullptr;
240 return;
241 }
242
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000243 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
244 if (BasePtrOriginSAI)
245 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000246}
247
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000248ScopArrayInfo::~ScopArrayInfo() = default;
249
Tobias Grosser77eef902017-07-21 23:07:56 +0000250isl::space ScopArrayInfo::getSpace() const {
251 auto Space = isl::space(Id.get_ctx(), 0, getNumberOfDimensions());
252 Space = Space.set_tuple_id(isl::dim::set, Id);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000253 return Space;
254}
255
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000256bool ScopArrayInfo::isReadOnly() {
Tobias Grosser5ab39ff2017-08-06 19:22:27 +0000257 isl::union_set WriteSet = S.getWrites().range();
Tobias Grosser77eef902017-07-21 23:07:56 +0000258 isl::space Space = getSpace();
Tobias Grosser2ade9862017-05-23 06:41:04 +0000259 WriteSet = WriteSet.extract_set(Space);
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000260
Tobias Grosser2ade9862017-05-23 06:41:04 +0000261 return bool(WriteSet.is_empty());
Tobias Grosserfe74a7a2016-09-17 19:22:18 +0000262}
263
Tobias Grosserf3adab42017-05-10 10:59:58 +0000264bool ScopArrayInfo::isCompatibleWith(const ScopArrayInfo *Array) const {
265 if (Array->getElementType() != getElementType())
266 return false;
267
268 if (Array->getNumberOfDimensions() != getNumberOfDimensions())
269 return false;
270
271 for (unsigned i = 0; i < getNumberOfDimensions(); i++)
272 if (Array->getDimensionSize(i) != getDimensionSize(i))
273 return false;
274
275 return true;
276}
277
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000278void ScopArrayInfo::updateElementType(Type *NewElementType) {
279 if (NewElementType == ElementType)
280 return;
281
Tobias Grosserd840fc72016-02-04 13:18:42 +0000282 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
283 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
284
Johannes Doerferta7920982016-02-25 14:08:48 +0000285 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000286 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000287
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000288 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
289 ElementType = NewElementType;
290 } else {
291 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
292 ElementType = IntegerType::get(ElementType->getContext(), GCD);
293 }
294}
295
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000296/// Make the ScopArrayInfo model a Fortran Array
297void ScopArrayInfo::applyAndSetFAD(Value *FAD) {
298 assert(FAD && "got invalid Fortran array descriptor");
299 if (this->FAD) {
300 assert(this->FAD == FAD &&
301 "receiving different array descriptors for same array");
302 return;
303 }
304
305 assert(DimensionSizesPw.size() > 0 && !DimensionSizesPw[0]);
306 assert(!this->FAD);
307 this->FAD = FAD;
308
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000309 isl::space Space(S.getIslCtx(), 1, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000310
311 std::string param_name = getName();
312 param_name += "_fortranarr_size";
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000313 isl::id IdPwAff = isl::id::alloc(S.getIslCtx(), param_name, this);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000314
Tobias Grosserb1ed3d92017-05-23 07:07:05 +0000315 Space = Space.set_dim_id(isl::dim::param, 0, IdPwAff);
316 isl::pw_aff PwAff =
317 isl::aff::var_on_domain(isl::local_space(Space), isl::dim::param, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000318
Tobias Grosser77eef902017-07-21 23:07:56 +0000319 DimensionSizesPw[0] = PwAff;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000320}
321
Tobias Grosserbedef002016-12-02 08:10:56 +0000322bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
323 bool CheckConsistency) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000324 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
325 int ExtraDimsNew = NewSizes.size() - SharedDims;
326 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Roman Gareevf5aff702016-09-12 17:08:31 +0000327
Tobias Grosserbedef002016-12-02 08:10:56 +0000328 if (CheckConsistency) {
329 for (int i = 0; i < SharedDims; i++) {
330 auto *NewSize = NewSizes[i + ExtraDimsNew];
331 auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
332 if (NewSize && KnownSize && NewSize != KnownSize)
333 return false;
334 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000335
Tobias Grosserbedef002016-12-02 08:10:56 +0000336 if (DimensionSizes.size() >= NewSizes.size())
337 return true;
338 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000339
340 DimensionSizes.clear();
341 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
342 NewSizes.end());
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000343 DimensionSizesPw.clear();
344 for (const SCEV *Expr : DimensionSizes) {
Roman Gareevf5aff702016-09-12 17:08:31 +0000345 if (!Expr) {
346 DimensionSizesPw.push_back(nullptr);
347 continue;
348 }
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000349 isl::pw_aff Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000350 DimensionSizesPw.push_back(Size);
351 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000352 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000353}
354
Tobias Grosser77eef902017-07-21 23:07:56 +0000355std::string ScopArrayInfo::getName() const { return Id.get_name(); }
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000356
357int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000358 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000359}
360
Tobias Grosser77eef902017-07-21 23:07:56 +0000361isl::id ScopArrayInfo::getBasePtrId() const { return Id; }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000362
Michael Kruse5d518462017-07-21 15:54:07 +0000363#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000364LLVM_DUMP_METHOD void ScopArrayInfo::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000365#endif
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000366
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000367void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000368 OS.indent(8) << *getElementType() << " " << getName();
Roman Gareevf5aff702016-09-12 17:08:31 +0000369 unsigned u = 0;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +0000370 // If this is a Fortran array, then we can print the outermost dimension
371 // as a isl_pw_aff even though there is no SCEV information.
372 bool IsOutermostSizeKnown = SizeAsPwAff && FAD;
373
374 if (!IsOutermostSizeKnown && getNumberOfDimensions() > 0 &&
375 !getDimensionSize(0)) {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000376 OS << "[*]";
Roman Gareevf5aff702016-09-12 17:08:31 +0000377 u++;
378 }
379 for (; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000380 OS << "[";
381
Tobias Grosser26253842015-11-10 14:24:21 +0000382 if (SizeAsPwAff) {
Tobias Grosser77eef902017-07-21 23:07:56 +0000383 isl::pw_aff Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000384 OS << " " << Size << " ";
Tobias Grosser26253842015-11-10 14:24:21 +0000385 } else {
386 OS << *getDimensionSize(u);
387 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000388
389 OS << "]";
390 }
391
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000392 OS << ";";
393
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000394 if (BasePtrOriginSAI)
395 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
396
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000397 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000398}
399
400const ScopArrayInfo *
Tobias Grosser206e9e32017-07-24 16:22:27 +0000401ScopArrayInfo::getFromAccessFunction(isl::pw_multi_aff PMA) {
402 isl::id Id = PMA.get_tuple_id(isl::dim::out);
403 assert(!Id.is_null() && "Output dimension didn't have an ID");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000404 return getFromId(Id);
405}
406
Tobias Grosser206e9e32017-07-24 16:22:27 +0000407const ScopArrayInfo *ScopArrayInfo::getFromId(isl::id Id) {
408 void *User = Id.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000409 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000410 return SAI;
411}
412
Michael Kruse3b425ff2016-04-11 14:34:08 +0000413void MemoryAccess::wrapConstantDimensions() {
414 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000415 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000416 isl::ctx Ctx = ArraySpace.get_ctx();
Michael Kruse3b425ff2016-04-11 14:34:08 +0000417 unsigned DimsArray = SAI->getNumberOfDimensions();
418
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000419 isl::multi_aff DivModAff = isl::multi_aff::identity(
420 ArraySpace.map_from_domain_and_range(ArraySpace));
421 isl::local_space LArraySpace = isl::local_space(ArraySpace);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000422
423 // Begin with last dimension, to iteratively carry into higher dimensions.
424 for (int i = DimsArray - 1; i > 0; i--) {
425 auto *DimSize = SAI->getDimensionSize(i);
426 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
427
428 // This transformation is not applicable to dimensions with dynamic size.
429 if (!DimSizeCst)
430 continue;
431
Tobias Grosserca2cfd02017-02-17 04:48:52 +0000432 // This transformation is not applicable to dimensions of size zero.
433 if (DimSize->isZero())
434 continue;
435
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000436 isl::val DimSizeVal =
437 valFromAPInt(Ctx.get(), DimSizeCst->getAPInt(), false);
438 isl::aff Var = isl::aff::var_on_domain(LArraySpace, isl::dim::set, i);
439 isl::aff PrevVar =
440 isl::aff::var_on_domain(LArraySpace, isl::dim::set, i - 1);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000441
442 // Compute: index % size
443 // Modulo must apply in the divide of the previous iteration, if any.
Tobias Grossercb0224a2017-08-06 15:56:45 +0000444 isl::aff Modulo = Var.mod(DimSizeVal);
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000445 Modulo = Modulo.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000446
447 // Compute: floor(index / size)
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000448 isl::aff Divide = Var.div(isl::aff(LArraySpace, DimSizeVal));
449 Divide = Divide.floor();
450 Divide = Divide.add(PrevVar);
451 Divide = Divide.pullback(DivModAff);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000452
453 // Apply Modulo and Divide.
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000454 DivModAff = DivModAff.set_aff(i, Modulo);
455 DivModAff = DivModAff.set_aff(i - 1, Divide);
Michael Kruse3b425ff2016-04-11 14:34:08 +0000456 }
457
458 // Apply all modulo/divides on the accesses.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000459 isl::map Relation = AccessRelation;
Tobias Grosser3137f2c2017-05-21 20:23:23 +0000460 Relation = Relation.apply_range(isl::map::from_multi_aff(DivModAff));
461 Relation = Relation.detect_equalities();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000462 AccessRelation = Relation;
Michael Kruse3b425ff2016-04-11 14:34:08 +0000463}
464
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000465void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000466 auto *SAI = getScopArrayInfo();
Tobias Grosser77eef902017-07-21 23:07:56 +0000467 isl::space ArraySpace = SAI->getSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000468 isl::space AccessSpace = AccessRelation.get_space().range();
Tobias Grosser7be82452017-05-21 20:38:33 +0000469 isl::ctx Ctx = ArraySpace.get_ctx();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000470
Tobias Grosser7be82452017-05-21 20:38:33 +0000471 auto DimsArray = ArraySpace.dim(isl::dim::set);
472 auto DimsAccess = AccessSpace.dim(isl::dim::set);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000473 auto DimsMissing = DimsArray - DimsAccess;
474
Michael Kruse375cb5f2016-02-24 22:08:24 +0000475 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000476 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000477 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000478 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000479
Tobias Grosser7be82452017-05-21 20:38:33 +0000480 isl::map Map = isl::map::from_domain_and_range(
481 isl::set::universe(AccessSpace), isl::set::universe(ArraySpace));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000482
483 for (unsigned i = 0; i < DimsMissing; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000484 Map = Map.fix_si(isl::dim::out, i, 0);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000485
486 for (unsigned i = DimsMissing; i < DimsArray; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000487 Map = Map.equate(isl::dim::in, i - DimsMissing, isl::dim::out, i);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000488
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000489 AccessRelation = AccessRelation.apply_range(Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000490
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000491 // For the non delinearized arrays, divide the access function of the last
492 // subscript by the size of the elements in the array.
493 //
494 // A stride one array access in C expressed as A[i] is expressed in
495 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
496 // two subsequent values of 'i' index two values that are stored next to
497 // each other in memory. By this division we make this characteristic
498 // obvious again. If the base pointer was accessed with offsets not divisible
Tobias Grosser2219d152016-08-03 05:28:09 +0000499 // by the accesses element size, we will have chosen a smaller ArrayElemSize
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000500 // that divides the offsets of all accesses to this base pointer.
501 if (DimsAccess == 1) {
Tobias Grosser7be82452017-05-21 20:38:33 +0000502 isl::val V = isl::val(Ctx, ArrayElemSize);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000503 AccessRelation = AccessRelation.floordiv_val(V);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000504 }
505
Michael Kruse3b425ff2016-04-11 14:34:08 +0000506 // We currently do this only if we added at least one dimension, which means
507 // some dimension's indices have not been specified, an indicator that some
508 // index values have been added together.
509 // TODO: Investigate general usefulness; Effect on unit tests is to make index
510 // expressions more complicated.
511 if (DimsMissing)
512 wrapConstantDimensions();
513
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000514 if (!isAffine())
515 computeBoundsOnAccessRelation(ArrayElemSize);
516
Tobias Grosserd840fc72016-02-04 13:18:42 +0000517 // Introduce multi-element accesses in case the type loaded by this memory
518 // access is larger than the canonical element type of the array.
519 //
520 // An access ((float *)A)[i] to an array char *A is modeled as
521 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000522 if (ElemBytes > ArrayElemSize) {
523 assert(ElemBytes % ArrayElemSize == 0 &&
524 "Loaded element size should be multiple of canonical element size");
Tobias Grosser7be82452017-05-21 20:38:33 +0000525 isl::map Map = isl::map::from_domain_and_range(
526 isl::set::universe(ArraySpace), isl::set::universe(ArraySpace));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000527 for (unsigned i = 0; i < DimsArray - 1; i++)
Tobias Grosser7be82452017-05-21 20:38:33 +0000528 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000529
Tobias Grosser7be82452017-05-21 20:38:33 +0000530 isl::constraint C;
531 isl::local_space LS;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000532
Tobias Grosser7be82452017-05-21 20:38:33 +0000533 LS = isl::local_space(Map.get_space());
Tobias Grosserd840fc72016-02-04 13:18:42 +0000534 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
535
Tobias Grosser7be82452017-05-21 20:38:33 +0000536 C = isl::constraint::alloc_inequality(LS);
537 C = C.set_constant_val(isl::val(Ctx, Num - 1));
538 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, 1);
539 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, -1);
540 Map = Map.add_constraint(C);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000541
Tobias Grosser7be82452017-05-21 20:38:33 +0000542 C = isl::constraint::alloc_inequality(LS);
543 C = C.set_coefficient_si(isl::dim::in, DimsArray - 1, -1);
544 C = C.set_coefficient_si(isl::dim::out, DimsArray - 1, 1);
545 C = C.set_constant_val(isl::val(Ctx, 0));
546 Map = Map.add_constraint(C);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000547 AccessRelation = AccessRelation.apply_range(Map);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000548 }
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000549}
550
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000551const std::string
552MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
553 switch (RT) {
554 case MemoryAccess::RT_NONE:
555 llvm_unreachable("Requested a reduction operator string for a memory "
556 "access which isn't a reduction");
557 case MemoryAccess::RT_ADD:
558 return "+";
559 case MemoryAccess::RT_MUL:
560 return "*";
561 case MemoryAccess::RT_BOR:
562 return "|";
563 case MemoryAccess::RT_BXOR:
564 return "^";
565 case MemoryAccess::RT_BAND:
566 return "&";
567 }
568 llvm_unreachable("Unknown reduction type");
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000569}
570
Michael Kruse2fa35192016-09-01 19:53:31 +0000571const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000572 isl::id ArrayId = getArrayId();
573 void *User = ArrayId.get_user();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000574 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000575 return SAI;
576}
577
Michael Kruse2fa35192016-09-01 19:53:31 +0000578const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000579 isl::id ArrayId = getLatestArrayId();
580 void *User = ArrayId.get_user();
Michael Kruse2fa35192016-09-01 19:53:31 +0000581 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
Michael Kruse2fa35192016-09-01 19:53:31 +0000582 return SAI;
583}
584
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000585isl::id MemoryAccess::getOriginalArrayId() const {
586 return AccessRelation.get_tuple_id(isl::dim::out);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000587}
588
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000589isl::id MemoryAccess::getLatestArrayId() const {
Michael Kruse2fa35192016-09-01 19:53:31 +0000590 if (!hasNewAccessRelation())
591 return getOriginalArrayId();
Tobias Grosser1959dbd2017-07-23 04:08:59 +0000592 return NewAccessRelation.get_tuple_id(isl::dim::out);
Michael Kruse2fa35192016-09-01 19:53:31 +0000593}
594
Tobias Grosser6a870362017-07-23 04:08:45 +0000595isl::map MemoryAccess::getAddressFunction() const {
596 return getAccessRelation().lexmin();
Tobias Grosserd840fc72016-02-04 13:18:42 +0000597}
598
Tobias Grosser3b196132017-07-23 04:08:52 +0000599isl::pw_multi_aff
600MemoryAccess::applyScheduleToAccessRelation(isl::union_map USchedule) const {
601 isl::map Schedule, ScheduledAccRel;
602 isl::union_set UDomain;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000603
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000604 UDomain = getStatement()->getDomain();
Tobias Grosser3b196132017-07-23 04:08:52 +0000605 USchedule = USchedule.intersect_domain(UDomain);
606 Schedule = isl::map::from_union_map(USchedule);
607 ScheduledAccRel = getAddressFunction().apply_domain(Schedule);
608 return isl::pw_multi_aff::from_map(ScheduledAccRel);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000609}
610
Tobias Grosser22da5f02017-07-23 04:08:27 +0000611isl::map MemoryAccess::getOriginalAccessRelation() const {
612 return AccessRelation;
Tobias Grosser5d453812011-10-06 00:04:11 +0000613}
614
Johannes Doerferta99130f2014-10-13 12:58:03 +0000615std::string MemoryAccess::getOriginalAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000616 return AccessRelation.to_str();
Tobias Grosser5d453812011-10-06 00:04:11 +0000617}
618
Tobias Grosser22da5f02017-07-23 04:08:27 +0000619isl::space MemoryAccess::getOriginalAccessRelationSpace() const {
620 return AccessRelation.get_space();
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000621}
622
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000623isl::map MemoryAccess::getNewAccessRelation() const {
624 return NewAccessRelation;
Tobias Grosser75805372011-04-29 06:27:02 +0000625}
626
Tobias Grosser6f730082015-09-05 07:46:47 +0000627std::string MemoryAccess::getNewAccessRelationStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000628 return NewAccessRelation.to_str();
Tobias Grosser6f730082015-09-05 07:46:47 +0000629}
630
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000631std::string MemoryAccess::getAccessRelationStr() const {
Tobias Grosser2b7479b2017-08-06 11:41:10 +0000632 return getAccessRelation().to_str();
Tobias Grosser6a4c12f2017-07-11 10:10:13 +0000633}
634
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000635isl::basic_map MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
636 isl::space Space = isl::space(Statement->getIslCtx(), 0, 1);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000637 Space = Space.align_params(Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000638
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000639 return isl::basic_map::from_domain_and_range(
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000640 isl::basic_set::universe(Statement->getDomainSpace()),
Tobias Grosserb6e7a852017-07-23 04:08:17 +0000641 isl::basic_set::universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000642}
643
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000644// Formalize no out-of-bound access assumption
645//
646// When delinearizing array accesses we optimistically assume that the
647// delinearized accesses do not access out of bound locations (the subscript
648// expression of each array evaluates for each statement instance that is
649// executed to a value that is larger than zero and strictly smaller than the
650// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000651// dimension for which we do not need to assume any upper bound. At this point
652// we formalize this assumption to ensure that at code generation time the
653// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000654//
655// To find the set of constraints necessary to avoid out of bound accesses, we
656// first build the set of data locations that are not within array bounds. We
657// then apply the reverse access relation to obtain the set of iterations that
658// may contain invalid accesses and reduce this set of iterations to the ones
659// that are actually executed by intersecting them with the domain of the
660// statement. If we now project out all loop dimensions, we obtain a set of
661// parameters that may cause statement instances to be executed that may
662// possibly yield out of bound memory accesses. The complement of these
663// constraints is the set of constraints that needs to be assumed to ensure such
664// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000665void MemoryAccess::assumeNoOutOfBound() {
Tobias Grosser8a6e6052017-03-17 12:26:58 +0000666 if (PollyIgnoreInbounds)
667 return;
Johannes Doerfertadeab372016-02-07 13:57:32 +0000668 auto *SAI = getScopArrayInfo();
Tobias Grosser22da5f02017-07-23 04:08:27 +0000669 isl::space Space = getOriginalAccessRelationSpace().range();
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000670 isl::set Outside = isl::set::empty(Space);
671 for (int i = 1, Size = Space.dim(isl::dim::set); i < Size; ++i) {
672 isl::local_space LS(Space);
673 isl::pw_aff Var = isl::pw_aff::var_on_domain(LS, isl::dim::set, i);
674 isl::pw_aff Zero = isl::pw_aff(LS);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000675
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000676 isl::set DimOutside = Var.lt_set(Zero);
Tobias Grosser77eef902017-07-21 23:07:56 +0000677 isl::pw_aff SizeE = SAI->getDimensionSizePw(i);
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000678 SizeE = SizeE.add_dims(isl::dim::in, Space.dim(isl::dim::set));
679 SizeE = SizeE.set_tuple_id(isl::dim::in, Space.get_tuple_id(isl::dim::set));
680 DimOutside = DimOutside.unite(SizeE.le_set(Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000681
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000682 Outside = Outside.unite(DimOutside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000683 }
684
Tobias Grosser1515f6b2017-07-23 04:08:38 +0000685 Outside = Outside.apply(getAccessRelation().reverse());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000686 Outside = Outside.intersect(Statement->getDomain());
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000687 Outside = Outside.params();
Tobias Grosserf54bb772015-06-26 12:09:28 +0000688
689 // Remove divs to avoid the construction of overly complicated assumptions.
690 // Doing so increases the set of parameter combinations that are assumed to
691 // not appear. This is always save, but may make the resulting run-time check
692 // bail out more often than strictly necessary.
Tobias Grosser1e2edaf2017-05-23 07:07:07 +0000693 Outside = Outside.remove_divs();
694 Outside = Outside.complement();
Michael Kruse7071e8b2016-04-11 13:24:29 +0000695 const auto &Loc = getAccessInstruction()
696 ? getAccessInstruction()->getDebugLoc()
697 : DebugLoc();
Tobias Grosserd7c49752017-02-28 09:45:54 +0000698 if (!PollyPreciseInbounds)
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000699 Outside = Outside.gist_params(Statement->getDomain().params());
Philip Pfaffe00fd43b2017-11-19 22:13:34 +0000700 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000701 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000702}
703
Johannes Doerfertcea61932016-02-21 19:13:19 +0000704void MemoryAccess::buildMemIntrinsicAccessRelation() {
Johannes Doerfertc9765462016-11-17 22:11:56 +0000705 assert(isMemoryIntrinsic());
Roman Gareevf5aff702016-09-12 17:08:31 +0000706 assert(Subscripts.size() == 2 && Sizes.size() == 1);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000707
Tobias Grossercdf471b2017-07-24 16:36:34 +0000708 isl::pw_aff SubscriptPWA = getPwAff(Subscripts[0]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000709 isl::map SubscriptMap = isl::map::from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000710
Tobias Grosser53fc3552017-05-23 07:07:09 +0000711 isl::map LengthMap;
Johannes Doerferta7920982016-02-25 14:08:48 +0000712 if (Subscripts[1] == nullptr) {
Tobias Grosser53fc3552017-05-23 07:07:09 +0000713 LengthMap = isl::map::universe(SubscriptMap.get_space());
Johannes Doerferta7920982016-02-25 14:08:48 +0000714 } else {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000715 isl::pw_aff LengthPWA = getPwAff(Subscripts[1]);
Tobias Grosser53fc3552017-05-23 07:07:09 +0000716 LengthMap = isl::map::from_pw_aff(LengthPWA);
717 isl::space RangeSpace = LengthMap.get_space().range();
718 LengthMap = LengthMap.apply_range(isl::map::lex_gt(RangeSpace));
Johannes Doerferta7920982016-02-25 14:08:48 +0000719 }
Tobias Grosser53fc3552017-05-23 07:07:09 +0000720 LengthMap = LengthMap.lower_bound_si(isl::dim::out, 0, 0);
721 LengthMap = LengthMap.align_params(SubscriptMap.get_space());
722 SubscriptMap = SubscriptMap.align_params(LengthMap.get_space());
723 LengthMap = LengthMap.sum(SubscriptMap);
724 AccessRelation =
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000725 LengthMap.set_tuple_id(isl::dim::in, getStatement()->getDomainId());
Johannes Doerfertcea61932016-02-21 19:13:19 +0000726}
727
Johannes Doerferte7044942015-02-24 11:58:30 +0000728void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
729 ScalarEvolution *SE = Statement->getParent()->getSE();
730
Johannes Doerfertcea61932016-02-21 19:13:19 +0000731 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000732 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000733 return;
734
735 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000736 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
737 return;
738
739 auto *PtrSCEV = SE->getSCEV(Ptr);
740 if (isa<SCEVCouldNotCompute>(PtrSCEV))
741 return;
742
743 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
744 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
745 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
746
747 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
748 if (Range.isFullSet())
749 return;
750
Nikita Popov6d855ea2019-03-27 18:19:33 +0000751 if (Range.isUpperWrapped() || Range.isSignWrappedSet())
Tobias Grosserb3a85882017-02-12 08:11:12 +0000752 return;
753
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000754 bool isWrapping = Range.isSignWrappedSet();
Tobias Grosserb3a85882017-02-12 08:11:12 +0000755
Johannes Doerferte7044942015-02-24 11:58:30 +0000756 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000757 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000758 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000759 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000760
761 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000762 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000763
Tobias Grosserb3a85882017-02-12 08:11:12 +0000764 assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
765
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000766 isl::map Relation = AccessRelation;
Tobias Grosser99ea1d02017-05-21 20:23:20 +0000767 isl::set AccessRange = Relation.range();
768 AccessRange = addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0,
769 isl::dim::set);
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000770 AccessRelation = Relation.intersect_range(AccessRange);
Johannes Doerferte7044942015-02-24 11:58:30 +0000771}
772
Tobias Grosser491b7992016-12-02 05:21:22 +0000773void MemoryAccess::foldAccessRelation() {
774 if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
775 return;
776
Michael Krusee2bccbb2015-09-18 19:59:43 +0000777 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000778
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000779 isl::map NewAccessRelation = AccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000780
Tobias Grosser619190d2015-03-30 17:22:28 +0000781 for (int i = Size - 2; i >= 0; --i) {
Tobias Grossera32de132017-05-23 07:22:56 +0000782 isl::space Space;
783 isl::map MapOne, MapTwo;
Tobias Grossercdf471b2017-07-24 16:36:34 +0000784 isl::pw_aff DimSize = getPwAff(Sizes[i + 1]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000785
Tobias Grossera32de132017-05-23 07:22:56 +0000786 isl::space SpaceSize = DimSize.get_space();
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000787 isl::id ParamId = SpaceSize.get_dim_id(isl::dim::param, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000788
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000789 Space = AccessRelation.get_space();
Tobias Grossera32de132017-05-23 07:22:56 +0000790 Space = Space.range().map_from_set();
791 Space = Space.align_params(SpaceSize);
Tobias Grosser619190d2015-03-30 17:22:28 +0000792
Tobias Grossera32de132017-05-23 07:22:56 +0000793 int ParamLocation = Space.find_dim_by_id(isl::dim::param, ParamId);
Tobias Grosser619190d2015-03-30 17:22:28 +0000794
Tobias Grossera32de132017-05-23 07:22:56 +0000795 MapOne = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000796 for (int j = 0; j < Size; ++j)
Tobias Grossera32de132017-05-23 07:22:56 +0000797 MapOne = MapOne.equate(isl::dim::in, j, isl::dim::out, j);
798 MapOne = MapOne.lower_bound_si(isl::dim::in, i + 1, 0);
Tobias Grosser619190d2015-03-30 17:22:28 +0000799
Tobias Grossera32de132017-05-23 07:22:56 +0000800 MapTwo = isl::map::universe(Space);
Tobias Grosser619190d2015-03-30 17:22:28 +0000801 for (int j = 0; j < Size; ++j)
802 if (j < i || j > i + 1)
Tobias Grossera32de132017-05-23 07:22:56 +0000803 MapTwo = MapTwo.equate(isl::dim::in, j, isl::dim::out, j);
Tobias Grosser619190d2015-03-30 17:22:28 +0000804
Tobias Grossera32de132017-05-23 07:22:56 +0000805 isl::local_space LS(Space);
806 isl::constraint C;
807 C = isl::constraint::alloc_equality(LS);
808 C = C.set_constant_si(-1);
809 C = C.set_coefficient_si(isl::dim::in, i, 1);
810 C = C.set_coefficient_si(isl::dim::out, i, -1);
811 MapTwo = MapTwo.add_constraint(C);
812 C = isl::constraint::alloc_equality(LS);
813 C = C.set_coefficient_si(isl::dim::in, i + 1, 1);
814 C = C.set_coefficient_si(isl::dim::out, i + 1, -1);
815 C = C.set_coefficient_si(isl::dim::param, ParamLocation, 1);
816 MapTwo = MapTwo.add_constraint(C);
817 MapTwo = MapTwo.upper_bound_si(isl::dim::in, i + 1, -1);
Tobias Grosser619190d2015-03-30 17:22:28 +0000818
Tobias Grossera32de132017-05-23 07:22:56 +0000819 MapOne = MapOne.unite(MapTwo);
820 NewAccessRelation = NewAccessRelation.apply_range(MapOne);
Tobias Grosser619190d2015-03-30 17:22:28 +0000821 }
Tobias Grosser491b7992016-12-02 05:21:22 +0000822
Tobias Grosser77eef902017-07-21 23:07:56 +0000823 isl::id BaseAddrId = getScopArrayInfo()->getBasePtrId();
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000824 isl::space Space = Statement->getDomainSpace();
Tobias Grossera32de132017-05-23 07:22:56 +0000825 NewAccessRelation = NewAccessRelation.set_tuple_id(
826 isl::dim::in, Space.get_tuple_id(isl::dim::set));
827 NewAccessRelation = NewAccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000828 NewAccessRelation = NewAccessRelation.gist_domain(Statement->getDomain());
Tobias Grosserc2f15102017-03-01 21:11:27 +0000829
830 // Access dimension folding might in certain cases increase the number of
831 // disjuncts in the memory access, which can possibly complicate the generated
832 // run-time checks and can lead to costly compilation.
Tobias Grossera32de132017-05-23 07:22:56 +0000833 if (!PollyPreciseFoldAccesses &&
Tobias Grosser6ec6e1d2018-06-19 08:13:53 +0000834 NewAccessRelation.n_basic_map() > AccessRelation.n_basic_map()) {
Tobias Grosserc2f15102017-03-01 21:11:27 +0000835 } else {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000836 AccessRelation = NewAccessRelation;
Tobias Grosserc2f15102017-03-01 21:11:27 +0000837 }
Tobias Grosser619190d2015-03-30 17:22:28 +0000838}
839
Michael Krusee2bccbb2015-09-18 19:59:43 +0000840void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000841 assert(AccessRelation.is_null() && "AccessRelation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000842
Johannes Doerfert85676e32016-04-23 14:32:34 +0000843 // Initialize the invalid domain which describes all iterations for which the
844 // access relation is not modeled correctly.
Tobias Grosser2332fa32017-08-06 15:36:48 +0000845 isl::set StmtInvalidDomain = getStatement()->getInvalidDomain();
Tobias Grosserb739cb42017-07-24 20:30:34 +0000846 InvalidDomain = isl::set::empty(StmtInvalidDomain.get_space());
Johannes Doerfert85676e32016-04-23 14:32:34 +0000847
Tobias Grosserb739cb42017-07-24 20:30:34 +0000848 isl::ctx Ctx = Id.get_ctx();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000849 isl::id BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000850
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000851 if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
852 buildMemIntrinsicAccessRelation();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000853 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000854 return;
855 }
Johannes Doerfertcea61932016-02-21 19:13:19 +0000856
Eli Friedmanb9c6f012016-11-01 20:53:11 +0000857 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000858 // We overapproximate non-affine accesses with a possible access to the
859 // whole array. For read accesses it does not make a difference, if an
860 // access must or may happen. However, for write accesses it is important to
861 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000862 if (AccessRelation.is_null())
863 AccessRelation = createBasicAccessMap(Statement);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000864
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000865 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000866 return;
867 }
868
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000869 isl::space Space = isl::space(Ctx, 0, Statement->getNumIterators(), 0);
870 AccessRelation = isl::map::universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000871
Michael Krusee2bccbb2015-09-18 19:59:43 +0000872 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grossercdf471b2017-07-24 16:36:34 +0000873 isl::pw_aff Affine = getPwAff(Subscripts[i]);
874 isl::map SubscriptMap = isl::map::from_pw_aff(Affine);
875 AccessRelation = AccessRelation.flat_range_product(SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000876 }
877
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000878 Space = Statement->getDomainSpace();
Tobias Grosser0c4c2ee2017-07-23 04:08:22 +0000879 AccessRelation = AccessRelation.set_tuple_id(
880 isl::dim::in, Space.get_tuple_id(isl::dim::set));
881 AccessRelation = AccessRelation.set_tuple_id(isl::dim::out, BaseAddrId);
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000882
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000883 AccessRelation = AccessRelation.gist_domain(Statement->getDomain());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000884}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000885
Michael Krusecac948e2015-10-02 13:53:07 +0000886MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000887 AccessType AccType, Value *BaseAddress,
888 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000889 ArrayRef<const SCEV *> Subscripts,
890 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grosser72684bb2017-05-03 08:02:32 +0000891 MemoryKind Kind)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000892 : Kind(Kind), AccType(AccType), Statement(Stmt), InvalidDomain(nullptr),
893 BaseAddr(BaseAddress), ElementType(ElementType),
Tobias Grosser81331282017-05-03 07:57:35 +0000894 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
895 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000896 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Siddharth Bhatf2dbba82017-05-10 13:11:20 +0000897 NewAccessRelation(nullptr), FAD(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000898 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +0000899 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000900
Tobias Grosser81331282017-05-03 07:57:35 +0000901 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000902 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000903}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000904
Tobias Grosser1f6ba7e2017-07-24 16:22:32 +0000905MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType, isl::map AccRel)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000906 : Kind(MemoryKind::Array), AccType(AccType), Statement(Stmt),
907 InvalidDomain(nullptr), AccessRelation(nullptr),
908 NewAccessRelation(AccRel), FAD(nullptr) {
Tobias Grosser206e9e32017-07-24 16:22:27 +0000909 isl::id ArrayInfoId = NewAccessRelation.get_tuple_id(isl::dim::out);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000910 auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
911 Sizes.push_back(nullptr);
912 for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
913 Sizes.push_back(SAI->getDimensionSize(i));
914 ElementType = SAI->getElementType();
915 BaseAddr = SAI->getBasePtr();
Roman Gareevb3224ad2016-09-14 06:26:09 +0000916 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Tobias Grosser81331282017-05-03 07:57:35 +0000917 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size());
Roman Gareevb3224ad2016-09-14 06:26:09 +0000918
Tobias Grosser81331282017-05-03 07:57:35 +0000919 std::string IdName = Stmt->getBaseName() + Access;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000920 Id = isl::id::alloc(Stmt->getParent()->getIslCtx(), IdName, this);
Roman Gareevb3224ad2016-09-14 06:26:09 +0000921}
922
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +0000923MemoryAccess::~MemoryAccess() = default;
924
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000925void MemoryAccess::realignParams() {
Tobias Grosser8ea1fc12017-08-06 19:52:38 +0000926 isl::set Ctx = Statement->getParent()->getContext();
Tobias Grosserb739cb42017-07-24 20:30:34 +0000927 InvalidDomain = InvalidDomain.gist_params(Ctx);
928 AccessRelation = AccessRelation.gist_params(Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000929}
930
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000931const std::string MemoryAccess::getReductionOperatorStr() const {
932 return MemoryAccess::getReductionOperatorStr(getReductionType());
933}
934
Tobias Grosserfe46c3f2017-07-23 04:08:11 +0000935isl::id MemoryAccess::getId() const { return Id; }
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000936
Johannes Doerfertf6183392014-07-01 20:52:51 +0000937raw_ostream &polly::operator<<(raw_ostream &OS,
938 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000939 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000940 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000941 else
942 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000943 return OS;
944}
945
Siddharth Bhat0fe72312017-05-15 08:41:30 +0000946void MemoryAccess::setFortranArrayDescriptor(Value *FAD) { this->FAD = FAD; }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +0000947
Tobias Grosser75805372011-04-29 06:27:02 +0000948void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000949 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000950 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000951 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000952 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000953 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000954 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000955 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000956 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000957 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000958 break;
959 }
Siddharth Bhatf2dbba82017-05-10 13:11:20 +0000960
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000961 OS << "[Reduction Type: " << getReductionType() << "] ";
Siddharth Bhatf2dbba82017-05-10 13:11:20 +0000962
963 if (FAD) {
964 OS << "[Fortran array descriptor: " << FAD->getName();
965 OS << "] ";
966 };
967
Tobias Grossera535dff2015-12-13 19:59:01 +0000968 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000969 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000970 if (hasNewAccessRelation())
971 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000972}
973
Michael Kruse5d518462017-07-21 15:54:07 +0000974#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +0000975LLVM_DUMP_METHOD void MemoryAccess::dump() const { print(errs()); }
Michael Kruse5d518462017-07-21 15:54:07 +0000976#endif
Tobias Grosser75805372011-04-29 06:27:02 +0000977
Tobias Grossercdf471b2017-07-24 16:36:34 +0000978isl::pw_aff MemoryAccess::getPwAff(const SCEV *E) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000979 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000980 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000981 isl::set StmtDom = getStatement()->getDomain();
Tobias Grossercdf471b2017-07-24 16:36:34 +0000982 StmtDom = StmtDom.reset_tuple_id();
Philip Pfaffed98dbee2017-12-06 21:02:22 +0000983 isl::set NewInvalidDom = StmtDom.intersect(PWAC.second);
Tobias Grosserb739cb42017-07-24 20:30:34 +0000984 InvalidDomain = InvalidDomain.unite(NewInvalidDom);
Philip Pfaffed98dbee2017-12-06 21:02:22 +0000985 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000986}
987
Tobias Grosser75805372011-04-29 06:27:02 +0000988// Create a map in the size of the provided set domain, that maps from the
989// one element of the provided set domain to another element of the provided
990// set domain.
991// The mapping is limited to all points that are equal in all but the last
992// dimension and for which the last dimension of the input is strict smaller
993// than the last dimension of the output.
994//
995// getEqualAndLarger(set[i0, i1, ..., iX]):
996//
997// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
998// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
999//
Tobias Grosserd7065e52017-07-24 20:50:22 +00001000static isl::map getEqualAndLarger(isl::space SetDomain) {
1001 isl::space Space = SetDomain.map_from_set();
1002 isl::map Map = isl::map::universe(Space);
1003 unsigned lastDimension = Map.dim(isl::dim::in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +00001004
1005 // Set all but the last dimension to be equal for the input and output
1006 //
1007 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1008 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +00001009 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserd7065e52017-07-24 20:50:22 +00001010 Map = Map.equate(isl::dim::in, i, isl::dim::out, i);
Tobias Grosser75805372011-04-29 06:27:02 +00001011
1012 // Set the last dimension of the input to be strict smaller than the
1013 // last dimension of the output.
1014 //
1015 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosserd7065e52017-07-24 20:50:22 +00001016 Map = Map.order_lt(isl::dim::in, lastDimension, isl::dim::out, lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +00001017 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +00001018}
1019
Tobias Grosserd7065e52017-07-24 20:50:22 +00001020isl::set MemoryAccess::getStride(isl::map Schedule) const {
1021 isl::map AccessRelation = getAccessRelation();
1022 isl::space Space = Schedule.get_space().range();
1023 isl::map NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001024
Tobias Grosserd7065e52017-07-24 20:50:22 +00001025 Schedule = Schedule.reverse();
1026 NextScatt = NextScatt.lexmin();
Tobias Grosser75805372011-04-29 06:27:02 +00001027
Tobias Grosserd7065e52017-07-24 20:50:22 +00001028 NextScatt = NextScatt.apply_range(Schedule);
1029 NextScatt = NextScatt.apply_range(AccessRelation);
1030 NextScatt = NextScatt.apply_domain(Schedule);
1031 NextScatt = NextScatt.apply_domain(AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +00001032
Tobias Grosserd7065e52017-07-24 20:50:22 +00001033 isl::set Deltas = NextScatt.deltas();
Sebastian Popa00a0292012-12-18 07:46:06 +00001034 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +00001035}
1036
Tobias Grosserd7065e52017-07-24 20:50:22 +00001037bool MemoryAccess::isStrideX(isl::map Schedule, int StrideWidth) const {
1038 isl::set Stride, StrideX;
Tobias Grosser28dd4862012-01-24 16:42:16 +00001039 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +00001040
Sebastian Popa00a0292012-12-18 07:46:06 +00001041 Stride = getStride(Schedule);
Tobias Grosserd7065e52017-07-24 20:50:22 +00001042 StrideX = isl::set::universe(Stride.get_space());
1043 for (unsigned i = 0; i < StrideX.dim(isl::dim::set) - 1; i++)
1044 StrideX = StrideX.fix_si(isl::dim::set, i, 0);
1045 StrideX = StrideX.fix_si(isl::dim::set, StrideX.dim(isl::dim::set) - 1,
1046 StrideWidth);
1047 IsStrideX = Stride.is_subset(StrideX);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001048
Tobias Grosser28dd4862012-01-24 16:42:16 +00001049 return IsStrideX;
1050}
1051
Tobias Grosserd7065e52017-07-24 20:50:22 +00001052bool MemoryAccess::isStrideZero(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001053 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +00001054}
1055
Tobias Grosserd7065e52017-07-24 20:50:22 +00001056bool MemoryAccess::isStrideOne(isl::map Schedule) const {
Sebastian Popa00a0292012-12-18 07:46:06 +00001057 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +00001058}
1059
Tobias Grosser6d588042017-08-02 19:27:16 +00001060void MemoryAccess::setAccessRelation(isl::map NewAccess) {
1061 AccessRelation = NewAccess;
Tobias Grosserbedef002016-12-02 08:10:56 +00001062}
1063
Tobias Grosser7b45af12017-08-02 19:27:25 +00001064void MemoryAccess::setNewAccessRelation(isl::map NewAccess) {
Michael Kruse772ce722016-09-01 19:16:58 +00001065 assert(NewAccess);
1066
1067#ifndef NDEBUG
1068 // Check domain space compatibility.
Tobias Grosser7b45af12017-08-02 19:27:25 +00001069 isl::space NewSpace = NewAccess.get_space();
1070 isl::space NewDomainSpace = NewSpace.domain();
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001071 isl::space OriginalDomainSpace = getStatement()->getDomainSpace();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001072 assert(OriginalDomainSpace.has_equal_tuples(NewDomainSpace));
Michael Kruse772ce722016-09-01 19:16:58 +00001073
Michael Kruse706f79a2017-05-21 22:46:57 +00001074 // Reads must be executed unconditionally. Writes might be executed in a
1075 // subdomain only.
1076 if (isRead()) {
1077 // Check whether there is an access for every statement instance.
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001078 isl::set StmtDomain = getStatement()->getDomain();
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001079 StmtDomain =
1080 StmtDomain.intersect_params(getStatement()->getParent()->getContext());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001081 isl::set NewDomain = NewAccess.domain();
1082 assert(StmtDomain.is_subset(NewDomain) &&
Michael Kruse706f79a2017-05-21 22:46:57 +00001083 "Partial READ accesses not supported");
Michael Kruse706f79a2017-05-21 22:46:57 +00001084 }
Michael Kruse772ce722016-09-01 19:16:58 +00001085
Tobias Grosser7b45af12017-08-02 19:27:25 +00001086 isl::space NewAccessSpace = NewAccess.get_space();
1087 assert(NewAccessSpace.has_tuple_id(isl::dim::set) &&
Michael Kruse772ce722016-09-01 19:16:58 +00001088 "Must specify the array that is accessed");
Tobias Grosser7b45af12017-08-02 19:27:25 +00001089 isl::id NewArrayId = NewAccessSpace.get_tuple_id(isl::dim::set);
1090 auto *SAI = static_cast<ScopArrayInfo *>(NewArrayId.get_user());
Michael Kruse772ce722016-09-01 19:16:58 +00001091 assert(SAI && "Must set a ScopArrayInfo");
Tobias Grossere1ff0cf2017-01-17 12:00:42 +00001092
1093 if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1094 InvariantEquivClassTy *EqClass =
1095 getStatement()->getParent()->lookupInvariantEquivClass(
1096 SAI->getBasePtr());
1097 assert(EqClass &&
1098 "Access functions to indirect arrays must have an invariant and "
1099 "hoisted base pointer");
1100 }
1101
1102 // Check whether access dimensions correspond to number of dimensions of the
1103 // accesses array.
Michael Kruse772ce722016-09-01 19:16:58 +00001104 auto Dims = SAI->getNumberOfDimensions();
Tobias Grosser7b45af12017-08-02 19:27:25 +00001105 assert(NewAccessSpace.dim(isl::dim::set) == Dims &&
Michael Kruse772ce722016-09-01 19:16:58 +00001106 "Access dims must match array dims");
Michael Kruse772ce722016-09-01 19:16:58 +00001107#endif
1108
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001109 NewAccess = NewAccess.gist_domain(getStatement()->getDomain());
Tobias Grosser7b45af12017-08-02 19:27:25 +00001110 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +00001111}
Tobias Grosser75805372011-04-29 06:27:02 +00001112
Michael Kruse706f79a2017-05-21 22:46:57 +00001113bool MemoryAccess::isLatestPartialAccess() const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001114 isl::set StmtDom = getStatement()->getDomain();
Tobias Grosser1515f6b2017-07-23 04:08:38 +00001115 isl::set AccDom = getLatestAccessRelation().domain();
Michael Kruse706f79a2017-05-21 22:46:57 +00001116
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +00001117 return !StmtDom.is_subset(AccDom);
Michael Kruse706f79a2017-05-21 22:46:57 +00001118}
1119
Tobias Grosser75805372011-04-29 06:27:02 +00001120//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +00001121
Tobias Grosser6ad16402017-08-06 17:45:28 +00001122isl::map ScopStmt::getSchedule() const {
Tobias Grosser1e09c132017-08-14 06:49:06 +00001123 isl::set Domain = getDomain();
1124 if (Domain.is_empty())
1125 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1126 auto Schedule = getParent()->getSchedule();
1127 if (!Schedule)
Roman Gareevb3224ad2016-09-14 06:26:09 +00001128 return nullptr;
Tobias Grosser1e09c132017-08-14 06:49:06 +00001129 Schedule = Schedule.intersect_domain(isl::union_set(Domain));
1130 if (Schedule.is_empty())
1131 return isl::map::from_aff(isl::aff(isl::local_space(getDomainSpace())));
1132 isl::map M = M.from_union_map(Schedule);
1133 M = M.coalesce();
1134 M = M.gist_domain(Domain);
1135 M = M.coalesce();
1136 return M;
Tobias Grosser808cd692015-07-14 09:33:13 +00001137}
Tobias Grossercf3942d2011-10-06 00:04:05 +00001138
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001139void ScopStmt::restrictDomain(isl::set NewDomain) {
1140 assert(NewDomain.is_subset(Domain) &&
Tobias Grosser37eb4222014-02-20 21:43:54 +00001141 "New domain is not a subset of old domain!");
Tobias Grosser37eb4222014-02-20 21:43:54 +00001142 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +00001143}
1144
Michael Kruse70af4f52017-08-07 18:40:29 +00001145void ScopStmt::addAccess(MemoryAccess *Access, bool Prepend) {
Michael Krusecac948e2015-10-02 13:53:07 +00001146 Instruction *AccessInst = Access->getAccessInstruction();
1147
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001148 if (Access->isArrayKind()) {
1149 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1150 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001151 } else if (Access->isValueKind() && Access->isWrite()) {
1152 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse436db622016-01-26 13:33:10 +00001153 assert(!ValueWrites.lookup(AccessVal));
1154
1155 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001156 } else if (Access->isValueKind() && Access->isRead()) {
1157 Value *AccessVal = Access->getAccessValue();
1158 assert(!ValueReads.lookup(AccessVal));
1159
1160 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001161 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
Tobias Grosser5db171a2017-02-10 10:09:44 +00001162 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001163 assert(!PHIWrites.lookup(PHI));
1164
1165 PHIWrites[PHI] = Access;
Michael Kruse3562f272017-07-20 16:47:57 +00001166 } else if (Access->isAnyPHIKind() && Access->isRead()) {
1167 PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1168 assert(!PHIReads.lookup(PHI));
1169
1170 PHIReads[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001171 }
1172
Michael Kruse70af4f52017-08-07 18:40:29 +00001173 if (Prepend) {
1174 MemAccs.insert(MemAccs.begin(), Access);
1175 return;
1176 }
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001177 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001178}
1179
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001180void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001181 for (MemoryAccess *MA : *this)
1182 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001183
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001184 isl::set Ctx = Parent.getContext();
Tobias Grosser2332fa32017-08-06 15:36:48 +00001185 InvalidDomain = InvalidDomain.gist_params(Ctx);
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001186 Domain = Domain.gist_params(Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001187}
1188
Michael Krused6e22082018-01-18 15:15:38 +00001189ScopStmt::ScopStmt(Scop &parent, Region &R, StringRef Name,
1190 Loop *SurroundingLoop,
Tobias Grosserbd15d132017-08-31 03:15:56 +00001191 std::vector<Instruction *> EntryBlockInstructions)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001192 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), R(&R),
Michael Krused6e22082018-01-18 15:15:38 +00001193 Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1194 Instructions(EntryBlockInstructions) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001195
Michael Krused6e22082018-01-18 15:15:38 +00001196ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb, StringRef Name,
1197 Loop *SurroundingLoop,
1198 std::vector<Instruction *> Instructions)
Johannes Doerferta3519512016-04-23 13:02:23 +00001199 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
Michael Krused6e22082018-01-18 15:15:38 +00001200 Build(nullptr), BaseName(Name), SurroundingLoop(SurroundingLoop),
1201 Instructions(Instructions) {}
Michael Krusecac948e2015-10-02 13:53:07 +00001202
Tobias Grosser85048ef2017-08-06 17:24:59 +00001203ScopStmt::ScopStmt(Scop &parent, isl::map SourceRel, isl::map TargetRel,
1204 isl::set NewDomain)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001205 : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain),
1206 Build(nullptr) {
Roman Gareevb3224ad2016-09-14 06:26:09 +00001207 BaseName = getIslCompatibleName("CopyStmt_", "",
1208 std::to_string(parent.getCopyStmtsNum()));
Tobias Grosser85048ef2017-08-06 17:24:59 +00001209 isl::id Id = isl::id::alloc(getIslCtx(), getBaseName(), this);
1210 Domain = Domain.set_tuple_id(Id);
1211 TargetRel = TargetRel.set_tuple_id(isl::dim::in, Id);
1212 auto *Access =
1213 new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001214 parent.addAccessFunction(Access);
1215 addAccess(Access);
Tobias Grosser85048ef2017-08-06 17:24:59 +00001216 SourceRel = SourceRel.set_tuple_id(isl::dim::in, Id);
1217 Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
Roman Gareevb3224ad2016-09-14 06:26:09 +00001218 parent.addAccessFunction(Access);
1219 addAccess(Access);
1220}
1221
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001222ScopStmt::~ScopStmt() = default;
1223
Tobias Grossera9b5bba2017-08-06 16:11:53 +00001224std::string ScopStmt::getDomainStr() const { return Domain.to_str(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001225
Tobias Grosser54839312015-04-21 11:37:25 +00001226std::string ScopStmt::getScheduleStr() const {
Tobias Grosser6ad16402017-08-06 17:45:28 +00001227 auto *S = getSchedule().release();
Roman Gareevb3224ad2016-09-14 06:26:09 +00001228 if (!S)
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001229 return {};
Tobias Grosser808cd692015-07-14 09:33:13 +00001230 auto Str = stringFromIslObj(S);
1231 isl_map_free(S);
1232 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001233}
1234
Tobias Grosser2332fa32017-08-06 15:36:48 +00001235void ScopStmt::setInvalidDomain(isl::set ID) { InvalidDomain = ID; }
Johannes Doerfert7c013572016-04-12 09:57:34 +00001236
Michael Kruse375cb5f2016-02-24 22:08:24 +00001237BasicBlock *ScopStmt::getEntryBlock() const {
1238 if (isBlockStmt())
1239 return getBasicBlock();
1240 return getRegion()->getEntry();
1241}
1242
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001243unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001244
Tobias Grosser75805372011-04-29 06:27:02 +00001245const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1246
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001247Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001248 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001249}
1250
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001251isl::ctx ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001252
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001253isl::set ScopStmt::getDomain() const { return Domain; }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001254
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001255isl::space ScopStmt::getDomainSpace() const { return Domain.get_space(); }
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001256
Tobias Grosserdcf8d692017-08-06 16:39:52 +00001257isl::id ScopStmt::getDomainId() const { return Domain.get_tuple_id(); }
Tobias Grossercd95b772012-08-30 11:49:38 +00001258
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001259void ScopStmt::printInstructions(raw_ostream &OS) const {
1260 OS << "Instructions {\n";
1261
1262 for (Instruction *Inst : Instructions)
1263 OS.indent(16) << *Inst << "\n";
1264
Michael Krusee52ebd12017-07-22 16:44:39 +00001265 OS.indent(12) << "}\n";
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001266}
1267
Michael Krusecd4c9772017-07-21 15:35:53 +00001268void ScopStmt::print(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00001269 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001270 OS.indent(12) << "Domain :=\n";
1271
1272 if (Domain) {
1273 OS.indent(16) << getDomainStr() << ";\n";
1274 } else
1275 OS.indent(16) << "n/a\n";
1276
Tobias Grosser54839312015-04-21 11:37:25 +00001277 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001278
1279 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001280 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001281 } else
1282 OS.indent(16) << "n/a\n";
1283
Tobias Grosser083d3d32014-06-28 08:59:45 +00001284 for (MemoryAccess *Access : MemAccs)
1285 Access->print(OS);
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001286
Tobias Grosserbd15d132017-08-31 03:15:56 +00001287 if (PrintInstructions)
Tobias Grosserd5fcbef2017-05-27 04:40:18 +00001288 printInstructions(OS.indent(12));
Tobias Grosser75805372011-04-29 06:27:02 +00001289}
1290
Michael Kruse5d518462017-07-21 15:54:07 +00001291#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00001292LLVM_DUMP_METHOD void ScopStmt::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00001293#endif
Tobias Grosser75805372011-04-29 06:27:02 +00001294
Michael Krusee60eca72017-05-11 22:56:12 +00001295void ScopStmt::removeAccessData(MemoryAccess *MA) {
1296 if (MA->isRead() && MA->isOriginalValueKind()) {
1297 bool Found = ValueReads.erase(MA->getAccessValue());
1298 (void)Found;
1299 assert(Found && "Expected access data not found");
1300 }
1301 if (MA->isWrite() && MA->isOriginalValueKind()) {
1302 bool Found = ValueWrites.erase(cast<Instruction>(MA->getAccessValue()));
1303 (void)Found;
1304 assert(Found && "Expected access data not found");
1305 }
1306 if (MA->isWrite() && MA->isOriginalAnyPHIKind()) {
1307 bool Found = PHIWrites.erase(cast<PHINode>(MA->getAccessInstruction()));
1308 (void)Found;
1309 assert(Found && "Expected access data not found");
1310 }
Michael Kruse3562f272017-07-20 16:47:57 +00001311 if (MA->isRead() && MA->isOriginalAnyPHIKind()) {
1312 bool Found = PHIReads.erase(cast<PHINode>(MA->getAccessInstruction()));
1313 (void)Found;
1314 assert(Found && "Expected access data not found");
1315 }
Michael Krusee60eca72017-05-11 22:56:12 +00001316}
1317
Michael Kruse10071822016-05-23 14:45:58 +00001318void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001319 // Remove the memory accesses from this statement together with all scalar
1320 // accesses that were caused by it. MemoryKind::Value READs have no access
1321 // instruction, hence would not be removed by this function. However, it is
1322 // only used for invariant LoadInst accesses, its arguments are always affine,
1323 // hence synthesizable, and therefore there are no MemoryKind::Value READ
1324 // accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001325 auto Predicate = [&](MemoryAccess *Acc) {
1326 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1327 };
Michael Krusee60eca72017-05-11 22:56:12 +00001328 for (auto *MA : MemAccs) {
Michael Kruse8b805802017-07-19 17:11:25 +00001329 if (Predicate(MA)) {
Michael Krusee60eca72017-05-11 22:56:12 +00001330 removeAccessData(MA);
Michael Kruse8b805802017-07-19 17:11:25 +00001331 Parent.removeAccessData(MA);
1332 }
Michael Krusee60eca72017-05-11 22:56:12 +00001333 }
Michael Kruse10071822016-05-23 14:45:58 +00001334 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1335 MemAccs.end());
1336 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001337}
1338
Michael Kruse192e7f72018-04-09 23:13:05 +00001339void ScopStmt::removeSingleMemoryAccess(MemoryAccess *MA, bool AfterHoisting) {
1340 if (AfterHoisting) {
1341 auto MAIt = std::find(MemAccs.begin(), MemAccs.end(), MA);
1342 assert(MAIt != MemAccs.end());
1343 MemAccs.erase(MAIt);
Michael Kruse0446d812017-03-10 16:05:24 +00001344
Michael Kruse192e7f72018-04-09 23:13:05 +00001345 removeAccessData(MA);
1346 Parent.removeAccessData(MA);
1347 }
Michael Krusee60eca72017-05-11 22:56:12 +00001348
Michael Kruse0446d812017-03-10 16:05:24 +00001349 auto It = InstructionToAccess.find(MA->getAccessInstruction());
1350 if (It != InstructionToAccess.end()) {
1351 It->second.remove(MA);
1352 if (It->second.empty())
1353 InstructionToAccess.erase(MA->getAccessInstruction());
1354 }
1355}
1356
Michael Kruse07e8c362017-07-24 12:43:27 +00001357MemoryAccess *ScopStmt::ensureValueRead(Value *V) {
1358 MemoryAccess *Access = lookupInputAccessOf(V);
1359 if (Access)
1360 return Access;
1361
1362 ScopArrayInfo *SAI =
1363 Parent.getOrCreateScopArrayInfo(V, V->getType(), {}, MemoryKind::Value);
1364 Access = new MemoryAccess(this, nullptr, MemoryAccess::READ, V, V->getType(),
1365 true, {}, {}, V, MemoryKind::Value);
1366 Parent.addAccessFunction(Access);
1367 Access->buildAccessRelation(SAI);
1368 addAccess(Access);
1369 Parent.addAccessData(Access);
1370 return Access;
1371}
1372
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001373raw_ostream &polly::operator<<(raw_ostream &OS, const ScopStmt &S) {
1374 S.print(OS, PollyPrintInstructions);
1375 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00001376}
1377
Tobias Grosser75805372011-04-29 06:27:02 +00001378//===----------------------------------------------------------------------===//
1379/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001380
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001381void Scop::setContext(isl::set NewContext) {
1382 Context = NewContext.align_params(Context.get_space());
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001383}
1384
Eli Friedman5e589ea2017-06-20 22:53:02 +00001385namespace {
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001386
Tobias Grosserc80d6972016-09-02 06:33:33 +00001387/// Remap parameter values but keep AddRecs valid wrt. invariant loads.
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001388struct SCEVSensitiveParameterRewriter
Tobias Grosser278f9e72016-11-26 17:58:40 +00001389 : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001390 const ValueToValueMap &VMap;
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001391
1392public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001393 SCEVSensitiveParameterRewriter(const ValueToValueMap &VMap,
1394 ScalarEvolution &SE)
Tobias Grosser278f9e72016-11-26 17:58:40 +00001395 : SCEVRewriteVisitor(SE), VMap(VMap) {}
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001396
1397 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001398 const ValueToValueMap &VMap) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001399 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1400 return SSPR.visit(E);
1401 }
1402
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001403 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1404 auto *Start = visit(E->getStart());
1405 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1406 visit(E->getStepRecurrence(SE)),
1407 E->getLoop(), SCEV::FlagAnyWrap);
1408 return SE.getAddExpr(Start, AddRec);
1409 }
1410
1411 const SCEV *visitUnknown(const SCEVUnknown *E) {
1412 if (auto *NewValue = VMap.lookup(E->getValue()))
1413 return SE.getUnknown(NewValue);
1414 return E;
1415 }
1416};
1417
Eli Friedman5e589ea2017-06-20 22:53:02 +00001418/// Check whether we should remap a SCEV expression.
1419struct SCEVFindInsideScop : public SCEVTraversal<SCEVFindInsideScop> {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001420 const ValueToValueMap &VMap;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001421 bool FoundInside = false;
Tobias Grosserb5563c62017-08-03 13:51:15 +00001422 const Scop *S;
Eli Friedman5e589ea2017-06-20 22:53:02 +00001423
1424public:
Tobias Grosserb5563c62017-08-03 13:51:15 +00001425 SCEVFindInsideScop(const ValueToValueMap &VMap, ScalarEvolution &SE,
1426 const Scop *S)
Eli Friedman5e589ea2017-06-20 22:53:02 +00001427 : SCEVTraversal(*this), VMap(VMap), S(S) {}
1428
1429 static bool hasVariant(const SCEV *E, ScalarEvolution &SE,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001430 const ValueToValueMap &VMap, const Scop *S) {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001431 SCEVFindInsideScop SFIS(VMap, SE, S);
1432 SFIS.visitAll(E);
1433 return SFIS.FoundInside;
1434 }
1435
1436 bool follow(const SCEV *E) {
1437 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(E)) {
1438 FoundInside |= S->getRegion().contains(AddRec->getLoop());
1439 } else if (auto *Unknown = dyn_cast<SCEVUnknown>(E)) {
1440 if (Instruction *I = dyn_cast<Instruction>(Unknown->getValue()))
1441 FoundInside |= S->getRegion().contains(I) && !VMap.count(I);
1442 }
1443 return !FoundInside;
1444 }
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001445
Eli Friedman5e589ea2017-06-20 22:53:02 +00001446 bool isDone() { return FoundInside; }
1447};
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001448} // end anonymous namespace
Eli Friedman5e589ea2017-06-20 22:53:02 +00001449
Tobias Grosserb5563c62017-08-03 13:51:15 +00001450const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *E) const {
Eli Friedman5e589ea2017-06-20 22:53:02 +00001451 // Check whether it makes sense to rewrite the SCEV. (ScalarEvolution
1452 // doesn't like addition between an AddRec and an expression that
1453 // doesn't have a dominance relationship with it.)
1454 if (SCEVFindInsideScop::hasVariant(E, *SE, InvEquivClassVMap, this))
1455 return E;
1456
1457 // Rewrite SCEV.
1458 return SCEVSensitiveParameterRewriter::rewrite(E, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001459}
1460
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001461// This table of function names is used to translate parameter names in more
1462// human-readable names. This makes it easier to interpret Polly analysis
1463// results.
1464StringMap<std::string> KnownNames = {
1465 {"_Z13get_global_idj", "global_id"},
1466 {"_Z12get_local_idj", "local_id"},
1467 {"_Z15get_global_sizej", "global_size"},
1468 {"_Z14get_local_sizej", "local_size"},
1469 {"_Z12get_work_dimv", "work_dim"},
1470 {"_Z17get_global_offsetj", "global_offset"},
1471 {"_Z12get_group_idj", "group_id"},
1472 {"_Z14get_num_groupsj", "num_groups"},
1473};
1474
1475static std::string getCallParamName(CallInst *Call) {
1476 std::string Result;
1477 raw_string_ostream OS(Result);
1478 std::string Name = Call->getCalledFunction()->getName();
1479
1480 auto Iterator = KnownNames.find(Name);
1481 if (Iterator != KnownNames.end())
Tobias Grosserdff902f2017-06-01 12:46:51 +00001482 Name = "__" + Iterator->getValue();
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001483 OS << Name;
1484 for (auto &Operand : Call->arg_operands()) {
1485 ConstantInt *Op = cast<ConstantInt>(&Operand);
1486 OS << "_" << Op->getValue();
1487 }
1488 OS.flush();
1489 return Result;
1490}
1491
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001492void Scop::createParameterId(const SCEV *Parameter) {
1493 assert(Parameters.count(Parameter));
1494 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001495
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001496 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001497
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001498 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1499 Value *Val = ValueParameter->getValue();
1500 CallInst *Call = dyn_cast<CallInst>(Val);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001501
Tobias Grosserf5e7e602017-05-27 15:18:46 +00001502 if (Call && isConstCall(Call)) {
1503 ParameterName = getCallParamName(Call);
1504 } else if (UseInstructionNames) {
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001505 // If this parameter references a specific Value and this value has a name
1506 // we use this name as it is likely to be unique and more useful than just
1507 // a number.
1508 if (Val->hasName())
1509 ParameterName = Val->getName();
1510 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1511 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1512 if (LoadOrigin->hasName()) {
1513 ParameterName += "_loaded_from_";
1514 ParameterName +=
1515 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1516 }
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001517 }
1518 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001519
Tobias Grossere2ccc3f2017-05-03 20:08:52 +00001520 ParameterName = getIslCompatibleName("", ParameterName, "");
1521 }
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001522
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001523 isl::id Id = isl::id::alloc(getIslCtx(), ParameterName,
Tobias Grosser6e78cc62017-08-13 17:54:51 +00001524 const_cast<void *>((const void *)Parameter));
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001525 ParameterIds[Parameter] = Id;
1526}
1527
1528void Scop::addParams(const ParameterSetTy &NewParameters) {
1529 for (const SCEV *Parameter : NewParameters) {
1530 // Normalize the SCEV to get the representing element for an invariant load.
1531 Parameter = extractConstantFactor(Parameter, *SE).second;
1532 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1533
1534 if (Parameters.insert(Parameter))
1535 createParameterId(Parameter);
1536 }
1537}
1538
Tobias Grosser9a635702017-08-06 19:31:27 +00001539isl::id Scop::getIdForParam(const SCEV *Parameter) const {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001540 // Normalize the SCEV to get the representing element for an invariant load.
1541 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
Tobias Grosser6e78cc62017-08-13 17:54:51 +00001542 return ParameterIds.lookup(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001543}
Tobias Grosser75805372011-04-29 06:27:02 +00001544
Johannes Doerferte0b08072016-05-23 12:43:44 +00001545bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1546 return DT.dominates(BB, getEntry());
1547}
1548
Tobias Grosser6be480c2011-11-08 15:41:13 +00001549void Scop::buildContext() {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001550 isl::space Space = isl::space::params_alloc(getIslCtx(), 0);
1551 Context = isl::set::universe(Space);
1552 InvalidContext = isl::set::empty(Space);
1553 AssumedContext = isl::set::universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001554}
1555
Tobias Grosser18daaca2012-05-22 10:47:27 +00001556void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001557 unsigned PDim = 0;
1558 for (auto *Parameter : Parameters) {
1559 ConstantRange SRange = SE->getSignedRange(Parameter);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001560 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl::dim::param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001561 }
1562}
1563
Tobias Grosserb5563c62017-08-03 13:51:15 +00001564static std::vector<isl::id> getFortranArrayIds(Scop::array_range Arrays) {
1565 std::vector<isl::id> OutermostSizeIds;
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00001566 for (auto Array : Arrays) {
1567 // To check if an array is a Fortran array, we check if it has a isl_pw_aff
1568 // for its outermost dimension. Fortran arrays will have this since the
1569 // outermost dimension size can be picked up from their runtime description.
1570 // TODO: actually need to check if it has a FAD, but for now this works.
1571 if (Array->getNumberOfDimensions() > 0) {
Tobias Grosserb5563c62017-08-03 13:51:15 +00001572 isl::pw_aff PwAff = Array->getDimensionSizePw(0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00001573 if (!PwAff)
1574 continue;
1575
Tobias Grosser9b29af92018-06-18 12:49:47 +00001576 isl::id Id = PwAff.get_dim_id(isl::dim::param, 0);
Tobias Grosserb5563c62017-08-03 13:51:15 +00001577 assert(!Id.is_null() &&
1578 "Invalid Id for PwAff expression in Fortran array");
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00001579 OutermostSizeIds.push_back(Id);
1580 }
1581 }
Tobias Grosserb5563c62017-08-03 13:51:15 +00001582 return OutermostSizeIds;
1583}
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00001584
Tobias Grosserb5563c62017-08-03 13:51:15 +00001585// The FORTRAN array size parameters are known to be non-negative.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001586static isl::set boundFortranArrayParams(isl::set Context,
Tobias Grosserb5563c62017-08-03 13:51:15 +00001587 Scop::array_range Arrays) {
1588 std::vector<isl::id> OutermostSizeIds;
1589 OutermostSizeIds = getFortranArrayIds(Arrays);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00001590
Tobias Grosserb5563c62017-08-03 13:51:15 +00001591 for (isl::id Id : OutermostSizeIds) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001592 int dim = Context.find_dim_by_id(isl::dim::param, Id);
1593 Context = Context.lower_bound_si(isl::dim::param, dim, 0);
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00001594 }
1595
1596 return Context;
1597}
1598
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001599void Scop::realignParams() {
Tobias Grosser5842dee2017-03-17 13:00:53 +00001600 if (PollyIgnoreParamBounds)
1601 return;
1602
Tobias Grosser6be480c2011-11-08 15:41:13 +00001603 // Add all parameters into a common model.
Tobias Grosserb5563c62017-08-03 13:51:15 +00001604 isl::space Space = getFullParamSpace();
Tobias Grosser6be480c2011-11-08 15:41:13 +00001605
1606 // Align the parameters of all data structures to the model.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001607 Context = Context.align_params(Space);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001608
Tobias Grosserb5563c62017-08-03 13:51:15 +00001609 // Bound the size of the fortran array dimensions.
1610 Context = boundFortranArrayParams(Context, arrays());
Siddharth Bhatb7f68b82017-05-19 15:07:45 +00001611
Johannes Doerferta60ad842016-05-10 12:18:22 +00001612 // As all parameters are known add bounds to them.
1613 addParameterBounds();
1614
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001615 for (ScopStmt &Stmt : *this)
1616 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00001617 // Simplify the schedule according to the context too.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001618 Schedule = Schedule.gist_domain_params(getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001619}
1620
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001621static isl::set simplifyAssumptionContext(isl::set AssumptionContext,
1622 const Scop &S) {
Tobias Grossercdbe5c92017-01-06 17:30:34 +00001623 // If we have modeled all blocks in the SCoP that have side effects we can
1624 // simplify the context with the constraints that are needed for anything to
1625 // be executed at all. However, if we have error blocks in the SCoP we already
1626 // assumed some parameter combinations cannot occur and removed them from the
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001627 // domains, thus we cannot use the remaining domain to simplify the
1628 // assumptions.
1629 if (!S.hasErrorBlock()) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001630 auto DomainParameters = S.getDomains().params();
1631 AssumptionContext = AssumptionContext.gist_params(DomainParameters);
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001632 }
1633
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001634 AssumptionContext = AssumptionContext.gist_params(S.getContext());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001635 return AssumptionContext;
1636}
1637
1638void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001639 // The parameter constraints of the iteration domains give us a set of
1640 // constraints that need to hold for all cases where at least a single
1641 // statement iteration is executed in the whole scop. We now simplify the
1642 // assumed context under the assumption that such constraints hold and at
1643 // least a single statement iteration is executed. For cases where no
1644 // statement instances are executed, the assumptions we have taken about
1645 // the executed code do not matter and can be changed.
1646 //
1647 // WARNING: This only holds if the assumptions we have taken do not reduce
1648 // the set of statement instances that are executed. Otherwise we
1649 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001650 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001651 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001652 // performed. In such a case, modifying the run-time conditions and
1653 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001654 // to not be executed.
1655 //
1656 // Example:
1657 //
1658 // When delinearizing the following code:
1659 //
1660 // for (long i = 0; i < 100; i++)
1661 // for (long j = 0; j < m; j++)
1662 // A[i+p][j] = 1.0;
1663 //
1664 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001665 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001666 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001667 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001668 InvalidContext = InvalidContext.align_params(getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001669}
1670
Tobias Grosser61bd3a42017-08-06 21:42:38 +00001671isl::set Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00001672 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001673}
1674
Tobias Grosser61bd3a42017-08-06 21:42:38 +00001675isl::set Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00001676 auto DIt = DomainMap.find(BB);
1677 if (DIt != DomainMap.end())
Tobias Grosser61bd3a42017-08-06 21:42:38 +00001678 return DIt->getSecond();
Johannes Doerfert41cda152016-04-08 10:32:26 +00001679
1680 auto &RI = *R.getRegionInfo();
1681 auto *BBR = RI.getRegionFor(BB);
1682 while (BBR->getEntry() == BB)
1683 BBR = BBR->getParent();
1684 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001685}
1686
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00001687int Scop::NextScopID = 0;
1688
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001689std::string Scop::CurrentFunc;
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00001690
1691int Scop::getNextID(std::string ParentFunc) {
1692 if (ParentFunc != CurrentFunc) {
1693 CurrentFunc = ParentFunc;
1694 NextScopID = 0;
1695 }
1696 return NextScopID++;
1697}
1698
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001699Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Tobias Grosseree457592017-09-24 09:25:30 +00001700 DominatorTree &DT, ScopDetection::DetectionContext &DC,
1701 OptimizationRemarkEmitter &ORE)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001702 : IslCtx(isl_ctx_alloc(), isl_ctx_free), SE(&ScalarEvolution), DT(&DT),
Philip Pfaffed477bb92018-05-15 14:53:25 +00001703 R(R), name(None), HasSingleExitEdge(R.getExitingBlock()), DC(DC),
1704 ORE(ORE), Affinator(this, LI),
Singapuram Sanjay Srivallabh1abd9ff2017-07-12 16:46:19 +00001705 ID(getNextID((*R.getEntry()->getParent()).getName().str())) {
Tobias Grosser2937b592016-04-29 11:43:20 +00001706 if (IslOnErrorAbort)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001707 isl_options_set_on_error(getIslCtx().get(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00001708 buildContext();
1709}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001710
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001711Scop::~Scop() = default;
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00001712
Tobias Grosser21cbcf02017-07-16 23:55:38 +00001713void Scop::removeFromStmtMap(ScopStmt &Stmt) {
Tobias Grosserbd15d132017-08-31 03:15:56 +00001714 for (Instruction *Inst : Stmt.getInstructions())
1715 InstStmtMap.erase(Inst);
1716
1717 if (Stmt.isRegionStmt()) {
Michael Krusecd3b9fe2017-08-09 16:45:37 +00001718 for (BasicBlock *BB : Stmt.getRegion()->blocks()) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00001719 StmtMap.erase(BB);
Tobias Grosserbd15d132017-08-31 03:15:56 +00001720 // Skip entry basic block, as its instructions are already deleted as
1721 // part of the statement's instruction list.
1722 if (BB == Stmt.getEntryBlock())
1723 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00001724 for (Instruction &Inst : *BB)
1725 InstStmtMap.erase(&Inst);
1726 }
Tobias Grosserbd15d132017-08-31 03:15:56 +00001727 } else {
Michael Kruse0c6c5552017-09-01 11:36:52 +00001728 auto StmtMapIt = StmtMap.find(Stmt.getBasicBlock());
1729 if (StmtMapIt != StmtMap.end())
1730 StmtMapIt->second.erase(std::remove(StmtMapIt->second.begin(),
1731 StmtMapIt->second.end(), &Stmt),
1732 StmtMapIt->second.end());
1733 for (Instruction *Inst : Stmt.getInstructions())
1734 InstStmtMap.erase(Inst);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00001735 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00001736}
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001737
Michael Kruse192e7f72018-04-09 23:13:05 +00001738void Scop::removeStmts(std::function<bool(ScopStmt &)> ShouldDelete,
1739 bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00001740 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
1741 if (!ShouldDelete(*StmtIt)) {
1742 StmtIt++;
1743 continue;
1744 }
1745
Michael Kruse192e7f72018-04-09 23:13:05 +00001746 // Start with removing all of the statement's accesses including erasing it
1747 // from all maps that are pointing to them.
Michael Krusedb6f71e2018-04-10 01:20:41 +00001748 // Make a temporary copy because removing MAs invalidates the iterator.
1749 SmallVector<MemoryAccess *, 16> MAList(StmtIt->begin(), StmtIt->end());
1750 for (MemoryAccess *MA : MAList)
Michael Kruse192e7f72018-04-09 23:13:05 +00001751 StmtIt->removeSingleMemoryAccess(MA, AfterHoisting);
1752
Tobias Grosser21cbcf02017-07-16 23:55:38 +00001753 removeFromStmtMap(*StmtIt);
1754 StmtIt = Stmts.erase(StmtIt);
1755 }
1756}
1757
1758void Scop::removeStmtNotInDomainMap() {
1759 auto ShouldDelete = [this](ScopStmt &Stmt) -> bool {
Michael Kruse842bdd02018-08-01 22:28:32 +00001760 isl::set Domain = DomainMap.lookup(Stmt.getEntryBlock());
1761 if (!Domain)
1762 return true;
1763 return Domain.is_empty();
Tobias Grosser21cbcf02017-07-16 23:55:38 +00001764 };
Michael Kruse192e7f72018-04-09 23:13:05 +00001765 removeStmts(ShouldDelete, false);
Tobias Grosser21cbcf02017-07-16 23:55:38 +00001766}
1767
1768void Scop::simplifySCoP(bool AfterHoisting) {
Tobias Grosser21cbcf02017-07-16 23:55:38 +00001769 auto ShouldDelete = [AfterHoisting](ScopStmt &Stmt) -> bool {
Michael Kruse5369ea52018-04-20 18:55:44 +00001770 // Never delete statements that contain calls to debug functions.
1771 if (hasDebugCall(&Stmt))
1772 return false;
1773
Johannes Doerfert26404542016-05-10 12:19:47 +00001774 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00001775
Tobias Grosser3012a0b2017-07-16 22:44:17 +00001776 // Remove read only statements only after invariant load hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00001777 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00001778 bool OnlyRead = true;
1779 for (MemoryAccess *MA : Stmt) {
1780 if (MA->isRead())
1781 continue;
1782
1783 OnlyRead = false;
1784 break;
1785 }
1786
1787 RemoveStmt = OnlyRead;
1788 }
Tobias Grosser21cbcf02017-07-16 23:55:38 +00001789 return RemoveStmt;
1790 };
Johannes Doerferteca9e892015-11-03 16:54:49 +00001791
Michael Kruse192e7f72018-04-09 23:13:05 +00001792 removeStmts(ShouldDelete, AfterHoisting);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001793}
1794
Johannes Doerfert8ab28032016-04-27 12:49:11 +00001795InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001796 LoadInst *LInst = dyn_cast<LoadInst>(Val);
1797 if (!LInst)
1798 return nullptr;
1799
1800 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
1801 LInst = cast<LoadInst>(Rep);
1802
Johannes Doerfert96e54712016-02-07 17:30:13 +00001803 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001804 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00001805 for (auto &IAClass : InvariantEquivClasses) {
Tobias Grosserfaef9a72016-07-11 12:27:04 +00001806 if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
Johannes Doerfert549768c2016-03-24 13:22:16 +00001807 continue;
1808
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00001809 auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfert549768c2016-03-24 13:22:16 +00001810 for (auto *MA : MAs)
1811 if (MA->getAccessInstruction() == Val)
1812 return &IAClass;
1813 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001814
1815 return nullptr;
1816}
1817
Michael Kruseb738ffa2017-06-28 13:02:43 +00001818ScopArrayInfo *Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
1819 ArrayRef<const SCEV *> Sizes,
1820 MemoryKind Kind,
1821 const char *BaseName) {
Roman Gareevd7754a12016-07-30 09:25:51 +00001822 assert((BasePtr || BaseName) &&
1823 "BasePtr and BaseName can not be nullptr at the same time.");
1824 assert(!(BasePtr && BaseName) && "BaseName is redundant.");
1825 auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
1826 : ScopArrayNameMap[BaseName];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00001827 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001828 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00001829 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Roman Gareevd7754a12016-07-30 09:25:51 +00001830 DL, this, BaseName));
1831 ScopArrayInfoSet.insert(SAI.get());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00001832 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00001833 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00001834 // In case of mismatching array sizes, we bail out by setting the run-time
1835 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00001836 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00001837 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00001838 }
Tobias Grosserab671442015-05-23 05:58:27 +00001839 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001840}
1841
Michael Kruseb738ffa2017-06-28 13:02:43 +00001842ScopArrayInfo *Scop::createScopArrayInfo(Type *ElementType,
1843 const std::string &BaseName,
1844 const std::vector<unsigned> &Sizes) {
Roman Gareevd7754a12016-07-30 09:25:51 +00001845 auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
1846 std::vector<const SCEV *> SCEVSizes;
1847
1848 for (auto size : Sizes)
Roman Gareevf5aff702016-09-12 17:08:31 +00001849 if (size)
1850 SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
1851 else
1852 SCEVSizes.push_back(nullptr);
Roman Gareevd7754a12016-07-30 09:25:51 +00001853
Tobias Grosser4d5a9172017-01-14 20:25:44 +00001854 auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
1855 MemoryKind::Array, BaseName.c_str());
Roman Gareevd7754a12016-07-30 09:25:51 +00001856 return SAI;
1857}
1858
Tobias Grosserf3adab42017-05-10 10:59:58 +00001859const ScopArrayInfo *Scop::getScopArrayInfoOrNull(Value *BasePtr,
1860 MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001861 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Tobias Grosserf3adab42017-05-10 10:59:58 +00001862 return SAI;
1863}
1864
1865const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
1866 auto *SAI = getScopArrayInfoOrNull(BasePtr, Kind);
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001867 assert(SAI && "No ScopArrayInfo available for this base pointer");
1868 return SAI;
1869}
1870
Tobias Grosser8ea1fc12017-08-06 19:52:38 +00001871std::string Scop::getContextStr() const { return getContext().to_str(); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00001872
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001873std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001874 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001875 return AssumedContext.to_str();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001876}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00001877
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001878std::string Scop::getInvalidContextStr() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001879 return InvalidContext.to_str();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001880}
Tobias Grosser75805372011-04-29 06:27:02 +00001881
1882std::string Scop::getNameStr() const {
1883 std::string ExitName, EntryName;
Siddharth Bhat07bee292017-06-02 08:01:22 +00001884 std::tie(EntryName, ExitName) = getEntryExitStr();
1885 return EntryName + "---" + ExitName;
1886}
1887
1888std::pair<std::string, std::string> Scop::getEntryExitStr() const {
1889 std::string ExitName, EntryName;
Tobias Grosser75805372011-04-29 06:27:02 +00001890 raw_string_ostream ExitStr(ExitName);
1891 raw_string_ostream EntryStr(EntryName);
1892
Tobias Grosserf240b482014-01-09 10:42:15 +00001893 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001894 EntryStr.str();
1895
1896 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001897 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001898 ExitStr.str();
1899 } else
1900 ExitName = "FunctionExit";
1901
Siddharth Bhat07bee292017-06-02 08:01:22 +00001902 return std::make_pair(EntryName, ExitName);
Tobias Grosser75805372011-04-29 06:27:02 +00001903}
1904
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001905isl::set Scop::getContext() const { return Context; }
Dominik Adamskib169e582019-08-06 21:25:35 +00001906
Tobias Grosserb65ccc42017-08-06 20:11:59 +00001907isl::space Scop::getParamSpace() const { return getContext().get_space(); }
Tobias Grosser37487052011-10-06 00:03:42 +00001908
Tobias Grosserb5563c62017-08-03 13:51:15 +00001909isl::space Scop::getFullParamSpace() const {
1910 std::vector<isl::id> FortranIDs;
1911 FortranIDs = getFortranArrayIds(arrays());
1912
1913 isl::space Space = isl::space::params_alloc(
1914 getIslCtx(), ParameterIds.size() + FortranIDs.size());
1915
1916 unsigned PDim = 0;
1917 for (const SCEV *Parameter : Parameters) {
Tobias Grosser9a635702017-08-06 19:31:27 +00001918 isl::id Id = getIdForParam(Parameter);
Tobias Grosserb5563c62017-08-03 13:51:15 +00001919 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
1920 }
1921
1922 for (isl::id Id : FortranIDs)
1923 Space = Space.set_dim_id(isl::dim::param, PDim++, Id);
1924
1925 return Space;
1926}
1927
Tobias Grossere1270332017-08-06 21:42:09 +00001928isl::set Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001929 assert(AssumedContext && "Assumed context not yet built");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001930 return AssumedContext;
Tobias Grossere86109f2013-10-29 21:05:49 +00001931}
1932
Michael Krusef3091bf2017-03-17 13:09:52 +00001933bool Scop::isProfitable(bool ScalarsAreUnprofitable) const {
Johannes Doerfert27d12d32016-05-10 16:38:09 +00001934 if (PollyProcessUnprofitable)
1935 return true;
1936
Johannes Doerfert27d12d32016-05-10 16:38:09 +00001937 if (isEmpty())
1938 return false;
1939
1940 unsigned OptimizableStmtsOrLoops = 0;
1941 for (auto &Stmt : *this) {
1942 if (Stmt.getNumIterators() == 0)
1943 continue;
1944
1945 bool ContainsArrayAccs = false;
1946 bool ContainsScalarAccs = false;
1947 for (auto *MA : Stmt) {
1948 if (MA->isRead())
1949 continue;
Michael Krusef3091bf2017-03-17 13:09:52 +00001950 ContainsArrayAccs |= MA->isLatestArrayKind();
1951 ContainsScalarAccs |= MA->isLatestScalarKind();
Johannes Doerfert27d12d32016-05-10 16:38:09 +00001952 }
1953
Michael Krusef3091bf2017-03-17 13:09:52 +00001954 if (!ScalarsAreUnprofitable || (ContainsArrayAccs && !ContainsScalarAccs))
Johannes Doerfert27d12d32016-05-10 16:38:09 +00001955 OptimizableStmtsOrLoops += Stmt.getNumIterators();
1956 }
1957
1958 return OptimizableStmtsOrLoops > 1;
1959}
1960
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001961bool Scop::hasFeasibleRuntimeContext() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001962 auto PositiveContext = getAssumedContext();
1963 auto NegativeContext = getInvalidContext();
1964 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
1965 // addNonEmptyDomainConstraints returns null if ScopStmts have a null domain
1966 if (!PositiveContext)
Johannes Doerfert94341c92016-04-23 13:00:27 +00001967 return false;
Johannes Doerfert94341c92016-04-23 13:00:27 +00001968
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00001969 bool IsFeasible = !(PositiveContext.is_empty() ||
1970 PositiveContext.is_subset(NegativeContext));
1971 if (!IsFeasible)
1972 return false;
1973
1974 auto DomainContext = getDomains().params();
1975 IsFeasible = !DomainContext.is_subset(NegativeContext);
Dominik Adamski588fc9e2019-07-16 21:10:45 +00001976 IsFeasible &= !getContext().is_subset(NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001977
Johannes Doerfert43788c52015-08-20 05:58:56 +00001978 return IsFeasible;
1979}
1980
Dominik Adamski588fc9e2019-07-16 21:10:45 +00001981isl::set Scop::addNonEmptyDomainConstraints(isl::set C) const {
1982 isl::set DomainContext = getDomains().params();
1983 return C.intersect_params(DomainContext);
1984}
1985
1986MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
1987 Value *PointerBase = MA->getOriginalBaseAddr();
1988
1989 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
1990 if (!PointerBaseInst)
1991 return nullptr;
1992
1993 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
1994 if (!BasePtrStmt)
1995 return nullptr;
1996
1997 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
1998}
1999
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002000static std::string toString(AssumptionKind Kind) {
2001 switch (Kind) {
2002 case ALIASING:
2003 return "No-aliasing";
2004 case INBOUNDS:
2005 return "Inbounds";
2006 case WRAPPING:
2007 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00002008 case UNSIGNED:
2009 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00002010 case COMPLEXITY:
2011 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00002012 case PROFITABLE:
2013 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002014 case ERRORBLOCK:
2015 return "No-error";
2016 case INFINITELOOP:
2017 return "Finite loop";
2018 case INVARIANTLOAD:
2019 return "Invariant load";
2020 case DELINEARIZATION:
2021 return "Delinearization";
2022 }
2023 llvm_unreachable("Unknown AssumptionKind!");
2024}
2025
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002026bool Scop::isEffectiveAssumption(isl::set Set, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00002027 if (Sign == AS_ASSUMPTION) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002028 if (Context.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00002029 return false;
2030
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002031 if (AssumedContext.is_subset(Set))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00002032 return false;
2033 } else {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002034 if (Set.is_disjoint(Context))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00002035 return false;
2036
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002037 if (Set.is_subset(InvalidContext))
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00002038 return false;
2039 }
2040 return true;
2041}
2042
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002043bool Scop::trackAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2044 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00002045 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
2046 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002047
Johannes Doerfertb3265a32016-11-17 22:08:40 +00002048 // Do never emit trivial assumptions as they only clutter the output.
2049 if (!PollyRemarksMinimal) {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002050 isl::set Univ;
Johannes Doerfertb3265a32016-11-17 22:08:40 +00002051 if (Sign == AS_ASSUMPTION)
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002052 Univ = isl::set::universe(Set.get_space());
Johannes Doerfertb3265a32016-11-17 22:08:40 +00002053
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002054 bool IsTrivial = (Sign == AS_RESTRICTION && Set.is_empty()) ||
2055 (Sign == AS_ASSUMPTION && Univ.is_equal(Set));
Johannes Doerfertb3265a32016-11-17 22:08:40 +00002056
2057 if (IsTrivial)
2058 return false;
2059 }
2060
Johannes Doerfertcd195322016-11-17 21:41:08 +00002061 switch (Kind) {
2062 case ALIASING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002063 AssumptionsAliasing++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002064 break;
2065 case INBOUNDS:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002066 AssumptionsInbounds++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002067 break;
2068 case WRAPPING:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002069 AssumptionsWrapping++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002070 break;
2071 case UNSIGNED:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002072 AssumptionsUnsigned++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002073 break;
2074 case COMPLEXITY:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002075 AssumptionsComplexity++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002076 break;
2077 case PROFITABLE:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002078 AssumptionsUnprofitable++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002079 break;
2080 case ERRORBLOCK:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002081 AssumptionsErrorBlock++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002082 break;
2083 case INFINITELOOP:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002084 AssumptionsInfiniteLoop++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002085 break;
2086 case INVARIANTLOAD:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002087 AssumptionsInvariantLoad++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002088 break;
2089 case DELINEARIZATION:
Johannes Doerfert81aa6e82016-11-18 14:37:08 +00002090 AssumptionsDelinearization++;
Johannes Doerfertcd195322016-11-17 21:41:08 +00002091 break;
2092 }
2093
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002094 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002095 std::string Msg = toString(Kind) + Suffix + Set.to_str();
Eli Friedmane737fc12017-07-17 23:58:33 +00002096 if (BB)
2097 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc, BB)
2098 << Msg);
2099 else
2100 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "AssumpRestrict", Loc,
2101 R.getEntry())
2102 << Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002103 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002104}
2105
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002106void Scop::addAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2107 AssumptionSign Sign, BasicBlock *BB) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002108 // Simplify the assumptions/restrictions first.
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002109 Set = Set.gist_params(getContext());
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002110
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002111 if (!trackAssumption(Kind, Set, Loc, Sign, BB))
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002112 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002113
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002114 if (Sign == AS_ASSUMPTION)
2115 AssumedContext = AssumedContext.intersect(Set).coalesce();
2116 else
2117 InvalidContext = InvalidContext.unite(Set).coalesce();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002118}
2119
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002120void Scop::recordAssumption(AssumptionKind Kind, isl::set Set, DebugLoc Loc,
2121 AssumptionSign Sign, BasicBlock *BB) {
2122 assert((Set.is_params() || BB) &&
Tobias Grosserf67433a2016-11-10 11:44:10 +00002123 "Assumptions without a basic block must be parameter sets");
Johannes Doerfert615e0b82016-04-12 13:28:39 +00002124 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002125}
2126
Eli Friedmane737fc12017-07-17 23:58:33 +00002127void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc, BasicBlock *BB) {
Nicola Zaghen349506a2018-05-15 13:37:17 +00002128 LLVM_DEBUG(dbgs() << "Invalidate SCoP because of reason " << Kind << "\n");
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002129 addAssumption(Kind, isl::set::empty(getParamSpace()), Loc, AS_ASSUMPTION, BB);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002130}
2131
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002132isl::set Scop::getInvalidContext() const { return InvalidContext; }
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002133
Tobias Grosser75805372011-04-29 06:27:02 +00002134void Scop::printContext(raw_ostream &OS) const {
2135 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002136 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002137
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002138 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002139 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002140
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002141 OS.indent(4) << "Invalid Context:\n";
2142 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002143
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00002144 unsigned Dim = 0;
2145 for (const SCEV *Parameter : Parameters)
2146 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002147}
2148
Johannes Doerfertb164c792014-09-18 11:17:17 +00002149void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002150 int noOfGroups = 0;
2151 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002152 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002153 noOfGroups += 1;
2154 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002155 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002156 }
2157
Tobias Grosserbb853c22015-07-25 12:31:03 +00002158 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002159 if (MinMaxAliasGroups.empty()) {
2160 OS.indent(8) << "n/a\n";
2161 return;
2162 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002163
Tobias Grosserbb853c22015-07-25 12:31:03 +00002164 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002165
2166 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002167 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002168 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002169 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002170 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2171 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002172 }
2173 OS << " ]]\n";
2174 }
2175
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002176 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002177 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002178 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002179 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002180 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2181 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002182 }
2183 OS << " ]]\n";
2184 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002185 }
2186}
2187
Michael Krusecd4c9772017-07-21 15:35:53 +00002188void Scop::printStatements(raw_ostream &OS, bool PrintInstructions) const {
Tobias Grosser75805372011-04-29 06:27:02 +00002189 OS << "Statements {\n";
2190
Michael Krusecd4c9772017-07-21 15:35:53 +00002191 for (const ScopStmt &Stmt : *this) {
2192 OS.indent(4);
2193 Stmt.print(OS, PrintInstructions);
2194 }
Tobias Grosser75805372011-04-29 06:27:02 +00002195
2196 OS.indent(4) << "}\n";
2197}
2198
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002199void Scop::printArrayInfo(raw_ostream &OS) const {
2200 OS << "Arrays {\n";
2201
Tobias Grosserab671442015-05-23 05:58:27 +00002202 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00002203 Array->print(OS);
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002204
2205 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002206
2207 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2208
2209 for (auto &Array : arrays())
Roman Gareevd7754a12016-07-30 09:25:51 +00002210 Array->print(OS, /* SizeAsPwAff */ true);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002211
2212 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002213}
2214
Michael Krusecd4c9772017-07-21 15:35:53 +00002215void Scop::print(raw_ostream &OS, bool PrintInstructions) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002216 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002217 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002218 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002219 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002220 for (const auto &IAClass : InvariantEquivClasses) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002221 const auto &MAs = IAClass.InvariantAccesses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002222 if (MAs.empty()) {
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002223 OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002224 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002225 MAs.front()->print(OS);
Tobias Grosser4e2d9c42016-07-11 12:15:10 +00002226 OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
2227 << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002228 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002229 }
2230 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002231 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002232 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002233 printAliasAssumptions(OS);
Michael Krusecd4c9772017-07-21 15:35:53 +00002234 printStatements(OS.indent(4), PrintInstructions);
Tobias Grosser75805372011-04-29 06:27:02 +00002235}
2236
Michael Kruse5d518462017-07-21 15:54:07 +00002237#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Michael Krusee1860132017-07-21 15:54:13 +00002238LLVM_DUMP_METHOD void Scop::dump() const { print(dbgs(), true); }
Michael Kruse5d518462017-07-21 15:54:07 +00002239#endif
Tobias Grosser75805372011-04-29 06:27:02 +00002240
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002241isl::ctx Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00002242
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00002243__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
2244 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00002245 // First try to use the SCEVAffinator to generate a piecewise defined
2246 // affine function from @p E in the context of @p BB. If that tasks becomes to
2247 // complex the affinator might return a nullptr. In such a case we invalidate
2248 // the SCoP and return a dummy value. This way we do not need to add error
Tobias Grossercdbe5c92017-01-06 17:30:34 +00002249 // handling code to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002250 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00002251 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00002252 // TODO: We could use a heuristic and either use:
2253 // SCEVAffinator::takeNonNegativeAssumption
2254 // or
2255 // SCEVAffinator::interpretAsUnsigned
2256 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00002257 if (NonNegative)
2258 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002259 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00002260 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00002261
2262 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
Eli Friedmane737fc12017-07-17 23:58:33 +00002263 invalidate(COMPLEXITY, DL, BB);
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00002264 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002265}
2266
Tobias Grosser31df6f32017-08-06 21:42:25 +00002267isl::union_set Scop::getDomains() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002268 isl_space *EmptySpace = isl_space_params_alloc(getIslCtx().get(), 0);
Tobias Grosser941cb7d2017-03-17 09:02:50 +00002269 isl_union_set *Domain = isl_union_set_empty(EmptySpace);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002270
Tobias Grosser808cd692015-07-14 09:33:13 +00002271 for (const ScopStmt &Stmt : *this)
Tobias Grosserdcf8d692017-08-06 16:39:52 +00002272 Domain = isl_union_set_add_set(Domain, Stmt.getDomain().release());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002273
Tobias Grosser31df6f32017-08-06 21:42:25 +00002274 return isl::manage(Domain);
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002275}
2276
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002277isl::pw_aff Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002278 PWACtx PWAC = getPwAff(E, BB);
Philip Pfaffed98dbee2017-12-06 21:02:22 +00002279 return PWAC.first;
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002280}
2281
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00002282isl::union_map
Tobias Grossere5a35142015-11-12 14:07:09 +00002283Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
Tobias Grosserb65ccc42017-08-06 20:11:59 +00002284 isl::union_map Accesses = isl::union_map::empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002285
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002286 for (ScopStmt &Stmt : *this) {
2287 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00002288 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002289 continue;
2290
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00002291 isl::set Domain = Stmt.getDomain();
2292 isl::map AccessDomain = MA->getAccessRelation();
2293 AccessDomain = AccessDomain.intersect_domain(Domain);
2294 Accesses = Accesses.add_map(AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002295 }
2296 }
Tobias Grosser206e9e32017-07-24 16:22:27 +00002297
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00002298 return Accesses.coalesce();
Tobias Grossere5a35142015-11-12 14:07:09 +00002299}
2300
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00002301isl::union_map Scop::getMustWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00002302 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002303}
2304
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00002305isl::union_map Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00002306 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002307}
2308
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00002309isl::union_map Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00002310 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00002311}
2312
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00002313isl::union_map Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00002314 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00002315}
2316
Tobias Grosser5ab39ff2017-08-06 19:22:27 +00002317isl::union_map Scop::getAccesses() {
Tobias Grosser2ac23382015-11-12 14:07:13 +00002318 return getAccessesOfType([](MemoryAccess &MA) { return true; });
2319}
2320
Tobias Grosserfa03cb72017-08-17 22:04:53 +00002321isl::union_map Scop::getAccesses(ScopArrayInfo *Array) {
2322 return getAccessesOfType(
2323 [Array](MemoryAccess &MA) { return MA.getScopArrayInfo() == Array; });
2324}
2325
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002326isl::union_map Scop::getSchedule() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002327 auto Tree = getScheduleTree();
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002328 return Tree.get_map();
Tobias Grosser808cd692015-07-14 09:33:13 +00002329}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002330
Tobias Grosser61bd3a42017-08-06 21:42:38 +00002331isl::schedule Scop::getScheduleTree() const {
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002332 return Schedule.intersect_domain(getDomains());
Tobias Grosser808cd692015-07-14 09:33:13 +00002333}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002334
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002335void Scop::setSchedule(isl::union_map NewSchedule) {
2336 auto S = isl::schedule::from_domain(getDomains());
2337 Schedule = S.insert_partial_schedule(
2338 isl::multi_union_pw_aff::from_union_map(NewSchedule));
Michael Kruse2dab88e2018-06-06 21:37:35 +00002339 ScheduleModified = true;
Tobias Grosser808cd692015-07-14 09:33:13 +00002340}
2341
Philip Pfaffe00fd43b2017-11-19 22:13:34 +00002342void Scop::setScheduleTree(isl::schedule NewSchedule) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002343 Schedule = NewSchedule;
Michael Kruse2dab88e2018-06-06 21:37:35 +00002344 ScheduleModified = true;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002345}
2346
Tobias Grosser990cbb42017-08-14 06:49:01 +00002347bool Scop::restrictDomains(isl::union_set Domain) {
Tobias Grosser37eb4222014-02-20 21:43:54 +00002348 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002349 for (ScopStmt &Stmt : *this) {
Tobias Grosser990cbb42017-08-14 06:49:01 +00002350 isl::union_set StmtDomain = isl::union_set(Stmt.getDomain());
2351 isl::union_set NewStmtDomain = StmtDomain.intersect(Domain);
Tobias Grosser37eb4222014-02-20 21:43:54 +00002352
Tobias Grosser990cbb42017-08-14 06:49:01 +00002353 if (StmtDomain.is_subset(NewStmtDomain))
Tobias Grosser37eb4222014-02-20 21:43:54 +00002354 continue;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002355
2356 Changed = true;
2357
Tobias Grosser990cbb42017-08-14 06:49:01 +00002358 NewStmtDomain = NewStmtDomain.coalesce();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002359
Tobias Grosser990cbb42017-08-14 06:49:01 +00002360 if (NewStmtDomain.is_empty())
Tobias Grosserdcf8d692017-08-06 16:39:52 +00002361 Stmt.restrictDomain(isl::set::empty(Stmt.getDomainSpace()));
Tobias Grosser990cbb42017-08-14 06:49:01 +00002362 else
2363 Stmt.restrictDomain(isl::set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002364 }
Tobias Grosser37eb4222014-02-20 21:43:54 +00002365 return Changed;
2366}
2367
Tobias Grosser75805372011-04-29 06:27:02 +00002368ScalarEvolution *Scop::getSE() const { return SE; }
2369
Michael Krused6e22082018-01-18 15:15:38 +00002370void Scop::addScopStmt(BasicBlock *BB, StringRef Name, Loop *SurroundingLoop,
2371 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00002372 assert(BB && "Unexpected nullptr!");
Michael Krused6e22082018-01-18 15:15:38 +00002373 Stmts.emplace_back(*this, *BB, Name, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00002374 auto *Stmt = &Stmts.back();
Michael Kruse4dfa7322017-07-18 15:41:49 +00002375 StmtMap[BB].push_back(Stmt);
Michael Krusecd3b9fe2017-08-09 16:45:37 +00002376 for (Instruction *Inst : Instructions) {
2377 assert(!InstStmtMap.count(Inst) &&
2378 "Unexpected statement corresponding to the instruction.");
2379 InstStmtMap[Inst] = Stmt;
2380 }
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00002381}
2382
Michael Krused6e22082018-01-18 15:15:38 +00002383void Scop::addScopStmt(Region *R, StringRef Name, Loop *SurroundingLoop,
Tobias Grosserbd15d132017-08-31 03:15:56 +00002384 std::vector<Instruction *> Instructions) {
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00002385 assert(R && "Unexpected nullptr!");
Michael Krused6e22082018-01-18 15:15:38 +00002386 Stmts.emplace_back(*this, *R, Name, SurroundingLoop, Instructions);
Hongbin Zhenga8fb73f2016-11-21 20:09:40 +00002387 auto *Stmt = &Stmts.back();
Tobias Grosserbd15d132017-08-31 03:15:56 +00002388
2389 for (Instruction *Inst : Instructions) {
2390 assert(!InstStmtMap.count(Inst) &&
2391 "Unexpected statement corresponding to the instruction.");
2392 InstStmtMap[Inst] = Stmt;
2393 }
2394
Michael Krusecd3b9fe2017-08-09 16:45:37 +00002395 for (BasicBlock *BB : R->blocks()) {
Michael Kruse4dfa7322017-07-18 15:41:49 +00002396 StmtMap[BB].push_back(Stmt);
Tobias Grosserbd15d132017-08-31 03:15:56 +00002397 if (BB == R->getEntry())
2398 continue;
Michael Krusecd3b9fe2017-08-09 16:45:37 +00002399 for (Instruction &Inst : *BB) {
2400 assert(!InstStmtMap.count(&Inst) &&
2401 "Unexpected statement corresponding to the instruction.");
2402 InstStmtMap[&Inst] = Stmt;
2403 }
2404 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002405}
2406
Tobias Grosser85048ef2017-08-06 17:24:59 +00002407ScopStmt *Scop::addScopStmt(isl::map SourceRel, isl::map TargetRel,
2408 isl::set Domain) {
Tobias Grossereba86a12016-11-09 04:24:49 +00002409#ifndef NDEBUG
Tobias Grosser85048ef2017-08-06 17:24:59 +00002410 isl::set SourceDomain = SourceRel.domain();
2411 isl::set TargetDomain = TargetRel.domain();
2412 assert(Domain.is_subset(TargetDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00002413 "Target access not defined for complete statement domain");
Tobias Grosser85048ef2017-08-06 17:24:59 +00002414 assert(Domain.is_subset(SourceDomain) &&
Tobias Grosser744740a2016-11-05 21:02:43 +00002415 "Source access not defined for complete statement domain");
Tobias Grossereba86a12016-11-09 04:24:49 +00002416#endif
Roman Gareevb3224ad2016-09-14 06:26:09 +00002417 Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
2418 CopyStmtsNum++;
2419 return &(Stmts.back());
2420}
2421
Michael Kruse6eba4b12017-07-20 17:08:50 +00002422ArrayRef<ScopStmt *> Scop::getStmtListFor(BasicBlock *BB) const {
2423 auto StmtMapIt = StmtMap.find(BB);
2424 if (StmtMapIt == StmtMap.end())
2425 return {};
Michael Kruse6eba4b12017-07-20 17:08:50 +00002426 return StmtMapIt->second;
2427}
2428
Michael Krusea230f222018-01-23 23:56:36 +00002429ScopStmt *Scop::getIncomingStmtFor(const Use &U) const {
2430 auto *PHI = cast<PHINode>(U.getUser());
2431 BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
2432
2433 // If the value is a non-synthesizable from the incoming block, use the
2434 // statement that contains it as user statement.
2435 if (auto *IncomingInst = dyn_cast<Instruction>(U.get())) {
2436 if (IncomingInst->getParent() == IncomingBB) {
2437 if (ScopStmt *IncomingStmt = getStmtFor(IncomingInst))
2438 return IncomingStmt;
2439 }
2440 }
2441
2442 // Otherwise, use the epilogue/last statement.
2443 return getLastStmtFor(IncomingBB);
2444}
2445
Michael Kruse6eba4b12017-07-20 17:08:50 +00002446ScopStmt *Scop::getLastStmtFor(BasicBlock *BB) const {
2447 ArrayRef<ScopStmt *> StmtList = getStmtListFor(BB);
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002448 if (!StmtList.empty())
Michael Kruse6eba4b12017-07-20 17:08:50 +00002449 return StmtList.back();
2450 return nullptr;
2451}
2452
Michael Kruse1ce67912017-07-20 17:18:58 +00002453ArrayRef<ScopStmt *> Scop::getStmtListFor(RegionNode *RN) const {
Michael Kruse6f7721f2016-02-24 22:08:19 +00002454 if (RN->isSubRegion())
Michael Kruse1ce67912017-07-20 17:18:58 +00002455 return getStmtListFor(RN->getNodeAs<Region>());
2456 return getStmtListFor(RN->getNodeAs<BasicBlock>());
Michael Kruse6f7721f2016-02-24 22:08:19 +00002457}
2458
Michael Kruse1ce67912017-07-20 17:18:58 +00002459ArrayRef<ScopStmt *> Scop::getStmtListFor(Region *R) const {
2460 return getStmtListFor(R->getEntry());
Michael Krusea902ba62015-12-13 19:21:45 +00002461}
2462
Johannes Doerfert96425c22015-08-30 21:13:53 +00002463int Scop::getRelativeLoopDepth(const Loop *L) const {
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00002464 if (!L || !R.contains(L))
Johannes Doerfert96425c22015-08-30 21:13:53 +00002465 return -1;
Philip Pfaffe1a0128f2017-05-24 18:39:39 +00002466 // outermostLoopInRegion always returns nullptr for top level regions
2467 if (R.isTopLevelRegion()) {
2468 // LoopInfo's depths start at 1, we start at 0
2469 return L->getLoopDepth() - 1;
2470 } else {
2471 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
2472 assert(OuterLoop);
2473 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2474 }
Johannes Doerfertd020b772015-08-27 06:53:52 +00002475}
2476
Roman Gareevd7754a12016-07-30 09:25:51 +00002477ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
2478 for (auto &SAI : arrays()) {
2479 if (SAI->getName() == BaseName)
2480 return SAI;
2481 }
2482 return nullptr;
2483}
2484
Michael Kruse8b805802017-07-19 17:11:25 +00002485void Scop::addAccessData(MemoryAccess *Access) {
2486 const ScopArrayInfo *SAI = Access->getOriginalScopArrayInfo();
2487 assert(SAI && "can only use after access relations have been constructed");
2488
2489 if (Access->isOriginalValueKind() && Access->isRead())
2490 ValueUseAccs[SAI].push_back(Access);
2491 else if (Access->isOriginalAnyPHIKind() && Access->isWrite())
2492 PHIIncomingAccs[SAI].push_back(Access);
2493}
2494
2495void Scop::removeAccessData(MemoryAccess *Access) {
Michael Kruse6d7a7892017-09-21 14:23:11 +00002496 if (Access->isOriginalValueKind() && Access->isWrite()) {
2497 ValueDefAccs.erase(Access->getAccessValue());
2498 } else if (Access->isOriginalValueKind() && Access->isRead()) {
Michael Kruse8b805802017-07-19 17:11:25 +00002499 auto &Uses = ValueUseAccs[Access->getScopArrayInfo()];
Michael Kruse7de61662018-04-09 23:13:01 +00002500 auto NewEnd = std::remove(Uses.begin(), Uses.end(), Access);
2501 Uses.erase(NewEnd, Uses.end());
Michael Kruse6d7a7892017-09-21 14:23:11 +00002502 } else if (Access->isOriginalPHIKind() && Access->isRead()) {
2503 PHINode *PHI = cast<PHINode>(Access->getAccessInstruction());
2504 PHIReadAccs.erase(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00002505 } else if (Access->isOriginalAnyPHIKind() && Access->isWrite()) {
2506 auto &Incomings = PHIIncomingAccs[Access->getScopArrayInfo()];
Michael Kruse7de61662018-04-09 23:13:01 +00002507 auto NewEnd = std::remove(Incomings.begin(), Incomings.end(), Access);
2508 Incomings.erase(NewEnd, Incomings.end());
Michael Kruse8b805802017-07-19 17:11:25 +00002509 }
2510}
2511
2512MemoryAccess *Scop::getValueDef(const ScopArrayInfo *SAI) const {
2513 assert(SAI->isValueKind());
2514
2515 Instruction *Val = dyn_cast<Instruction>(SAI->getBasePtr());
2516 if (!Val)
2517 return nullptr;
2518
Michael Kruse6d7a7892017-09-21 14:23:11 +00002519 return ValueDefAccs.lookup(Val);
Michael Kruse8b805802017-07-19 17:11:25 +00002520}
2521
2522ArrayRef<MemoryAccess *> Scop::getValueUses(const ScopArrayInfo *SAI) const {
2523 assert(SAI->isValueKind());
2524 auto It = ValueUseAccs.find(SAI);
2525 if (It == ValueUseAccs.end())
2526 return {};
2527 return It->second;
2528}
2529
2530MemoryAccess *Scop::getPHIRead(const ScopArrayInfo *SAI) const {
2531 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
2532
2533 if (SAI->isExitPHIKind())
2534 return nullptr;
2535
2536 PHINode *PHI = cast<PHINode>(SAI->getBasePtr());
Michael Kruse6d7a7892017-09-21 14:23:11 +00002537 return PHIReadAccs.lookup(PHI);
Michael Kruse8b805802017-07-19 17:11:25 +00002538}
2539
2540ArrayRef<MemoryAccess *> Scop::getPHIIncomings(const ScopArrayInfo *SAI) const {
2541 assert(SAI->isPHIKind() || SAI->isExitPHIKind());
2542 auto It = PHIIncomingAccs.find(SAI);
2543 if (It == PHIIncomingAccs.end())
2544 return {};
2545 return It->second;
2546}
2547
Michael Krusea508a4e2017-07-27 14:39:52 +00002548bool Scop::isEscaping(Instruction *Inst) {
2549 assert(contains(Inst) && "The concept of escaping makes only sense for "
2550 "values defined inside the SCoP");
2551
2552 for (Use &Use : Inst->uses()) {
2553 BasicBlock *UserBB = getUseBlock(Use);
2554 if (!contains(UserBB))
2555 return true;
2556
2557 // When the SCoP region exit needs to be simplified, PHIs in the region exit
2558 // move to a new basic block such that its incoming blocks are not in the
2559 // SCoP anymore.
2560 if (hasSingleExitEdge() && isa<PHINode>(Use.getUser()) &&
2561 isExit(cast<PHINode>(Use.getUser())->getParent()))
2562 return true;
2563 }
2564 return false;
2565}
2566
Dominik Adamski588fc9e2019-07-16 21:10:45 +00002567void Scop::incrementNumberOfAliasingAssumptions(unsigned step) {
2568 AssumptionsAliasing += step;
2569}
2570
Michael Kruse06ed5292017-08-23 13:50:30 +00002571Scop::ScopStatistics Scop::getStatistics() const {
2572 ScopStatistics Result;
2573#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
2574 auto LoopStat = ScopDetection::countBeneficialLoops(&R, *SE, *getLI(), 0);
2575
2576 int NumTotalLoops = LoopStat.NumLoops;
2577 Result.NumBoxedLoops = getBoxedLoops().size();
2578 Result.NumAffineLoops = NumTotalLoops - Result.NumBoxedLoops;
2579
2580 for (const ScopStmt &Stmt : *this) {
2581 isl::set Domain = Stmt.getDomain().intersect_params(getContext());
2582 bool IsInLoop = Stmt.getNumIterators() >= 1;
2583 for (MemoryAccess *MA : Stmt) {
2584 if (!MA->isWrite())
2585 continue;
2586
2587 if (MA->isLatestValueKind()) {
2588 Result.NumValueWrites += 1;
2589 if (IsInLoop)
2590 Result.NumValueWritesInLoops += 1;
2591 }
2592
2593 if (MA->isLatestAnyPHIKind()) {
2594 Result.NumPHIWrites += 1;
2595 if (IsInLoop)
2596 Result.NumPHIWritesInLoops += 1;
2597 }
2598
2599 isl::set AccSet =
2600 MA->getAccessRelation().intersect_domain(Domain).range();
2601 if (AccSet.is_singleton()) {
2602 Result.NumSingletonWrites += 1;
2603 if (IsInLoop)
2604 Result.NumSingletonWritesInLoops += 1;
2605 }
2606 }
2607 }
2608#endif
2609 return Result;
2610}
2611
Eugene Zelenko0c4c2ce2017-08-22 21:25:51 +00002612raw_ostream &polly::operator<<(raw_ostream &OS, const Scop &scop) {
2613 scop.print(OS, PollyPrintInstructions);
2614 return OS;
Michael Krusecd4c9772017-07-21 15:35:53 +00002615}
2616
Johannes Doerfert99191c72016-05-31 09:41:04 +00002617//===----------------------------------------------------------------------===//
2618void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
2619 AU.addRequired<LoopInfoWrapperPass>();
2620 AU.addRequired<RegionInfoPass>();
2621 AU.addRequired<DominatorTreeWrapperPass>();
2622 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00002623 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00002624 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00002625 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00002626 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert99191c72016-05-31 09:41:04 +00002627 AU.setPreservesAll();
2628}
2629
Michael Kruse06ed5292017-08-23 13:50:30 +00002630void updateLoopCountStatistic(ScopDetection::LoopStats Stats,
2631 Scop::ScopStatistics ScopStats) {
2632 assert(Stats.NumLoops == ScopStats.NumAffineLoops + ScopStats.NumBoxedLoops);
2633
2634 NumScops++;
Tobias Grossercd01a362017-02-17 08:12:36 +00002635 NumLoopsInScop += Stats.NumLoops;
2636 MaxNumLoopsInScop =
2637 std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
2638
Tobias Grosserfcc3ad52018-04-18 20:03:36 +00002639 if (Stats.MaxDepth == 0)
2640 NumScopsDepthZero++;
2641 else if (Stats.MaxDepth == 1)
Tobias Grossercd01a362017-02-17 08:12:36 +00002642 NumScopsDepthOne++;
2643 else if (Stats.MaxDepth == 2)
2644 NumScopsDepthTwo++;
2645 else if (Stats.MaxDepth == 3)
2646 NumScopsDepthThree++;
2647 else if (Stats.MaxDepth == 4)
2648 NumScopsDepthFour++;
2649 else if (Stats.MaxDepth == 5)
2650 NumScopsDepthFive++;
2651 else
2652 NumScopsDepthLarger++;
Michael Kruse06ed5292017-08-23 13:50:30 +00002653
2654 NumAffineLoops += ScopStats.NumAffineLoops;
2655 NumBoxedLoops += ScopStats.NumBoxedLoops;
2656
2657 NumValueWrites += ScopStats.NumValueWrites;
2658 NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
2659 NumPHIWrites += ScopStats.NumPHIWrites;
2660 NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
2661 NumSingletonWrites += ScopStats.NumSingletonWrites;
2662 NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
Tobias Grossercd01a362017-02-17 08:12:36 +00002663}
2664
Johannes Doerfert99191c72016-05-31 09:41:04 +00002665bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00002666 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert99191c72016-05-31 09:41:04 +00002667
2668 if (!SD.isMaxRegionInScop(*R))
2669 return false;
2670
2671 Function *F = R->getEntry()->getParent();
2672 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2673 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2674 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2675 auto const &DL = F->getParent()->getDataLayout();
2676 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00002677 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krusea4f447c2017-08-28 14:07:33 +00002678 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert99191c72016-05-31 09:41:04 +00002679
Michael Krusea4f447c2017-08-28 14:07:33 +00002680 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00002681 S = SB.getScop(); // take ownership of scop object
Tobias Grossercd01a362017-02-17 08:12:36 +00002682
Michael Kruse06ed5292017-08-23 13:50:30 +00002683#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Tobias Grossercd01a362017-02-17 08:12:36 +00002684 if (S) {
2685 ScopDetection::LoopStats Stats =
2686 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00002687 updateLoopCountStatistic(Stats, S->getStatistics());
Tobias Grossercd01a362017-02-17 08:12:36 +00002688 }
Michael Kruse06ed5292017-08-23 13:50:30 +00002689#endif
Tobias Grossercd01a362017-02-17 08:12:36 +00002690
Tobias Grosser75805372011-04-29 06:27:02 +00002691 return false;
2692}
2693
Johannes Doerfert99191c72016-05-31 09:41:04 +00002694void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00002695 if (S)
Michael Krusecd4c9772017-07-21 15:35:53 +00002696 S->print(OS, PollyPrintInstructions);
Johannes Doerfertb7e97132016-06-27 09:25:40 +00002697 else
2698 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00002699}
Tobias Grosser75805372011-04-29 06:27:02 +00002700
Johannes Doerfert99191c72016-05-31 09:41:04 +00002701char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002702
Johannes Doerfert99191c72016-05-31 09:41:04 +00002703Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
2704
2705INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00002706 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002707 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00002708INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00002709INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00002710INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002711INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002712INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00002713INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002714INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00002715INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00002716 "Polly - Create polyhedral description of Scops", false,
2717 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002718
2719//===----------------------------------------------------------------------===//
Philip Pfaffe838e0882017-05-15 12:55:14 +00002720ScopInfo::ScopInfo(const DataLayout &DL, ScopDetection &SD, ScalarEvolution &SE,
2721 LoopInfo &LI, AliasAnalysis &AA, DominatorTree &DT,
Michael Krusea4f447c2017-08-28 14:07:33 +00002722 AssumptionCache &AC, OptimizationRemarkEmitter &ORE)
2723 : DL(DL), SD(SD), SE(SE), LI(LI), AA(AA), DT(DT), AC(AC), ORE(ORE) {
Philip Pfaffef43e7c22017-08-10 07:43:46 +00002724 recompute();
2725}
2726
2727void ScopInfo::recompute() {
2728 RegionToScopMap.clear();
Michael Krusea6d48f52017-06-08 12:06:15 +00002729 /// Create polyhedral description of scops for all the valid regions of a
Philip Pfaffe838e0882017-05-15 12:55:14 +00002730 /// function.
2731 for (auto &It : SD) {
2732 Region *R = const_cast<Region *>(It);
2733 if (!SD.isMaxRegionInScop(*R))
2734 continue;
2735
Michael Krusea4f447c2017-08-28 14:07:33 +00002736 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE, ORE);
Philip Pfaffe838e0882017-05-15 12:55:14 +00002737 std::unique_ptr<Scop> S = SB.getScop();
2738 if (!S)
2739 continue;
Michael Kruse06ed5292017-08-23 13:50:30 +00002740#if !defined(NDEBUG) || defined(LLVM_ENABLE_STATS)
Philip Pfaffeead67db2017-08-02 11:14:41 +00002741 ScopDetection::LoopStats Stats =
2742 ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
Michael Kruse06ed5292017-08-23 13:50:30 +00002743 updateLoopCountStatistic(Stats, S->getStatistics());
2744#endif
Philip Pfaffe838e0882017-05-15 12:55:14 +00002745 bool Inserted = RegionToScopMap.insert({R, std::move(S)}).second;
2746 assert(Inserted && "Building Scop for the same region twice!");
2747 (void)Inserted;
2748 }
2749}
2750
Philip Pfaffef43e7c22017-08-10 07:43:46 +00002751bool ScopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
2752 FunctionAnalysisManager::Invalidator &Inv) {
2753 // Check whether the analysis, all analyses on functions have been preserved
2754 // or anything we're holding references to is being invalidated
2755 auto PAC = PA.getChecker<ScopInfoAnalysis>();
2756 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
2757 Inv.invalidate<ScopAnalysis>(F, PA) ||
2758 Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
2759 Inv.invalidate<LoopAnalysis>(F, PA) ||
2760 Inv.invalidate<AAManager>(F, PA) ||
2761 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
2762 Inv.invalidate<AssumptionAnalysis>(F, PA);
2763}
2764
Philip Pfaffe838e0882017-05-15 12:55:14 +00002765AnalysisKey ScopInfoAnalysis::Key;
2766
2767ScopInfoAnalysis::Result ScopInfoAnalysis::run(Function &F,
2768 FunctionAnalysisManager &FAM) {
2769 auto &SD = FAM.getResult<ScopAnalysis>(F);
2770 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
2771 auto &LI = FAM.getResult<LoopAnalysis>(F);
2772 auto &AA = FAM.getResult<AAManager>(F);
2773 auto &DT = FAM.getResult<DominatorTreeAnalysis>(F);
2774 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
2775 auto &DL = F.getParent()->getDataLayout();
Michael Krusea4f447c2017-08-28 14:07:33 +00002776 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2777 return {DL, SD, SE, LI, AA, DT, AC, ORE};
Philip Pfaffe838e0882017-05-15 12:55:14 +00002778}
2779
2780PreservedAnalyses ScopInfoPrinterPass::run(Function &F,
2781 FunctionAnalysisManager &FAM) {
2782 auto &SI = FAM.getResult<ScopInfoAnalysis>(F);
Philip Pfaffe96d21432017-08-04 11:28:51 +00002783 // Since the legacy PM processes Scops in bottom up, we print them in reverse
2784 // order here to keep the output persistent
2785 for (auto &It : reverse(SI)) {
Philip Pfaffe838e0882017-05-15 12:55:14 +00002786 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00002787 It.second->print(Stream, PollyPrintInstructions);
Philip Pfaffe838e0882017-05-15 12:55:14 +00002788 else
2789 Stream << "Invalid Scop!\n";
2790 }
2791 return PreservedAnalyses::all();
2792}
2793
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002794void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
2795 AU.addRequired<LoopInfoWrapperPass>();
2796 AU.addRequired<RegionInfoPass>();
2797 AU.addRequired<DominatorTreeWrapperPass>();
2798 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00002799 AU.addRequiredTransitive<ScopDetectionWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002800 AU.addRequired<AAResultsWrapperPass>();
Michael Kruse89b1f942017-03-17 13:56:53 +00002801 AU.addRequired<AssumptionCacheTracker>();
Michael Krusea4f447c2017-08-28 14:07:33 +00002802 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002803 AU.setPreservesAll();
2804}
2805
2806bool ScopInfoWrapperPass::runOnFunction(Function &F) {
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00002807 auto &SD = getAnalysis<ScopDetectionWrapperPass>().getSD();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002808 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2809 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2810 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2811 auto const &DL = F.getParent()->getDataLayout();
2812 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Kruse89b1f942017-03-17 13:56:53 +00002813 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Michael Krusea4f447c2017-08-28 14:07:33 +00002814 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002815
Michael Krusea4f447c2017-08-28 14:07:33 +00002816 Result.reset(new ScopInfo{DL, SD, SE, LI, AA, DT, AC, ORE});
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002817 return false;
2818}
2819
2820void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Philip Pfaffe838e0882017-05-15 12:55:14 +00002821 for (auto &It : *Result) {
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002822 if (It.second)
Michael Krusecd4c9772017-07-21 15:35:53 +00002823 It.second->print(OS, PollyPrintInstructions);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002824 else
2825 OS << "Invalid Scop!\n";
2826 }
2827}
2828
2829char ScopInfoWrapperPass::ID = 0;
2830
2831Pass *polly::createScopInfoWrapperPassPass() {
2832 return new ScopInfoWrapperPass();
2833}
2834
2835INITIALIZE_PASS_BEGIN(
2836 ScopInfoWrapperPass, "polly-function-scops",
2837 "Polly - Create polyhedral description of all Scops of a function", false,
2838 false);
2839INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Michael Kruse89b1f942017-03-17 13:56:53 +00002840INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002841INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
2842INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
2843INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Philip Pfaffe5cc87e32017-05-12 14:37:29 +00002844INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00002845INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
2846INITIALIZE_PASS_END(
2847 ScopInfoWrapperPass, "polly-function-scops",
2848 "Polly - Create polyhedral description of all Scops of a function", false,
2849 false)