blob: 206e42b4576ecf7230f5f91dd7c0cd2d69e16b45 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000026#include "polly/TempScopInfo.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Johannes Doerfertecff11d2015-05-22 23:43:58 +000030#include "llvm/ADT/STLExtras.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000034#include "llvm/Analysis/RegionIterator.h"
35#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000036#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000037#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000038#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000039#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000041#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000043#include "isl/schedule.h"
44#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/set.h"
46#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000047#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000048#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include <sstream>
50#include <string>
51#include <vector>
52
53using namespace llvm;
54using namespace polly;
55
Chandler Carruth95fef942014-04-22 03:30:19 +000056#define DEBUG_TYPE "polly-scops"
57
Tobias Grosser74394f02013-01-14 22:40:23 +000058STATISTIC(ScopFound, "Number of valid Scops");
59STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000060
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000061// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000062// operations can overflow easily. Additive reductions and bit operations
63// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000064static cl::opt<bool> DisableMultiplicativeReductions(
65 "polly-disable-multiplicative-reductions",
66 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
67 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068
Johannes Doerfert9143d672014-09-27 11:02:39 +000069static cl::opt<unsigned> RunTimeChecksMaxParameters(
70 "polly-rtc-max-parameters",
71 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
72 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
73
Tobias Grosser71500722015-03-28 15:11:14 +000074static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
75 "polly-rtc-max-arrays-per-group",
76 cl::desc("The maximal number of arrays to compare in each alias group."),
77 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000078static cl::opt<std::string> UserContextStr(
79 "polly-context", cl::value_desc("isl parameter set"),
80 cl::desc("Provide additional constraints on the context parameters"),
81 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000082
Tobias Grosserd83b8a82015-08-20 19:08:11 +000083static cl::opt<bool> DetectReductions("polly-detect-reductions",
84 cl::desc("Detect and exploit reductions"),
85 cl::Hidden, cl::ZeroOrMore,
86 cl::init(true), cl::cat(PollyCategory));
87
Michael Kruse046dde42015-08-10 13:01:57 +000088// Create a sequence of two schedules. Either argument may be null and is
89// interpreted as the empty schedule. Can also return null if both schedules are
90// empty.
91static __isl_give isl_schedule *
92combineInSequence(__isl_take isl_schedule *Prev,
93 __isl_take isl_schedule *Succ) {
94 if (!Prev)
95 return Succ;
96 if (!Succ)
97 return Prev;
98
99 return isl_schedule_sequence(Prev, Succ);
100}
101
Johannes Doerferte7044942015-02-24 11:58:30 +0000102static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
103 const ConstantRange &Range,
104 int dim,
105 enum isl_dim_type type) {
106 isl_val *V;
107 isl_ctx *ctx = isl_set_get_ctx(S);
108
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000109 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
110 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000111 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000112 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
113
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000114 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000115 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000116 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000117 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000118 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
119
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000120 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000121 return isl_set_union(SLB, SUB);
122 else
123 return isl_set_intersect(SLB, SUB);
124}
125
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000126static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
127 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
128 if (!BasePtrLI)
129 return nullptr;
130
131 if (!S->getRegion().contains(BasePtrLI))
132 return nullptr;
133
134 ScalarEvolution &SE = *S->getSE();
135
136 auto *OriginBaseSCEV =
137 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
138 if (!OriginBaseSCEV)
139 return nullptr;
140
141 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
142 if (!OriginBaseSCEVUnknown)
143 return nullptr;
144
145 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
146}
147
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000148ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser92245222015-07-28 14:53:44 +0000149 const SmallVector<const SCEV *, 4> &DimensionSizes,
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000150 bool IsPHI, Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000151 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000152 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
153 std::string BasePtrName =
154 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000155 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000156 for (const SCEV *Expr : DimensionSizes) {
157 isl_pw_aff *Size = S->getPwAff(Expr);
158 DimensionSizesPw.push_back(Size);
159 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000160
161 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
162 if (BasePtrOriginSAI)
163 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000164}
165
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000166ScopArrayInfo::~ScopArrayInfo() {
167 isl_id_free(Id);
168 for (isl_pw_aff *Size : DimensionSizesPw)
169 isl_pw_aff_free(Size);
170}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000171
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000172std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
173
174int ScopArrayInfo::getElemSizeInBytes() const {
175 return ElementType->getPrimitiveSizeInBits() / 8;
176}
177
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000178isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
179
180void ScopArrayInfo::dump() const { print(errs()); }
181
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000182void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000183 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000184 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
185 OS << "[";
186
187 if (SizeAsPwAff)
188 OS << " " << DimensionSizesPw[u] << " ";
189 else
190 OS << *DimensionSizes[u];
191
192 OS << "]";
193 }
194
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000195 if (BasePtrOriginSAI)
196 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
197
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000198 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000199}
200
201const ScopArrayInfo *
202ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
203 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
204 assert(Id && "Output dimension didn't have an ID");
205 return getFromId(Id);
206}
207
208const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
209 void *User = isl_id_get_user(Id);
210 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
211 isl_id_free(Id);
212 return SAI;
213}
214
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000215const std::string
216MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
217 switch (RT) {
218 case MemoryAccess::RT_NONE:
219 llvm_unreachable("Requested a reduction operator string for a memory "
220 "access which isn't a reduction");
221 case MemoryAccess::RT_ADD:
222 return "+";
223 case MemoryAccess::RT_MUL:
224 return "*";
225 case MemoryAccess::RT_BOR:
226 return "|";
227 case MemoryAccess::RT_BXOR:
228 return "^";
229 case MemoryAccess::RT_BAND:
230 return "&";
231 }
232 llvm_unreachable("Unknown reduction type");
233 return "";
234}
235
Johannes Doerfertf6183392014-07-01 20:52:51 +0000236/// @brief Return the reduction type for a given binary operator
237static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
238 const Instruction *Load) {
239 if (!BinOp)
240 return MemoryAccess::RT_NONE;
241 switch (BinOp->getOpcode()) {
242 case Instruction::FAdd:
243 if (!BinOp->hasUnsafeAlgebra())
244 return MemoryAccess::RT_NONE;
245 // Fall through
246 case Instruction::Add:
247 return MemoryAccess::RT_ADD;
248 case Instruction::Or:
249 return MemoryAccess::RT_BOR;
250 case Instruction::Xor:
251 return MemoryAccess::RT_BXOR;
252 case Instruction::And:
253 return MemoryAccess::RT_BAND;
254 case Instruction::FMul:
255 if (!BinOp->hasUnsafeAlgebra())
256 return MemoryAccess::RT_NONE;
257 // Fall through
258 case Instruction::Mul:
259 if (DisableMultiplicativeReductions)
260 return MemoryAccess::RT_NONE;
261 return MemoryAccess::RT_MUL;
262 default:
263 return MemoryAccess::RT_NONE;
264 }
265}
Tobias Grosser75805372011-04-29 06:27:02 +0000266//===----------------------------------------------------------------------===//
267
268MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000269 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000270 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000271 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000272}
273
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000274static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
275 switch (Access.getType()) {
276 case IRAccess::READ:
277 return MemoryAccess::READ;
278 case IRAccess::MUST_WRITE:
279 return MemoryAccess::MUST_WRITE;
280 case IRAccess::MAY_WRITE:
281 return MemoryAccess::MAY_WRITE;
282 }
283 llvm_unreachable("Unknown IRAccess type!");
284}
285
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000286const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
287 isl_id *ArrayId = getArrayId();
288 void *User = isl_id_get_user(ArrayId);
289 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
290 isl_id_free(ArrayId);
291 return SAI;
292}
293
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000294__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000295 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
296}
297
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000298__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
299 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000300 isl_map *Schedule, *ScheduledAccRel;
301 isl_union_set *UDomain;
302
303 UDomain = isl_union_set_from_set(getStatement()->getDomain());
304 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
305 Schedule = isl_map_from_union_map(USchedule);
306 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
307 return isl_pw_multi_aff_from_map(ScheduledAccRel);
308}
309
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000310__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000311 return isl_map_copy(AccessRelation);
312}
313
Johannes Doerferta99130f2014-10-13 12:58:03 +0000314std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000315 return stringFromIslObj(AccessRelation);
316}
317
Johannes Doerferta99130f2014-10-13 12:58:03 +0000318__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000319 return isl_map_get_space(AccessRelation);
320}
321
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000322__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000323 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000324}
325
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000326__isl_give isl_basic_map *
327MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000328 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000329 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000330
Tobias Grosser084d8f72012-05-29 09:29:44 +0000331 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000332 isl_basic_set_universe(Statement->getDomainSpace()),
333 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000334}
335
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000336// Formalize no out-of-bound access assumption
337//
338// When delinearizing array accesses we optimistically assume that the
339// delinearized accesses do not access out of bound locations (the subscript
340// expression of each array evaluates for each statement instance that is
341// executed to a value that is larger than zero and strictly smaller than the
342// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000343// dimension for which we do not need to assume any upper bound. At this point
344// we formalize this assumption to ensure that at code generation time the
345// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000346//
347// To find the set of constraints necessary to avoid out of bound accesses, we
348// first build the set of data locations that are not within array bounds. We
349// then apply the reverse access relation to obtain the set of iterations that
350// may contain invalid accesses and reduce this set of iterations to the ones
351// that are actually executed by intersecting them with the domain of the
352// statement. If we now project out all loop dimensions, we obtain a set of
353// parameters that may cause statement instances to be executed that may
354// possibly yield out of bound memory accesses. The complement of these
355// constraints is the set of constraints that needs to be assumed to ensure such
356// statement instances are never executed.
357void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000358 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000359 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000360 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000361 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
362 isl_pw_aff *Var =
363 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
364 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
365
366 isl_set *DimOutside;
367
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000368 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000369 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000370
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000371 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
372 Statement->getNumIterators());
373 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
374 isl_space_dim(Space, isl_dim_set));
375 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
376 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000377
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000378 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000379
380 Outside = isl_set_union(Outside, DimOutside);
381 }
382
383 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
384 Outside = isl_set_intersect(Outside, Statement->getDomain());
385 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000386
387 // Remove divs to avoid the construction of overly complicated assumptions.
388 // Doing so increases the set of parameter combinations that are assumed to
389 // not appear. This is always save, but may make the resulting run-time check
390 // bail out more often than strictly necessary.
391 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000392 Outside = isl_set_complement(Outside);
393 Statement->getParent()->addAssumption(Outside);
394 isl_space_free(Space);
395}
396
Johannes Doerferte7044942015-02-24 11:58:30 +0000397void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
398 ScalarEvolution *SE = Statement->getParent()->getSE();
399
400 Value *Ptr = getPointerOperand(*getAccessInstruction());
401 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
402 return;
403
404 auto *PtrSCEV = SE->getSCEV(Ptr);
405 if (isa<SCEVCouldNotCompute>(PtrSCEV))
406 return;
407
408 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
409 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
410 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
411
412 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
413 if (Range.isFullSet())
414 return;
415
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000416 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000417 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000418 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
419 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
420
421 auto Min = LB.sdiv(APInt(BW, ElementSize));
422 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000423
424 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
425 AccessRange =
426 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
427 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
428}
429
Tobias Grosser619190d2015-03-30 17:22:28 +0000430__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
431 __isl_take isl_map *AccessRelation,
432 ScopStmt *Statement) {
433 int Size = Access.Subscripts.size();
434
435 for (int i = Size - 2; i >= 0; --i) {
436 isl_space *Space;
437 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000438 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000439
440 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
441 isl_pw_aff_free(DimSize);
442 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
443
444 Space = isl_map_get_space(AccessRelation);
445 Space = isl_space_map_from_set(isl_space_range(Space));
446 Space = isl_space_align_params(Space, SpaceSize);
447
448 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
449 isl_id_free(ParamId);
450
451 MapOne = isl_map_universe(isl_space_copy(Space));
452 for (int j = 0; j < Size; ++j)
453 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
454 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
455
456 MapTwo = isl_map_universe(isl_space_copy(Space));
457 for (int j = 0; j < Size; ++j)
458 if (j < i || j > i + 1)
459 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
460
461 isl_local_space *LS = isl_local_space_from_space(Space);
462 isl_constraint *C;
463 C = isl_equality_alloc(isl_local_space_copy(LS));
464 C = isl_constraint_set_constant_si(C, -1);
465 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
466 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
467 MapTwo = isl_map_add_constraint(MapTwo, C);
468 C = isl_equality_alloc(LS);
469 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
470 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
471 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
472 MapTwo = isl_map_add_constraint(MapTwo, C);
473 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
474
475 MapOne = isl_map_union(MapOne, MapTwo);
476 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
477 }
478 return AccessRelation;
479}
480
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000481MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000482 ScopStmt *Statement, const ScopArrayInfo *SAI,
483 int Identifier)
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000484 : AccType(getMemoryAccessType(Access)), Statement(Statement),
485 AccessInstruction(AccInst), AccessValue(Access.getAccessValue()),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000486 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000487
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000488 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000489 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000490 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000491
492 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000493
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000494 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000495 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000496
Tobias Grossera1879642011-12-20 10:43:14 +0000497 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000498 // We overapproximate non-affine accesses with a possible access to the
499 // whole array. For read accesses it does not make a difference, if an
500 // access must or may happen. However, for write accesses it is important to
501 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000502 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000503 AccessRelation =
504 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000505
506 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000507 return;
508 }
509
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000510 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000511 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000512
Tobias Grosser79baa212014-04-10 08:38:02 +0000513 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000514 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000515
Sebastian Pop422e33f2014-06-03 18:16:31 +0000516 if (Size == 1) {
517 // For the non delinearized arrays, divide the access function of the last
518 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000519 //
520 // A stride one array access in C expressed as A[i] is expressed in
521 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
522 // two subsequent values of 'i' index two values that are stored next to
523 // each other in memory. By this division we make this characteristic
524 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000525 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000526 Affine = isl_pw_aff_scale_down_val(Affine, v);
527 }
528
529 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
530
Tobias Grosser79baa212014-04-10 08:38:02 +0000531 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000532 }
533
Tobias Grosser619190d2015-03-30 17:22:28 +0000534 AccessRelation = foldAccess(Access, AccessRelation, Statement);
535
Tobias Grosser79baa212014-04-10 08:38:02 +0000536 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000537 AccessRelation = isl_map_set_tuple_id(
538 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000539 AccessRelation =
540 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
541
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000542 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000543 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000544 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000545}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000546
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000547void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000548 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000549 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000550}
551
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000552const std::string MemoryAccess::getReductionOperatorStr() const {
553 return MemoryAccess::getReductionOperatorStr(getReductionType());
554}
555
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000556__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
557
Johannes Doerfertf6183392014-07-01 20:52:51 +0000558raw_ostream &polly::operator<<(raw_ostream &OS,
559 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000560 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000561 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000562 else
563 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000564 return OS;
565}
566
Tobias Grosser75805372011-04-29 06:27:02 +0000567void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000568 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000569 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000570 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000571 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000572 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000573 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000574 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000575 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000576 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000577 break;
578 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000579 OS << "[Reduction Type: " << getReductionType() << "] ";
580 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000581 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000582}
583
Tobias Grosser74394f02013-01-14 22:40:23 +0000584void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000585
586// Create a map in the size of the provided set domain, that maps from the
587// one element of the provided set domain to another element of the provided
588// set domain.
589// The mapping is limited to all points that are equal in all but the last
590// dimension and for which the last dimension of the input is strict smaller
591// than the last dimension of the output.
592//
593// getEqualAndLarger(set[i0, i1, ..., iX]):
594//
595// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
596// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
597//
Tobias Grosserf5338802011-10-06 00:03:35 +0000598static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000599 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000600 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000601 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000602
603 // Set all but the last dimension to be equal for the input and output
604 //
605 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
606 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000607 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000608 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000609
610 // Set the last dimension of the input to be strict smaller than the
611 // last dimension of the output.
612 //
613 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000614 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
615 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000616 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000617}
618
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000619__isl_give isl_set *
620MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000621 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000622 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000623 isl_space *Space = isl_space_range(isl_map_get_space(S));
624 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000625
Sebastian Popa00a0292012-12-18 07:46:06 +0000626 S = isl_map_reverse(S);
627 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000628
Sebastian Popa00a0292012-12-18 07:46:06 +0000629 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
630 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
631 NextScatt = isl_map_apply_domain(NextScatt, S);
632 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000633
Sebastian Popa00a0292012-12-18 07:46:06 +0000634 isl_set *Deltas = isl_map_deltas(NextScatt);
635 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000636}
637
Sebastian Popa00a0292012-12-18 07:46:06 +0000638bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000639 int StrideWidth) const {
640 isl_set *Stride, *StrideX;
641 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000642
Sebastian Popa00a0292012-12-18 07:46:06 +0000643 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000644 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000645 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
646 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
647 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
648 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000649 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000650
Tobias Grosser28dd4862012-01-24 16:42:16 +0000651 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000652 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000653
Tobias Grosser28dd4862012-01-24 16:42:16 +0000654 return IsStrideX;
655}
656
Sebastian Popa00a0292012-12-18 07:46:06 +0000657bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
658 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000659}
660
Tobias Grosser79baa212014-04-10 08:38:02 +0000661bool MemoryAccess::isScalar() const {
662 return isl_map_n_out(AccessRelation) == 0;
663}
664
Sebastian Popa00a0292012-12-18 07:46:06 +0000665bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
666 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000667}
668
Tobias Grosser5d453812011-10-06 00:04:11 +0000669void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000670 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000671 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000672}
Tobias Grosser75805372011-04-29 06:27:02 +0000673
674//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000675
Tobias Grosser808cd692015-07-14 09:33:13 +0000676isl_map *ScopStmt::getSchedule() const {
677 isl_set *Domain = getDomain();
678 if (isl_set_is_empty(Domain)) {
679 isl_set_free(Domain);
680 return isl_map_from_aff(
681 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
682 }
683 auto *Schedule = getParent()->getSchedule();
684 Schedule = isl_union_map_intersect_domain(
685 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
686 if (isl_union_map_is_empty(Schedule)) {
687 isl_set_free(Domain);
688 isl_union_map_free(Schedule);
689 return isl_map_from_aff(
690 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
691 }
692 auto *M = isl_map_from_union_map(Schedule);
693 M = isl_map_coalesce(M);
694 M = isl_map_gist_domain(M, Domain);
695 M = isl_map_coalesce(M);
696 return M;
697}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000698
Johannes Doerfert574182d2015-08-12 10:19:50 +0000699__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertb409fdc2015-08-28 09:24:35 +0000700 return getParent()->getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000701}
702
Tobias Grosser37eb4222014-02-20 21:43:54 +0000703void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
704 assert(isl_set_is_subset(NewDomain, Domain) &&
705 "New domain is not a subset of old domain!");
706 isl_set_free(Domain);
707 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000708}
709
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000710void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
711 bool isApproximated) {
712 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
713 if (!AFS)
714 return;
715
716 for (auto &AccessPair : *AFS) {
717 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000718 Instruction *AccessInst = AccessPair.second;
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000719 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000720
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000721 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000722 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000723
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000724 if (isApproximated && Access.isWrite())
725 Access.setMayWrite();
726
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000727 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
728 if (!MAL)
729 MAL = new MemoryAccessList();
730 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
731 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000732 }
733}
734
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000735void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000736 for (MemoryAccess *MA : *this)
737 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000738
739 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000740}
741
Johannes Doerfertd020b772015-08-27 06:53:52 +0000742void ScopStmt::addLoopTripCountToDomain(const Loop *L) {
743
744 unsigned loopDimension = getParent()->getRelativeLoopDepth(L);
745 ScalarEvolution *SE = getParent()->getSE();
746 isl_space *DomSpace = isl_set_get_space(Domain);
747
748 isl_space *MapSpace = isl_space_map_from_set(isl_space_copy(DomSpace));
749 isl_multi_aff *LoopMAff = isl_multi_aff_identity(MapSpace);
750 isl_aff *LoopAff = isl_multi_aff_get_aff(LoopMAff, loopDimension);
751 LoopAff = isl_aff_add_constant_si(LoopAff, 1);
752 LoopMAff = isl_multi_aff_set_aff(LoopMAff, loopDimension, LoopAff);
753 isl_map *TranslationMap = isl_map_from_multi_aff(LoopMAff);
754
755 BasicBlock *ExitingBB = L->getExitingBlock();
756 assert(ExitingBB && "Loop has more than one exiting block");
757
758 BranchInst *Term = dyn_cast<BranchInst>(ExitingBB->getTerminator());
759 assert(Term && Term->isConditional() && "Terminator is not conditional");
760
761 const SCEV *LHS = nullptr;
762 const SCEV *RHS = nullptr;
763 Value *Cond = Term->getCondition();
764 CmpInst::Predicate Pred = CmpInst::Predicate::BAD_ICMP_PREDICATE;
765
766 ICmpInst *CondICmpInst = dyn_cast<ICmpInst>(Cond);
767 ConstantInt *CondConstant = dyn_cast<ConstantInt>(Cond);
768 if (CondICmpInst) {
769 LHS = SE->getSCEVAtScope(CondICmpInst->getOperand(0), L);
770 RHS = SE->getSCEVAtScope(CondICmpInst->getOperand(1), L);
771 Pred = CondICmpInst->getPredicate();
772 } else if (CondConstant) {
773 LHS = SE->getConstant(CondConstant);
774 RHS = SE->getConstant(ConstantInt::getTrue(SE->getContext()));
775 Pred = CmpInst::Predicate::ICMP_EQ;
776 } else {
777 llvm_unreachable("Condition is neither a ConstantInt nor a ICmpInst");
778 }
779
780 if (!L->contains(Term->getSuccessor(0)))
781 Pred = ICmpInst::getInversePredicate(Pred);
782 Comparison Comp(LHS, RHS, Pred);
783
784 isl_set *CondSet = buildConditionSet(Comp);
785 isl_map *ForwardMap = isl_map_lex_le(isl_space_copy(DomSpace));
786 for (unsigned i = 0; i < isl_set_n_dim(Domain); i++)
787 if (i != loopDimension)
788 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
789
790 ForwardMap = isl_map_apply_range(ForwardMap, isl_map_copy(TranslationMap));
791 isl_set *CondDom = isl_set_subtract(isl_set_copy(Domain), CondSet);
792 isl_set *ForwardCond = isl_set_apply(CondDom, isl_map_copy(ForwardMap));
793 isl_set *ForwardDomain = isl_set_apply(isl_set_copy(Domain), ForwardMap);
794 ForwardCond = isl_set_gist(ForwardCond, ForwardDomain);
795 Domain = isl_set_subtract(Domain, ForwardCond);
796
797 isl_map_free(TranslationMap);
798 isl_space_free(DomSpace);
799}
800
Tobias Grosser65b00582011-11-08 15:41:19 +0000801__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000802 isl_pw_aff *L = getPwAff(Comp.getLHS());
803 isl_pw_aff *R = getPwAff(Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000804
Tobias Grosserd2795d02011-08-18 07:51:40 +0000805 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000806 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000807 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000808 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000809 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000810 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000811 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000812 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000813 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000814 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000815 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000816 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000817 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000818 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000819 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000820 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000821 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000822 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000823 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000824 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000825 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000826 default:
827 llvm_unreachable("Non integer predicate not supported");
828 }
Tobias Grosser75805372011-04-29 06:27:02 +0000829}
830
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000831void ScopStmt::addLoopBoundsToDomain(TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000832 isl_space *Space;
833 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000834
Tobias Grossere19661e2011-10-07 08:46:57 +0000835 Space = isl_set_get_space(Domain);
836 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000837
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000838 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000839 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000840 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000841 isl_pw_aff *IV =
842 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000843
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000844 // 0 <= IV.
845 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
846 Domain = isl_set_intersect(Domain, LowerBound);
847
848 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000849 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000850 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Johannes Doerfertd020b772015-08-27 06:53:52 +0000851 if (!isa<SCEVCouldNotCompute>(LatchExecutions)) {
852 isl_pw_aff *UpperBound = getPwAff(LatchExecutions);
853 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
854 Domain = isl_set_intersect(Domain, UpperBoundSet);
855 } else {
856 // If SCEV cannot provide a loop trip count we compute it with ISL.
857 addLoopTripCountToDomain(L);
858 isl_pw_aff_free(IV);
859 }
Tobias Grosser75805372011-04-29 06:27:02 +0000860 }
861
Tobias Grosserf5338802011-10-06 00:03:35 +0000862 isl_local_space_free(LocalSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000863}
864
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000865void ScopStmt::addConditionsToDomain(TempScop &tempScop,
866 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000867 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000868 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000869 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000870
Tobias Grosser75805372011-04-29 06:27:02 +0000871 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000872 if (BranchingBB != CurrentRegion->getEntry()) {
873 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000874 for (const auto &C : *Condition) {
875 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000876 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000877 }
878 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000879 BranchingBB = CurrentRegion->getEntry();
880 CurrentRegion = CurrentRegion->getParent();
881 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000882}
883
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000884void ScopStmt::buildDomain(TempScop &tempScop, const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000885 isl_space *Space;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000886 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000887
888 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
889
Tobias Grosser084d8f72012-05-29 09:29:44 +0000890 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
891
Tobias Grossere19661e2011-10-07 08:46:57 +0000892 Domain = isl_set_universe(Space);
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000893 addLoopBoundsToDomain(tempScop);
894 addConditionsToDomain(tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000895 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000896}
897
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000898void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
899 int Dimension = 0;
900 isl_ctx *Ctx = Parent.getIslCtx();
901 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
902 Type *Ty = GEP->getPointerOperandType();
903 ScalarEvolution &SE = *Parent.getSE();
904
905 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
906 Dimension = 1;
907 Ty = PtrTy->getElementType();
908 }
909
910 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
911 unsigned int Operand = 1 + Dimension;
912
913 if (GEP->getNumOperands() <= Operand)
914 break;
915
916 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
917
918 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000919 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000920 AccessOffset =
921 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
922
923 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
924 isl_local_space_copy(LSpace),
925 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
926
927 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
928 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
929 OutOfBound = isl_set_params(OutOfBound);
930 isl_set *InBound = isl_set_complement(OutOfBound);
931 isl_set *Executed = isl_set_params(getDomain());
932
933 // A => B == !A or B
934 isl_set *InBoundIfExecuted =
935 isl_set_union(isl_set_complement(Executed), InBound);
936
937 Parent.addAssumption(InBoundIfExecuted);
938 }
939
940 Dimension += 1;
941 Ty = ArrayTy->getElementType();
942 }
943
944 isl_local_space_free(LSpace);
945}
946
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000947void ScopStmt::deriveAssumptions(BasicBlock *Block) {
948 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000949 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
950 deriveAssumptionsFromGEP(GEP);
951}
952
Tobias Grosser74394f02013-01-14 22:40:23 +0000953ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000954 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000955 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
956 NestLoops(Nest.size()) {
957 // Setup the induction variables.
958 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
959 NestLoops[i] = Nest[i];
960
Tobias Grosser16c44032015-07-09 07:31:45 +0000961 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000962
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000963 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000964
965 BasicBlock *EntryBB = R.getEntry();
966 for (BasicBlock *Block : R.blocks()) {
967 buildAccesses(tempScop, Block, Block != EntryBB);
968 deriveAssumptions(Block);
969 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000970 if (DetectReductions)
971 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000972}
973
974ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000975 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000976 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
977 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000978 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +0000979 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +0000980 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000981
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000982 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000983
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000984 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000985 buildAccesses(tempScop, BB);
986 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +0000987 if (DetectReductions)
988 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000989}
990
Johannes Doerferte58a0122014-06-27 20:31:28 +0000991/// @brief Collect loads which might form a reduction chain with @p StoreMA
992///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000993/// Check if the stored value for @p StoreMA is a binary operator with one or
994/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000995/// used only once (by @p StoreMA) and its load operands are also used only
996/// once, we have found a possible reduction chain. It starts at an operand
997/// load and includes the binary operator and @p StoreMA.
998///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000999/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001000/// escape this block or into any other store except @p StoreMA.
1001void ScopStmt::collectCandiateReductionLoads(
1002 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1003 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1004 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001005 return;
1006
1007 // Skip if there is not one binary operator between the load and the store
1008 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001009 if (!BinOp)
1010 return;
1011
1012 // Skip if the binary operators has multiple uses
1013 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001014 return;
1015
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001016 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001017 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1018 return;
1019
Johannes Doerfert9890a052014-07-01 00:32:29 +00001020 // Skip if the binary operator is outside the current SCoP
1021 if (BinOp->getParent() != Store->getParent())
1022 return;
1023
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001024 // Skip if it is a multiplicative reduction and we disabled them
1025 if (DisableMultiplicativeReductions &&
1026 (BinOp->getOpcode() == Instruction::Mul ||
1027 BinOp->getOpcode() == Instruction::FMul))
1028 return;
1029
Johannes Doerferte58a0122014-06-27 20:31:28 +00001030 // Check the binary operator operands for a candidate load
1031 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1032 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1033 if (!PossibleLoad0 && !PossibleLoad1)
1034 return;
1035
1036 // A load is only a candidate if it cannot escape (thus has only this use)
1037 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001038 if (PossibleLoad0->getParent() == Store->getParent())
1039 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001040 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001041 if (PossibleLoad1->getParent() == Store->getParent())
1042 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001043}
1044
1045/// @brief Check for reductions in this ScopStmt
1046///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001047/// Iterate over all store memory accesses and check for valid binary reduction
1048/// like chains. For all candidates we check if they have the same base address
1049/// and there are no other accesses which overlap with them. The base address
1050/// check rules out impossible reductions candidates early. The overlap check,
1051/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001052/// guarantees that none of the intermediate results will escape during
1053/// execution of the loop nest. We basically check here that no other memory
1054/// access can access the same memory as the potential reduction.
1055void ScopStmt::checkForReductions() {
1056 SmallVector<MemoryAccess *, 2> Loads;
1057 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1058
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001059 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001060 // stores and collecting possible reduction loads.
1061 for (MemoryAccess *StoreMA : MemAccs) {
1062 if (StoreMA->isRead())
1063 continue;
1064
1065 Loads.clear();
1066 collectCandiateReductionLoads(StoreMA, Loads);
1067 for (MemoryAccess *LoadMA : Loads)
1068 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1069 }
1070
1071 // Then check each possible candidate pair.
1072 for (const auto &CandidatePair : Candidates) {
1073 bool Valid = true;
1074 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1075 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1076
1077 // Skip those with obviously unequal base addresses.
1078 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1079 isl_map_free(LoadAccs);
1080 isl_map_free(StoreAccs);
1081 continue;
1082 }
1083
1084 // And check if the remaining for overlap with other memory accesses.
1085 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1086 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1087 isl_set *AllAccs = isl_map_range(AllAccsRel);
1088
1089 for (MemoryAccess *MA : MemAccs) {
1090 if (MA == CandidatePair.first || MA == CandidatePair.second)
1091 continue;
1092
1093 isl_map *AccRel =
1094 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1095 isl_set *Accs = isl_map_range(AccRel);
1096
1097 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1098 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1099 Valid = Valid && isl_set_is_empty(OverlapAccs);
1100 isl_set_free(OverlapAccs);
1101 }
1102 }
1103
1104 isl_set_free(AllAccs);
1105 if (!Valid)
1106 continue;
1107
Johannes Doerfertf6183392014-07-01 20:52:51 +00001108 const LoadInst *Load =
1109 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1110 MemoryAccess::ReductionType RT =
1111 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1112
Johannes Doerferte58a0122014-06-27 20:31:28 +00001113 // If no overlapping access was found we mark the load and store as
1114 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001115 CandidatePair.first->markAsReductionLike(RT);
1116 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001117 }
Tobias Grosser75805372011-04-29 06:27:02 +00001118}
1119
Tobias Grosser74394f02013-01-14 22:40:23 +00001120std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001121
Tobias Grosser54839312015-04-21 11:37:25 +00001122std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001123 auto *S = getSchedule();
1124 auto Str = stringFromIslObj(S);
1125 isl_map_free(S);
1126 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001127}
1128
Tobias Grosser74394f02013-01-14 22:40:23 +00001129unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001130
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001131unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001132
Tobias Grosser75805372011-04-29 06:27:02 +00001133const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1134
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001135const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001136 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001137}
1138
Tobias Grosser74394f02013-01-14 22:40:23 +00001139isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001140
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001141__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001142
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001143__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001144 return isl_set_get_space(Domain);
1145}
1146
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001147__isl_give isl_id *ScopStmt::getDomainId() const {
1148 return isl_set_get_tuple_id(Domain);
1149}
Tobias Grossercd95b772012-08-30 11:49:38 +00001150
Tobias Grosser75805372011-04-29 06:27:02 +00001151ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001152 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001153 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001154}
1155
1156void ScopStmt::print(raw_ostream &OS) const {
1157 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001158 OS.indent(12) << "Domain :=\n";
1159
1160 if (Domain) {
1161 OS.indent(16) << getDomainStr() << ";\n";
1162 } else
1163 OS.indent(16) << "n/a\n";
1164
Tobias Grosser54839312015-04-21 11:37:25 +00001165 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001166
1167 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001168 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001169 } else
1170 OS.indent(16) << "n/a\n";
1171
Tobias Grosser083d3d32014-06-28 08:59:45 +00001172 for (MemoryAccess *Access : MemAccs)
1173 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001174}
1175
1176void ScopStmt::dump() const { print(dbgs()); }
1177
1178//===----------------------------------------------------------------------===//
1179/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001180
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001181void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001182 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1183 isl_set_free(Context);
1184 Context = NewContext;
1185}
1186
Tobias Grosserabfbe632013-02-05 12:09:06 +00001187void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001188 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001189 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001190 if (ParameterIds.find(Parameter) != ParameterIds.end())
1191 continue;
1192
1193 int dimension = Parameters.size();
1194
1195 Parameters.push_back(Parameter);
1196 ParameterIds[Parameter] = dimension;
1197 }
1198}
1199
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001200__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1201 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001202
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001203 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001204 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001205
Tobias Grosser8f99c162011-11-15 11:38:55 +00001206 std::string ParameterName;
1207
1208 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1209 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001210 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001211 }
1212
1213 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001214 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001215
Tobias Grosser20532b82014-04-11 17:56:49 +00001216 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1217 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001218}
Tobias Grosser75805372011-04-29 06:27:02 +00001219
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001220isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1221 isl_set *DomainContext = isl_union_set_params(getDomains());
1222 return isl_set_intersect_params(C, DomainContext);
1223}
1224
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001225void Scop::addUserContext() {
1226 if (UserContextStr.empty())
1227 return;
1228
1229 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1230 isl_space *Space = getParamSpace();
1231 if (isl_space_dim(Space, isl_dim_param) !=
1232 isl_set_dim(UserContext, isl_dim_param)) {
1233 auto SpaceStr = isl_space_to_str(Space);
1234 errs() << "Error: the context provided in -polly-context has not the same "
1235 << "number of dimensions than the computed context. Due to this "
1236 << "mismatch, the -polly-context option is ignored. Please provide "
1237 << "the context in the parameter space: " << SpaceStr << ".\n";
1238 free(SpaceStr);
1239 isl_set_free(UserContext);
1240 isl_space_free(Space);
1241 return;
1242 }
1243
1244 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1245 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1246 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1247
1248 if (strcmp(NameContext, NameUserContext) != 0) {
1249 auto SpaceStr = isl_space_to_str(Space);
1250 errs() << "Error: the name of dimension " << i
1251 << " provided in -polly-context "
1252 << "is '" << NameUserContext << "', but the name in the computed "
1253 << "context is '" << NameContext
1254 << "'. Due to this name mismatch, "
1255 << "the -polly-context option is ignored. Please provide "
1256 << "the context in the parameter space: " << SpaceStr << ".\n";
1257 free(SpaceStr);
1258 isl_set_free(UserContext);
1259 isl_space_free(Space);
1260 return;
1261 }
1262
1263 UserContext =
1264 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1265 isl_space_get_dim_id(Space, isl_dim_param, i));
1266 }
1267
1268 Context = isl_set_intersect(Context, UserContext);
1269 isl_space_free(Space);
1270}
1271
Tobias Grosser6be480c2011-11-08 15:41:13 +00001272void Scop::buildContext() {
1273 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001274 Context = isl_set_universe(isl_space_copy(Space));
1275 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001276}
1277
Tobias Grosser18daaca2012-05-22 10:47:27 +00001278void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001279 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001280 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001281
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001282 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001283
Johannes Doerferte7044942015-02-24 11:58:30 +00001284 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001285 }
1286}
1287
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001288void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001289 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001290 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001291
Tobias Grosser083d3d32014-06-28 08:59:45 +00001292 for (const auto &ParamID : ParameterIds) {
1293 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001294 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001295 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001296 }
1297
1298 // Align the parameters of all data structures to the model.
1299 Context = isl_set_align_params(Context, Space);
1300
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001301 for (ScopStmt &Stmt : *this)
1302 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001303}
1304
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001305void Scop::simplifyAssumedContext() {
1306 // The parameter constraints of the iteration domains give us a set of
1307 // constraints that need to hold for all cases where at least a single
1308 // statement iteration is executed in the whole scop. We now simplify the
1309 // assumed context under the assumption that such constraints hold and at
1310 // least a single statement iteration is executed. For cases where no
1311 // statement instances are executed, the assumptions we have taken about
1312 // the executed code do not matter and can be changed.
1313 //
1314 // WARNING: This only holds if the assumptions we have taken do not reduce
1315 // the set of statement instances that are executed. Otherwise we
1316 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001317 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001318 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001319 // performed. In such a case, modifying the run-time conditions and
1320 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001321 // to not be executed.
1322 //
1323 // Example:
1324 //
1325 // When delinearizing the following code:
1326 //
1327 // for (long i = 0; i < 100; i++)
1328 // for (long j = 0; j < m; j++)
1329 // A[i+p][j] = 1.0;
1330 //
1331 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001332 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001333 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1334 AssumedContext =
1335 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001336 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001337}
1338
Johannes Doerfertb164c792014-09-18 11:17:17 +00001339/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001340static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001341 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1342 isl_pw_multi_aff *MinPMA, *MaxPMA;
1343 isl_pw_aff *LastDimAff;
1344 isl_aff *OneAff;
1345 unsigned Pos;
1346
Johannes Doerfert9143d672014-09-27 11:02:39 +00001347 // Restrict the number of parameters involved in the access as the lexmin/
1348 // lexmax computation will take too long if this number is high.
1349 //
1350 // Experiments with a simple test case using an i7 4800MQ:
1351 //
1352 // #Parameters involved | Time (in sec)
1353 // 6 | 0.01
1354 // 7 | 0.04
1355 // 8 | 0.12
1356 // 9 | 0.40
1357 // 10 | 1.54
1358 // 11 | 6.78
1359 // 12 | 30.38
1360 //
1361 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1362 unsigned InvolvedParams = 0;
1363 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1364 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1365 InvolvedParams++;
1366
1367 if (InvolvedParams > RunTimeChecksMaxParameters) {
1368 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001369 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001370 }
1371 }
1372
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001373 Set = isl_set_remove_divs(Set);
1374
Johannes Doerfertb164c792014-09-18 11:17:17 +00001375 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1376 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1377
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001378 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1379 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1380
Johannes Doerfertb164c792014-09-18 11:17:17 +00001381 // Adjust the last dimension of the maximal access by one as we want to
1382 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1383 // we test during code generation might now point after the end of the
1384 // allocated array but we will never dereference it anyway.
1385 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1386 "Assumed at least one output dimension");
1387 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1388 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1389 OneAff = isl_aff_zero_on_domain(
1390 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1391 OneAff = isl_aff_add_constant_si(OneAff, 1);
1392 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1393 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1394
1395 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1396
1397 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001398 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001399}
1400
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001401static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1402 isl_set *Domain = MA->getStatement()->getDomain();
1403 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1404 return isl_set_reset_tuple_id(Domain);
1405}
1406
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001407/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1408static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001409 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001410 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001411
1412 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1413 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001414 Locations = isl_union_set_coalesce(Locations);
1415 Locations = isl_union_set_detect_equalities(Locations);
1416 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001417 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001418 isl_union_set_free(Locations);
1419 return Valid;
1420}
1421
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001422void Scop::buildAliasChecks(AliasAnalysis &AA) {
1423 if (!PollyUseRuntimeAliasChecks)
1424 return;
1425
1426 if (buildAliasGroups(AA))
1427 return;
1428
1429 // If a problem occurs while building the alias groups we need to delete
1430 // this SCoP and pretend it wasn't valid in the first place. To this end
1431 // we make the assumed context infeasible.
1432 addAssumption(isl_set_empty(getParamSpace()));
1433
1434 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1435 << " could not be created as the number of parameters involved "
1436 "is too high. The SCoP will be "
1437 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1438 "the maximal number of parameters but be advised that the "
1439 "compile time might increase exponentially.\n\n");
1440}
1441
Johannes Doerfert9143d672014-09-27 11:02:39 +00001442bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001443 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001444 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001445 // for all memory accesses inside the SCoP.
1446 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001447 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001448 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001449 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001450 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001451 // if their access domains intersect, otherwise they are in different
1452 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001453 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001454 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001455 // and maximal accesses to each array of a group in read only and non
1456 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001457 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1458
1459 AliasSetTracker AST(AA);
1460
1461 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001462 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001463 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001464
1465 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001466 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001467 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1468 isl_set_free(StmtDomain);
1469 if (StmtDomainEmpty)
1470 continue;
1471
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001472 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001473 if (MA->isScalar())
1474 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001475 if (!MA->isRead())
1476 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001477 Instruction *Acc = MA->getAccessInstruction();
1478 PtrToAcc[getPointerOperand(*Acc)] = MA;
1479 AST.add(Acc);
1480 }
1481 }
1482
1483 SmallVector<AliasGroupTy, 4> AliasGroups;
1484 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001485 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001486 continue;
1487 AliasGroupTy AG;
1488 for (auto PR : AS)
1489 AG.push_back(PtrToAcc[PR.getValue()]);
1490 assert(AG.size() > 1 &&
1491 "Alias groups should contain at least two accesses");
1492 AliasGroups.push_back(std::move(AG));
1493 }
1494
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001495 // Split the alias groups based on their domain.
1496 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1497 AliasGroupTy NewAG;
1498 AliasGroupTy &AG = AliasGroups[u];
1499 AliasGroupTy::iterator AGI = AG.begin();
1500 isl_set *AGDomain = getAccessDomain(*AGI);
1501 while (AGI != AG.end()) {
1502 MemoryAccess *MA = *AGI;
1503 isl_set *MADomain = getAccessDomain(MA);
1504 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1505 NewAG.push_back(MA);
1506 AGI = AG.erase(AGI);
1507 isl_set_free(MADomain);
1508 } else {
1509 AGDomain = isl_set_union(AGDomain, MADomain);
1510 AGI++;
1511 }
1512 }
1513 if (NewAG.size() > 1)
1514 AliasGroups.push_back(std::move(NewAG));
1515 isl_set_free(AGDomain);
1516 }
1517
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001518 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001519 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1520 for (AliasGroupTy &AG : AliasGroups) {
1521 NonReadOnlyBaseValues.clear();
1522 ReadOnlyPairs.clear();
1523
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001524 if (AG.size() < 2) {
1525 AG.clear();
1526 continue;
1527 }
1528
Johannes Doerfert13771732014-10-01 12:40:46 +00001529 for (auto II = AG.begin(); II != AG.end();) {
1530 Value *BaseAddr = (*II)->getBaseAddr();
1531 if (HasWriteAccess.count(BaseAddr)) {
1532 NonReadOnlyBaseValues.insert(BaseAddr);
1533 II++;
1534 } else {
1535 ReadOnlyPairs[BaseAddr].insert(*II);
1536 II = AG.erase(II);
1537 }
1538 }
1539
1540 // If we don't have read only pointers check if there are at least two
1541 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001542 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001543 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001544 continue;
1545 }
1546
1547 // If we don't have non read only pointers clear the alias group.
1548 if (NonReadOnlyBaseValues.empty()) {
1549 AG.clear();
1550 continue;
1551 }
1552
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001553 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001554 MinMaxAliasGroups.emplace_back();
1555 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1556 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1557 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1558 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001559
1560 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001561
1562 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001563 for (MemoryAccess *MA : AG)
1564 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001565
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001566 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
1567 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001568
1569 // Bail out if the number of values we need to compare is too large.
1570 // This is important as the number of comparisions grows quadratically with
1571 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001572 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1573 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001574 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001575
1576 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001577 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001578 Accesses = isl_union_map_empty(getParamSpace());
1579
1580 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1581 for (MemoryAccess *MA : ReadOnlyPair.second)
1582 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1583
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001584 Valid =
1585 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001586
1587 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001588 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001589 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001590
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001591 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001592}
1593
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001594static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1595 ScopDetection &SD) {
1596
1597 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1598
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001599 unsigned MinLD = INT_MAX, MaxLD = 0;
1600 for (BasicBlock *BB : R.blocks()) {
1601 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001602 if (!R.contains(L))
1603 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001604 if (BoxedLoops && BoxedLoops->count(L))
1605 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001606 unsigned LD = L->getLoopDepth();
1607 MinLD = std::min(MinLD, LD);
1608 MaxLD = std::max(MaxLD, LD);
1609 }
1610 }
1611
1612 // Handle the case that there is no loop in the SCoP first.
1613 if (MaxLD == 0)
1614 return 1;
1615
1616 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1617 assert(MaxLD >= MinLD &&
1618 "Maximal loop depth was smaller than mininaml loop depth?");
1619 return MaxLD - MinLD + 1;
1620}
1621
Michael Kruse471a5e32015-07-30 19:27:04 +00001622Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, isl_ctx *Context,
1623 unsigned MaxLoopDepth)
1624 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert574182d2015-08-12 10:19:50 +00001625 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001626
Tobias Grosser40985012015-08-20 19:08:05 +00001627void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI, ScopDetection &SD,
1628 AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001629 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001630
Tobias Grosserabfbe632013-02-05 12:09:06 +00001631 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001632
Tobias Grosser54839312015-04-21 11:37:25 +00001633 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001634 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00001635 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00001636 if (!Schedule)
1637 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00001638
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001639 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001640 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001641 addUserContext();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001642 simplifyAssumedContext();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001643 buildAliasChecks(AA);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001644
Tobias Grosser75805372011-04-29 06:27:02 +00001645 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1646}
1647
Michael Kruse471a5e32015-07-30 19:27:04 +00001648Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
1649 ScalarEvolution &SE, ScopDetection &SD,
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001650 AliasAnalysis &AA, isl_ctx *ctx) {
Michael Kruse471a5e32015-07-30 19:27:04 +00001651 auto &R = TempScop.getMaxRegion();
1652 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
1653 auto S = new Scop(R, SE, ctx, MaxLoopDepth);
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001654 S->initFromTempScop(TempScop, LI, SD, AA);
1655
Michael Kruse471a5e32015-07-30 19:27:04 +00001656 return S;
1657}
1658
Tobias Grosser75805372011-04-29 06:27:02 +00001659Scop::~Scop() {
1660 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001661 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00001662 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001663
Johannes Doerfertb164c792014-09-18 11:17:17 +00001664 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001665 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001666 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001667 isl_pw_multi_aff_free(MMA.first);
1668 isl_pw_multi_aff_free(MMA.second);
1669 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001670 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001671 isl_pw_multi_aff_free(MMA.first);
1672 isl_pw_multi_aff_free(MMA.second);
1673 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001674 }
Tobias Grosser75805372011-04-29 06:27:02 +00001675}
1676
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001677const ScopArrayInfo *
1678Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00001679 const SmallVector<const SCEV *, 4> &Sizes,
1680 bool IsPHI) {
1681 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001682 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001683 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
1684 this));
Tobias Grosserab671442015-05-23 05:58:27 +00001685 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001686}
1687
Tobias Grosser92245222015-07-28 14:53:44 +00001688const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
1689 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001690 assert(SAI && "No ScopArrayInfo available for this base pointer");
1691 return SAI;
1692}
1693
Tobias Grosser74394f02013-01-14 22:40:23 +00001694std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001695std::string Scop::getAssumedContextStr() const {
1696 return stringFromIslObj(AssumedContext);
1697}
Tobias Grosser75805372011-04-29 06:27:02 +00001698
1699std::string Scop::getNameStr() const {
1700 std::string ExitName, EntryName;
1701 raw_string_ostream ExitStr(ExitName);
1702 raw_string_ostream EntryStr(EntryName);
1703
Tobias Grosserf240b482014-01-09 10:42:15 +00001704 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001705 EntryStr.str();
1706
1707 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001708 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001709 ExitStr.str();
1710 } else
1711 ExitName = "FunctionExit";
1712
1713 return EntryName + "---" + ExitName;
1714}
1715
Tobias Grosser74394f02013-01-14 22:40:23 +00001716__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001717__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001718 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001719}
1720
Tobias Grossere86109f2013-10-29 21:05:49 +00001721__isl_give isl_set *Scop::getAssumedContext() const {
1722 return isl_set_copy(AssumedContext);
1723}
1724
Johannes Doerfert43788c52015-08-20 05:58:56 +00001725__isl_give isl_set *Scop::getRuntimeCheckContext() const {
1726 isl_set *RuntimeCheckContext = getAssumedContext();
1727 return RuntimeCheckContext;
1728}
1729
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001730bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00001731 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001732 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00001733 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
1734 isl_set_free(RuntimeCheckContext);
1735 return IsFeasible;
1736}
1737
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001738void Scop::addAssumption(__isl_take isl_set *Set) {
1739 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001740 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001741}
1742
Tobias Grosser75805372011-04-29 06:27:02 +00001743void Scop::printContext(raw_ostream &OS) const {
1744 OS << "Context:\n";
1745
1746 if (!Context) {
1747 OS.indent(4) << "n/a\n\n";
1748 return;
1749 }
1750
1751 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001752
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001753 OS.indent(4) << "Assumed Context:\n";
1754 if (!AssumedContext) {
1755 OS.indent(4) << "n/a\n\n";
1756 return;
1757 }
1758
1759 OS.indent(4) << getAssumedContextStr() << "\n";
1760
Tobias Grosser083d3d32014-06-28 08:59:45 +00001761 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001762 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001763 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1764 }
Tobias Grosser75805372011-04-29 06:27:02 +00001765}
1766
Johannes Doerfertb164c792014-09-18 11:17:17 +00001767void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001768 int noOfGroups = 0;
1769 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001770 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001771 noOfGroups += 1;
1772 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001773 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001774 }
1775
Tobias Grosserbb853c22015-07-25 12:31:03 +00001776 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00001777 if (MinMaxAliasGroups.empty()) {
1778 OS.indent(8) << "n/a\n";
1779 return;
1780 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001781
Tobias Grosserbb853c22015-07-25 12:31:03 +00001782 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001783
1784 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001785 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001786 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001787 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001788 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1789 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001790 }
1791 OS << " ]]\n";
1792 }
1793
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001794 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001795 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00001796 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001797 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001798 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1799 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001800 }
1801 OS << " ]]\n";
1802 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001803 }
1804}
1805
Tobias Grosser75805372011-04-29 06:27:02 +00001806void Scop::printStatements(raw_ostream &OS) const {
1807 OS << "Statements {\n";
1808
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001809 for (const ScopStmt &Stmt : *this)
1810 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001811
1812 OS.indent(4) << "}\n";
1813}
1814
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001815void Scop::printArrayInfo(raw_ostream &OS) const {
1816 OS << "Arrays {\n";
1817
Tobias Grosserab671442015-05-23 05:58:27 +00001818 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001819 Array.second->print(OS);
1820
1821 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001822
1823 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
1824
1825 for (auto &Array : arrays())
1826 Array.second->print(OS, /* SizeAsPwAff */ true);
1827
1828 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001829}
1830
Tobias Grosser75805372011-04-29 06:27:02 +00001831void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001832 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1833 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001834 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001835 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001836 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001837 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001838 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001839 printStatements(OS.indent(4));
1840}
1841
1842void Scop::dump() const { print(dbgs()); }
1843
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001844isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001845
Johannes Doerfertb409fdc2015-08-28 09:24:35 +00001846__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, isl_set *Domain) {
1847 return Affinator.getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +00001848}
1849
Tobias Grosser808cd692015-07-14 09:33:13 +00001850__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001851 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001852
Tobias Grosser808cd692015-07-14 09:33:13 +00001853 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001854 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001855
1856 return Domain;
1857}
1858
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001859__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001860 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001861
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001862 for (ScopStmt &Stmt : *this) {
1863 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001864 if (!MA->isMustWrite())
1865 continue;
1866
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001867 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001868 isl_map *AccessDomain = MA->getAccessRelation();
1869 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1870 Write = isl_union_map_add_map(Write, AccessDomain);
1871 }
1872 }
1873 return isl_union_map_coalesce(Write);
1874}
1875
1876__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001877 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001878
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001879 for (ScopStmt &Stmt : *this) {
1880 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001881 if (!MA->isMayWrite())
1882 continue;
1883
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001884 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001885 isl_map *AccessDomain = MA->getAccessRelation();
1886 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1887 Write = isl_union_map_add_map(Write, AccessDomain);
1888 }
1889 }
1890 return isl_union_map_coalesce(Write);
1891}
1892
Tobias Grosser37eb4222014-02-20 21:43:54 +00001893__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001894 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001895
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001896 for (ScopStmt &Stmt : *this) {
1897 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001898 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001899 continue;
1900
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001901 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001902 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001903 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1904 Write = isl_union_map_add_map(Write, AccessDomain);
1905 }
1906 }
1907 return isl_union_map_coalesce(Write);
1908}
1909
1910__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001911 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001912
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001913 for (ScopStmt &Stmt : *this) {
1914 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001915 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001916 continue;
1917
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001918 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001919 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001920
1921 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1922 Read = isl_union_map_add_map(Read, AccessDomain);
1923 }
1924 }
1925 return isl_union_map_coalesce(Read);
1926}
1927
Tobias Grosser808cd692015-07-14 09:33:13 +00001928__isl_give isl_union_map *Scop::getSchedule() const {
1929 auto Tree = getScheduleTree();
1930 auto S = isl_schedule_get_map(Tree);
1931 isl_schedule_free(Tree);
1932 return S;
1933}
Tobias Grosser37eb4222014-02-20 21:43:54 +00001934
Tobias Grosser808cd692015-07-14 09:33:13 +00001935__isl_give isl_schedule *Scop::getScheduleTree() const {
1936 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
1937 getDomains());
1938}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001939
Tobias Grosser808cd692015-07-14 09:33:13 +00001940void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
1941 auto *S = isl_schedule_from_domain(getDomains());
1942 S = isl_schedule_insert_partial_schedule(
1943 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
1944 isl_schedule_free(Schedule);
1945 Schedule = S;
1946}
1947
1948void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
1949 isl_schedule_free(Schedule);
1950 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00001951}
1952
1953bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1954 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001955 for (ScopStmt &Stmt : *this) {
1956 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001957 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1958 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1959
1960 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1961 isl_union_set_free(StmtDomain);
1962 isl_union_set_free(NewStmtDomain);
1963 continue;
1964 }
1965
1966 Changed = true;
1967
1968 isl_union_set_free(StmtDomain);
1969 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1970
1971 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001972 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001973 isl_union_set_free(NewStmtDomain);
1974 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001975 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001976 }
1977 isl_union_set_free(Domain);
1978 return Changed;
1979}
1980
Tobias Grosser75805372011-04-29 06:27:02 +00001981ScalarEvolution *Scop::getSE() const { return SE; }
1982
1983bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1984 if (tempScop.getAccessFunctions(BB))
1985 return false;
1986
1987 return true;
1988}
1989
Tobias Grosser808cd692015-07-14 09:33:13 +00001990struct MapToDimensionDataTy {
1991 int N;
1992 isl_union_pw_multi_aff *Res;
1993};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001994
Tobias Grosser808cd692015-07-14 09:33:13 +00001995// @brief Create a function that maps the elements of 'Set' to its N-th
1996// dimension.
1997//
1998// The result is added to 'User->Res'.
1999//
2000// @param Set The input set.
2001// @param N The dimension to map to.
2002//
2003// @returns Zero if no error occurred, non-zero otherwise.
2004static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2005 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2006 int Dim;
2007 isl_space *Space;
2008 isl_pw_multi_aff *PMA;
2009
2010 Dim = isl_set_dim(Set, isl_dim_set);
2011 Space = isl_set_get_space(Set);
2012 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2013 Dim - Data->N);
2014 if (Data->N > 1)
2015 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2016 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2017
2018 isl_set_free(Set);
2019
2020 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002021}
2022
Tobias Grosser808cd692015-07-14 09:33:13 +00002023// @brief Create a function that maps the elements of Domain to their Nth
2024// dimension.
2025//
2026// @param Domain The set of elements to map.
2027// @param N The dimension to map to.
2028static __isl_give isl_multi_union_pw_aff *
2029mapToDimension(__isl_take isl_union_set *Domain, int N) {
2030 struct MapToDimensionDataTy Data;
2031 isl_space *Space;
2032
2033 Space = isl_union_set_get_space(Domain);
2034 Data.N = N;
2035 Data.Res = isl_union_pw_multi_aff_empty(Space);
2036 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2037 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2038
2039 isl_union_set_free(Domain);
2040 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2041}
2042
2043ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
2044 const Region &CurRegion,
2045 SmallVectorImpl<Loop *> &NestLoops) {
2046 ScopStmt *Stmt;
2047 if (BB) {
2048 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
2049 Stmt = &Stmts.back();
2050 StmtMap[BB] = Stmt;
2051 } else {
2052 assert(R && "Either basic block or a region expected.");
2053 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
2054 Stmt = &Stmts.back();
2055 for (BasicBlock *BB : R->blocks())
2056 StmtMap[BB] = Stmt;
2057 }
2058 return Stmt;
2059}
2060
Michael Kruse046dde42015-08-10 13:01:57 +00002061__isl_give isl_schedule *
2062Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
2063 const Region &CurRegion,
2064 SmallVectorImpl<Loop *> &NestLoops) {
2065 if (isTrivialBB(BB, tempScop))
2066 return nullptr;
2067
2068 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
2069 auto *Domain = Stmt->getDomain();
2070 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2071}
2072
Tobias Grosser808cd692015-07-14 09:33:13 +00002073__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
2074 const Region &CurRegion,
2075 SmallVectorImpl<Loop *> &NestLoops,
2076 LoopInfo &LI, ScopDetection &SD) {
2077 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
2078 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
2079 tempScop, CurRegion, NestLoops);
2080 auto *Domain = Stmt->getDomain();
2081 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2082 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002083
Tobias Grosser75805372011-04-29 06:27:02 +00002084 Loop *L = castToLoop(CurRegion, LI);
2085
2086 if (L)
2087 NestLoops.push_back(L);
2088
2089 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00002090 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002091
2092 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002093 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00002094 I != E; ++I) {
2095 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002096 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002097 StmtSchedule =
2098 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002099 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00002100 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
2101 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00002102 }
Michael Kruse046dde42015-08-10 13:01:57 +00002103 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00002104 }
Tobias Grosser75805372011-04-29 06:27:02 +00002105
Tobias Grosser808cd692015-07-14 09:33:13 +00002106 if (!L)
2107 return Schedule;
2108
2109 auto *Domain = isl_schedule_get_domain(Schedule);
2110 if (!isl_union_set_is_empty(Domain)) {
2111 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
2112 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
2113 }
2114 isl_union_set_free(Domain);
2115
Tobias Grosser75805372011-04-29 06:27:02 +00002116 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00002117 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00002118}
2119
Johannes Doerfert7c494212014-10-31 23:13:39 +00002120ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002121 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002122 if (StmtMapIt == StmtMap.end())
2123 return nullptr;
2124 return StmtMapIt->second;
2125}
2126
Johannes Doerfertd020b772015-08-27 06:53:52 +00002127unsigned Scop::getRelativeLoopDepth(const Loop *L) const {
2128 Loop *OuterLoop = R.outermostLoopInRegion(const_cast<Loop *>(L));
2129 assert(OuterLoop && "Scop does not contain this loop");
2130 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2131}
2132
Tobias Grosser75805372011-04-29 06:27:02 +00002133//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002134ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2135 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002136 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002137}
2138
2139ScopInfo::~ScopInfo() {
2140 clear();
2141 isl_ctx_free(ctx);
2142}
2143
Tobias Grosser75805372011-04-29 06:27:02 +00002144void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002145 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002146 AU.addRequired<RegionInfoPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002147 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002148 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002149 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002150 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002151 AU.setPreservesAll();
2152}
2153
2154bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002155 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002156 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002157 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002158 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Tobias Grosser75805372011-04-29 06:27:02 +00002159
Michael Kruse82a1c7d2015-08-14 20:10:27 +00002160 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop();
Tobias Grosser75805372011-04-29 06:27:02 +00002161
2162 // This region is no Scop.
2163 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002164 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002165 return false;
2166 }
2167
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002168 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, AA, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002169
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002170 DEBUG(scop->print(dbgs()));
2171
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002172 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002173 delete scop;
2174 scop = nullptr;
2175 return false;
2176 }
2177
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002178 // Statistics.
2179 ++ScopFound;
2180 if (scop->getMaxLoopDepth() > 0)
2181 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00002182 return false;
2183}
2184
2185char ScopInfo::ID = 0;
2186
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002187Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2188
Tobias Grosser73600b82011-10-08 00:30:40 +00002189INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2190 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002191 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002192INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002193INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002194INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002195INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002196INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002197INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002198INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2199 "Polly - Create polyhedral description of Scops", false,
2200 false)