blob: d3b1fffd3a8bbf467511c07fa161e5252b52cc22 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000026#include "polly/TempScopInfo.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Johannes Doerfertecff11d2015-05-22 23:43:58 +000030#include "llvm/ADT/STLExtras.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000034#include "llvm/Analysis/RegionIterator.h"
35#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000036#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000037#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000038#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000039#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000041#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000043#include "isl/schedule.h"
44#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/set.h"
46#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000047#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000048#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include <sstream>
50#include <string>
51#include <vector>
52
53using namespace llvm;
54using namespace polly;
55
Chandler Carruth95fef942014-04-22 03:30:19 +000056#define DEBUG_TYPE "polly-scops"
57
Tobias Grosser74394f02013-01-14 22:40:23 +000058STATISTIC(ScopFound, "Number of valid Scops");
59STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000060
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000061// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000062// operations can overflow easily. Additive reductions and bit operations
63// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000064static cl::opt<bool> DisableMultiplicativeReductions(
65 "polly-disable-multiplicative-reductions",
66 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
67 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068
Johannes Doerfert9143d672014-09-27 11:02:39 +000069static cl::opt<unsigned> RunTimeChecksMaxParameters(
70 "polly-rtc-max-parameters",
71 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
72 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
73
Tobias Grosser71500722015-03-28 15:11:14 +000074static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
75 "polly-rtc-max-arrays-per-group",
76 cl::desc("The maximal number of arrays to compare in each alias group."),
77 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000078static cl::opt<std::string> UserContextStr(
79 "polly-context", cl::value_desc("isl parameter set"),
80 cl::desc("Provide additional constraints on the context parameters"),
81 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000082
Michael Kruse046dde42015-08-10 13:01:57 +000083// Create a sequence of two schedules. Either argument may be null and is
84// interpreted as the empty schedule. Can also return null if both schedules are
85// empty.
86static __isl_give isl_schedule *
87combineInSequence(__isl_take isl_schedule *Prev,
88 __isl_take isl_schedule *Succ) {
89 if (!Prev)
90 return Succ;
91 if (!Succ)
92 return Prev;
93
94 return isl_schedule_sequence(Prev, Succ);
95}
96
Johannes Doerferte7044942015-02-24 11:58:30 +000097static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
98 const ConstantRange &Range,
99 int dim,
100 enum isl_dim_type type) {
101 isl_val *V;
102 isl_ctx *ctx = isl_set_get_ctx(S);
103
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000104 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
105 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000106 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000107 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
108
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000109 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000110 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000111 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000112 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000113 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
114
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000115 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000116 return isl_set_union(SLB, SUB);
117 else
118 return isl_set_intersect(SLB, SUB);
119}
120
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000121static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
122 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
123 if (!BasePtrLI)
124 return nullptr;
125
126 if (!S->getRegion().contains(BasePtrLI))
127 return nullptr;
128
129 ScalarEvolution &SE = *S->getSE();
130
131 auto *OriginBaseSCEV =
132 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
133 if (!OriginBaseSCEV)
134 return nullptr;
135
136 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
137 if (!OriginBaseSCEVUnknown)
138 return nullptr;
139
140 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
141}
142
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000143ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser92245222015-07-28 14:53:44 +0000144 const SmallVector<const SCEV *, 4> &DimensionSizes,
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000145 bool IsPHI, Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000146 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000147 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
148 std::string BasePtrName =
149 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000150 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000151 for (const SCEV *Expr : DimensionSizes) {
152 isl_pw_aff *Size = S->getPwAff(Expr);
153 DimensionSizesPw.push_back(Size);
154 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000155
156 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
157 if (BasePtrOriginSAI)
158 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000159}
160
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000161ScopArrayInfo::~ScopArrayInfo() {
162 isl_id_free(Id);
163 for (isl_pw_aff *Size : DimensionSizesPw)
164 isl_pw_aff_free(Size);
165}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000166
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000167std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
168
169int ScopArrayInfo::getElemSizeInBytes() const {
170 return ElementType->getPrimitiveSizeInBits() / 8;
171}
172
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000173isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
174
175void ScopArrayInfo::dump() const { print(errs()); }
176
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000177void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000178 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000179 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
180 OS << "[";
181
182 if (SizeAsPwAff)
183 OS << " " << DimensionSizesPw[u] << " ";
184 else
185 OS << *DimensionSizes[u];
186
187 OS << "]";
188 }
189
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000190 if (BasePtrOriginSAI)
191 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
192
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000193 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000194}
195
196const ScopArrayInfo *
197ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
198 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
199 assert(Id && "Output dimension didn't have an ID");
200 return getFromId(Id);
201}
202
203const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
204 void *User = isl_id_get_user(Id);
205 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
206 isl_id_free(Id);
207 return SAI;
208}
209
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000210const std::string
211MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
212 switch (RT) {
213 case MemoryAccess::RT_NONE:
214 llvm_unreachable("Requested a reduction operator string for a memory "
215 "access which isn't a reduction");
216 case MemoryAccess::RT_ADD:
217 return "+";
218 case MemoryAccess::RT_MUL:
219 return "*";
220 case MemoryAccess::RT_BOR:
221 return "|";
222 case MemoryAccess::RT_BXOR:
223 return "^";
224 case MemoryAccess::RT_BAND:
225 return "&";
226 }
227 llvm_unreachable("Unknown reduction type");
228 return "";
229}
230
Johannes Doerfertf6183392014-07-01 20:52:51 +0000231/// @brief Return the reduction type for a given binary operator
232static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
233 const Instruction *Load) {
234 if (!BinOp)
235 return MemoryAccess::RT_NONE;
236 switch (BinOp->getOpcode()) {
237 case Instruction::FAdd:
238 if (!BinOp->hasUnsafeAlgebra())
239 return MemoryAccess::RT_NONE;
240 // Fall through
241 case Instruction::Add:
242 return MemoryAccess::RT_ADD;
243 case Instruction::Or:
244 return MemoryAccess::RT_BOR;
245 case Instruction::Xor:
246 return MemoryAccess::RT_BXOR;
247 case Instruction::And:
248 return MemoryAccess::RT_BAND;
249 case Instruction::FMul:
250 if (!BinOp->hasUnsafeAlgebra())
251 return MemoryAccess::RT_NONE;
252 // Fall through
253 case Instruction::Mul:
254 if (DisableMultiplicativeReductions)
255 return MemoryAccess::RT_NONE;
256 return MemoryAccess::RT_MUL;
257 default:
258 return MemoryAccess::RT_NONE;
259 }
260}
Tobias Grosser75805372011-04-29 06:27:02 +0000261//===----------------------------------------------------------------------===//
262
263MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000264 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000265 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000266 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000267}
268
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000269static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
270 switch (Access.getType()) {
271 case IRAccess::READ:
272 return MemoryAccess::READ;
273 case IRAccess::MUST_WRITE:
274 return MemoryAccess::MUST_WRITE;
275 case IRAccess::MAY_WRITE:
276 return MemoryAccess::MAY_WRITE;
277 }
278 llvm_unreachable("Unknown IRAccess type!");
279}
280
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000281const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
282 isl_id *ArrayId = getArrayId();
283 void *User = isl_id_get_user(ArrayId);
284 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
285 isl_id_free(ArrayId);
286 return SAI;
287}
288
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000289__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000290 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
291}
292
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000293__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
294 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000295 isl_map *Schedule, *ScheduledAccRel;
296 isl_union_set *UDomain;
297
298 UDomain = isl_union_set_from_set(getStatement()->getDomain());
299 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
300 Schedule = isl_map_from_union_map(USchedule);
301 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
302 return isl_pw_multi_aff_from_map(ScheduledAccRel);
303}
304
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000305__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000306 return isl_map_copy(AccessRelation);
307}
308
Johannes Doerferta99130f2014-10-13 12:58:03 +0000309std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000310 return stringFromIslObj(AccessRelation);
311}
312
Johannes Doerferta99130f2014-10-13 12:58:03 +0000313__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000314 return isl_map_get_space(AccessRelation);
315}
316
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000317__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000318 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000319}
320
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000321__isl_give isl_basic_map *
322MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000323 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000324 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000325
Tobias Grosser084d8f72012-05-29 09:29:44 +0000326 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000327 isl_basic_set_universe(Statement->getDomainSpace()),
328 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000329}
330
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000331// Formalize no out-of-bound access assumption
332//
333// When delinearizing array accesses we optimistically assume that the
334// delinearized accesses do not access out of bound locations (the subscript
335// expression of each array evaluates for each statement instance that is
336// executed to a value that is larger than zero and strictly smaller than the
337// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000338// dimension for which we do not need to assume any upper bound. At this point
339// we formalize this assumption to ensure that at code generation time the
340// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000341//
342// To find the set of constraints necessary to avoid out of bound accesses, we
343// first build the set of data locations that are not within array bounds. We
344// then apply the reverse access relation to obtain the set of iterations that
345// may contain invalid accesses and reduce this set of iterations to the ones
346// that are actually executed by intersecting them with the domain of the
347// statement. If we now project out all loop dimensions, we obtain a set of
348// parameters that may cause statement instances to be executed that may
349// possibly yield out of bound memory accesses. The complement of these
350// constraints is the set of constraints that needs to be assumed to ensure such
351// statement instances are never executed.
352void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000353 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000354 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000355 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000356 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
357 isl_pw_aff *Var =
358 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
359 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
360
361 isl_set *DimOutside;
362
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000363 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000364 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000365
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000366 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
367 Statement->getNumIterators());
368 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
369 isl_space_dim(Space, isl_dim_set));
370 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
371 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000372
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000373 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000374
375 Outside = isl_set_union(Outside, DimOutside);
376 }
377
378 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
379 Outside = isl_set_intersect(Outside, Statement->getDomain());
380 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000381
382 // Remove divs to avoid the construction of overly complicated assumptions.
383 // Doing so increases the set of parameter combinations that are assumed to
384 // not appear. This is always save, but may make the resulting run-time check
385 // bail out more often than strictly necessary.
386 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000387 Outside = isl_set_complement(Outside);
388 Statement->getParent()->addAssumption(Outside);
389 isl_space_free(Space);
390}
391
Johannes Doerferte7044942015-02-24 11:58:30 +0000392void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
393 ScalarEvolution *SE = Statement->getParent()->getSE();
394
395 Value *Ptr = getPointerOperand(*getAccessInstruction());
396 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
397 return;
398
399 auto *PtrSCEV = SE->getSCEV(Ptr);
400 if (isa<SCEVCouldNotCompute>(PtrSCEV))
401 return;
402
403 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
404 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
405 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
406
407 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
408 if (Range.isFullSet())
409 return;
410
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000411 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000412 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000413 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
414 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
415
416 auto Min = LB.sdiv(APInt(BW, ElementSize));
417 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000418
419 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
420 AccessRange =
421 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
422 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
423}
424
Tobias Grosser619190d2015-03-30 17:22:28 +0000425__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
426 __isl_take isl_map *AccessRelation,
427 ScopStmt *Statement) {
428 int Size = Access.Subscripts.size();
429
430 for (int i = Size - 2; i >= 0; --i) {
431 isl_space *Space;
432 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000433 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000434
435 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
436 isl_pw_aff_free(DimSize);
437 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
438
439 Space = isl_map_get_space(AccessRelation);
440 Space = isl_space_map_from_set(isl_space_range(Space));
441 Space = isl_space_align_params(Space, SpaceSize);
442
443 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
444 isl_id_free(ParamId);
445
446 MapOne = isl_map_universe(isl_space_copy(Space));
447 for (int j = 0; j < Size; ++j)
448 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
449 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
450
451 MapTwo = isl_map_universe(isl_space_copy(Space));
452 for (int j = 0; j < Size; ++j)
453 if (j < i || j > i + 1)
454 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
455
456 isl_local_space *LS = isl_local_space_from_space(Space);
457 isl_constraint *C;
458 C = isl_equality_alloc(isl_local_space_copy(LS));
459 C = isl_constraint_set_constant_si(C, -1);
460 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
461 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
462 MapTwo = isl_map_add_constraint(MapTwo, C);
463 C = isl_equality_alloc(LS);
464 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
465 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
466 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
467 MapTwo = isl_map_add_constraint(MapTwo, C);
468 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
469
470 MapOne = isl_map_union(MapOne, MapTwo);
471 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
472 }
473 return AccessRelation;
474}
475
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000476MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000477 ScopStmt *Statement, const ScopArrayInfo *SAI,
478 int Identifier)
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000479 : AccType(getMemoryAccessType(Access)), Statement(Statement),
480 AccessInstruction(AccInst), AccessValue(Access.getAccessValue()),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000481 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000482
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000483 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000484 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000485 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000486
487 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000488
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000489 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000490 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000491
Tobias Grossera1879642011-12-20 10:43:14 +0000492 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000493 // We overapproximate non-affine accesses with a possible access to the
494 // whole array. For read accesses it does not make a difference, if an
495 // access must or may happen. However, for write accesses it is important to
496 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000497 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000498 AccessRelation =
499 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000500
501 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000502 return;
503 }
504
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000505 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000506 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000507
Tobias Grosser79baa212014-04-10 08:38:02 +0000508 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000509 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000510
Sebastian Pop422e33f2014-06-03 18:16:31 +0000511 if (Size == 1) {
512 // For the non delinearized arrays, divide the access function of the last
513 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000514 //
515 // A stride one array access in C expressed as A[i] is expressed in
516 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
517 // two subsequent values of 'i' index two values that are stored next to
518 // each other in memory. By this division we make this characteristic
519 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000520 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000521 Affine = isl_pw_aff_scale_down_val(Affine, v);
522 }
523
524 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
525
Tobias Grosser79baa212014-04-10 08:38:02 +0000526 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000527 }
528
Tobias Grosser619190d2015-03-30 17:22:28 +0000529 AccessRelation = foldAccess(Access, AccessRelation, Statement);
530
Tobias Grosser79baa212014-04-10 08:38:02 +0000531 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000532 AccessRelation = isl_map_set_tuple_id(
533 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000534 AccessRelation =
535 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
536
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000537 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000538 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000539 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000540}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000541
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000542void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000543 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000544 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000545}
546
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000547const std::string MemoryAccess::getReductionOperatorStr() const {
548 return MemoryAccess::getReductionOperatorStr(getReductionType());
549}
550
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000551__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
552
Johannes Doerfertf6183392014-07-01 20:52:51 +0000553raw_ostream &polly::operator<<(raw_ostream &OS,
554 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000555 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000556 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000557 else
558 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000559 return OS;
560}
561
Tobias Grosser75805372011-04-29 06:27:02 +0000562void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000563 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000564 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000565 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000566 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000567 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000568 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000569 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000570 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000571 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000572 break;
573 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000574 OS << "[Reduction Type: " << getReductionType() << "] ";
575 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000576 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000577}
578
Tobias Grosser74394f02013-01-14 22:40:23 +0000579void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000580
581// Create a map in the size of the provided set domain, that maps from the
582// one element of the provided set domain to another element of the provided
583// set domain.
584// The mapping is limited to all points that are equal in all but the last
585// dimension and for which the last dimension of the input is strict smaller
586// than the last dimension of the output.
587//
588// getEqualAndLarger(set[i0, i1, ..., iX]):
589//
590// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
591// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
592//
Tobias Grosserf5338802011-10-06 00:03:35 +0000593static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000594 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000595 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000596 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000597
598 // Set all but the last dimension to be equal for the input and output
599 //
600 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
601 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000602 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000603 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000604
605 // Set the last dimension of the input to be strict smaller than the
606 // last dimension of the output.
607 //
608 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000609 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
610 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000611 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000612}
613
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000614__isl_give isl_set *
615MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000616 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000617 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000618 isl_space *Space = isl_space_range(isl_map_get_space(S));
619 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000620
Sebastian Popa00a0292012-12-18 07:46:06 +0000621 S = isl_map_reverse(S);
622 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000623
Sebastian Popa00a0292012-12-18 07:46:06 +0000624 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
625 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
626 NextScatt = isl_map_apply_domain(NextScatt, S);
627 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000628
Sebastian Popa00a0292012-12-18 07:46:06 +0000629 isl_set *Deltas = isl_map_deltas(NextScatt);
630 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000631}
632
Sebastian Popa00a0292012-12-18 07:46:06 +0000633bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000634 int StrideWidth) const {
635 isl_set *Stride, *StrideX;
636 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000637
Sebastian Popa00a0292012-12-18 07:46:06 +0000638 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000639 StrideX = isl_set_universe(isl_set_get_space(Stride));
640 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000641 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000642
Tobias Grosser28dd4862012-01-24 16:42:16 +0000643 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000644 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000645
Tobias Grosser28dd4862012-01-24 16:42:16 +0000646 return IsStrideX;
647}
648
Sebastian Popa00a0292012-12-18 07:46:06 +0000649bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
650 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000651}
652
Tobias Grosser79baa212014-04-10 08:38:02 +0000653bool MemoryAccess::isScalar() const {
654 return isl_map_n_out(AccessRelation) == 0;
655}
656
Sebastian Popa00a0292012-12-18 07:46:06 +0000657bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
658 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000659}
660
Tobias Grosser5d453812011-10-06 00:04:11 +0000661void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000662 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000663 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000664}
Tobias Grosser75805372011-04-29 06:27:02 +0000665
666//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000667
Tobias Grosser808cd692015-07-14 09:33:13 +0000668isl_map *ScopStmt::getSchedule() const {
669 isl_set *Domain = getDomain();
670 if (isl_set_is_empty(Domain)) {
671 isl_set_free(Domain);
672 return isl_map_from_aff(
673 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
674 }
675 auto *Schedule = getParent()->getSchedule();
676 Schedule = isl_union_map_intersect_domain(
677 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
678 if (isl_union_map_is_empty(Schedule)) {
679 isl_set_free(Domain);
680 isl_union_map_free(Schedule);
681 return isl_map_from_aff(
682 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
683 }
684 auto *M = isl_map_from_union_map(Schedule);
685 M = isl_map_coalesce(M);
686 M = isl_map_gist_domain(M, Domain);
687 M = isl_map_coalesce(M);
688 return M;
689}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000690
Johannes Doerfert574182d2015-08-12 10:19:50 +0000691__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
692 return getParent()->getPwAff(E, this);
693}
694
Tobias Grosser37eb4222014-02-20 21:43:54 +0000695void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
696 assert(isl_set_is_subset(NewDomain, Domain) &&
697 "New domain is not a subset of old domain!");
698 isl_set_free(Domain);
699 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000700}
701
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000702void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
703 bool isApproximated) {
704 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
705 if (!AFS)
706 return;
707
708 for (auto &AccessPair : *AFS) {
709 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000710 Instruction *AccessInst = AccessPair.second;
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000711 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000712
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000713 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000714 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000715
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000716 if (isApproximated && Access.isWrite())
717 Access.setMayWrite();
718
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000719 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
720 if (!MAL)
721 MAL = new MemoryAccessList();
722 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
723 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000724 }
725}
726
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000727void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000728 for (MemoryAccess *MA : *this)
729 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000730
731 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000732}
733
Tobias Grosser65b00582011-11-08 15:41:19 +0000734__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000735 isl_pw_aff *L = getPwAff(Comp.getLHS());
736 isl_pw_aff *R = getPwAff(Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000737
Tobias Grosserd2795d02011-08-18 07:51:40 +0000738 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000739 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000740 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000741 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000742 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000743 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000744 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000745 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000746 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000747 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000748 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000749 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000750 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000751 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000752 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000753 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000754 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000755 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000756 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000757 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000758 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000759 default:
760 llvm_unreachable("Non integer predicate not supported");
761 }
Tobias Grosser75805372011-04-29 06:27:02 +0000762}
763
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000764void ScopStmt::addLoopBoundsToDomain(TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000765 isl_space *Space;
766 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000767
Tobias Grossere19661e2011-10-07 08:46:57 +0000768 Space = isl_set_get_space(Domain);
769 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000770
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000771 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000772 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000773 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000774 isl_pw_aff *IV =
775 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000776
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000777 // 0 <= IV.
778 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
779 Domain = isl_set_intersect(Domain, LowerBound);
780
781 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000782 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000783 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000784 isl_pw_aff *UpperBound = getPwAff(LatchExecutions);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000785 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000786 Domain = isl_set_intersect(Domain, UpperBoundSet);
787 }
788
Tobias Grosserf5338802011-10-06 00:03:35 +0000789 isl_local_space_free(LocalSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000790}
791
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000792void ScopStmt::addConditionsToDomain(TempScop &tempScop,
793 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000794 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000795 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000796 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000797
Tobias Grosser75805372011-04-29 06:27:02 +0000798 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000799 if (BranchingBB != CurrentRegion->getEntry()) {
800 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000801 for (const auto &C : *Condition) {
802 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000803 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000804 }
805 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000806 BranchingBB = CurrentRegion->getEntry();
807 CurrentRegion = CurrentRegion->getParent();
808 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000809}
810
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000811void ScopStmt::buildDomain(TempScop &tempScop, const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000812 isl_space *Space;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000813 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000814
815 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
816
Tobias Grosser084d8f72012-05-29 09:29:44 +0000817 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
818
Tobias Grossere19661e2011-10-07 08:46:57 +0000819 Domain = isl_set_universe(Space);
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000820 addLoopBoundsToDomain(tempScop);
821 addConditionsToDomain(tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000822 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000823}
824
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000825void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
826 int Dimension = 0;
827 isl_ctx *Ctx = Parent.getIslCtx();
828 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
829 Type *Ty = GEP->getPointerOperandType();
830 ScalarEvolution &SE = *Parent.getSE();
831
832 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
833 Dimension = 1;
834 Ty = PtrTy->getElementType();
835 }
836
837 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
838 unsigned int Operand = 1 + Dimension;
839
840 if (GEP->getNumOperands() <= Operand)
841 break;
842
843 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
844
845 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000846 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000847 AccessOffset =
848 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
849
850 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
851 isl_local_space_copy(LSpace),
852 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
853
854 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
855 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
856 OutOfBound = isl_set_params(OutOfBound);
857 isl_set *InBound = isl_set_complement(OutOfBound);
858 isl_set *Executed = isl_set_params(getDomain());
859
860 // A => B == !A or B
861 isl_set *InBoundIfExecuted =
862 isl_set_union(isl_set_complement(Executed), InBound);
863
864 Parent.addAssumption(InBoundIfExecuted);
865 }
866
867 Dimension += 1;
868 Ty = ArrayTy->getElementType();
869 }
870
871 isl_local_space_free(LSpace);
872}
873
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000874void ScopStmt::deriveAssumptions(BasicBlock *Block) {
875 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000876 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
877 deriveAssumptionsFromGEP(GEP);
878}
879
Tobias Grosser74394f02013-01-14 22:40:23 +0000880ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000881 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000882 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
883 NestLoops(Nest.size()) {
884 // Setup the induction variables.
885 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
886 NestLoops[i] = Nest[i];
887
Tobias Grosser16c44032015-07-09 07:31:45 +0000888 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000889
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000890 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000891
892 BasicBlock *EntryBB = R.getEntry();
893 for (BasicBlock *Block : R.blocks()) {
894 buildAccesses(tempScop, Block, Block != EntryBB);
895 deriveAssumptions(Block);
896 }
897 checkForReductions();
898}
899
900ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000901 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000902 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
903 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000904 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +0000905 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +0000906 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000907
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000908 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000909
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000910 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000911 buildAccesses(tempScop, BB);
912 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000913 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000914}
915
Johannes Doerferte58a0122014-06-27 20:31:28 +0000916/// @brief Collect loads which might form a reduction chain with @p StoreMA
917///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000918/// Check if the stored value for @p StoreMA is a binary operator with one or
919/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000920/// used only once (by @p StoreMA) and its load operands are also used only
921/// once, we have found a possible reduction chain. It starts at an operand
922/// load and includes the binary operator and @p StoreMA.
923///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000924/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +0000925/// escape this block or into any other store except @p StoreMA.
926void ScopStmt::collectCandiateReductionLoads(
927 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
928 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
929 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000930 return;
931
932 // Skip if there is not one binary operator between the load and the store
933 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000934 if (!BinOp)
935 return;
936
937 // Skip if the binary operators has multiple uses
938 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000939 return;
940
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000941 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000942 if (!BinOp->isCommutative() || !BinOp->isAssociative())
943 return;
944
Johannes Doerfert9890a052014-07-01 00:32:29 +0000945 // Skip if the binary operator is outside the current SCoP
946 if (BinOp->getParent() != Store->getParent())
947 return;
948
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000949 // Skip if it is a multiplicative reduction and we disabled them
950 if (DisableMultiplicativeReductions &&
951 (BinOp->getOpcode() == Instruction::Mul ||
952 BinOp->getOpcode() == Instruction::FMul))
953 return;
954
Johannes Doerferte58a0122014-06-27 20:31:28 +0000955 // Check the binary operator operands for a candidate load
956 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
957 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
958 if (!PossibleLoad0 && !PossibleLoad1)
959 return;
960
961 // A load is only a candidate if it cannot escape (thus has only this use)
962 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000963 if (PossibleLoad0->getParent() == Store->getParent())
964 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000965 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000966 if (PossibleLoad1->getParent() == Store->getParent())
967 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000968}
969
970/// @brief Check for reductions in this ScopStmt
971///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000972/// Iterate over all store memory accesses and check for valid binary reduction
973/// like chains. For all candidates we check if they have the same base address
974/// and there are no other accesses which overlap with them. The base address
975/// check rules out impossible reductions candidates early. The overlap check,
976/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000977/// guarantees that none of the intermediate results will escape during
978/// execution of the loop nest. We basically check here that no other memory
979/// access can access the same memory as the potential reduction.
980void ScopStmt::checkForReductions() {
981 SmallVector<MemoryAccess *, 2> Loads;
982 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
983
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000984 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +0000985 // stores and collecting possible reduction loads.
986 for (MemoryAccess *StoreMA : MemAccs) {
987 if (StoreMA->isRead())
988 continue;
989
990 Loads.clear();
991 collectCandiateReductionLoads(StoreMA, Loads);
992 for (MemoryAccess *LoadMA : Loads)
993 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
994 }
995
996 // Then check each possible candidate pair.
997 for (const auto &CandidatePair : Candidates) {
998 bool Valid = true;
999 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1000 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1001
1002 // Skip those with obviously unequal base addresses.
1003 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1004 isl_map_free(LoadAccs);
1005 isl_map_free(StoreAccs);
1006 continue;
1007 }
1008
1009 // And check if the remaining for overlap with other memory accesses.
1010 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1011 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1012 isl_set *AllAccs = isl_map_range(AllAccsRel);
1013
1014 for (MemoryAccess *MA : MemAccs) {
1015 if (MA == CandidatePair.first || MA == CandidatePair.second)
1016 continue;
1017
1018 isl_map *AccRel =
1019 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1020 isl_set *Accs = isl_map_range(AccRel);
1021
1022 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1023 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1024 Valid = Valid && isl_set_is_empty(OverlapAccs);
1025 isl_set_free(OverlapAccs);
1026 }
1027 }
1028
1029 isl_set_free(AllAccs);
1030 if (!Valid)
1031 continue;
1032
Johannes Doerfertf6183392014-07-01 20:52:51 +00001033 const LoadInst *Load =
1034 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1035 MemoryAccess::ReductionType RT =
1036 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1037
Johannes Doerferte58a0122014-06-27 20:31:28 +00001038 // If no overlapping access was found we mark the load and store as
1039 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001040 CandidatePair.first->markAsReductionLike(RT);
1041 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001042 }
Tobias Grosser75805372011-04-29 06:27:02 +00001043}
1044
Tobias Grosser74394f02013-01-14 22:40:23 +00001045std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001046
Tobias Grosser54839312015-04-21 11:37:25 +00001047std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001048 auto *S = getSchedule();
1049 auto Str = stringFromIslObj(S);
1050 isl_map_free(S);
1051 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001052}
1053
Tobias Grosser74394f02013-01-14 22:40:23 +00001054unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001055
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001056unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001057
Tobias Grosser75805372011-04-29 06:27:02 +00001058const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1059
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001060const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001061 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001062}
1063
Tobias Grosser74394f02013-01-14 22:40:23 +00001064isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001065
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001066__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001067
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001068__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001069 return isl_set_get_space(Domain);
1070}
1071
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001072__isl_give isl_id *ScopStmt::getDomainId() const {
1073 return isl_set_get_tuple_id(Domain);
1074}
Tobias Grossercd95b772012-08-30 11:49:38 +00001075
Tobias Grosser75805372011-04-29 06:27:02 +00001076ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001077 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001078 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001079}
1080
1081void ScopStmt::print(raw_ostream &OS) const {
1082 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001083 OS.indent(12) << "Domain :=\n";
1084
1085 if (Domain) {
1086 OS.indent(16) << getDomainStr() << ";\n";
1087 } else
1088 OS.indent(16) << "n/a\n";
1089
Tobias Grosser54839312015-04-21 11:37:25 +00001090 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001091
1092 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001093 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001094 } else
1095 OS.indent(16) << "n/a\n";
1096
Tobias Grosser083d3d32014-06-28 08:59:45 +00001097 for (MemoryAccess *Access : MemAccs)
1098 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001099}
1100
1101void ScopStmt::dump() const { print(dbgs()); }
1102
1103//===----------------------------------------------------------------------===//
1104/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001105
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001106void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001107 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1108 isl_set_free(Context);
1109 Context = NewContext;
1110}
1111
Tobias Grosserabfbe632013-02-05 12:09:06 +00001112void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001113 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001114 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001115 if (ParameterIds.find(Parameter) != ParameterIds.end())
1116 continue;
1117
1118 int dimension = Parameters.size();
1119
1120 Parameters.push_back(Parameter);
1121 ParameterIds[Parameter] = dimension;
1122 }
1123}
1124
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001125__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1126 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001127
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001128 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001129 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001130
Tobias Grosser8f99c162011-11-15 11:38:55 +00001131 std::string ParameterName;
1132
1133 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1134 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001135 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001136 }
1137
1138 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001139 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001140
Tobias Grosser20532b82014-04-11 17:56:49 +00001141 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1142 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001143}
Tobias Grosser75805372011-04-29 06:27:02 +00001144
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001145isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1146 isl_set *DomainContext = isl_union_set_params(getDomains());
1147 return isl_set_intersect_params(C, DomainContext);
1148}
1149
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001150void Scop::addUserContext() {
1151 if (UserContextStr.empty())
1152 return;
1153
1154 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1155 isl_space *Space = getParamSpace();
1156 if (isl_space_dim(Space, isl_dim_param) !=
1157 isl_set_dim(UserContext, isl_dim_param)) {
1158 auto SpaceStr = isl_space_to_str(Space);
1159 errs() << "Error: the context provided in -polly-context has not the same "
1160 << "number of dimensions than the computed context. Due to this "
1161 << "mismatch, the -polly-context option is ignored. Please provide "
1162 << "the context in the parameter space: " << SpaceStr << ".\n";
1163 free(SpaceStr);
1164 isl_set_free(UserContext);
1165 isl_space_free(Space);
1166 return;
1167 }
1168
1169 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1170 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1171 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1172
1173 if (strcmp(NameContext, NameUserContext) != 0) {
1174 auto SpaceStr = isl_space_to_str(Space);
1175 errs() << "Error: the name of dimension " << i
1176 << " provided in -polly-context "
1177 << "is '" << NameUserContext << "', but the name in the computed "
1178 << "context is '" << NameContext
1179 << "'. Due to this name mismatch, "
1180 << "the -polly-context option is ignored. Please provide "
1181 << "the context in the parameter space: " << SpaceStr << ".\n";
1182 free(SpaceStr);
1183 isl_set_free(UserContext);
1184 isl_space_free(Space);
1185 return;
1186 }
1187
1188 UserContext =
1189 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1190 isl_space_get_dim_id(Space, isl_dim_param, i));
1191 }
1192
1193 Context = isl_set_intersect(Context, UserContext);
1194 isl_space_free(Space);
1195}
1196
Tobias Grosser6be480c2011-11-08 15:41:13 +00001197void Scop::buildContext() {
1198 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001199 Context = isl_set_universe(isl_space_copy(Space));
1200 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001201}
1202
Tobias Grosser18daaca2012-05-22 10:47:27 +00001203void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001204 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001205 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001206
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001207 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001208
Johannes Doerferte7044942015-02-24 11:58:30 +00001209 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001210 }
1211}
1212
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001213void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001214 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001215 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001216
Tobias Grosser083d3d32014-06-28 08:59:45 +00001217 for (const auto &ParamID : ParameterIds) {
1218 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001219 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001220 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001221 }
1222
1223 // Align the parameters of all data structures to the model.
1224 Context = isl_set_align_params(Context, Space);
1225
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001226 for (ScopStmt &Stmt : *this)
1227 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001228}
1229
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001230void Scop::simplifyAssumedContext() {
1231 // The parameter constraints of the iteration domains give us a set of
1232 // constraints that need to hold for all cases where at least a single
1233 // statement iteration is executed in the whole scop. We now simplify the
1234 // assumed context under the assumption that such constraints hold and at
1235 // least a single statement iteration is executed. For cases where no
1236 // statement instances are executed, the assumptions we have taken about
1237 // the executed code do not matter and can be changed.
1238 //
1239 // WARNING: This only holds if the assumptions we have taken do not reduce
1240 // the set of statement instances that are executed. Otherwise we
1241 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001242 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001243 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001244 // performed. In such a case, modifying the run-time conditions and
1245 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001246 // to not be executed.
1247 //
1248 // Example:
1249 //
1250 // When delinearizing the following code:
1251 //
1252 // for (long i = 0; i < 100; i++)
1253 // for (long j = 0; j < m; j++)
1254 // A[i+p][j] = 1.0;
1255 //
1256 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001257 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001258 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1259 AssumedContext =
1260 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001261 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001262}
1263
Johannes Doerfertb164c792014-09-18 11:17:17 +00001264/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001265static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001266 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1267 isl_pw_multi_aff *MinPMA, *MaxPMA;
1268 isl_pw_aff *LastDimAff;
1269 isl_aff *OneAff;
1270 unsigned Pos;
1271
Johannes Doerfert9143d672014-09-27 11:02:39 +00001272 // Restrict the number of parameters involved in the access as the lexmin/
1273 // lexmax computation will take too long if this number is high.
1274 //
1275 // Experiments with a simple test case using an i7 4800MQ:
1276 //
1277 // #Parameters involved | Time (in sec)
1278 // 6 | 0.01
1279 // 7 | 0.04
1280 // 8 | 0.12
1281 // 9 | 0.40
1282 // 10 | 1.54
1283 // 11 | 6.78
1284 // 12 | 30.38
1285 //
1286 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1287 unsigned InvolvedParams = 0;
1288 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1289 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1290 InvolvedParams++;
1291
1292 if (InvolvedParams > RunTimeChecksMaxParameters) {
1293 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001294 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001295 }
1296 }
1297
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001298 Set = isl_set_remove_divs(Set);
1299
Johannes Doerfertb164c792014-09-18 11:17:17 +00001300 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1301 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1302
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001303 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1304 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1305
Johannes Doerfertb164c792014-09-18 11:17:17 +00001306 // Adjust the last dimension of the maximal access by one as we want to
1307 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1308 // we test during code generation might now point after the end of the
1309 // allocated array but we will never dereference it anyway.
1310 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1311 "Assumed at least one output dimension");
1312 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1313 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1314 OneAff = isl_aff_zero_on_domain(
1315 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1316 OneAff = isl_aff_add_constant_si(OneAff, 1);
1317 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1318 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1319
1320 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1321
1322 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001323 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001324}
1325
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001326static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1327 isl_set *Domain = MA->getStatement()->getDomain();
1328 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1329 return isl_set_reset_tuple_id(Domain);
1330}
1331
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001332/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1333static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001334 __isl_take isl_union_set *Domains,
1335 __isl_take isl_set *AssumedContext,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001336 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001337
1338 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1339 isl_union_set *Locations = isl_union_map_range(Accesses);
1340 Locations = isl_union_set_intersect_params(Locations, AssumedContext);
1341 Locations = isl_union_set_coalesce(Locations);
1342 Locations = isl_union_set_detect_equalities(Locations);
1343 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001344 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001345 isl_union_set_free(Locations);
1346 return Valid;
1347}
1348
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001349void Scop::buildAliasChecks(AliasAnalysis &AA) {
1350 if (!PollyUseRuntimeAliasChecks)
1351 return;
1352
1353 if (buildAliasGroups(AA))
1354 return;
1355
1356 // If a problem occurs while building the alias groups we need to delete
1357 // this SCoP and pretend it wasn't valid in the first place. To this end
1358 // we make the assumed context infeasible.
1359 addAssumption(isl_set_empty(getParamSpace()));
1360
1361 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1362 << " could not be created as the number of parameters involved "
1363 "is too high. The SCoP will be "
1364 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1365 "the maximal number of parameters but be advised that the "
1366 "compile time might increase exponentially.\n\n");
1367}
1368
Johannes Doerfert9143d672014-09-27 11:02:39 +00001369bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001370 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001371 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001372 // for all memory accesses inside the SCoP.
1373 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001374 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001375 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001376 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001377 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001378 // if their access domains intersect, otherwise they are in different
1379 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001380 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001381 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001382 // and maximal accesses to each array of a group in read only and non
1383 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001384 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1385
1386 AliasSetTracker AST(AA);
1387
1388 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001389 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001390 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001391
1392 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001393 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001394 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1395 isl_set_free(StmtDomain);
1396 if (StmtDomainEmpty)
1397 continue;
1398
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001399 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001400 if (MA->isScalar())
1401 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001402 if (!MA->isRead())
1403 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001404 Instruction *Acc = MA->getAccessInstruction();
1405 PtrToAcc[getPointerOperand(*Acc)] = MA;
1406 AST.add(Acc);
1407 }
1408 }
1409
1410 SmallVector<AliasGroupTy, 4> AliasGroups;
1411 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001412 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001413 continue;
1414 AliasGroupTy AG;
1415 for (auto PR : AS)
1416 AG.push_back(PtrToAcc[PR.getValue()]);
1417 assert(AG.size() > 1 &&
1418 "Alias groups should contain at least two accesses");
1419 AliasGroups.push_back(std::move(AG));
1420 }
1421
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001422 // Split the alias groups based on their domain.
1423 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1424 AliasGroupTy NewAG;
1425 AliasGroupTy &AG = AliasGroups[u];
1426 AliasGroupTy::iterator AGI = AG.begin();
1427 isl_set *AGDomain = getAccessDomain(*AGI);
1428 while (AGI != AG.end()) {
1429 MemoryAccess *MA = *AGI;
1430 isl_set *MADomain = getAccessDomain(MA);
1431 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1432 NewAG.push_back(MA);
1433 AGI = AG.erase(AGI);
1434 isl_set_free(MADomain);
1435 } else {
1436 AGDomain = isl_set_union(AGDomain, MADomain);
1437 AGI++;
1438 }
1439 }
1440 if (NewAG.size() > 1)
1441 AliasGroups.push_back(std::move(NewAG));
1442 isl_set_free(AGDomain);
1443 }
1444
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001445 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001446 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1447 for (AliasGroupTy &AG : AliasGroups) {
1448 NonReadOnlyBaseValues.clear();
1449 ReadOnlyPairs.clear();
1450
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001451 if (AG.size() < 2) {
1452 AG.clear();
1453 continue;
1454 }
1455
Johannes Doerfert13771732014-10-01 12:40:46 +00001456 for (auto II = AG.begin(); II != AG.end();) {
1457 Value *BaseAddr = (*II)->getBaseAddr();
1458 if (HasWriteAccess.count(BaseAddr)) {
1459 NonReadOnlyBaseValues.insert(BaseAddr);
1460 II++;
1461 } else {
1462 ReadOnlyPairs[BaseAddr].insert(*II);
1463 II = AG.erase(II);
1464 }
1465 }
1466
1467 // If we don't have read only pointers check if there are at least two
1468 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001469 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001470 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001471 continue;
1472 }
1473
1474 // If we don't have non read only pointers clear the alias group.
1475 if (NonReadOnlyBaseValues.empty()) {
1476 AG.clear();
1477 continue;
1478 }
1479
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001480 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001481 MinMaxAliasGroups.emplace_back();
1482 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1483 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1484 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1485 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001486
1487 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001488
1489 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001490 for (MemoryAccess *MA : AG)
1491 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001492
Tobias Grosserbb853c22015-07-25 12:31:03 +00001493 bool Valid = calculateMinMaxAccess(
1494 Accesses, getDomains(), getAssumedContext(), MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001495
1496 // Bail out if the number of values we need to compare is too large.
1497 // This is important as the number of comparisions grows quadratically with
1498 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001499 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1500 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001501 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001502
1503 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001504 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001505 Accesses = isl_union_map_empty(getParamSpace());
1506
1507 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1508 for (MemoryAccess *MA : ReadOnlyPair.second)
1509 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1510
Tobias Grosserbb853c22015-07-25 12:31:03 +00001511 Valid = calculateMinMaxAccess(Accesses, getDomains(), getAssumedContext(),
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001512 MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001513
1514 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001515 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001516 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001517
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001518 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001519}
1520
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001521static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1522 ScopDetection &SD) {
1523
1524 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1525
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001526 unsigned MinLD = INT_MAX, MaxLD = 0;
1527 for (BasicBlock *BB : R.blocks()) {
1528 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001529 if (!R.contains(L))
1530 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001531 if (BoxedLoops && BoxedLoops->count(L))
1532 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001533 unsigned LD = L->getLoopDepth();
1534 MinLD = std::min(MinLD, LD);
1535 MaxLD = std::max(MaxLD, LD);
1536 }
1537 }
1538
1539 // Handle the case that there is no loop in the SCoP first.
1540 if (MaxLD == 0)
1541 return 1;
1542
1543 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1544 assert(MaxLD >= MinLD &&
1545 "Maximal loop depth was smaller than mininaml loop depth?");
1546 return MaxLD - MinLD + 1;
1547}
1548
Michael Kruse471a5e32015-07-30 19:27:04 +00001549Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, isl_ctx *Context,
1550 unsigned MaxLoopDepth)
1551 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert574182d2015-08-12 10:19:50 +00001552 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001553
Michael Kruse471a5e32015-07-30 19:27:04 +00001554void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI,
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001555 ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001556 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001557
Tobias Grosserabfbe632013-02-05 12:09:06 +00001558 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001559
Tobias Grosser54839312015-04-21 11:37:25 +00001560 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001561 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00001562 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00001563 if (!Schedule)
1564 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00001565
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001566 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001567 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001568 addUserContext();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001569 simplifyAssumedContext();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001570 buildAliasChecks(AA);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001571
Tobias Grosser75805372011-04-29 06:27:02 +00001572 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1573}
1574
Michael Kruse471a5e32015-07-30 19:27:04 +00001575Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
1576 ScalarEvolution &SE, ScopDetection &SD,
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001577 AliasAnalysis &AA, isl_ctx *ctx) {
Michael Kruse471a5e32015-07-30 19:27:04 +00001578 auto &R = TempScop.getMaxRegion();
1579 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
1580 auto S = new Scop(R, SE, ctx, MaxLoopDepth);
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001581 S->initFromTempScop(TempScop, LI, SD, AA);
1582
Michael Kruse471a5e32015-07-30 19:27:04 +00001583 return S;
1584}
1585
Tobias Grosser75805372011-04-29 06:27:02 +00001586Scop::~Scop() {
1587 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001588 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00001589 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001590
Johannes Doerfertb164c792014-09-18 11:17:17 +00001591 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001592 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001593 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001594 isl_pw_multi_aff_free(MMA.first);
1595 isl_pw_multi_aff_free(MMA.second);
1596 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001597 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001598 isl_pw_multi_aff_free(MMA.first);
1599 isl_pw_multi_aff_free(MMA.second);
1600 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001601 }
Tobias Grosser75805372011-04-29 06:27:02 +00001602}
1603
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001604const ScopArrayInfo *
1605Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00001606 const SmallVector<const SCEV *, 4> &Sizes,
1607 bool IsPHI) {
1608 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001609 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001610 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
1611 this));
Tobias Grosserab671442015-05-23 05:58:27 +00001612 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001613}
1614
Tobias Grosser92245222015-07-28 14:53:44 +00001615const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
1616 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001617 assert(SAI && "No ScopArrayInfo available for this base pointer");
1618 return SAI;
1619}
1620
Tobias Grosser74394f02013-01-14 22:40:23 +00001621std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001622std::string Scop::getAssumedContextStr() const {
1623 return stringFromIslObj(AssumedContext);
1624}
Tobias Grosser75805372011-04-29 06:27:02 +00001625
1626std::string Scop::getNameStr() const {
1627 std::string ExitName, EntryName;
1628 raw_string_ostream ExitStr(ExitName);
1629 raw_string_ostream EntryStr(EntryName);
1630
Tobias Grosserf240b482014-01-09 10:42:15 +00001631 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001632 EntryStr.str();
1633
1634 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001635 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001636 ExitStr.str();
1637 } else
1638 ExitName = "FunctionExit";
1639
1640 return EntryName + "---" + ExitName;
1641}
1642
Tobias Grosser74394f02013-01-14 22:40:23 +00001643__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001644__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001645 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001646}
1647
Tobias Grossere86109f2013-10-29 21:05:49 +00001648__isl_give isl_set *Scop::getAssumedContext() const {
1649 return isl_set_copy(AssumedContext);
1650}
1651
Johannes Doerfert43788c52015-08-20 05:58:56 +00001652__isl_give isl_set *Scop::getRuntimeCheckContext() const {
1653 isl_set *RuntimeCheckContext = getAssumedContext();
1654 return RuntimeCheckContext;
1655}
1656
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001657bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00001658 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001659 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00001660 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
1661 isl_set_free(RuntimeCheckContext);
1662 return IsFeasible;
1663}
1664
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001665void Scop::addAssumption(__isl_take isl_set *Set) {
1666 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001667 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001668}
1669
Tobias Grosser75805372011-04-29 06:27:02 +00001670void Scop::printContext(raw_ostream &OS) const {
1671 OS << "Context:\n";
1672
1673 if (!Context) {
1674 OS.indent(4) << "n/a\n\n";
1675 return;
1676 }
1677
1678 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001679
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001680 OS.indent(4) << "Assumed Context:\n";
1681 if (!AssumedContext) {
1682 OS.indent(4) << "n/a\n\n";
1683 return;
1684 }
1685
1686 OS.indent(4) << getAssumedContextStr() << "\n";
1687
Tobias Grosser083d3d32014-06-28 08:59:45 +00001688 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001689 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001690 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1691 }
Tobias Grosser75805372011-04-29 06:27:02 +00001692}
1693
Johannes Doerfertb164c792014-09-18 11:17:17 +00001694void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001695 int noOfGroups = 0;
1696 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001697 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001698 noOfGroups += 1;
1699 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001700 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001701 }
1702
Tobias Grosserbb853c22015-07-25 12:31:03 +00001703 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00001704 if (MinMaxAliasGroups.empty()) {
1705 OS.indent(8) << "n/a\n";
1706 return;
1707 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001708
Tobias Grosserbb853c22015-07-25 12:31:03 +00001709 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001710
1711 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001712 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001713 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001714 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001715 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1716 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001717 }
1718 OS << " ]]\n";
1719 }
1720
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001721 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001722 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00001723 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001724 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001725 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1726 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001727 }
1728 OS << " ]]\n";
1729 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001730 }
1731}
1732
Tobias Grosser75805372011-04-29 06:27:02 +00001733void Scop::printStatements(raw_ostream &OS) const {
1734 OS << "Statements {\n";
1735
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001736 for (const ScopStmt &Stmt : *this)
1737 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001738
1739 OS.indent(4) << "}\n";
1740}
1741
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001742void Scop::printArrayInfo(raw_ostream &OS) const {
1743 OS << "Arrays {\n";
1744
Tobias Grosserab671442015-05-23 05:58:27 +00001745 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001746 Array.second->print(OS);
1747
1748 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001749
1750 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
1751
1752 for (auto &Array : arrays())
1753 Array.second->print(OS, /* SizeAsPwAff */ true);
1754
1755 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001756}
1757
Tobias Grosser75805372011-04-29 06:27:02 +00001758void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001759 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1760 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001761 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001762 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001763 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001764 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001765 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001766 printStatements(OS.indent(4));
1767}
1768
1769void Scop::dump() const { print(dbgs()); }
1770
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001771isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001772
Johannes Doerfert574182d2015-08-12 10:19:50 +00001773__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, ScopStmt *Stmt) {
1774 return Affinator.getPwAff(E, Stmt);
1775}
1776
Tobias Grosser808cd692015-07-14 09:33:13 +00001777__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001778 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001779
Tobias Grosser808cd692015-07-14 09:33:13 +00001780 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001781 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001782
1783 return Domain;
1784}
1785
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001786__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001787 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001788
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001789 for (ScopStmt &Stmt : *this) {
1790 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001791 if (!MA->isMustWrite())
1792 continue;
1793
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001794 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001795 isl_map *AccessDomain = MA->getAccessRelation();
1796 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1797 Write = isl_union_map_add_map(Write, AccessDomain);
1798 }
1799 }
1800 return isl_union_map_coalesce(Write);
1801}
1802
1803__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001804 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001805
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001806 for (ScopStmt &Stmt : *this) {
1807 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001808 if (!MA->isMayWrite())
1809 continue;
1810
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001811 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001812 isl_map *AccessDomain = MA->getAccessRelation();
1813 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1814 Write = isl_union_map_add_map(Write, AccessDomain);
1815 }
1816 }
1817 return isl_union_map_coalesce(Write);
1818}
1819
Tobias Grosser37eb4222014-02-20 21:43:54 +00001820__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001821 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001822
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001823 for (ScopStmt &Stmt : *this) {
1824 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001825 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001826 continue;
1827
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001828 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001829 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001830 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1831 Write = isl_union_map_add_map(Write, AccessDomain);
1832 }
1833 }
1834 return isl_union_map_coalesce(Write);
1835}
1836
1837__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001838 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001839
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001840 for (ScopStmt &Stmt : *this) {
1841 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001842 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001843 continue;
1844
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001845 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001846 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001847
1848 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1849 Read = isl_union_map_add_map(Read, AccessDomain);
1850 }
1851 }
1852 return isl_union_map_coalesce(Read);
1853}
1854
Tobias Grosser808cd692015-07-14 09:33:13 +00001855__isl_give isl_union_map *Scop::getSchedule() const {
1856 auto Tree = getScheduleTree();
1857 auto S = isl_schedule_get_map(Tree);
1858 isl_schedule_free(Tree);
1859 return S;
1860}
Tobias Grosser37eb4222014-02-20 21:43:54 +00001861
Tobias Grosser808cd692015-07-14 09:33:13 +00001862__isl_give isl_schedule *Scop::getScheduleTree() const {
1863 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
1864 getDomains());
1865}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001866
Tobias Grosser808cd692015-07-14 09:33:13 +00001867void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
1868 auto *S = isl_schedule_from_domain(getDomains());
1869 S = isl_schedule_insert_partial_schedule(
1870 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
1871 isl_schedule_free(Schedule);
1872 Schedule = S;
1873}
1874
1875void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
1876 isl_schedule_free(Schedule);
1877 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00001878}
1879
1880bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1881 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001882 for (ScopStmt &Stmt : *this) {
1883 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001884 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1885 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1886
1887 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1888 isl_union_set_free(StmtDomain);
1889 isl_union_set_free(NewStmtDomain);
1890 continue;
1891 }
1892
1893 Changed = true;
1894
1895 isl_union_set_free(StmtDomain);
1896 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1897
1898 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001899 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001900 isl_union_set_free(NewStmtDomain);
1901 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001902 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001903 }
1904 isl_union_set_free(Domain);
1905 return Changed;
1906}
1907
Tobias Grosser75805372011-04-29 06:27:02 +00001908ScalarEvolution *Scop::getSE() const { return SE; }
1909
1910bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1911 if (tempScop.getAccessFunctions(BB))
1912 return false;
1913
1914 return true;
1915}
1916
Tobias Grosser808cd692015-07-14 09:33:13 +00001917struct MapToDimensionDataTy {
1918 int N;
1919 isl_union_pw_multi_aff *Res;
1920};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001921
Tobias Grosser808cd692015-07-14 09:33:13 +00001922// @brief Create a function that maps the elements of 'Set' to its N-th
1923// dimension.
1924//
1925// The result is added to 'User->Res'.
1926//
1927// @param Set The input set.
1928// @param N The dimension to map to.
1929//
1930// @returns Zero if no error occurred, non-zero otherwise.
1931static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
1932 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
1933 int Dim;
1934 isl_space *Space;
1935 isl_pw_multi_aff *PMA;
1936
1937 Dim = isl_set_dim(Set, isl_dim_set);
1938 Space = isl_set_get_space(Set);
1939 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
1940 Dim - Data->N);
1941 if (Data->N > 1)
1942 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
1943 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
1944
1945 isl_set_free(Set);
1946
1947 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001948}
1949
Tobias Grosser808cd692015-07-14 09:33:13 +00001950// @brief Create a function that maps the elements of Domain to their Nth
1951// dimension.
1952//
1953// @param Domain The set of elements to map.
1954// @param N The dimension to map to.
1955static __isl_give isl_multi_union_pw_aff *
1956mapToDimension(__isl_take isl_union_set *Domain, int N) {
1957 struct MapToDimensionDataTy Data;
1958 isl_space *Space;
1959
1960 Space = isl_union_set_get_space(Domain);
1961 Data.N = N;
1962 Data.Res = isl_union_pw_multi_aff_empty(Space);
1963 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
1964 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
1965
1966 isl_union_set_free(Domain);
1967 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
1968}
1969
1970ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1971 const Region &CurRegion,
1972 SmallVectorImpl<Loop *> &NestLoops) {
1973 ScopStmt *Stmt;
1974 if (BB) {
1975 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
1976 Stmt = &Stmts.back();
1977 StmtMap[BB] = Stmt;
1978 } else {
1979 assert(R && "Either basic block or a region expected.");
1980 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
1981 Stmt = &Stmts.back();
1982 for (BasicBlock *BB : R->blocks())
1983 StmtMap[BB] = Stmt;
1984 }
1985 return Stmt;
1986}
1987
Michael Kruse046dde42015-08-10 13:01:57 +00001988__isl_give isl_schedule *
1989Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
1990 const Region &CurRegion,
1991 SmallVectorImpl<Loop *> &NestLoops) {
1992 if (isTrivialBB(BB, tempScop))
1993 return nullptr;
1994
1995 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
1996 auto *Domain = Stmt->getDomain();
1997 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
1998}
1999
Tobias Grosser808cd692015-07-14 09:33:13 +00002000__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
2001 const Region &CurRegion,
2002 SmallVectorImpl<Loop *> &NestLoops,
2003 LoopInfo &LI, ScopDetection &SD) {
2004 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
2005 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
2006 tempScop, CurRegion, NestLoops);
2007 auto *Domain = Stmt->getDomain();
2008 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2009 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002010
Tobias Grosser75805372011-04-29 06:27:02 +00002011 Loop *L = castToLoop(CurRegion, LI);
2012
2013 if (L)
2014 NestLoops.push_back(L);
2015
2016 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00002017 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002018
2019 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002020 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00002021 I != E; ++I) {
2022 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002023 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002024 StmtSchedule =
2025 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002026 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00002027 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
2028 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00002029 }
Michael Kruse046dde42015-08-10 13:01:57 +00002030 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00002031 }
Tobias Grosser75805372011-04-29 06:27:02 +00002032
Tobias Grosser808cd692015-07-14 09:33:13 +00002033 if (!L)
2034 return Schedule;
2035
2036 auto *Domain = isl_schedule_get_domain(Schedule);
2037 if (!isl_union_set_is_empty(Domain)) {
2038 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
2039 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
2040 }
2041 isl_union_set_free(Domain);
2042
Tobias Grosser75805372011-04-29 06:27:02 +00002043 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00002044 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00002045}
2046
Johannes Doerfert7c494212014-10-31 23:13:39 +00002047ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002048 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002049 if (StmtMapIt == StmtMap.end())
2050 return nullptr;
2051 return StmtMapIt->second;
2052}
2053
Tobias Grosser75805372011-04-29 06:27:02 +00002054//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002055ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2056 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002057 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002058}
2059
2060ScopInfo::~ScopInfo() {
2061 clear();
2062 isl_ctx_free(ctx);
2063}
2064
Tobias Grosser75805372011-04-29 06:27:02 +00002065void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002066 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002067 AU.addRequired<RegionInfoPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002068 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002069 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002070 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002071 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002072 AU.setPreservesAll();
2073}
2074
2075bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002076 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002077 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002078 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002079 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Tobias Grosser75805372011-04-29 06:27:02 +00002080
Michael Kruse82a1c7d2015-08-14 20:10:27 +00002081 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop();
Tobias Grosser75805372011-04-29 06:27:02 +00002082
2083 // This region is no Scop.
2084 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002085 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002086 return false;
2087 }
2088
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002089 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, AA, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002090
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002091 DEBUG(scop->print(dbgs()));
2092
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002093 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002094 delete scop;
2095 scop = nullptr;
2096 return false;
2097 }
2098
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002099 // Statistics.
2100 ++ScopFound;
2101 if (scop->getMaxLoopDepth() > 0)
2102 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00002103 return false;
2104}
2105
2106char ScopInfo::ID = 0;
2107
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002108Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2109
Tobias Grosser73600b82011-10-08 00:30:40 +00002110INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2111 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002112 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002113INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002114INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002115INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002116INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002117INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002118INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002119INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2120 "Polly - Create polyhedral description of Scops", false,
2121 false)