blob: c7a92f5a906043e541fb53e6137460a977953777 [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
Michael Kruse046dde42015-08-10 13:01:57 +000083// Create a sequence of two schedules. Either argument may be null and is
84// interpreted as the empty schedule. Can also return null if both schedules are
85// empty.
86static __isl_give isl_schedule *
87combineInSequence(__isl_take isl_schedule *Prev,
88 __isl_take isl_schedule *Succ) {
89 if (!Prev)
90 return Succ;
91 if (!Succ)
92 return Prev;
93
94 return isl_schedule_sequence(Prev, Succ);
95}
96
Johannes Doerferte7044942015-02-24 11:58:30 +000097static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
98 const ConstantRange &Range,
99 int dim,
100 enum isl_dim_type type) {
101 isl_val *V;
102 isl_ctx *ctx = isl_set_get_ctx(S);
103
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000104 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
105 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000106 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000107 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
108
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000109 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000110 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000111 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000112 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000113 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
114
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000115 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000116 return isl_set_union(SLB, SUB);
117 else
118 return isl_set_intersect(SLB, SUB);
119}
120
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000121ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser92245222015-07-28 14:53:44 +0000122 const SmallVector<const SCEV *, 4> &DimensionSizes,
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000123 bool IsPHI, Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000124 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000125 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
126 std::string BasePtrName =
127 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000128 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000129 for (const SCEV *Expr : DimensionSizes) {
130 isl_pw_aff *Size = S->getPwAff(Expr);
131 DimensionSizesPw.push_back(Size);
132 }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000133}
134
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000135ScopArrayInfo::~ScopArrayInfo() {
136 isl_id_free(Id);
137 for (isl_pw_aff *Size : DimensionSizesPw)
138 isl_pw_aff_free(Size);
139}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000140
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000141std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
142
143int ScopArrayInfo::getElemSizeInBytes() const {
144 return ElementType->getPrimitiveSizeInBits() / 8;
145}
146
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000147isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
148
149void ScopArrayInfo::dump() const { print(errs()); }
150
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000151void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000152 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000153 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
154 OS << "[";
155
156 if (SizeAsPwAff)
157 OS << " " << DimensionSizesPw[u] << " ";
158 else
159 OS << *DimensionSizes[u];
160
161 OS << "]";
162 }
163
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000164 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000165}
166
167const ScopArrayInfo *
168ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
169 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
170 assert(Id && "Output dimension didn't have an ID");
171 return getFromId(Id);
172}
173
174const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
175 void *User = isl_id_get_user(Id);
176 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
177 isl_id_free(Id);
178 return SAI;
179}
180
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000181const std::string
182MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
183 switch (RT) {
184 case MemoryAccess::RT_NONE:
185 llvm_unreachable("Requested a reduction operator string for a memory "
186 "access which isn't a reduction");
187 case MemoryAccess::RT_ADD:
188 return "+";
189 case MemoryAccess::RT_MUL:
190 return "*";
191 case MemoryAccess::RT_BOR:
192 return "|";
193 case MemoryAccess::RT_BXOR:
194 return "^";
195 case MemoryAccess::RT_BAND:
196 return "&";
197 }
198 llvm_unreachable("Unknown reduction type");
199 return "";
200}
201
Johannes Doerfertf6183392014-07-01 20:52:51 +0000202/// @brief Return the reduction type for a given binary operator
203static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
204 const Instruction *Load) {
205 if (!BinOp)
206 return MemoryAccess::RT_NONE;
207 switch (BinOp->getOpcode()) {
208 case Instruction::FAdd:
209 if (!BinOp->hasUnsafeAlgebra())
210 return MemoryAccess::RT_NONE;
211 // Fall through
212 case Instruction::Add:
213 return MemoryAccess::RT_ADD;
214 case Instruction::Or:
215 return MemoryAccess::RT_BOR;
216 case Instruction::Xor:
217 return MemoryAccess::RT_BXOR;
218 case Instruction::And:
219 return MemoryAccess::RT_BAND;
220 case Instruction::FMul:
221 if (!BinOp->hasUnsafeAlgebra())
222 return MemoryAccess::RT_NONE;
223 // Fall through
224 case Instruction::Mul:
225 if (DisableMultiplicativeReductions)
226 return MemoryAccess::RT_NONE;
227 return MemoryAccess::RT_MUL;
228 default:
229 return MemoryAccess::RT_NONE;
230 }
231}
Tobias Grosser75805372011-04-29 06:27:02 +0000232//===----------------------------------------------------------------------===//
233
234MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000235 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000236 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000237 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000238}
239
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000240static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
241 switch (Access.getType()) {
242 case IRAccess::READ:
243 return MemoryAccess::READ;
244 case IRAccess::MUST_WRITE:
245 return MemoryAccess::MUST_WRITE;
246 case IRAccess::MAY_WRITE:
247 return MemoryAccess::MAY_WRITE;
248 }
249 llvm_unreachable("Unknown IRAccess type!");
250}
251
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000252const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
253 isl_id *ArrayId = getArrayId();
254 void *User = isl_id_get_user(ArrayId);
255 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
256 isl_id_free(ArrayId);
257 return SAI;
258}
259
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000260__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000261 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
262}
263
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000264__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
265 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000266 isl_map *Schedule, *ScheduledAccRel;
267 isl_union_set *UDomain;
268
269 UDomain = isl_union_set_from_set(getStatement()->getDomain());
270 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
271 Schedule = isl_map_from_union_map(USchedule);
272 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
273 return isl_pw_multi_aff_from_map(ScheduledAccRel);
274}
275
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000276__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000277 return isl_map_copy(AccessRelation);
278}
279
Johannes Doerferta99130f2014-10-13 12:58:03 +0000280std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000281 return stringFromIslObj(AccessRelation);
282}
283
Johannes Doerferta99130f2014-10-13 12:58:03 +0000284__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000285 return isl_map_get_space(AccessRelation);
286}
287
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000288__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000289 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000290}
291
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000292__isl_give isl_basic_map *
293MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000294 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000295 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000296
Tobias Grosser084d8f72012-05-29 09:29:44 +0000297 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000298 isl_basic_set_universe(Statement->getDomainSpace()),
299 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000300}
301
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000302// Formalize no out-of-bound access assumption
303//
304// When delinearizing array accesses we optimistically assume that the
305// delinearized accesses do not access out of bound locations (the subscript
306// expression of each array evaluates for each statement instance that is
307// executed to a value that is larger than zero and strictly smaller than the
308// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000309// dimension for which we do not need to assume any upper bound. At this point
310// we formalize this assumption to ensure that at code generation time the
311// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000312//
313// To find the set of constraints necessary to avoid out of bound accesses, we
314// first build the set of data locations that are not within array bounds. We
315// then apply the reverse access relation to obtain the set of iterations that
316// may contain invalid accesses and reduce this set of iterations to the ones
317// that are actually executed by intersecting them with the domain of the
318// statement. If we now project out all loop dimensions, we obtain a set of
319// parameters that may cause statement instances to be executed that may
320// possibly yield out of bound memory accesses. The complement of these
321// constraints is the set of constraints that needs to be assumed to ensure such
322// statement instances are never executed.
323void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000324 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000325 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000326 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000327 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
328 isl_pw_aff *Var =
329 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
330 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
331
332 isl_set *DimOutside;
333
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000334 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000335 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000336
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000337 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
338 Statement->getNumIterators());
339 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
340 isl_space_dim(Space, isl_dim_set));
341 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
342 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000343
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000344 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000345
346 Outside = isl_set_union(Outside, DimOutside);
347 }
348
349 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
350 Outside = isl_set_intersect(Outside, Statement->getDomain());
351 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000352
353 // Remove divs to avoid the construction of overly complicated assumptions.
354 // Doing so increases the set of parameter combinations that are assumed to
355 // not appear. This is always save, but may make the resulting run-time check
356 // bail out more often than strictly necessary.
357 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000358 Outside = isl_set_complement(Outside);
359 Statement->getParent()->addAssumption(Outside);
360 isl_space_free(Space);
361}
362
Johannes Doerferte7044942015-02-24 11:58:30 +0000363void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
364 ScalarEvolution *SE = Statement->getParent()->getSE();
365
366 Value *Ptr = getPointerOperand(*getAccessInstruction());
367 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
368 return;
369
370 auto *PtrSCEV = SE->getSCEV(Ptr);
371 if (isa<SCEVCouldNotCompute>(PtrSCEV))
372 return;
373
374 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
375 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
376 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
377
378 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
379 if (Range.isFullSet())
380 return;
381
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000382 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000383 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000384 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
385 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
386
387 auto Min = LB.sdiv(APInt(BW, ElementSize));
388 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000389
390 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
391 AccessRange =
392 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
393 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
394}
395
Tobias Grosser619190d2015-03-30 17:22:28 +0000396__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
397 __isl_take isl_map *AccessRelation,
398 ScopStmt *Statement) {
399 int Size = Access.Subscripts.size();
400
401 for (int i = Size - 2; i >= 0; --i) {
402 isl_space *Space;
403 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000404 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000405
406 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
407 isl_pw_aff_free(DimSize);
408 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
409
410 Space = isl_map_get_space(AccessRelation);
411 Space = isl_space_map_from_set(isl_space_range(Space));
412 Space = isl_space_align_params(Space, SpaceSize);
413
414 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
415 isl_id_free(ParamId);
416
417 MapOne = isl_map_universe(isl_space_copy(Space));
418 for (int j = 0; j < Size; ++j)
419 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
420 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
421
422 MapTwo = isl_map_universe(isl_space_copy(Space));
423 for (int j = 0; j < Size; ++j)
424 if (j < i || j > i + 1)
425 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
426
427 isl_local_space *LS = isl_local_space_from_space(Space);
428 isl_constraint *C;
429 C = isl_equality_alloc(isl_local_space_copy(LS));
430 C = isl_constraint_set_constant_si(C, -1);
431 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
432 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
433 MapTwo = isl_map_add_constraint(MapTwo, C);
434 C = isl_equality_alloc(LS);
435 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
436 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
437 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
438 MapTwo = isl_map_add_constraint(MapTwo, C);
439 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
440
441 MapOne = isl_map_union(MapOne, MapTwo);
442 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
443 }
444 return AccessRelation;
445}
446
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000447MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000448 ScopStmt *Statement, const ScopArrayInfo *SAI,
449 int Identifier)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000450 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000451 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000452
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000453 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000454 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000455 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000456
457 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000458
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000459 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000460 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000461
Tobias Grossera1879642011-12-20 10:43:14 +0000462 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000463 // We overapproximate non-affine accesses with a possible access to the
464 // whole array. For read accesses it does not make a difference, if an
465 // access must or may happen. However, for write accesses it is important to
466 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000467 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000468 AccessRelation =
469 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000470
471 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000472 return;
473 }
474
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000475 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000476 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000477
Tobias Grosser79baa212014-04-10 08:38:02 +0000478 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000479 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000480
Sebastian Pop422e33f2014-06-03 18:16:31 +0000481 if (Size == 1) {
482 // For the non delinearized arrays, divide the access function of the last
483 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000484 //
485 // A stride one array access in C expressed as A[i] is expressed in
486 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
487 // two subsequent values of 'i' index two values that are stored next to
488 // each other in memory. By this division we make this characteristic
489 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000490 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000491 Affine = isl_pw_aff_scale_down_val(Affine, v);
492 }
493
494 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
495
Tobias Grosser79baa212014-04-10 08:38:02 +0000496 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000497 }
498
Tobias Grosser619190d2015-03-30 17:22:28 +0000499 AccessRelation = foldAccess(Access, AccessRelation, Statement);
500
Tobias Grosser79baa212014-04-10 08:38:02 +0000501 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000502 AccessRelation = isl_map_set_tuple_id(
503 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000504 AccessRelation =
505 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
506
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000507 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000508 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000509 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000510}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000511
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000512void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000513 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000514 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000515}
516
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000517const std::string MemoryAccess::getReductionOperatorStr() const {
518 return MemoryAccess::getReductionOperatorStr(getReductionType());
519}
520
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000521__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
522
Johannes Doerfertf6183392014-07-01 20:52:51 +0000523raw_ostream &polly::operator<<(raw_ostream &OS,
524 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000525 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000526 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000527 else
528 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000529 return OS;
530}
531
Tobias Grosser75805372011-04-29 06:27:02 +0000532void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000533 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000534 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000535 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000536 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000537 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000538 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000539 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000540 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000541 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000542 break;
543 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000544 OS << "[Reduction Type: " << getReductionType() << "] ";
545 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000546 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000547}
548
Tobias Grosser74394f02013-01-14 22:40:23 +0000549void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000550
551// Create a map in the size of the provided set domain, that maps from the
552// one element of the provided set domain to another element of the provided
553// set domain.
554// The mapping is limited to all points that are equal in all but the last
555// dimension and for which the last dimension of the input is strict smaller
556// than the last dimension of the output.
557//
558// getEqualAndLarger(set[i0, i1, ..., iX]):
559//
560// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
561// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
562//
Tobias Grosserf5338802011-10-06 00:03:35 +0000563static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000564 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000565 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000566 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000567
568 // Set all but the last dimension to be equal for the input and output
569 //
570 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
571 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000572 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000573 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000574
575 // Set the last dimension of the input to be strict smaller than the
576 // last dimension of the output.
577 //
578 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000579 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
580 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000581 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000582}
583
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000584__isl_give isl_set *
585MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000586 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000587 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000588 isl_space *Space = isl_space_range(isl_map_get_space(S));
589 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000590
Sebastian Popa00a0292012-12-18 07:46:06 +0000591 S = isl_map_reverse(S);
592 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000593
Sebastian Popa00a0292012-12-18 07:46:06 +0000594 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
595 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
596 NextScatt = isl_map_apply_domain(NextScatt, S);
597 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000598
Sebastian Popa00a0292012-12-18 07:46:06 +0000599 isl_set *Deltas = isl_map_deltas(NextScatt);
600 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000601}
602
Sebastian Popa00a0292012-12-18 07:46:06 +0000603bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000604 int StrideWidth) const {
605 isl_set *Stride, *StrideX;
606 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000607
Sebastian Popa00a0292012-12-18 07:46:06 +0000608 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000609 StrideX = isl_set_universe(isl_set_get_space(Stride));
610 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
611 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000612
Tobias Grosser28dd4862012-01-24 16:42:16 +0000613 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000614 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000615
Tobias Grosser28dd4862012-01-24 16:42:16 +0000616 return IsStrideX;
617}
618
Sebastian Popa00a0292012-12-18 07:46:06 +0000619bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
620 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000621}
622
Tobias Grosser79baa212014-04-10 08:38:02 +0000623bool MemoryAccess::isScalar() const {
624 return isl_map_n_out(AccessRelation) == 0;
625}
626
Sebastian Popa00a0292012-12-18 07:46:06 +0000627bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
628 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000629}
630
Tobias Grosser5d453812011-10-06 00:04:11 +0000631void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000632 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000633 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000634}
Tobias Grosser75805372011-04-29 06:27:02 +0000635
636//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000637
Tobias Grosser808cd692015-07-14 09:33:13 +0000638isl_map *ScopStmt::getSchedule() const {
639 isl_set *Domain = getDomain();
640 if (isl_set_is_empty(Domain)) {
641 isl_set_free(Domain);
642 return isl_map_from_aff(
643 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
644 }
645 auto *Schedule = getParent()->getSchedule();
646 Schedule = isl_union_map_intersect_domain(
647 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
648 if (isl_union_map_is_empty(Schedule)) {
649 isl_set_free(Domain);
650 isl_union_map_free(Schedule);
651 return isl_map_from_aff(
652 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
653 }
654 auto *M = isl_map_from_union_map(Schedule);
655 M = isl_map_coalesce(M);
656 M = isl_map_gist_domain(M, Domain);
657 M = isl_map_coalesce(M);
658 return M;
659}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000660
Johannes Doerfert574182d2015-08-12 10:19:50 +0000661__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
662 return getParent()->getPwAff(E, this);
663}
664
Tobias Grosser37eb4222014-02-20 21:43:54 +0000665void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
666 assert(isl_set_is_subset(NewDomain, Domain) &&
667 "New domain is not a subset of old domain!");
668 isl_set_free(Domain);
669 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000670}
671
Tobias Grosser62139132015-08-02 16:17:41 +0000672// @brief Get the data-type of the elements accessed
673static Type *getAccessType(IRAccess &Access, Instruction *AccessInst) {
674 if (Access.isPHI())
675 return Access.getBase()->getType();
676
677 if (StoreInst *Store = dyn_cast<StoreInst>(AccessInst))
678 return Store->getValueOperand()->getType();
679 if (BranchInst *Branch = dyn_cast<BranchInst>(AccessInst))
680 return Branch->getCondition()->getType();
681 return AccessInst->getType();
682}
683
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000684void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
685 bool isApproximated) {
686 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
687 if (!AFS)
688 return;
689
690 for (auto &AccessPair : *AFS) {
691 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000692 Instruction *AccessInst = AccessPair.second;
Tobias Grosser62139132015-08-02 16:17:41 +0000693 Type *ElementType = getAccessType(Access, AccessInst);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000694
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000695 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000696 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000697
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000698 if (isApproximated && Access.isWrite())
699 Access.setMayWrite();
700
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000701 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
702 if (!MAL)
703 MAL = new MemoryAccessList();
704 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
705 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000706 }
707}
708
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000709void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000710 for (MemoryAccess *MA : *this)
711 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000712
713 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000714}
715
Tobias Grosser65b00582011-11-08 15:41:19 +0000716__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000717 isl_pw_aff *L = getPwAff(Comp.getLHS());
718 isl_pw_aff *R = getPwAff(Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000719
Tobias Grosserd2795d02011-08-18 07:51:40 +0000720 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000721 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000722 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000723 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000724 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000725 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000726 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000727 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000728 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000729 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000730 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000731 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000732 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000733 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000734 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000735 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000736 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000737 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000738 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000739 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000740 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000741 default:
742 llvm_unreachable("Non integer predicate not supported");
743 }
Tobias Grosser75805372011-04-29 06:27:02 +0000744}
745
Tobias Grossere19661e2011-10-07 08:46:57 +0000746__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000747 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000748 isl_space *Space;
749 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000750
Tobias Grossere19661e2011-10-07 08:46:57 +0000751 Space = isl_set_get_space(Domain);
752 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000753
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000754 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000755 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000756 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000757 isl_pw_aff *IV =
758 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000759
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000760 // 0 <= IV.
761 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
762 Domain = isl_set_intersect(Domain, LowerBound);
763
764 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000765 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000766 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000767 isl_pw_aff *UpperBound = getPwAff(LatchExecutions);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000768 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000769 Domain = isl_set_intersect(Domain, UpperBoundSet);
770 }
771
Tobias Grosserf5338802011-10-06 00:03:35 +0000772 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000773 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000774}
775
Tobias Grossere602a072013-05-07 07:30:56 +0000776__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
777 TempScop &tempScop,
778 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000779 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000780 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000781 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000782
Tobias Grosser75805372011-04-29 06:27:02 +0000783 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000784 if (BranchingBB != CurrentRegion->getEntry()) {
785 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000786 for (const auto &C : *Condition) {
787 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000788 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000789 }
790 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000791 BranchingBB = CurrentRegion->getEntry();
792 CurrentRegion = CurrentRegion->getParent();
793 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000794
Tobias Grossere19661e2011-10-07 08:46:57 +0000795 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000796}
797
Tobias Grossere602a072013-05-07 07:30:56 +0000798__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
799 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000800 isl_space *Space;
801 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000802 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000803
804 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
805
Tobias Grosser084d8f72012-05-29 09:29:44 +0000806 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
807
Tobias Grossere19661e2011-10-07 08:46:57 +0000808 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000809 Domain = addLoopBoundsToDomain(Domain, tempScop);
810 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000811 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000812
813 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000814}
815
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000816void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
817 int Dimension = 0;
818 isl_ctx *Ctx = Parent.getIslCtx();
819 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
820 Type *Ty = GEP->getPointerOperandType();
821 ScalarEvolution &SE = *Parent.getSE();
822
823 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
824 Dimension = 1;
825 Ty = PtrTy->getElementType();
826 }
827
828 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
829 unsigned int Operand = 1 + Dimension;
830
831 if (GEP->getNumOperands() <= Operand)
832 break;
833
834 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
835
836 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000837 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000838 AccessOffset =
839 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
840
841 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
842 isl_local_space_copy(LSpace),
843 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
844
845 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
846 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
847 OutOfBound = isl_set_params(OutOfBound);
848 isl_set *InBound = isl_set_complement(OutOfBound);
849 isl_set *Executed = isl_set_params(getDomain());
850
851 // A => B == !A or B
852 isl_set *InBoundIfExecuted =
853 isl_set_union(isl_set_complement(Executed), InBound);
854
855 Parent.addAssumption(InBoundIfExecuted);
856 }
857
858 Dimension += 1;
859 Ty = ArrayTy->getElementType();
860 }
861
862 isl_local_space_free(LSpace);
863}
864
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000865void ScopStmt::deriveAssumptions(BasicBlock *Block) {
866 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000867 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
868 deriveAssumptionsFromGEP(GEP);
869}
870
Tobias Grosser74394f02013-01-14 22:40:23 +0000871ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000872 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000873 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
874 NestLoops(Nest.size()) {
875 // Setup the induction variables.
876 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
877 NestLoops[i] = Nest[i];
878
Tobias Grosser16c44032015-07-09 07:31:45 +0000879 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000880
881 Domain = buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000882
883 BasicBlock *EntryBB = R.getEntry();
884 for (BasicBlock *Block : R.blocks()) {
885 buildAccesses(tempScop, Block, Block != EntryBB);
886 deriveAssumptions(Block);
887 }
888 checkForReductions();
889}
890
891ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000892 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000893 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
894 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000895 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +0000896 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +0000897 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000898
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000899 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000900
Tobias Grossere19661e2011-10-07 08:46:57 +0000901 Domain = buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000902 buildAccesses(tempScop, BB);
903 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000904 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000905}
906
Johannes Doerferte58a0122014-06-27 20:31:28 +0000907/// @brief Collect loads which might form a reduction chain with @p StoreMA
908///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000909/// Check if the stored value for @p StoreMA is a binary operator with one or
910/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000911/// used only once (by @p StoreMA) and its load operands are also used only
912/// once, we have found a possible reduction chain. It starts at an operand
913/// load and includes the binary operator and @p StoreMA.
914///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000915/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +0000916/// escape this block or into any other store except @p StoreMA.
917void ScopStmt::collectCandiateReductionLoads(
918 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
919 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
920 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000921 return;
922
923 // Skip if there is not one binary operator between the load and the store
924 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000925 if (!BinOp)
926 return;
927
928 // Skip if the binary operators has multiple uses
929 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000930 return;
931
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000932 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000933 if (!BinOp->isCommutative() || !BinOp->isAssociative())
934 return;
935
Johannes Doerfert9890a052014-07-01 00:32:29 +0000936 // Skip if the binary operator is outside the current SCoP
937 if (BinOp->getParent() != Store->getParent())
938 return;
939
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000940 // Skip if it is a multiplicative reduction and we disabled them
941 if (DisableMultiplicativeReductions &&
942 (BinOp->getOpcode() == Instruction::Mul ||
943 BinOp->getOpcode() == Instruction::FMul))
944 return;
945
Johannes Doerferte58a0122014-06-27 20:31:28 +0000946 // Check the binary operator operands for a candidate load
947 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
948 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
949 if (!PossibleLoad0 && !PossibleLoad1)
950 return;
951
952 // A load is only a candidate if it cannot escape (thus has only this use)
953 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000954 if (PossibleLoad0->getParent() == Store->getParent())
955 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000956 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000957 if (PossibleLoad1->getParent() == Store->getParent())
958 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000959}
960
961/// @brief Check for reductions in this ScopStmt
962///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000963/// Iterate over all store memory accesses and check for valid binary reduction
964/// like chains. For all candidates we check if they have the same base address
965/// and there are no other accesses which overlap with them. The base address
966/// check rules out impossible reductions candidates early. The overlap check,
967/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000968/// guarantees that none of the intermediate results will escape during
969/// execution of the loop nest. We basically check here that no other memory
970/// access can access the same memory as the potential reduction.
971void ScopStmt::checkForReductions() {
972 SmallVector<MemoryAccess *, 2> Loads;
973 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
974
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000975 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +0000976 // stores and collecting possible reduction loads.
977 for (MemoryAccess *StoreMA : MemAccs) {
978 if (StoreMA->isRead())
979 continue;
980
981 Loads.clear();
982 collectCandiateReductionLoads(StoreMA, Loads);
983 for (MemoryAccess *LoadMA : Loads)
984 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
985 }
986
987 // Then check each possible candidate pair.
988 for (const auto &CandidatePair : Candidates) {
989 bool Valid = true;
990 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
991 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
992
993 // Skip those with obviously unequal base addresses.
994 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
995 isl_map_free(LoadAccs);
996 isl_map_free(StoreAccs);
997 continue;
998 }
999
1000 // And check if the remaining for overlap with other memory accesses.
1001 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1002 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1003 isl_set *AllAccs = isl_map_range(AllAccsRel);
1004
1005 for (MemoryAccess *MA : MemAccs) {
1006 if (MA == CandidatePair.first || MA == CandidatePair.second)
1007 continue;
1008
1009 isl_map *AccRel =
1010 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1011 isl_set *Accs = isl_map_range(AccRel);
1012
1013 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1014 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1015 Valid = Valid && isl_set_is_empty(OverlapAccs);
1016 isl_set_free(OverlapAccs);
1017 }
1018 }
1019
1020 isl_set_free(AllAccs);
1021 if (!Valid)
1022 continue;
1023
Johannes Doerfertf6183392014-07-01 20:52:51 +00001024 const LoadInst *Load =
1025 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1026 MemoryAccess::ReductionType RT =
1027 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1028
Johannes Doerferte58a0122014-06-27 20:31:28 +00001029 // If no overlapping access was found we mark the load and store as
1030 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001031 CandidatePair.first->markAsReductionLike(RT);
1032 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001033 }
Tobias Grosser75805372011-04-29 06:27:02 +00001034}
1035
Tobias Grosser74394f02013-01-14 22:40:23 +00001036std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001037
Tobias Grosser54839312015-04-21 11:37:25 +00001038std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001039 auto *S = getSchedule();
1040 auto Str = stringFromIslObj(S);
1041 isl_map_free(S);
1042 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001043}
1044
Tobias Grosser74394f02013-01-14 22:40:23 +00001045unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001046
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001047unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001048
Tobias Grosser75805372011-04-29 06:27:02 +00001049const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1050
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001051const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001052 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001053}
1054
Tobias Grosser74394f02013-01-14 22:40:23 +00001055isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001056
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001057__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001058
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001059__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001060 return isl_set_get_space(Domain);
1061}
1062
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001063__isl_give isl_id *ScopStmt::getDomainId() const {
1064 return isl_set_get_tuple_id(Domain);
1065}
Tobias Grossercd95b772012-08-30 11:49:38 +00001066
Tobias Grosser75805372011-04-29 06:27:02 +00001067ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001068 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001069 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001070}
1071
1072void ScopStmt::print(raw_ostream &OS) const {
1073 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001074 OS.indent(12) << "Domain :=\n";
1075
1076 if (Domain) {
1077 OS.indent(16) << getDomainStr() << ";\n";
1078 } else
1079 OS.indent(16) << "n/a\n";
1080
Tobias Grosser54839312015-04-21 11:37:25 +00001081 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001082
1083 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001084 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001085 } else
1086 OS.indent(16) << "n/a\n";
1087
Tobias Grosser083d3d32014-06-28 08:59:45 +00001088 for (MemoryAccess *Access : MemAccs)
1089 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001090}
1091
1092void ScopStmt::dump() const { print(dbgs()); }
1093
1094//===----------------------------------------------------------------------===//
1095/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001096
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001097void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001098 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1099 isl_set_free(Context);
1100 Context = NewContext;
1101}
1102
Tobias Grosserabfbe632013-02-05 12:09:06 +00001103void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001104 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001105 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001106 if (ParameterIds.find(Parameter) != ParameterIds.end())
1107 continue;
1108
1109 int dimension = Parameters.size();
1110
1111 Parameters.push_back(Parameter);
1112 ParameterIds[Parameter] = dimension;
1113 }
1114}
1115
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001116__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1117 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001118
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001119 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001120 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001121
Tobias Grosser8f99c162011-11-15 11:38:55 +00001122 std::string ParameterName;
1123
1124 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1125 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001126 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001127 }
1128
1129 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001130 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001131
Tobias Grosser20532b82014-04-11 17:56:49 +00001132 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1133 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001134}
Tobias Grosser75805372011-04-29 06:27:02 +00001135
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001136void Scop::addUserContext() {
1137 if (UserContextStr.empty())
1138 return;
1139
1140 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1141 isl_space *Space = getParamSpace();
1142 if (isl_space_dim(Space, isl_dim_param) !=
1143 isl_set_dim(UserContext, isl_dim_param)) {
1144 auto SpaceStr = isl_space_to_str(Space);
1145 errs() << "Error: the context provided in -polly-context has not the same "
1146 << "number of dimensions than the computed context. Due to this "
1147 << "mismatch, the -polly-context option is ignored. Please provide "
1148 << "the context in the parameter space: " << SpaceStr << ".\n";
1149 free(SpaceStr);
1150 isl_set_free(UserContext);
1151 isl_space_free(Space);
1152 return;
1153 }
1154
1155 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1156 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1157 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1158
1159 if (strcmp(NameContext, NameUserContext) != 0) {
1160 auto SpaceStr = isl_space_to_str(Space);
1161 errs() << "Error: the name of dimension " << i
1162 << " provided in -polly-context "
1163 << "is '" << NameUserContext << "', but the name in the computed "
1164 << "context is '" << NameContext
1165 << "'. Due to this name mismatch, "
1166 << "the -polly-context option is ignored. Please provide "
1167 << "the context in the parameter space: " << SpaceStr << ".\n";
1168 free(SpaceStr);
1169 isl_set_free(UserContext);
1170 isl_space_free(Space);
1171 return;
1172 }
1173
1174 UserContext =
1175 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1176 isl_space_get_dim_id(Space, isl_dim_param, i));
1177 }
1178
1179 Context = isl_set_intersect(Context, UserContext);
1180 isl_space_free(Space);
1181}
1182
Tobias Grosser6be480c2011-11-08 15:41:13 +00001183void Scop::buildContext() {
1184 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001185 Context = isl_set_universe(isl_space_copy(Space));
1186 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001187}
1188
Tobias Grosser18daaca2012-05-22 10:47:27 +00001189void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001190 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001191 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001192
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001193 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001194
Johannes Doerferte7044942015-02-24 11:58:30 +00001195 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001196 }
1197}
1198
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001199void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001200 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001201 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001202
Tobias Grosser083d3d32014-06-28 08:59:45 +00001203 for (const auto &ParamID : ParameterIds) {
1204 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001205 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001206 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001207 }
1208
1209 // Align the parameters of all data structures to the model.
1210 Context = isl_set_align_params(Context, Space);
1211
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001212 for (ScopStmt &Stmt : *this)
1213 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001214}
1215
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001216void Scop::simplifyAssumedContext() {
1217 // The parameter constraints of the iteration domains give us a set of
1218 // constraints that need to hold for all cases where at least a single
1219 // statement iteration is executed in the whole scop. We now simplify the
1220 // assumed context under the assumption that such constraints hold and at
1221 // least a single statement iteration is executed. For cases where no
1222 // statement instances are executed, the assumptions we have taken about
1223 // the executed code do not matter and can be changed.
1224 //
1225 // WARNING: This only holds if the assumptions we have taken do not reduce
1226 // the set of statement instances that are executed. Otherwise we
1227 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001228 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001229 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001230 // performed. In such a case, modifying the run-time conditions and
1231 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001232 // to not be executed.
1233 //
1234 // Example:
1235 //
1236 // When delinearizing the following code:
1237 //
1238 // for (long i = 0; i < 100; i++)
1239 // for (long j = 0; j < m; j++)
1240 // A[i+p][j] = 1.0;
1241 //
1242 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001243 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001244 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1245 AssumedContext =
1246 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001247 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001248}
1249
Johannes Doerfertb164c792014-09-18 11:17:17 +00001250/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001251static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001252 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1253 isl_pw_multi_aff *MinPMA, *MaxPMA;
1254 isl_pw_aff *LastDimAff;
1255 isl_aff *OneAff;
1256 unsigned Pos;
1257
Johannes Doerfert9143d672014-09-27 11:02:39 +00001258 // Restrict the number of parameters involved in the access as the lexmin/
1259 // lexmax computation will take too long if this number is high.
1260 //
1261 // Experiments with a simple test case using an i7 4800MQ:
1262 //
1263 // #Parameters involved | Time (in sec)
1264 // 6 | 0.01
1265 // 7 | 0.04
1266 // 8 | 0.12
1267 // 9 | 0.40
1268 // 10 | 1.54
1269 // 11 | 6.78
1270 // 12 | 30.38
1271 //
1272 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1273 unsigned InvolvedParams = 0;
1274 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1275 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1276 InvolvedParams++;
1277
1278 if (InvolvedParams > RunTimeChecksMaxParameters) {
1279 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001280 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001281 }
1282 }
1283
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001284 Set = isl_set_remove_divs(Set);
1285
Johannes Doerfertb164c792014-09-18 11:17:17 +00001286 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1287 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1288
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001289 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1290 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1291
Johannes Doerfertb164c792014-09-18 11:17:17 +00001292 // Adjust the last dimension of the maximal access by one as we want to
1293 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1294 // we test during code generation might now point after the end of the
1295 // allocated array but we will never dereference it anyway.
1296 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1297 "Assumed at least one output dimension");
1298 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1299 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1300 OneAff = isl_aff_zero_on_domain(
1301 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1302 OneAff = isl_aff_add_constant_si(OneAff, 1);
1303 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1304 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1305
1306 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1307
1308 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001309 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001310}
1311
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001312static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1313 isl_set *Domain = MA->getStatement()->getDomain();
1314 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1315 return isl_set_reset_tuple_id(Domain);
1316}
1317
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001318/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1319static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001320 __isl_take isl_union_set *Domains,
1321 __isl_take isl_set *AssumedContext,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001322 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001323
1324 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1325 isl_union_set *Locations = isl_union_map_range(Accesses);
1326 Locations = isl_union_set_intersect_params(Locations, AssumedContext);
1327 Locations = isl_union_set_coalesce(Locations);
1328 Locations = isl_union_set_detect_equalities(Locations);
1329 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001330 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001331 isl_union_set_free(Locations);
1332 return Valid;
1333}
1334
Johannes Doerfert9143d672014-09-27 11:02:39 +00001335bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001336 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001337 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001338 // for all memory accesses inside the SCoP.
1339 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001340 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001341 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001342 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001343 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001344 // if their access domains intersect, otherwise they are in different
1345 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001346 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001347 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001348 // and maximal accesses to each array of a group in read only and non
1349 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001350 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1351
1352 AliasSetTracker AST(AA);
1353
1354 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001355 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001356 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001357
1358 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001359 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001360 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1361 isl_set_free(StmtDomain);
1362 if (StmtDomainEmpty)
1363 continue;
1364
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001365 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001366 if (MA->isScalar())
1367 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001368 if (!MA->isRead())
1369 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001370 Instruction *Acc = MA->getAccessInstruction();
1371 PtrToAcc[getPointerOperand(*Acc)] = MA;
1372 AST.add(Acc);
1373 }
1374 }
1375
1376 SmallVector<AliasGroupTy, 4> AliasGroups;
1377 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001378 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001379 continue;
1380 AliasGroupTy AG;
1381 for (auto PR : AS)
1382 AG.push_back(PtrToAcc[PR.getValue()]);
1383 assert(AG.size() > 1 &&
1384 "Alias groups should contain at least two accesses");
1385 AliasGroups.push_back(std::move(AG));
1386 }
1387
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001388 // Split the alias groups based on their domain.
1389 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1390 AliasGroupTy NewAG;
1391 AliasGroupTy &AG = AliasGroups[u];
1392 AliasGroupTy::iterator AGI = AG.begin();
1393 isl_set *AGDomain = getAccessDomain(*AGI);
1394 while (AGI != AG.end()) {
1395 MemoryAccess *MA = *AGI;
1396 isl_set *MADomain = getAccessDomain(MA);
1397 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1398 NewAG.push_back(MA);
1399 AGI = AG.erase(AGI);
1400 isl_set_free(MADomain);
1401 } else {
1402 AGDomain = isl_set_union(AGDomain, MADomain);
1403 AGI++;
1404 }
1405 }
1406 if (NewAG.size() > 1)
1407 AliasGroups.push_back(std::move(NewAG));
1408 isl_set_free(AGDomain);
1409 }
1410
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001411 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001412 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1413 for (AliasGroupTy &AG : AliasGroups) {
1414 NonReadOnlyBaseValues.clear();
1415 ReadOnlyPairs.clear();
1416
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001417 if (AG.size() < 2) {
1418 AG.clear();
1419 continue;
1420 }
1421
Johannes Doerfert13771732014-10-01 12:40:46 +00001422 for (auto II = AG.begin(); II != AG.end();) {
1423 Value *BaseAddr = (*II)->getBaseAddr();
1424 if (HasWriteAccess.count(BaseAddr)) {
1425 NonReadOnlyBaseValues.insert(BaseAddr);
1426 II++;
1427 } else {
1428 ReadOnlyPairs[BaseAddr].insert(*II);
1429 II = AG.erase(II);
1430 }
1431 }
1432
1433 // If we don't have read only pointers check if there are at least two
1434 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001435 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001436 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001437 continue;
1438 }
1439
1440 // If we don't have non read only pointers clear the alias group.
1441 if (NonReadOnlyBaseValues.empty()) {
1442 AG.clear();
1443 continue;
1444 }
1445
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001446 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001447 MinMaxAliasGroups.emplace_back();
1448 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1449 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1450 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1451 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001452
1453 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001454
1455 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001456 for (MemoryAccess *MA : AG)
1457 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001458
Tobias Grosserbb853c22015-07-25 12:31:03 +00001459 bool Valid = calculateMinMaxAccess(
1460 Accesses, getDomains(), getAssumedContext(), MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001461
1462 // Bail out if the number of values we need to compare is too large.
1463 // This is important as the number of comparisions grows quadratically with
1464 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001465 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1466 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001467 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001468
1469 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001470 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001471 Accesses = isl_union_map_empty(getParamSpace());
1472
1473 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1474 for (MemoryAccess *MA : ReadOnlyPair.second)
1475 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1476
Tobias Grosserbb853c22015-07-25 12:31:03 +00001477 Valid = calculateMinMaxAccess(Accesses, getDomains(), getAssumedContext(),
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001478 MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001479
1480 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001481 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001482 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001483
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001484 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001485}
1486
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001487static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1488 ScopDetection &SD) {
1489
1490 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1491
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001492 unsigned MinLD = INT_MAX, MaxLD = 0;
1493 for (BasicBlock *BB : R.blocks()) {
1494 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001495 if (!R.contains(L))
1496 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001497 if (BoxedLoops && BoxedLoops->count(L))
1498 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001499 unsigned LD = L->getLoopDepth();
1500 MinLD = std::min(MinLD, LD);
1501 MaxLD = std::max(MaxLD, LD);
1502 }
1503 }
1504
1505 // Handle the case that there is no loop in the SCoP first.
1506 if (MaxLD == 0)
1507 return 1;
1508
1509 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1510 assert(MaxLD >= MinLD &&
1511 "Maximal loop depth was smaller than mininaml loop depth?");
1512 return MaxLD - MinLD + 1;
1513}
1514
Michael Kruse471a5e32015-07-30 19:27:04 +00001515Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, isl_ctx *Context,
1516 unsigned MaxLoopDepth)
1517 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert574182d2015-08-12 10:19:50 +00001518 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001519
Michael Kruse471a5e32015-07-30 19:27:04 +00001520void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI,
1521 ScopDetection &SD) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001522 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001523
Tobias Grosserabfbe632013-02-05 12:09:06 +00001524 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001525
Tobias Grosser54839312015-04-21 11:37:25 +00001526 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001527 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00001528 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00001529 if (!Schedule)
1530 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00001531
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001532 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001533 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001534 addUserContext();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001535 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001536
Tobias Grosser75805372011-04-29 06:27:02 +00001537 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1538}
1539
Michael Kruse471a5e32015-07-30 19:27:04 +00001540Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
1541 ScalarEvolution &SE, ScopDetection &SD,
1542 isl_ctx *ctx) {
1543 auto &R = TempScop.getMaxRegion();
1544 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
1545 auto S = new Scop(R, SE, ctx, MaxLoopDepth);
1546 S->initFromTempScop(TempScop, LI, SD);
1547 return S;
1548}
1549
Tobias Grosser75805372011-04-29 06:27:02 +00001550Scop::~Scop() {
1551 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001552 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00001553 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001554
Johannes Doerfertb164c792014-09-18 11:17:17 +00001555 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001556 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001557 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001558 isl_pw_multi_aff_free(MMA.first);
1559 isl_pw_multi_aff_free(MMA.second);
1560 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001561 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001562 isl_pw_multi_aff_free(MMA.first);
1563 isl_pw_multi_aff_free(MMA.second);
1564 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001565 }
Tobias Grosser75805372011-04-29 06:27:02 +00001566}
1567
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001568const ScopArrayInfo *
1569Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00001570 const SmallVector<const SCEV *, 4> &Sizes,
1571 bool IsPHI) {
1572 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001573 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001574 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
1575 this));
Tobias Grosserab671442015-05-23 05:58:27 +00001576 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001577}
1578
Tobias Grosser92245222015-07-28 14:53:44 +00001579const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
1580 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001581 assert(SAI && "No ScopArrayInfo available for this base pointer");
1582 return SAI;
1583}
1584
Tobias Grosser74394f02013-01-14 22:40:23 +00001585std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001586std::string Scop::getAssumedContextStr() const {
1587 return stringFromIslObj(AssumedContext);
1588}
Tobias Grosser75805372011-04-29 06:27:02 +00001589
1590std::string Scop::getNameStr() const {
1591 std::string ExitName, EntryName;
1592 raw_string_ostream ExitStr(ExitName);
1593 raw_string_ostream EntryStr(EntryName);
1594
Tobias Grosserf240b482014-01-09 10:42:15 +00001595 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001596 EntryStr.str();
1597
1598 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001599 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001600 ExitStr.str();
1601 } else
1602 ExitName = "FunctionExit";
1603
1604 return EntryName + "---" + ExitName;
1605}
1606
Tobias Grosser74394f02013-01-14 22:40:23 +00001607__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001608__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001609 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001610}
1611
Tobias Grossere86109f2013-10-29 21:05:49 +00001612__isl_give isl_set *Scop::getAssumedContext() const {
1613 return isl_set_copy(AssumedContext);
1614}
1615
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001616void Scop::addAssumption(__isl_take isl_set *Set) {
1617 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001618 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001619}
1620
Tobias Grosser75805372011-04-29 06:27:02 +00001621void Scop::printContext(raw_ostream &OS) const {
1622 OS << "Context:\n";
1623
1624 if (!Context) {
1625 OS.indent(4) << "n/a\n\n";
1626 return;
1627 }
1628
1629 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001630
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001631 OS.indent(4) << "Assumed Context:\n";
1632 if (!AssumedContext) {
1633 OS.indent(4) << "n/a\n\n";
1634 return;
1635 }
1636
1637 OS.indent(4) << getAssumedContextStr() << "\n";
1638
Tobias Grosser083d3d32014-06-28 08:59:45 +00001639 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001640 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001641 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1642 }
Tobias Grosser75805372011-04-29 06:27:02 +00001643}
1644
Johannes Doerfertb164c792014-09-18 11:17:17 +00001645void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001646 int noOfGroups = 0;
1647 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001648 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001649 noOfGroups += 1;
1650 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001651 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001652 }
1653
Tobias Grosserbb853c22015-07-25 12:31:03 +00001654 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00001655 if (MinMaxAliasGroups.empty()) {
1656 OS.indent(8) << "n/a\n";
1657 return;
1658 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001659
Tobias Grosserbb853c22015-07-25 12:31:03 +00001660 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001661
1662 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001663 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001664 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001665 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001666 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1667 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001668 }
1669 OS << " ]]\n";
1670 }
1671
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001672 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001673 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00001674 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001675 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001676 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1677 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001678 }
1679 OS << " ]]\n";
1680 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001681 }
1682}
1683
Tobias Grosser75805372011-04-29 06:27:02 +00001684void Scop::printStatements(raw_ostream &OS) const {
1685 OS << "Statements {\n";
1686
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001687 for (const ScopStmt &Stmt : *this)
1688 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001689
1690 OS.indent(4) << "}\n";
1691}
1692
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001693void Scop::printArrayInfo(raw_ostream &OS) const {
1694 OS << "Arrays {\n";
1695
Tobias Grosserab671442015-05-23 05:58:27 +00001696 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001697 Array.second->print(OS);
1698
1699 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001700
1701 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
1702
1703 for (auto &Array : arrays())
1704 Array.second->print(OS, /* SizeAsPwAff */ true);
1705
1706 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001707}
1708
Tobias Grosser75805372011-04-29 06:27:02 +00001709void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001710 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1711 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001712 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001713 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001714 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001715 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001716 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001717 printStatements(OS.indent(4));
1718}
1719
1720void Scop::dump() const { print(dbgs()); }
1721
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001722isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001723
Johannes Doerfert574182d2015-08-12 10:19:50 +00001724__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, ScopStmt *Stmt) {
1725 return Affinator.getPwAff(E, Stmt);
1726}
1727
Tobias Grosser808cd692015-07-14 09:33:13 +00001728__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001729 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001730
Tobias Grosser808cd692015-07-14 09:33:13 +00001731 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001732 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001733
1734 return Domain;
1735}
1736
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001737__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001738 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001739
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001740 for (ScopStmt &Stmt : *this) {
1741 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001742 if (!MA->isMustWrite())
1743 continue;
1744
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001745 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001746 isl_map *AccessDomain = MA->getAccessRelation();
1747 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1748 Write = isl_union_map_add_map(Write, AccessDomain);
1749 }
1750 }
1751 return isl_union_map_coalesce(Write);
1752}
1753
1754__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001755 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001756
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001757 for (ScopStmt &Stmt : *this) {
1758 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001759 if (!MA->isMayWrite())
1760 continue;
1761
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001762 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001763 isl_map *AccessDomain = MA->getAccessRelation();
1764 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1765 Write = isl_union_map_add_map(Write, AccessDomain);
1766 }
1767 }
1768 return isl_union_map_coalesce(Write);
1769}
1770
Tobias Grosser37eb4222014-02-20 21:43:54 +00001771__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001772 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001773
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001774 for (ScopStmt &Stmt : *this) {
1775 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001776 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001777 continue;
1778
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001779 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001780 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001781 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1782 Write = isl_union_map_add_map(Write, AccessDomain);
1783 }
1784 }
1785 return isl_union_map_coalesce(Write);
1786}
1787
1788__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001789 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001790
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001791 for (ScopStmt &Stmt : *this) {
1792 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001793 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001794 continue;
1795
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001796 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001797 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001798
1799 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1800 Read = isl_union_map_add_map(Read, AccessDomain);
1801 }
1802 }
1803 return isl_union_map_coalesce(Read);
1804}
1805
Tobias Grosser808cd692015-07-14 09:33:13 +00001806__isl_give isl_union_map *Scop::getSchedule() const {
1807 auto Tree = getScheduleTree();
1808 auto S = isl_schedule_get_map(Tree);
1809 isl_schedule_free(Tree);
1810 return S;
1811}
Tobias Grosser37eb4222014-02-20 21:43:54 +00001812
Tobias Grosser808cd692015-07-14 09:33:13 +00001813__isl_give isl_schedule *Scop::getScheduleTree() const {
1814 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
1815 getDomains());
1816}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001817
Tobias Grosser808cd692015-07-14 09:33:13 +00001818void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
1819 auto *S = isl_schedule_from_domain(getDomains());
1820 S = isl_schedule_insert_partial_schedule(
1821 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
1822 isl_schedule_free(Schedule);
1823 Schedule = S;
1824}
1825
1826void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
1827 isl_schedule_free(Schedule);
1828 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00001829}
1830
1831bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1832 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001833 for (ScopStmt &Stmt : *this) {
1834 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001835 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1836 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1837
1838 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1839 isl_union_set_free(StmtDomain);
1840 isl_union_set_free(NewStmtDomain);
1841 continue;
1842 }
1843
1844 Changed = true;
1845
1846 isl_union_set_free(StmtDomain);
1847 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1848
1849 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001850 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001851 isl_union_set_free(NewStmtDomain);
1852 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001853 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001854 }
1855 isl_union_set_free(Domain);
1856 return Changed;
1857}
1858
Tobias Grosser75805372011-04-29 06:27:02 +00001859ScalarEvolution *Scop::getSE() const { return SE; }
1860
1861bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1862 if (tempScop.getAccessFunctions(BB))
1863 return false;
1864
1865 return true;
1866}
1867
Tobias Grosser808cd692015-07-14 09:33:13 +00001868struct MapToDimensionDataTy {
1869 int N;
1870 isl_union_pw_multi_aff *Res;
1871};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001872
Tobias Grosser808cd692015-07-14 09:33:13 +00001873// @brief Create a function that maps the elements of 'Set' to its N-th
1874// dimension.
1875//
1876// The result is added to 'User->Res'.
1877//
1878// @param Set The input set.
1879// @param N The dimension to map to.
1880//
1881// @returns Zero if no error occurred, non-zero otherwise.
1882static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
1883 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
1884 int Dim;
1885 isl_space *Space;
1886 isl_pw_multi_aff *PMA;
1887
1888 Dim = isl_set_dim(Set, isl_dim_set);
1889 Space = isl_set_get_space(Set);
1890 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
1891 Dim - Data->N);
1892 if (Data->N > 1)
1893 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
1894 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
1895
1896 isl_set_free(Set);
1897
1898 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001899}
1900
Tobias Grosser808cd692015-07-14 09:33:13 +00001901// @brief Create a function that maps the elements of Domain to their Nth
1902// dimension.
1903//
1904// @param Domain The set of elements to map.
1905// @param N The dimension to map to.
1906static __isl_give isl_multi_union_pw_aff *
1907mapToDimension(__isl_take isl_union_set *Domain, int N) {
1908 struct MapToDimensionDataTy Data;
1909 isl_space *Space;
1910
1911 Space = isl_union_set_get_space(Domain);
1912 Data.N = N;
1913 Data.Res = isl_union_pw_multi_aff_empty(Space);
1914 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
1915 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
1916
1917 isl_union_set_free(Domain);
1918 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
1919}
1920
1921ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1922 const Region &CurRegion,
1923 SmallVectorImpl<Loop *> &NestLoops) {
1924 ScopStmt *Stmt;
1925 if (BB) {
1926 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
1927 Stmt = &Stmts.back();
1928 StmtMap[BB] = Stmt;
1929 } else {
1930 assert(R && "Either basic block or a region expected.");
1931 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
1932 Stmt = &Stmts.back();
1933 for (BasicBlock *BB : R->blocks())
1934 StmtMap[BB] = Stmt;
1935 }
1936 return Stmt;
1937}
1938
Michael Kruse046dde42015-08-10 13:01:57 +00001939__isl_give isl_schedule *
1940Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
1941 const Region &CurRegion,
1942 SmallVectorImpl<Loop *> &NestLoops) {
1943 if (isTrivialBB(BB, tempScop))
1944 return nullptr;
1945
1946 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
1947 auto *Domain = Stmt->getDomain();
1948 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
1949}
1950
Tobias Grosser808cd692015-07-14 09:33:13 +00001951__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
1952 const Region &CurRegion,
1953 SmallVectorImpl<Loop *> &NestLoops,
1954 LoopInfo &LI, ScopDetection &SD) {
1955 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
1956 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
1957 tempScop, CurRegion, NestLoops);
1958 auto *Domain = Stmt->getDomain();
1959 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
1960 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001961
Tobias Grosser75805372011-04-29 06:27:02 +00001962 Loop *L = castToLoop(CurRegion, LI);
1963
1964 if (L)
1965 NestLoops.push_back(L);
1966
1967 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00001968 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001969
1970 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001971 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00001972 I != E; ++I) {
1973 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001974 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00001975 StmtSchedule =
1976 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001977 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00001978 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
1979 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00001980 }
Michael Kruse046dde42015-08-10 13:01:57 +00001981 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00001982 }
Tobias Grosser75805372011-04-29 06:27:02 +00001983
Tobias Grosser808cd692015-07-14 09:33:13 +00001984 if (!L)
1985 return Schedule;
1986
1987 auto *Domain = isl_schedule_get_domain(Schedule);
1988 if (!isl_union_set_is_empty(Domain)) {
1989 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
1990 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
1991 }
1992 isl_union_set_free(Domain);
1993
Tobias Grosser75805372011-04-29 06:27:02 +00001994 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00001995 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00001996}
1997
Johannes Doerfert7c494212014-10-31 23:13:39 +00001998ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00001999 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002000 if (StmtMapIt == StmtMap.end())
2001 return nullptr;
2002 return StmtMapIt->second;
2003}
2004
Tobias Grosser75805372011-04-29 06:27:02 +00002005//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002006ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2007 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002008 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002009}
2010
2011ScopInfo::~ScopInfo() {
2012 clear();
2013 isl_ctx_free(ctx);
2014}
2015
Tobias Grosser75805372011-04-29 06:27:02 +00002016void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002017 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002018 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00002019 AU.addRequired<ScalarEvolution>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002020 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002021 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002022 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002023 AU.setPreservesAll();
2024}
2025
2026bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002027 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002028 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002029 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002030 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
2031
Michael Kruse82a1c7d2015-08-14 20:10:27 +00002032 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop();
Tobias Grosser75805372011-04-29 06:27:02 +00002033
2034 // This region is no Scop.
2035 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002036 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002037 return false;
2038 }
2039
Michael Kruse471a5e32015-07-30 19:27:04 +00002040 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002041
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002042 DEBUG(scop->print(dbgs()));
2043
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002044 if (!PollyUseRuntimeAliasChecks) {
2045 // Statistics.
2046 ++ScopFound;
2047 if (scop->getMaxLoopDepth() > 0)
2048 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002049 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002050 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002051
Johannes Doerfert9143d672014-09-27 11:02:39 +00002052 // If a problem occurs while building the alias groups we need to delete
2053 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002054 if (scop->buildAliasGroups(AA)) {
2055 // Statistics.
2056 ++ScopFound;
2057 if (scop->getMaxLoopDepth() > 0)
2058 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002059 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002060 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002061
2062 DEBUG(dbgs()
2063 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002064 << " could not be created as the number of parameters involved is too "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002065 "high. The SCoP will be "
2066 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002067 "maximal number of parameters but be advised that the compile time "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002068 "might increase exponentially.\n\n");
2069
2070 delete scop;
2071 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002072 return false;
2073}
2074
2075char ScopInfo::ID = 0;
2076
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002077Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2078
Tobias Grosser73600b82011-10-08 00:30:40 +00002079INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2080 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002081 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002082INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002083INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002084INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002085INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002086INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002087INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002088INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2089 "Polly - Create polyhedral description of Scops", false,
2090 false)