blob: 2678138205c30ec226966f4e7877a31e1f4aaffc [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));
78
Michael Kruse046dde42015-08-10 13:01:57 +000079// Create a sequence of two schedules. Either argument may be null and is
80// interpreted as the empty schedule. Can also return null if both schedules are
81// empty.
82static __isl_give isl_schedule *
83combineInSequence(__isl_take isl_schedule *Prev,
84 __isl_take isl_schedule *Succ) {
85 if (!Prev)
86 return Succ;
87 if (!Succ)
88 return Prev;
89
90 return isl_schedule_sequence(Prev, Succ);
91}
92
Johannes Doerferte7044942015-02-24 11:58:30 +000093static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
94 const ConstantRange &Range,
95 int dim,
96 enum isl_dim_type type) {
97 isl_val *V;
98 isl_ctx *ctx = isl_set_get_ctx(S);
99
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000100 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
101 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000102 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000103 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
104
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000105 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000106 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000107 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000108 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000109 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
110
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000111 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000112 return isl_set_union(SLB, SUB);
113 else
114 return isl_set_intersect(SLB, SUB);
115}
116
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000117ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser92245222015-07-28 14:53:44 +0000118 const SmallVector<const SCEV *, 4> &DimensionSizes,
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000119 bool IsPHI, Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000120 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000121 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
122 std::string BasePtrName =
123 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000124 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000125 for (const SCEV *Expr : DimensionSizes) {
126 isl_pw_aff *Size = S->getPwAff(Expr);
127 DimensionSizesPw.push_back(Size);
128 }
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000129}
130
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000131ScopArrayInfo::~ScopArrayInfo() {
132 isl_id_free(Id);
133 for (isl_pw_aff *Size : DimensionSizesPw)
134 isl_pw_aff_free(Size);
135}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000136
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000137std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
138
139int ScopArrayInfo::getElemSizeInBytes() const {
140 return ElementType->getPrimitiveSizeInBits() / 8;
141}
142
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000143isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
144
145void ScopArrayInfo::dump() const { print(errs()); }
146
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000147void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000148 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000149 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
150 OS << "[";
151
152 if (SizeAsPwAff)
153 OS << " " << DimensionSizesPw[u] << " ";
154 else
155 OS << *DimensionSizes[u];
156
157 OS << "]";
158 }
159
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000160 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000161}
162
163const ScopArrayInfo *
164ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
165 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
166 assert(Id && "Output dimension didn't have an ID");
167 return getFromId(Id);
168}
169
170const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
171 void *User = isl_id_get_user(Id);
172 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
173 isl_id_free(Id);
174 return SAI;
175}
176
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000177const std::string
178MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
179 switch (RT) {
180 case MemoryAccess::RT_NONE:
181 llvm_unreachable("Requested a reduction operator string for a memory "
182 "access which isn't a reduction");
183 case MemoryAccess::RT_ADD:
184 return "+";
185 case MemoryAccess::RT_MUL:
186 return "*";
187 case MemoryAccess::RT_BOR:
188 return "|";
189 case MemoryAccess::RT_BXOR:
190 return "^";
191 case MemoryAccess::RT_BAND:
192 return "&";
193 }
194 llvm_unreachable("Unknown reduction type");
195 return "";
196}
197
Johannes Doerfertf6183392014-07-01 20:52:51 +0000198/// @brief Return the reduction type for a given binary operator
199static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
200 const Instruction *Load) {
201 if (!BinOp)
202 return MemoryAccess::RT_NONE;
203 switch (BinOp->getOpcode()) {
204 case Instruction::FAdd:
205 if (!BinOp->hasUnsafeAlgebra())
206 return MemoryAccess::RT_NONE;
207 // Fall through
208 case Instruction::Add:
209 return MemoryAccess::RT_ADD;
210 case Instruction::Or:
211 return MemoryAccess::RT_BOR;
212 case Instruction::Xor:
213 return MemoryAccess::RT_BXOR;
214 case Instruction::And:
215 return MemoryAccess::RT_BAND;
216 case Instruction::FMul:
217 if (!BinOp->hasUnsafeAlgebra())
218 return MemoryAccess::RT_NONE;
219 // Fall through
220 case Instruction::Mul:
221 if (DisableMultiplicativeReductions)
222 return MemoryAccess::RT_NONE;
223 return MemoryAccess::RT_MUL;
224 default:
225 return MemoryAccess::RT_NONE;
226 }
227}
Tobias Grosser75805372011-04-29 06:27:02 +0000228//===----------------------------------------------------------------------===//
229
230MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000231 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000232 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000233 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000234}
235
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000236static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
237 switch (Access.getType()) {
238 case IRAccess::READ:
239 return MemoryAccess::READ;
240 case IRAccess::MUST_WRITE:
241 return MemoryAccess::MUST_WRITE;
242 case IRAccess::MAY_WRITE:
243 return MemoryAccess::MAY_WRITE;
244 }
245 llvm_unreachable("Unknown IRAccess type!");
246}
247
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000248const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
249 isl_id *ArrayId = getArrayId();
250 void *User = isl_id_get_user(ArrayId);
251 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
252 isl_id_free(ArrayId);
253 return SAI;
254}
255
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000256__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000257 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
258}
259
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000260__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
261 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000262 isl_map *Schedule, *ScheduledAccRel;
263 isl_union_set *UDomain;
264
265 UDomain = isl_union_set_from_set(getStatement()->getDomain());
266 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
267 Schedule = isl_map_from_union_map(USchedule);
268 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
269 return isl_pw_multi_aff_from_map(ScheduledAccRel);
270}
271
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000272__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000273 return isl_map_copy(AccessRelation);
274}
275
Johannes Doerferta99130f2014-10-13 12:58:03 +0000276std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000277 return stringFromIslObj(AccessRelation);
278}
279
Johannes Doerferta99130f2014-10-13 12:58:03 +0000280__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000281 return isl_map_get_space(AccessRelation);
282}
283
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000284__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000285 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000286}
287
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000288__isl_give isl_basic_map *
289MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000290 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000291 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000292
Tobias Grosser084d8f72012-05-29 09:29:44 +0000293 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000294 isl_basic_set_universe(Statement->getDomainSpace()),
295 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000296}
297
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000298// Formalize no out-of-bound access assumption
299//
300// When delinearizing array accesses we optimistically assume that the
301// delinearized accesses do not access out of bound locations (the subscript
302// expression of each array evaluates for each statement instance that is
303// executed to a value that is larger than zero and strictly smaller than the
304// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000305// dimension for which we do not need to assume any upper bound. At this point
306// we formalize this assumption to ensure that at code generation time the
307// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000308//
309// To find the set of constraints necessary to avoid out of bound accesses, we
310// first build the set of data locations that are not within array bounds. We
311// then apply the reverse access relation to obtain the set of iterations that
312// may contain invalid accesses and reduce this set of iterations to the ones
313// that are actually executed by intersecting them with the domain of the
314// statement. If we now project out all loop dimensions, we obtain a set of
315// parameters that may cause statement instances to be executed that may
316// possibly yield out of bound memory accesses. The complement of these
317// constraints is the set of constraints that needs to be assumed to ensure such
318// statement instances are never executed.
319void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000320 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000321 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000322 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000323 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
324 isl_pw_aff *Var =
325 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
326 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
327
328 isl_set *DimOutside;
329
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000330 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000331 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000332
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000333 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
334 Statement->getNumIterators());
335 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
336 isl_space_dim(Space, isl_dim_set));
337 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
338 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000339
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000340 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000341
342 Outside = isl_set_union(Outside, DimOutside);
343 }
344
345 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
346 Outside = isl_set_intersect(Outside, Statement->getDomain());
347 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000348
349 // Remove divs to avoid the construction of overly complicated assumptions.
350 // Doing so increases the set of parameter combinations that are assumed to
351 // not appear. This is always save, but may make the resulting run-time check
352 // bail out more often than strictly necessary.
353 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000354 Outside = isl_set_complement(Outside);
355 Statement->getParent()->addAssumption(Outside);
356 isl_space_free(Space);
357}
358
Johannes Doerferte7044942015-02-24 11:58:30 +0000359void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
360 ScalarEvolution *SE = Statement->getParent()->getSE();
361
362 Value *Ptr = getPointerOperand(*getAccessInstruction());
363 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
364 return;
365
366 auto *PtrSCEV = SE->getSCEV(Ptr);
367 if (isa<SCEVCouldNotCompute>(PtrSCEV))
368 return;
369
370 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
371 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
372 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
373
374 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
375 if (Range.isFullSet())
376 return;
377
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000378 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000379 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000380 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
381 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
382
383 auto Min = LB.sdiv(APInt(BW, ElementSize));
384 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000385
386 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
387 AccessRange =
388 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
389 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
390}
391
Tobias Grosser619190d2015-03-30 17:22:28 +0000392__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
393 __isl_take isl_map *AccessRelation,
394 ScopStmt *Statement) {
395 int Size = Access.Subscripts.size();
396
397 for (int i = Size - 2; i >= 0; --i) {
398 isl_space *Space;
399 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000400 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000401
402 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
403 isl_pw_aff_free(DimSize);
404 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
405
406 Space = isl_map_get_space(AccessRelation);
407 Space = isl_space_map_from_set(isl_space_range(Space));
408 Space = isl_space_align_params(Space, SpaceSize);
409
410 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
411 isl_id_free(ParamId);
412
413 MapOne = isl_map_universe(isl_space_copy(Space));
414 for (int j = 0; j < Size; ++j)
415 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
416 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
417
418 MapTwo = isl_map_universe(isl_space_copy(Space));
419 for (int j = 0; j < Size; ++j)
420 if (j < i || j > i + 1)
421 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
422
423 isl_local_space *LS = isl_local_space_from_space(Space);
424 isl_constraint *C;
425 C = isl_equality_alloc(isl_local_space_copy(LS));
426 C = isl_constraint_set_constant_si(C, -1);
427 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
428 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
429 MapTwo = isl_map_add_constraint(MapTwo, C);
430 C = isl_equality_alloc(LS);
431 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
432 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
433 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
434 MapTwo = isl_map_add_constraint(MapTwo, C);
435 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
436
437 MapOne = isl_map_union(MapOne, MapTwo);
438 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
439 }
440 return AccessRelation;
441}
442
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000443MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000444 ScopStmt *Statement, const ScopArrayInfo *SAI,
445 int Identifier)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000446 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000447 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000448
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000449 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000450 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000451 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000452
453 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000454
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000455 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000456 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000457
Tobias Grossera1879642011-12-20 10:43:14 +0000458 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000459 // We overapproximate non-affine accesses with a possible access to the
460 // whole array. For read accesses it does not make a difference, if an
461 // access must or may happen. However, for write accesses it is important to
462 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000463 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000464 AccessRelation =
465 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000466
467 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000468 return;
469 }
470
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000471 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000472 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000473
Tobias Grosser79baa212014-04-10 08:38:02 +0000474 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000475 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000476
Sebastian Pop422e33f2014-06-03 18:16:31 +0000477 if (Size == 1) {
478 // For the non delinearized arrays, divide the access function of the last
479 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000480 //
481 // A stride one array access in C expressed as A[i] is expressed in
482 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
483 // two subsequent values of 'i' index two values that are stored next to
484 // each other in memory. By this division we make this characteristic
485 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000486 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000487 Affine = isl_pw_aff_scale_down_val(Affine, v);
488 }
489
490 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
491
Tobias Grosser79baa212014-04-10 08:38:02 +0000492 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000493 }
494
Tobias Grosser619190d2015-03-30 17:22:28 +0000495 AccessRelation = foldAccess(Access, AccessRelation, Statement);
496
Tobias Grosser79baa212014-04-10 08:38:02 +0000497 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000498 AccessRelation = isl_map_set_tuple_id(
499 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000500 AccessRelation =
501 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
502
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000503 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000504 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000505 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000506}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000507
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000508void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000509 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000510 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000511}
512
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000513const std::string MemoryAccess::getReductionOperatorStr() const {
514 return MemoryAccess::getReductionOperatorStr(getReductionType());
515}
516
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000517__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
518
Johannes Doerfertf6183392014-07-01 20:52:51 +0000519raw_ostream &polly::operator<<(raw_ostream &OS,
520 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000521 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000522 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000523 else
524 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000525 return OS;
526}
527
Tobias Grosser75805372011-04-29 06:27:02 +0000528void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000529 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000530 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000531 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000532 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000533 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000534 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000535 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000536 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000537 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000538 break;
539 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000540 OS << "[Reduction Type: " << getReductionType() << "] ";
541 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000542 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000543}
544
Tobias Grosser74394f02013-01-14 22:40:23 +0000545void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000546
547// Create a map in the size of the provided set domain, that maps from the
548// one element of the provided set domain to another element of the provided
549// set domain.
550// The mapping is limited to all points that are equal in all but the last
551// dimension and for which the last dimension of the input is strict smaller
552// than the last dimension of the output.
553//
554// getEqualAndLarger(set[i0, i1, ..., iX]):
555//
556// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
557// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
558//
Tobias Grosserf5338802011-10-06 00:03:35 +0000559static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000560 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000561 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000562 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000563
564 // Set all but the last dimension to be equal for the input and output
565 //
566 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
567 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000568 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000569 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000570
571 // Set the last dimension of the input to be strict smaller than the
572 // last dimension of the output.
573 //
574 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000575 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
576 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000577 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000578}
579
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000580__isl_give isl_set *
581MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000582 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000583 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000584 isl_space *Space = isl_space_range(isl_map_get_space(S));
585 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000586
Sebastian Popa00a0292012-12-18 07:46:06 +0000587 S = isl_map_reverse(S);
588 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000589
Sebastian Popa00a0292012-12-18 07:46:06 +0000590 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
591 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
592 NextScatt = isl_map_apply_domain(NextScatt, S);
593 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000594
Sebastian Popa00a0292012-12-18 07:46:06 +0000595 isl_set *Deltas = isl_map_deltas(NextScatt);
596 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000597}
598
Sebastian Popa00a0292012-12-18 07:46:06 +0000599bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000600 int StrideWidth) const {
601 isl_set *Stride, *StrideX;
602 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000603
Sebastian Popa00a0292012-12-18 07:46:06 +0000604 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000605 StrideX = isl_set_universe(isl_set_get_space(Stride));
606 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
607 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000608
Tobias Grosser28dd4862012-01-24 16:42:16 +0000609 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000610 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000611
Tobias Grosser28dd4862012-01-24 16:42:16 +0000612 return IsStrideX;
613}
614
Sebastian Popa00a0292012-12-18 07:46:06 +0000615bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
616 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000617}
618
Tobias Grosser79baa212014-04-10 08:38:02 +0000619bool MemoryAccess::isScalar() const {
620 return isl_map_n_out(AccessRelation) == 0;
621}
622
Sebastian Popa00a0292012-12-18 07:46:06 +0000623bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
624 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000625}
626
Tobias Grosser5d453812011-10-06 00:04:11 +0000627void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000628 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000629 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000630}
Tobias Grosser75805372011-04-29 06:27:02 +0000631
632//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000633
Tobias Grosser808cd692015-07-14 09:33:13 +0000634isl_map *ScopStmt::getSchedule() const {
635 isl_set *Domain = getDomain();
636 if (isl_set_is_empty(Domain)) {
637 isl_set_free(Domain);
638 return isl_map_from_aff(
639 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
640 }
641 auto *Schedule = getParent()->getSchedule();
642 Schedule = isl_union_map_intersect_domain(
643 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
644 if (isl_union_map_is_empty(Schedule)) {
645 isl_set_free(Domain);
646 isl_union_map_free(Schedule);
647 return isl_map_from_aff(
648 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
649 }
650 auto *M = isl_map_from_union_map(Schedule);
651 M = isl_map_coalesce(M);
652 M = isl_map_gist_domain(M, Domain);
653 M = isl_map_coalesce(M);
654 return M;
655}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000656
Johannes Doerfert574182d2015-08-12 10:19:50 +0000657__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
658 return getParent()->getPwAff(E, this);
659}
660
Tobias Grosser37eb4222014-02-20 21:43:54 +0000661void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
662 assert(isl_set_is_subset(NewDomain, Domain) &&
663 "New domain is not a subset of old domain!");
664 isl_set_free(Domain);
665 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000666}
667
Tobias Grosser62139132015-08-02 16:17:41 +0000668// @brief Get the data-type of the elements accessed
669static Type *getAccessType(IRAccess &Access, Instruction *AccessInst) {
670 if (Access.isPHI())
671 return Access.getBase()->getType();
672
673 if (StoreInst *Store = dyn_cast<StoreInst>(AccessInst))
674 return Store->getValueOperand()->getType();
675 if (BranchInst *Branch = dyn_cast<BranchInst>(AccessInst))
676 return Branch->getCondition()->getType();
677 return AccessInst->getType();
678}
679
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000680void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
681 bool isApproximated) {
682 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
683 if (!AFS)
684 return;
685
686 for (auto &AccessPair : *AFS) {
687 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000688 Instruction *AccessInst = AccessPair.second;
Tobias Grosser62139132015-08-02 16:17:41 +0000689 Type *ElementType = getAccessType(Access, AccessInst);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000690
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000691 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000692 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000693
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000694 if (isApproximated && Access.isWrite())
695 Access.setMayWrite();
696
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000697 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
698 if (!MAL)
699 MAL = new MemoryAccessList();
700 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
701 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000702 }
703}
704
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000705void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000706 for (MemoryAccess *MA : *this)
707 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000708
709 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000710}
711
Tobias Grosser65b00582011-11-08 15:41:19 +0000712__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000713 isl_pw_aff *L = getPwAff(Comp.getLHS());
714 isl_pw_aff *R = getPwAff(Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000715
Tobias Grosserd2795d02011-08-18 07:51:40 +0000716 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000717 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000718 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000719 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000720 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000721 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000722 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000723 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000724 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000725 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000726 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000727 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000728 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000729 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000730 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000731 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000732 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000733 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000734 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000735 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000736 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000737 default:
738 llvm_unreachable("Non integer predicate not supported");
739 }
Tobias Grosser75805372011-04-29 06:27:02 +0000740}
741
Tobias Grossere19661e2011-10-07 08:46:57 +0000742__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000743 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000744 isl_space *Space;
745 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000746
Tobias Grossere19661e2011-10-07 08:46:57 +0000747 Space = isl_set_get_space(Domain);
748 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000749
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000750 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000751 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000752 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000753 isl_pw_aff *IV =
754 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000755
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000756 // 0 <= IV.
757 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
758 Domain = isl_set_intersect(Domain, LowerBound);
759
760 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000761 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000762 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000763 isl_pw_aff *UpperBound = getPwAff(LatchExecutions);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000764 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000765 Domain = isl_set_intersect(Domain, UpperBoundSet);
766 }
767
Tobias Grosserf5338802011-10-06 00:03:35 +0000768 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000769 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000770}
771
Tobias Grossere602a072013-05-07 07:30:56 +0000772__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
773 TempScop &tempScop,
774 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000775 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000776 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000777 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000778
Tobias Grosser75805372011-04-29 06:27:02 +0000779 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000780 if (BranchingBB != CurrentRegion->getEntry()) {
781 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000782 for (const auto &C : *Condition) {
783 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000784 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000785 }
786 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000787 BranchingBB = CurrentRegion->getEntry();
788 CurrentRegion = CurrentRegion->getParent();
789 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000790
Tobias Grossere19661e2011-10-07 08:46:57 +0000791 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000792}
793
Tobias Grossere602a072013-05-07 07:30:56 +0000794__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
795 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000796 isl_space *Space;
797 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000798 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000799
800 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
801
Tobias Grosser084d8f72012-05-29 09:29:44 +0000802 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
803
Tobias Grossere19661e2011-10-07 08:46:57 +0000804 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000805 Domain = addLoopBoundsToDomain(Domain, tempScop);
806 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000807 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000808
809 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000810}
811
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000812void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
813 int Dimension = 0;
814 isl_ctx *Ctx = Parent.getIslCtx();
815 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
816 Type *Ty = GEP->getPointerOperandType();
817 ScalarEvolution &SE = *Parent.getSE();
818
819 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
820 Dimension = 1;
821 Ty = PtrTy->getElementType();
822 }
823
824 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
825 unsigned int Operand = 1 + Dimension;
826
827 if (GEP->getNumOperands() <= Operand)
828 break;
829
830 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
831
832 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000833 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000834 AccessOffset =
835 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
836
837 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
838 isl_local_space_copy(LSpace),
839 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
840
841 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
842 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
843 OutOfBound = isl_set_params(OutOfBound);
844 isl_set *InBound = isl_set_complement(OutOfBound);
845 isl_set *Executed = isl_set_params(getDomain());
846
847 // A => B == !A or B
848 isl_set *InBoundIfExecuted =
849 isl_set_union(isl_set_complement(Executed), InBound);
850
851 Parent.addAssumption(InBoundIfExecuted);
852 }
853
854 Dimension += 1;
855 Ty = ArrayTy->getElementType();
856 }
857
858 isl_local_space_free(LSpace);
859}
860
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000861void ScopStmt::deriveAssumptions(BasicBlock *Block) {
862 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000863 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
864 deriveAssumptionsFromGEP(GEP);
865}
866
Tobias Grosser74394f02013-01-14 22:40:23 +0000867ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000868 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000869 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
870 NestLoops(Nest.size()) {
871 // Setup the induction variables.
872 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
873 NestLoops[i] = Nest[i];
874
Tobias Grosser16c44032015-07-09 07:31:45 +0000875 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000876
877 Domain = buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000878
879 BasicBlock *EntryBB = R.getEntry();
880 for (BasicBlock *Block : R.blocks()) {
881 buildAccesses(tempScop, Block, Block != EntryBB);
882 deriveAssumptions(Block);
883 }
884 checkForReductions();
885}
886
887ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000888 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000889 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
890 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000891 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +0000892 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +0000893 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000894
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000895 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000896
Tobias Grossere19661e2011-10-07 08:46:57 +0000897 Domain = buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000898 buildAccesses(tempScop, BB);
899 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000900 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000901}
902
Johannes Doerferte58a0122014-06-27 20:31:28 +0000903/// @brief Collect loads which might form a reduction chain with @p StoreMA
904///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000905/// Check if the stored value for @p StoreMA is a binary operator with one or
906/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000907/// used only once (by @p StoreMA) and its load operands are also used only
908/// once, we have found a possible reduction chain. It starts at an operand
909/// load and includes the binary operator and @p StoreMA.
910///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000911/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +0000912/// escape this block or into any other store except @p StoreMA.
913void ScopStmt::collectCandiateReductionLoads(
914 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
915 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
916 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000917 return;
918
919 // Skip if there is not one binary operator between the load and the store
920 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000921 if (!BinOp)
922 return;
923
924 // Skip if the binary operators has multiple uses
925 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000926 return;
927
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000928 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000929 if (!BinOp->isCommutative() || !BinOp->isAssociative())
930 return;
931
Johannes Doerfert9890a052014-07-01 00:32:29 +0000932 // Skip if the binary operator is outside the current SCoP
933 if (BinOp->getParent() != Store->getParent())
934 return;
935
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000936 // Skip if it is a multiplicative reduction and we disabled them
937 if (DisableMultiplicativeReductions &&
938 (BinOp->getOpcode() == Instruction::Mul ||
939 BinOp->getOpcode() == Instruction::FMul))
940 return;
941
Johannes Doerferte58a0122014-06-27 20:31:28 +0000942 // Check the binary operator operands for a candidate load
943 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
944 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
945 if (!PossibleLoad0 && !PossibleLoad1)
946 return;
947
948 // A load is only a candidate if it cannot escape (thus has only this use)
949 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000950 if (PossibleLoad0->getParent() == Store->getParent())
951 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000952 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000953 if (PossibleLoad1->getParent() == Store->getParent())
954 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000955}
956
957/// @brief Check for reductions in this ScopStmt
958///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000959/// Iterate over all store memory accesses and check for valid binary reduction
960/// like chains. For all candidates we check if they have the same base address
961/// and there are no other accesses which overlap with them. The base address
962/// check rules out impossible reductions candidates early. The overlap check,
963/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000964/// guarantees that none of the intermediate results will escape during
965/// execution of the loop nest. We basically check here that no other memory
966/// access can access the same memory as the potential reduction.
967void ScopStmt::checkForReductions() {
968 SmallVector<MemoryAccess *, 2> Loads;
969 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
970
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000971 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +0000972 // stores and collecting possible reduction loads.
973 for (MemoryAccess *StoreMA : MemAccs) {
974 if (StoreMA->isRead())
975 continue;
976
977 Loads.clear();
978 collectCandiateReductionLoads(StoreMA, Loads);
979 for (MemoryAccess *LoadMA : Loads)
980 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
981 }
982
983 // Then check each possible candidate pair.
984 for (const auto &CandidatePair : Candidates) {
985 bool Valid = true;
986 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
987 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
988
989 // Skip those with obviously unequal base addresses.
990 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
991 isl_map_free(LoadAccs);
992 isl_map_free(StoreAccs);
993 continue;
994 }
995
996 // And check if the remaining for overlap with other memory accesses.
997 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
998 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
999 isl_set *AllAccs = isl_map_range(AllAccsRel);
1000
1001 for (MemoryAccess *MA : MemAccs) {
1002 if (MA == CandidatePair.first || MA == CandidatePair.second)
1003 continue;
1004
1005 isl_map *AccRel =
1006 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1007 isl_set *Accs = isl_map_range(AccRel);
1008
1009 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1010 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1011 Valid = Valid && isl_set_is_empty(OverlapAccs);
1012 isl_set_free(OverlapAccs);
1013 }
1014 }
1015
1016 isl_set_free(AllAccs);
1017 if (!Valid)
1018 continue;
1019
Johannes Doerfertf6183392014-07-01 20:52:51 +00001020 const LoadInst *Load =
1021 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1022 MemoryAccess::ReductionType RT =
1023 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1024
Johannes Doerferte58a0122014-06-27 20:31:28 +00001025 // If no overlapping access was found we mark the load and store as
1026 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001027 CandidatePair.first->markAsReductionLike(RT);
1028 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001029 }
Tobias Grosser75805372011-04-29 06:27:02 +00001030}
1031
Tobias Grosser74394f02013-01-14 22:40:23 +00001032std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001033
Tobias Grosser54839312015-04-21 11:37:25 +00001034std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001035 auto *S = getSchedule();
1036 auto Str = stringFromIslObj(S);
1037 isl_map_free(S);
1038 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001039}
1040
Tobias Grosser74394f02013-01-14 22:40:23 +00001041unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001042
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001043unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001044
Tobias Grosser75805372011-04-29 06:27:02 +00001045const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1046
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001047const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001048 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001049}
1050
Tobias Grosser74394f02013-01-14 22:40:23 +00001051isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001052
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001053__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001054
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001055__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001056 return isl_set_get_space(Domain);
1057}
1058
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001059__isl_give isl_id *ScopStmt::getDomainId() const {
1060 return isl_set_get_tuple_id(Domain);
1061}
Tobias Grossercd95b772012-08-30 11:49:38 +00001062
Tobias Grosser75805372011-04-29 06:27:02 +00001063ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001064 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001065 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001066}
1067
1068void ScopStmt::print(raw_ostream &OS) const {
1069 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001070 OS.indent(12) << "Domain :=\n";
1071
1072 if (Domain) {
1073 OS.indent(16) << getDomainStr() << ";\n";
1074 } else
1075 OS.indent(16) << "n/a\n";
1076
Tobias Grosser54839312015-04-21 11:37:25 +00001077 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001078
1079 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001080 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001081 } else
1082 OS.indent(16) << "n/a\n";
1083
Tobias Grosser083d3d32014-06-28 08:59:45 +00001084 for (MemoryAccess *Access : MemAccs)
1085 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001086}
1087
1088void ScopStmt::dump() const { print(dbgs()); }
1089
1090//===----------------------------------------------------------------------===//
1091/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001092
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001093void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001094 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1095 isl_set_free(Context);
1096 Context = NewContext;
1097}
1098
Tobias Grosserabfbe632013-02-05 12:09:06 +00001099void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001100 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001101 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001102 if (ParameterIds.find(Parameter) != ParameterIds.end())
1103 continue;
1104
1105 int dimension = Parameters.size();
1106
1107 Parameters.push_back(Parameter);
1108 ParameterIds[Parameter] = dimension;
1109 }
1110}
1111
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001112__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1113 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001114
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001115 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001116 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001117
Tobias Grosser8f99c162011-11-15 11:38:55 +00001118 std::string ParameterName;
1119
1120 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1121 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001122 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001123 }
1124
1125 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001126 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001127
Tobias Grosser20532b82014-04-11 17:56:49 +00001128 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1129 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001130}
Tobias Grosser75805372011-04-29 06:27:02 +00001131
Tobias Grosser6be480c2011-11-08 15:41:13 +00001132void Scop::buildContext() {
1133 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001134 Context = isl_set_universe(isl_space_copy(Space));
1135 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001136}
1137
Tobias Grosser18daaca2012-05-22 10:47:27 +00001138void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001139 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001140 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001141
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001142 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001143
Johannes Doerferte7044942015-02-24 11:58:30 +00001144 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001145 }
1146}
1147
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001148void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001149 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001150 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001151
Tobias Grosser083d3d32014-06-28 08:59:45 +00001152 for (const auto &ParamID : ParameterIds) {
1153 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001154 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001155 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001156 }
1157
1158 // Align the parameters of all data structures to the model.
1159 Context = isl_set_align_params(Context, Space);
1160
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001161 for (ScopStmt &Stmt : *this)
1162 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001163}
1164
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001165void Scop::simplifyAssumedContext() {
1166 // The parameter constraints of the iteration domains give us a set of
1167 // constraints that need to hold for all cases where at least a single
1168 // statement iteration is executed in the whole scop. We now simplify the
1169 // assumed context under the assumption that such constraints hold and at
1170 // least a single statement iteration is executed. For cases where no
1171 // statement instances are executed, the assumptions we have taken about
1172 // the executed code do not matter and can be changed.
1173 //
1174 // WARNING: This only holds if the assumptions we have taken do not reduce
1175 // the set of statement instances that are executed. Otherwise we
1176 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001177 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001178 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001179 // performed. In such a case, modifying the run-time conditions and
1180 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001181 // to not be executed.
1182 //
1183 // Example:
1184 //
1185 // When delinearizing the following code:
1186 //
1187 // for (long i = 0; i < 100; i++)
1188 // for (long j = 0; j < m; j++)
1189 // A[i+p][j] = 1.0;
1190 //
1191 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001192 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001193 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1194 AssumedContext =
1195 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001196 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001197}
1198
Johannes Doerfertb164c792014-09-18 11:17:17 +00001199/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001200static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001201 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1202 isl_pw_multi_aff *MinPMA, *MaxPMA;
1203 isl_pw_aff *LastDimAff;
1204 isl_aff *OneAff;
1205 unsigned Pos;
1206
Johannes Doerfert9143d672014-09-27 11:02:39 +00001207 // Restrict the number of parameters involved in the access as the lexmin/
1208 // lexmax computation will take too long if this number is high.
1209 //
1210 // Experiments with a simple test case using an i7 4800MQ:
1211 //
1212 // #Parameters involved | Time (in sec)
1213 // 6 | 0.01
1214 // 7 | 0.04
1215 // 8 | 0.12
1216 // 9 | 0.40
1217 // 10 | 1.54
1218 // 11 | 6.78
1219 // 12 | 30.38
1220 //
1221 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1222 unsigned InvolvedParams = 0;
1223 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1224 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1225 InvolvedParams++;
1226
1227 if (InvolvedParams > RunTimeChecksMaxParameters) {
1228 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001229 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001230 }
1231 }
1232
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001233 Set = isl_set_remove_divs(Set);
1234
Johannes Doerfertb164c792014-09-18 11:17:17 +00001235 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1236 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1237
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001238 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1239 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1240
Johannes Doerfertb164c792014-09-18 11:17:17 +00001241 // Adjust the last dimension of the maximal access by one as we want to
1242 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1243 // we test during code generation might now point after the end of the
1244 // allocated array but we will never dereference it anyway.
1245 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1246 "Assumed at least one output dimension");
1247 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1248 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1249 OneAff = isl_aff_zero_on_domain(
1250 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1251 OneAff = isl_aff_add_constant_si(OneAff, 1);
1252 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1253 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1254
1255 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1256
1257 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001258 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001259}
1260
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001261static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1262 isl_set *Domain = MA->getStatement()->getDomain();
1263 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1264 return isl_set_reset_tuple_id(Domain);
1265}
1266
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001267/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1268static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001269 __isl_take isl_union_set *Domains,
1270 __isl_take isl_set *AssumedContext,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001271 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001272
1273 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1274 isl_union_set *Locations = isl_union_map_range(Accesses);
1275 Locations = isl_union_set_intersect_params(Locations, AssumedContext);
1276 Locations = isl_union_set_coalesce(Locations);
1277 Locations = isl_union_set_detect_equalities(Locations);
1278 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001279 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001280 isl_union_set_free(Locations);
1281 return Valid;
1282}
1283
Johannes Doerfert9143d672014-09-27 11:02:39 +00001284bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001285 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001286 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001287 // for all memory accesses inside the SCoP.
1288 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001289 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001290 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001291 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001292 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001293 // if their access domains intersect, otherwise they are in different
1294 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001295 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001296 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001297 // and maximal accesses to each array of a group in read only and non
1298 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001299 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1300
1301 AliasSetTracker AST(AA);
1302
1303 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001304 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001305 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001306
1307 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001308 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001309 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1310 isl_set_free(StmtDomain);
1311 if (StmtDomainEmpty)
1312 continue;
1313
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001314 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001315 if (MA->isScalar())
1316 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001317 if (!MA->isRead())
1318 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001319 Instruction *Acc = MA->getAccessInstruction();
1320 PtrToAcc[getPointerOperand(*Acc)] = MA;
1321 AST.add(Acc);
1322 }
1323 }
1324
1325 SmallVector<AliasGroupTy, 4> AliasGroups;
1326 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001327 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001328 continue;
1329 AliasGroupTy AG;
1330 for (auto PR : AS)
1331 AG.push_back(PtrToAcc[PR.getValue()]);
1332 assert(AG.size() > 1 &&
1333 "Alias groups should contain at least two accesses");
1334 AliasGroups.push_back(std::move(AG));
1335 }
1336
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001337 // Split the alias groups based on their domain.
1338 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1339 AliasGroupTy NewAG;
1340 AliasGroupTy &AG = AliasGroups[u];
1341 AliasGroupTy::iterator AGI = AG.begin();
1342 isl_set *AGDomain = getAccessDomain(*AGI);
1343 while (AGI != AG.end()) {
1344 MemoryAccess *MA = *AGI;
1345 isl_set *MADomain = getAccessDomain(MA);
1346 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1347 NewAG.push_back(MA);
1348 AGI = AG.erase(AGI);
1349 isl_set_free(MADomain);
1350 } else {
1351 AGDomain = isl_set_union(AGDomain, MADomain);
1352 AGI++;
1353 }
1354 }
1355 if (NewAG.size() > 1)
1356 AliasGroups.push_back(std::move(NewAG));
1357 isl_set_free(AGDomain);
1358 }
1359
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001360 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001361 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1362 for (AliasGroupTy &AG : AliasGroups) {
1363 NonReadOnlyBaseValues.clear();
1364 ReadOnlyPairs.clear();
1365
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001366 if (AG.size() < 2) {
1367 AG.clear();
1368 continue;
1369 }
1370
Johannes Doerfert13771732014-10-01 12:40:46 +00001371 for (auto II = AG.begin(); II != AG.end();) {
1372 Value *BaseAddr = (*II)->getBaseAddr();
1373 if (HasWriteAccess.count(BaseAddr)) {
1374 NonReadOnlyBaseValues.insert(BaseAddr);
1375 II++;
1376 } else {
1377 ReadOnlyPairs[BaseAddr].insert(*II);
1378 II = AG.erase(II);
1379 }
1380 }
1381
1382 // If we don't have read only pointers check if there are at least two
1383 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001384 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001385 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001386 continue;
1387 }
1388
1389 // If we don't have non read only pointers clear the alias group.
1390 if (NonReadOnlyBaseValues.empty()) {
1391 AG.clear();
1392 continue;
1393 }
1394
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001395 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001396 MinMaxAliasGroups.emplace_back();
1397 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1398 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1399 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1400 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001401
1402 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001403
1404 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001405 for (MemoryAccess *MA : AG)
1406 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001407
Tobias Grosserbb853c22015-07-25 12:31:03 +00001408 bool Valid = calculateMinMaxAccess(
1409 Accesses, getDomains(), getAssumedContext(), MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001410
1411 // Bail out if the number of values we need to compare is too large.
1412 // This is important as the number of comparisions grows quadratically with
1413 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001414 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1415 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001416 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001417
1418 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001419 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001420 Accesses = isl_union_map_empty(getParamSpace());
1421
1422 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1423 for (MemoryAccess *MA : ReadOnlyPair.second)
1424 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1425
Tobias Grosserbb853c22015-07-25 12:31:03 +00001426 Valid = calculateMinMaxAccess(Accesses, getDomains(), getAssumedContext(),
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001427 MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001428
1429 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001430 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001431 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001432
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001433 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001434}
1435
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001436static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1437 ScopDetection &SD) {
1438
1439 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1440
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001441 unsigned MinLD = INT_MAX, MaxLD = 0;
1442 for (BasicBlock *BB : R.blocks()) {
1443 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001444 if (!R.contains(L))
1445 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001446 if (BoxedLoops && BoxedLoops->count(L))
1447 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001448 unsigned LD = L->getLoopDepth();
1449 MinLD = std::min(MinLD, LD);
1450 MaxLD = std::max(MaxLD, LD);
1451 }
1452 }
1453
1454 // Handle the case that there is no loop in the SCoP first.
1455 if (MaxLD == 0)
1456 return 1;
1457
1458 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1459 assert(MaxLD >= MinLD &&
1460 "Maximal loop depth was smaller than mininaml loop depth?");
1461 return MaxLD - MinLD + 1;
1462}
1463
Michael Kruse471a5e32015-07-30 19:27:04 +00001464Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, isl_ctx *Context,
1465 unsigned MaxLoopDepth)
1466 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert574182d2015-08-12 10:19:50 +00001467 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001468
Michael Kruse471a5e32015-07-30 19:27:04 +00001469void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI,
1470 ScopDetection &SD) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001471 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001472
Tobias Grosserabfbe632013-02-05 12:09:06 +00001473 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001474
Tobias Grosser54839312015-04-21 11:37:25 +00001475 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001476 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00001477 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00001478 if (!Schedule)
1479 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00001480
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001481 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001482 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001483 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001484
Tobias Grosser75805372011-04-29 06:27:02 +00001485 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1486}
1487
Michael Kruse471a5e32015-07-30 19:27:04 +00001488Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
1489 ScalarEvolution &SE, ScopDetection &SD,
1490 isl_ctx *ctx) {
1491 auto &R = TempScop.getMaxRegion();
1492 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
1493 auto S = new Scop(R, SE, ctx, MaxLoopDepth);
1494 S->initFromTempScop(TempScop, LI, SD);
1495 return S;
1496}
1497
Tobias Grosser75805372011-04-29 06:27:02 +00001498Scop::~Scop() {
1499 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001500 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00001501 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001502
Johannes Doerfertb164c792014-09-18 11:17:17 +00001503 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001504 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001505 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001506 isl_pw_multi_aff_free(MMA.first);
1507 isl_pw_multi_aff_free(MMA.second);
1508 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001509 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001510 isl_pw_multi_aff_free(MMA.first);
1511 isl_pw_multi_aff_free(MMA.second);
1512 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001513 }
Tobias Grosser75805372011-04-29 06:27:02 +00001514}
1515
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001516const ScopArrayInfo *
1517Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00001518 const SmallVector<const SCEV *, 4> &Sizes,
1519 bool IsPHI) {
1520 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001521 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001522 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
1523 this));
Tobias Grosserab671442015-05-23 05:58:27 +00001524 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001525}
1526
Tobias Grosser92245222015-07-28 14:53:44 +00001527const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
1528 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001529 assert(SAI && "No ScopArrayInfo available for this base pointer");
1530 return SAI;
1531}
1532
Tobias Grosser74394f02013-01-14 22:40:23 +00001533std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001534std::string Scop::getAssumedContextStr() const {
1535 return stringFromIslObj(AssumedContext);
1536}
Tobias Grosser75805372011-04-29 06:27:02 +00001537
1538std::string Scop::getNameStr() const {
1539 std::string ExitName, EntryName;
1540 raw_string_ostream ExitStr(ExitName);
1541 raw_string_ostream EntryStr(EntryName);
1542
Tobias Grosserf240b482014-01-09 10:42:15 +00001543 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001544 EntryStr.str();
1545
1546 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001547 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001548 ExitStr.str();
1549 } else
1550 ExitName = "FunctionExit";
1551
1552 return EntryName + "---" + ExitName;
1553}
1554
Tobias Grosser74394f02013-01-14 22:40:23 +00001555__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001556__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001557 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001558}
1559
Tobias Grossere86109f2013-10-29 21:05:49 +00001560__isl_give isl_set *Scop::getAssumedContext() const {
1561 return isl_set_copy(AssumedContext);
1562}
1563
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001564void Scop::addAssumption(__isl_take isl_set *Set) {
1565 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001566 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001567}
1568
Tobias Grosser75805372011-04-29 06:27:02 +00001569void Scop::printContext(raw_ostream &OS) const {
1570 OS << "Context:\n";
1571
1572 if (!Context) {
1573 OS.indent(4) << "n/a\n\n";
1574 return;
1575 }
1576
1577 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001578
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001579 OS.indent(4) << "Assumed Context:\n";
1580 if (!AssumedContext) {
1581 OS.indent(4) << "n/a\n\n";
1582 return;
1583 }
1584
1585 OS.indent(4) << getAssumedContextStr() << "\n";
1586
Tobias Grosser083d3d32014-06-28 08:59:45 +00001587 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001588 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001589 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1590 }
Tobias Grosser75805372011-04-29 06:27:02 +00001591}
1592
Johannes Doerfertb164c792014-09-18 11:17:17 +00001593void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001594 int noOfGroups = 0;
1595 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001596 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001597 noOfGroups += 1;
1598 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001599 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001600 }
1601
Tobias Grosserbb853c22015-07-25 12:31:03 +00001602 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00001603 if (MinMaxAliasGroups.empty()) {
1604 OS.indent(8) << "n/a\n";
1605 return;
1606 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001607
Tobias Grosserbb853c22015-07-25 12:31:03 +00001608 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001609
1610 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001611 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001612 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001613 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001614 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1615 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001616 }
1617 OS << " ]]\n";
1618 }
1619
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001620 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001621 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00001622 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001623 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001624 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1625 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001626 }
1627 OS << " ]]\n";
1628 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001629 }
1630}
1631
Tobias Grosser75805372011-04-29 06:27:02 +00001632void Scop::printStatements(raw_ostream &OS) const {
1633 OS << "Statements {\n";
1634
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001635 for (const ScopStmt &Stmt : *this)
1636 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001637
1638 OS.indent(4) << "}\n";
1639}
1640
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001641void Scop::printArrayInfo(raw_ostream &OS) const {
1642 OS << "Arrays {\n";
1643
Tobias Grosserab671442015-05-23 05:58:27 +00001644 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001645 Array.second->print(OS);
1646
1647 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001648
1649 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
1650
1651 for (auto &Array : arrays())
1652 Array.second->print(OS, /* SizeAsPwAff */ true);
1653
1654 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001655}
1656
Tobias Grosser75805372011-04-29 06:27:02 +00001657void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001658 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1659 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001660 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001661 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001662 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001663 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001664 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001665 printStatements(OS.indent(4));
1666}
1667
1668void Scop::dump() const { print(dbgs()); }
1669
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001670isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001671
Johannes Doerfert574182d2015-08-12 10:19:50 +00001672__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, ScopStmt *Stmt) {
1673 return Affinator.getPwAff(E, Stmt);
1674}
1675
Tobias Grosser808cd692015-07-14 09:33:13 +00001676__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001677 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001678
Tobias Grosser808cd692015-07-14 09:33:13 +00001679 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001680 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001681
1682 return Domain;
1683}
1684
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001685__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001686 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001687
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001688 for (ScopStmt &Stmt : *this) {
1689 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001690 if (!MA->isMustWrite())
1691 continue;
1692
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001693 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001694 isl_map *AccessDomain = MA->getAccessRelation();
1695 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1696 Write = isl_union_map_add_map(Write, AccessDomain);
1697 }
1698 }
1699 return isl_union_map_coalesce(Write);
1700}
1701
1702__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001703 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001704
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001705 for (ScopStmt &Stmt : *this) {
1706 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001707 if (!MA->isMayWrite())
1708 continue;
1709
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001710 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001711 isl_map *AccessDomain = MA->getAccessRelation();
1712 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1713 Write = isl_union_map_add_map(Write, AccessDomain);
1714 }
1715 }
1716 return isl_union_map_coalesce(Write);
1717}
1718
Tobias Grosser37eb4222014-02-20 21:43:54 +00001719__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001720 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001721
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001722 for (ScopStmt &Stmt : *this) {
1723 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001724 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001725 continue;
1726
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001727 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001728 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001729 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1730 Write = isl_union_map_add_map(Write, AccessDomain);
1731 }
1732 }
1733 return isl_union_map_coalesce(Write);
1734}
1735
1736__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001737 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001738
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001739 for (ScopStmt &Stmt : *this) {
1740 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001741 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001742 continue;
1743
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001744 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001745 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001746
1747 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1748 Read = isl_union_map_add_map(Read, AccessDomain);
1749 }
1750 }
1751 return isl_union_map_coalesce(Read);
1752}
1753
Tobias Grosser808cd692015-07-14 09:33:13 +00001754__isl_give isl_union_map *Scop::getSchedule() const {
1755 auto Tree = getScheduleTree();
1756 auto S = isl_schedule_get_map(Tree);
1757 isl_schedule_free(Tree);
1758 return S;
1759}
Tobias Grosser37eb4222014-02-20 21:43:54 +00001760
Tobias Grosser808cd692015-07-14 09:33:13 +00001761__isl_give isl_schedule *Scop::getScheduleTree() const {
1762 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
1763 getDomains());
1764}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001765
Tobias Grosser808cd692015-07-14 09:33:13 +00001766void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
1767 auto *S = isl_schedule_from_domain(getDomains());
1768 S = isl_schedule_insert_partial_schedule(
1769 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
1770 isl_schedule_free(Schedule);
1771 Schedule = S;
1772}
1773
1774void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
1775 isl_schedule_free(Schedule);
1776 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00001777}
1778
1779bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1780 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001781 for (ScopStmt &Stmt : *this) {
1782 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001783 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1784 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1785
1786 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1787 isl_union_set_free(StmtDomain);
1788 isl_union_set_free(NewStmtDomain);
1789 continue;
1790 }
1791
1792 Changed = true;
1793
1794 isl_union_set_free(StmtDomain);
1795 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1796
1797 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001798 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001799 isl_union_set_free(NewStmtDomain);
1800 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001801 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001802 }
1803 isl_union_set_free(Domain);
1804 return Changed;
1805}
1806
Tobias Grosser75805372011-04-29 06:27:02 +00001807ScalarEvolution *Scop::getSE() const { return SE; }
1808
1809bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1810 if (tempScop.getAccessFunctions(BB))
1811 return false;
1812
1813 return true;
1814}
1815
Tobias Grosser808cd692015-07-14 09:33:13 +00001816struct MapToDimensionDataTy {
1817 int N;
1818 isl_union_pw_multi_aff *Res;
1819};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001820
Tobias Grosser808cd692015-07-14 09:33:13 +00001821// @brief Create a function that maps the elements of 'Set' to its N-th
1822// dimension.
1823//
1824// The result is added to 'User->Res'.
1825//
1826// @param Set The input set.
1827// @param N The dimension to map to.
1828//
1829// @returns Zero if no error occurred, non-zero otherwise.
1830static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
1831 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
1832 int Dim;
1833 isl_space *Space;
1834 isl_pw_multi_aff *PMA;
1835
1836 Dim = isl_set_dim(Set, isl_dim_set);
1837 Space = isl_set_get_space(Set);
1838 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
1839 Dim - Data->N);
1840 if (Data->N > 1)
1841 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
1842 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
1843
1844 isl_set_free(Set);
1845
1846 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001847}
1848
Tobias Grosser808cd692015-07-14 09:33:13 +00001849// @brief Create a function that maps the elements of Domain to their Nth
1850// dimension.
1851//
1852// @param Domain The set of elements to map.
1853// @param N The dimension to map to.
1854static __isl_give isl_multi_union_pw_aff *
1855mapToDimension(__isl_take isl_union_set *Domain, int N) {
1856 struct MapToDimensionDataTy Data;
1857 isl_space *Space;
1858
1859 Space = isl_union_set_get_space(Domain);
1860 Data.N = N;
1861 Data.Res = isl_union_pw_multi_aff_empty(Space);
1862 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
1863 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
1864
1865 isl_union_set_free(Domain);
1866 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
1867}
1868
1869ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1870 const Region &CurRegion,
1871 SmallVectorImpl<Loop *> &NestLoops) {
1872 ScopStmt *Stmt;
1873 if (BB) {
1874 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
1875 Stmt = &Stmts.back();
1876 StmtMap[BB] = Stmt;
1877 } else {
1878 assert(R && "Either basic block or a region expected.");
1879 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
1880 Stmt = &Stmts.back();
1881 for (BasicBlock *BB : R->blocks())
1882 StmtMap[BB] = Stmt;
1883 }
1884 return Stmt;
1885}
1886
Michael Kruse046dde42015-08-10 13:01:57 +00001887__isl_give isl_schedule *
1888Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
1889 const Region &CurRegion,
1890 SmallVectorImpl<Loop *> &NestLoops) {
1891 if (isTrivialBB(BB, tempScop))
1892 return nullptr;
1893
1894 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
1895 auto *Domain = Stmt->getDomain();
1896 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
1897}
1898
Tobias Grosser808cd692015-07-14 09:33:13 +00001899__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
1900 const Region &CurRegion,
1901 SmallVectorImpl<Loop *> &NestLoops,
1902 LoopInfo &LI, ScopDetection &SD) {
1903 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
1904 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
1905 tempScop, CurRegion, NestLoops);
1906 auto *Domain = Stmt->getDomain();
1907 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
1908 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001909
Tobias Grosser75805372011-04-29 06:27:02 +00001910 Loop *L = castToLoop(CurRegion, LI);
1911
1912 if (L)
1913 NestLoops.push_back(L);
1914
1915 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00001916 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001917
1918 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001919 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00001920 I != E; ++I) {
1921 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001922 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00001923 StmtSchedule =
1924 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001925 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00001926 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
1927 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00001928 }
Michael Kruse046dde42015-08-10 13:01:57 +00001929 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00001930 }
Tobias Grosser75805372011-04-29 06:27:02 +00001931
Tobias Grosser808cd692015-07-14 09:33:13 +00001932 if (!L)
1933 return Schedule;
1934
1935 auto *Domain = isl_schedule_get_domain(Schedule);
1936 if (!isl_union_set_is_empty(Domain)) {
1937 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
1938 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
1939 }
1940 isl_union_set_free(Domain);
1941
Tobias Grosser75805372011-04-29 06:27:02 +00001942 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00001943 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00001944}
1945
Johannes Doerfert7c494212014-10-31 23:13:39 +00001946ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00001947 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00001948 if (StmtMapIt == StmtMap.end())
1949 return nullptr;
1950 return StmtMapIt->second;
1951}
1952
Tobias Grosser75805372011-04-29 06:27:02 +00001953//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001954ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1955 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001956 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001957}
1958
1959ScopInfo::~ScopInfo() {
1960 clear();
1961 isl_ctx_free(ctx);
1962}
1963
Tobias Grosser75805372011-04-29 06:27:02 +00001964void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001965 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001966 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001967 AU.addRequired<ScalarEvolution>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001968 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00001969 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001970 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001971 AU.setPreservesAll();
1972}
1973
1974bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001975 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001976 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001977 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00001978 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1979
Michael Kruse82a1c7d2015-08-14 20:10:27 +00001980 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop();
Tobias Grosser75805372011-04-29 06:27:02 +00001981
1982 // This region is no Scop.
1983 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00001984 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001985 return false;
1986 }
1987
Michael Kruse471a5e32015-07-30 19:27:04 +00001988 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001989
Tobias Grosserd6a50b32015-05-30 06:26:21 +00001990 DEBUG(scop->print(dbgs()));
1991
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001992 if (!PollyUseRuntimeAliasChecks) {
1993 // Statistics.
1994 ++ScopFound;
1995 if (scop->getMaxLoopDepth() > 0)
1996 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001997 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001998 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001999
Johannes Doerfert9143d672014-09-27 11:02:39 +00002000 // If a problem occurs while building the alias groups we need to delete
2001 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002002 if (scop->buildAliasGroups(AA)) {
2003 // Statistics.
2004 ++ScopFound;
2005 if (scop->getMaxLoopDepth() > 0)
2006 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002007 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00002008 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002009
2010 DEBUG(dbgs()
2011 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002012 << " could not be created as the number of parameters involved is too "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002013 "high. The SCoP will be "
2014 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002015 "maximal number of parameters but be advised that the compile time "
Johannes Doerfert9143d672014-09-27 11:02:39 +00002016 "might increase exponentially.\n\n");
2017
2018 delete scop;
2019 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002020 return false;
2021}
2022
2023char ScopInfo::ID = 0;
2024
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002025Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2026
Tobias Grosser73600b82011-10-08 00:30:40 +00002027INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2028 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002029 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002030INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002031INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002032INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002033INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002034INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002035INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002036INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2037 "Polly - Create polyhedral description of Scops", false,
2038 false)