blob: 5d65687ea24e16bf0a71c1ed6387e21a41fd572d [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Sebastian Pop27c10c62013-03-22 22:07:43 +000026#include "polly/TempScopInfo.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Johannes Doerfertecff11d2015-05-22 23:43:58 +000030#include "llvm/ADT/STLExtras.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000034#include "llvm/Analysis/RegionIterator.h"
35#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000036#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000037#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000038#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000039#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000041#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000043#include "isl/schedule.h"
44#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/set.h"
46#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000047#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000048#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000049#include <sstream>
50#include <string>
51#include <vector>
52
53using namespace llvm;
54using namespace polly;
55
Chandler Carruth95fef942014-04-22 03:30:19 +000056#define DEBUG_TYPE "polly-scops"
57
Tobias Grosser74394f02013-01-14 22:40:23 +000058STATISTIC(ScopFound, "Number of valid Scops");
59STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000060
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000061// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000062// operations can overflow easily. Additive reductions and bit operations
63// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000064static cl::opt<bool> DisableMultiplicativeReductions(
65 "polly-disable-multiplicative-reductions",
66 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
67 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068
Johannes Doerfert9143d672014-09-27 11:02:39 +000069static cl::opt<unsigned> RunTimeChecksMaxParameters(
70 "polly-rtc-max-parameters",
71 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
72 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
73
Tobias Grosser71500722015-03-28 15:11:14 +000074static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
75 "polly-rtc-max-arrays-per-group",
76 cl::desc("The maximal number of arrays to compare in each alias group."),
77 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
78
Michael Kruse046dde42015-08-10 13:01:57 +000079// Create a sequence of two schedules. Either argument may be null and is
80// interpreted as the empty schedule. Can also return null if both schedules are
81// empty.
82static __isl_give isl_schedule *
83combineInSequence(__isl_take isl_schedule *Prev,
84 __isl_take isl_schedule *Succ) {
85 if (!Prev)
86 return Succ;
87 if (!Succ)
88 return Prev;
89
90 return isl_schedule_sequence(Prev, Succ);
91}
92
Johannes Doerferte7044942015-02-24 11:58:30 +000093static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
94 const ConstantRange &Range,
95 int dim,
96 enum isl_dim_type type) {
97 isl_val *V;
98 isl_ctx *ctx = isl_set_get_ctx(S);
99
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000100 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
101 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000102 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000103 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
104
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000105 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000106 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000107 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000108 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000109 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
110
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000111 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000112 return isl_set_union(SLB, SUB);
113 else
114 return isl_set_intersect(SLB, SUB);
115}
116
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000117ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser92245222015-07-28 14:53:44 +0000118 const SmallVector<const SCEV *, 4> &DimensionSizes,
119 bool IsPHI)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000120 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000121 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
122 std::string BasePtrName =
123 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000124 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
125}
126
127ScopArrayInfo::~ScopArrayInfo() { isl_id_free(Id); }
128
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000129std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
130
131int ScopArrayInfo::getElemSizeInBytes() const {
132 return ElementType->getPrimitiveSizeInBits() / 8;
133}
134
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000135isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
136
137void ScopArrayInfo::dump() const { print(errs()); }
138
139void ScopArrayInfo::print(raw_ostream &OS) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000140 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000141 for (unsigned u = 0; u < getNumberOfDimensions(); u++)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000142 OS << "[" << *DimensionSizes[u] << "]";
143 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000144}
145
146const ScopArrayInfo *
147ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
148 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
149 assert(Id && "Output dimension didn't have an ID");
150 return getFromId(Id);
151}
152
153const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
154 void *User = isl_id_get_user(Id);
155 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
156 isl_id_free(Id);
157 return SAI;
158}
159
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000160const std::string
161MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
162 switch (RT) {
163 case MemoryAccess::RT_NONE:
164 llvm_unreachable("Requested a reduction operator string for a memory "
165 "access which isn't a reduction");
166 case MemoryAccess::RT_ADD:
167 return "+";
168 case MemoryAccess::RT_MUL:
169 return "*";
170 case MemoryAccess::RT_BOR:
171 return "|";
172 case MemoryAccess::RT_BXOR:
173 return "^";
174 case MemoryAccess::RT_BAND:
175 return "&";
176 }
177 llvm_unreachable("Unknown reduction type");
178 return "";
179}
180
Johannes Doerfertf6183392014-07-01 20:52:51 +0000181/// @brief Return the reduction type for a given binary operator
182static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
183 const Instruction *Load) {
184 if (!BinOp)
185 return MemoryAccess::RT_NONE;
186 switch (BinOp->getOpcode()) {
187 case Instruction::FAdd:
188 if (!BinOp->hasUnsafeAlgebra())
189 return MemoryAccess::RT_NONE;
190 // Fall through
191 case Instruction::Add:
192 return MemoryAccess::RT_ADD;
193 case Instruction::Or:
194 return MemoryAccess::RT_BOR;
195 case Instruction::Xor:
196 return MemoryAccess::RT_BXOR;
197 case Instruction::And:
198 return MemoryAccess::RT_BAND;
199 case Instruction::FMul:
200 if (!BinOp->hasUnsafeAlgebra())
201 return MemoryAccess::RT_NONE;
202 // Fall through
203 case Instruction::Mul:
204 if (DisableMultiplicativeReductions)
205 return MemoryAccess::RT_NONE;
206 return MemoryAccess::RT_MUL;
207 default:
208 return MemoryAccess::RT_NONE;
209 }
210}
Tobias Grosser75805372011-04-29 06:27:02 +0000211//===----------------------------------------------------------------------===//
212
213MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000214 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000215 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000216 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000217}
218
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000219static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
220 switch (Access.getType()) {
221 case IRAccess::READ:
222 return MemoryAccess::READ;
223 case IRAccess::MUST_WRITE:
224 return MemoryAccess::MUST_WRITE;
225 case IRAccess::MAY_WRITE:
226 return MemoryAccess::MAY_WRITE;
227 }
228 llvm_unreachable("Unknown IRAccess type!");
229}
230
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000231const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
232 isl_id *ArrayId = getArrayId();
233 void *User = isl_id_get_user(ArrayId);
234 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
235 isl_id_free(ArrayId);
236 return SAI;
237}
238
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000239__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000240 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
241}
242
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000243__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
244 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000245 isl_map *Schedule, *ScheduledAccRel;
246 isl_union_set *UDomain;
247
248 UDomain = isl_union_set_from_set(getStatement()->getDomain());
249 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
250 Schedule = isl_map_from_union_map(USchedule);
251 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
252 return isl_pw_multi_aff_from_map(ScheduledAccRel);
253}
254
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000255__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000256 return isl_map_copy(AccessRelation);
257}
258
Johannes Doerferta99130f2014-10-13 12:58:03 +0000259std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000260 return stringFromIslObj(AccessRelation);
261}
262
Johannes Doerferta99130f2014-10-13 12:58:03 +0000263__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000264 return isl_map_get_space(AccessRelation);
265}
266
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000267__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000268 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000269}
270
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000271__isl_give isl_basic_map *
272MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000273 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000274 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000275
Tobias Grosser084d8f72012-05-29 09:29:44 +0000276 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000277 isl_basic_set_universe(Statement->getDomainSpace()),
278 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000279}
280
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000281// Formalize no out-of-bound access assumption
282//
283// When delinearizing array accesses we optimistically assume that the
284// delinearized accesses do not access out of bound locations (the subscript
285// expression of each array evaluates for each statement instance that is
286// executed to a value that is larger than zero and strictly smaller than the
287// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000288// dimension for which we do not need to assume any upper bound. At this point
289// we formalize this assumption to ensure that at code generation time the
290// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000291//
292// To find the set of constraints necessary to avoid out of bound accesses, we
293// first build the set of data locations that are not within array bounds. We
294// then apply the reverse access relation to obtain the set of iterations that
295// may contain invalid accesses and reduce this set of iterations to the ones
296// that are actually executed by intersecting them with the domain of the
297// statement. If we now project out all loop dimensions, we obtain a set of
298// parameters that may cause statement instances to be executed that may
299// possibly yield out of bound memory accesses. The complement of these
300// constraints is the set of constraints that needs to be assumed to ensure such
301// statement instances are never executed.
302void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000303 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000304 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000305 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000306 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
307 isl_pw_aff *Var =
308 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
309 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
310
311 isl_set *DimOutside;
312
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000313 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000314 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000315
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000316 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
317 Statement->getNumIterators());
318 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
319 isl_space_dim(Space, isl_dim_set));
320 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
321 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000322
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000323 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000324
325 Outside = isl_set_union(Outside, DimOutside);
326 }
327
328 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
329 Outside = isl_set_intersect(Outside, Statement->getDomain());
330 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000331
332 // Remove divs to avoid the construction of overly complicated assumptions.
333 // Doing so increases the set of parameter combinations that are assumed to
334 // not appear. This is always save, but may make the resulting run-time check
335 // bail out more often than strictly necessary.
336 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000337 Outside = isl_set_complement(Outside);
338 Statement->getParent()->addAssumption(Outside);
339 isl_space_free(Space);
340}
341
Johannes Doerferte7044942015-02-24 11:58:30 +0000342void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
343 ScalarEvolution *SE = Statement->getParent()->getSE();
344
345 Value *Ptr = getPointerOperand(*getAccessInstruction());
346 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
347 return;
348
349 auto *PtrSCEV = SE->getSCEV(Ptr);
350 if (isa<SCEVCouldNotCompute>(PtrSCEV))
351 return;
352
353 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
354 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
355 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
356
357 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
358 if (Range.isFullSet())
359 return;
360
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000361 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000362 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000363 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
364 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
365
366 auto Min = LB.sdiv(APInt(BW, ElementSize));
367 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000368
369 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
370 AccessRange =
371 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
372 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
373}
374
Tobias Grosser619190d2015-03-30 17:22:28 +0000375__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
376 __isl_take isl_map *AccessRelation,
377 ScopStmt *Statement) {
378 int Size = Access.Subscripts.size();
379
380 for (int i = Size - 2; i >= 0; --i) {
381 isl_space *Space;
382 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000383 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000384
385 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
386 isl_pw_aff_free(DimSize);
387 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
388
389 Space = isl_map_get_space(AccessRelation);
390 Space = isl_space_map_from_set(isl_space_range(Space));
391 Space = isl_space_align_params(Space, SpaceSize);
392
393 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
394 isl_id_free(ParamId);
395
396 MapOne = isl_map_universe(isl_space_copy(Space));
397 for (int j = 0; j < Size; ++j)
398 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
399 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
400
401 MapTwo = isl_map_universe(isl_space_copy(Space));
402 for (int j = 0; j < Size; ++j)
403 if (j < i || j > i + 1)
404 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
405
406 isl_local_space *LS = isl_local_space_from_space(Space);
407 isl_constraint *C;
408 C = isl_equality_alloc(isl_local_space_copy(LS));
409 C = isl_constraint_set_constant_si(C, -1);
410 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
411 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
412 MapTwo = isl_map_add_constraint(MapTwo, C);
413 C = isl_equality_alloc(LS);
414 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
415 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
416 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
417 MapTwo = isl_map_add_constraint(MapTwo, C);
418 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
419
420 MapOne = isl_map_union(MapOne, MapTwo);
421 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
422 }
423 return AccessRelation;
424}
425
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000426MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000427 ScopStmt *Statement, const ScopArrayInfo *SAI,
428 int Identifier)
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000429 : AccType(getMemoryAccessType(Access)), Statement(Statement), Inst(AccInst),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000430 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000431
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000432 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000433 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000434 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000435
436 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000437
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000438 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000439 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000440
Tobias Grossera1879642011-12-20 10:43:14 +0000441 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000442 // We overapproximate non-affine accesses with a possible access to the
443 // whole array. For read accesses it does not make a difference, if an
444 // access must or may happen. However, for write accesses it is important to
445 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000446 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000447 AccessRelation =
448 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000449
450 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000451 return;
452 }
453
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000454 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000455 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000456
Tobias Grosser79baa212014-04-10 08:38:02 +0000457 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000458 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000459
Sebastian Pop422e33f2014-06-03 18:16:31 +0000460 if (Size == 1) {
461 // For the non delinearized arrays, divide the access function of the last
462 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000463 //
464 // A stride one array access in C expressed as A[i] is expressed in
465 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
466 // two subsequent values of 'i' index two values that are stored next to
467 // each other in memory. By this division we make this characteristic
468 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000469 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000470 Affine = isl_pw_aff_scale_down_val(Affine, v);
471 }
472
473 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
474
Tobias Grosser79baa212014-04-10 08:38:02 +0000475 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000476 }
477
Tobias Grosser619190d2015-03-30 17:22:28 +0000478 AccessRelation = foldAccess(Access, AccessRelation, Statement);
479
Tobias Grosser79baa212014-04-10 08:38:02 +0000480 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000481 AccessRelation = isl_map_set_tuple_id(
482 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000483 AccessRelation =
484 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
485
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000486 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000487 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000488 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000489}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000490
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000491void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000492 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000493 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000494}
495
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000496const std::string MemoryAccess::getReductionOperatorStr() const {
497 return MemoryAccess::getReductionOperatorStr(getReductionType());
498}
499
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000500__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
501
Johannes Doerfertf6183392014-07-01 20:52:51 +0000502raw_ostream &polly::operator<<(raw_ostream &OS,
503 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000504 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000505 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000506 else
507 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000508 return OS;
509}
510
Tobias Grosser75805372011-04-29 06:27:02 +0000511void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000512 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000513 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000514 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000515 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000516 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000517 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000518 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000519 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000520 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000521 break;
522 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000523 OS << "[Reduction Type: " << getReductionType() << "] ";
524 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000525 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000526}
527
Tobias Grosser74394f02013-01-14 22:40:23 +0000528void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000529
530// Create a map in the size of the provided set domain, that maps from the
531// one element of the provided set domain to another element of the provided
532// set domain.
533// The mapping is limited to all points that are equal in all but the last
534// dimension and for which the last dimension of the input is strict smaller
535// than the last dimension of the output.
536//
537// getEqualAndLarger(set[i0, i1, ..., iX]):
538//
539// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
540// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
541//
Tobias Grosserf5338802011-10-06 00:03:35 +0000542static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000543 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000544 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000545 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000546
547 // Set all but the last dimension to be equal for the input and output
548 //
549 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
550 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000551 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000552 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000553
554 // Set the last dimension of the input to be strict smaller than the
555 // last dimension of the output.
556 //
557 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000558 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
559 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000560 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000561}
562
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000563__isl_give isl_set *
564MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000565 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000566 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000567 isl_space *Space = isl_space_range(isl_map_get_space(S));
568 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000569
Sebastian Popa00a0292012-12-18 07:46:06 +0000570 S = isl_map_reverse(S);
571 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000572
Sebastian Popa00a0292012-12-18 07:46:06 +0000573 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
574 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
575 NextScatt = isl_map_apply_domain(NextScatt, S);
576 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000577
Sebastian Popa00a0292012-12-18 07:46:06 +0000578 isl_set *Deltas = isl_map_deltas(NextScatt);
579 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000580}
581
Sebastian Popa00a0292012-12-18 07:46:06 +0000582bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000583 int StrideWidth) const {
584 isl_set *Stride, *StrideX;
585 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000586
Sebastian Popa00a0292012-12-18 07:46:06 +0000587 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000588 StrideX = isl_set_universe(isl_set_get_space(Stride));
589 StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
590 IsStrideX = isl_set_is_equal(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000591
Tobias Grosser28dd4862012-01-24 16:42:16 +0000592 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000593 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000594
Tobias Grosser28dd4862012-01-24 16:42:16 +0000595 return IsStrideX;
596}
597
Sebastian Popa00a0292012-12-18 07:46:06 +0000598bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
599 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000600}
601
Tobias Grosser79baa212014-04-10 08:38:02 +0000602bool MemoryAccess::isScalar() const {
603 return isl_map_n_out(AccessRelation) == 0;
604}
605
Sebastian Popa00a0292012-12-18 07:46:06 +0000606bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
607 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000608}
609
Tobias Grosser5d453812011-10-06 00:04:11 +0000610void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000611 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000612 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000613}
Tobias Grosser75805372011-04-29 06:27:02 +0000614
615//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000616
Tobias Grosser808cd692015-07-14 09:33:13 +0000617isl_map *ScopStmt::getSchedule() const {
618 isl_set *Domain = getDomain();
619 if (isl_set_is_empty(Domain)) {
620 isl_set_free(Domain);
621 return isl_map_from_aff(
622 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
623 }
624 auto *Schedule = getParent()->getSchedule();
625 Schedule = isl_union_map_intersect_domain(
626 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
627 if (isl_union_map_is_empty(Schedule)) {
628 isl_set_free(Domain);
629 isl_union_map_free(Schedule);
630 return isl_map_from_aff(
631 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
632 }
633 auto *M = isl_map_from_union_map(Schedule);
634 M = isl_map_coalesce(M);
635 M = isl_map_gist_domain(M, Domain);
636 M = isl_map_coalesce(M);
637 return M;
638}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000639
Johannes Doerfert574182d2015-08-12 10:19:50 +0000640__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
641 return getParent()->getPwAff(E, this);
642}
643
Tobias Grosser37eb4222014-02-20 21:43:54 +0000644void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
645 assert(isl_set_is_subset(NewDomain, Domain) &&
646 "New domain is not a subset of old domain!");
647 isl_set_free(Domain);
648 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000649}
650
Tobias Grosser62139132015-08-02 16:17:41 +0000651// @brief Get the data-type of the elements accessed
652static Type *getAccessType(IRAccess &Access, Instruction *AccessInst) {
653 if (Access.isPHI())
654 return Access.getBase()->getType();
655
656 if (StoreInst *Store = dyn_cast<StoreInst>(AccessInst))
657 return Store->getValueOperand()->getType();
658 if (BranchInst *Branch = dyn_cast<BranchInst>(AccessInst))
659 return Branch->getCondition()->getType();
660 return AccessInst->getType();
661}
662
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000663void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
664 bool isApproximated) {
665 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
666 if (!AFS)
667 return;
668
669 for (auto &AccessPair : *AFS) {
670 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000671 Instruction *AccessInst = AccessPair.second;
Tobias Grosser62139132015-08-02 16:17:41 +0000672 Type *ElementType = getAccessType(Access, AccessInst);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000673
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000674 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000675 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000676
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000677 if (isApproximated && Access.isWrite())
678 Access.setMayWrite();
679
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000680 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
681 if (!MAL)
682 MAL = new MemoryAccessList();
683 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
684 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000685 }
686}
687
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000688void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000689 for (MemoryAccess *MA : *this)
690 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000691
692 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000693}
694
Tobias Grosser65b00582011-11-08 15:41:19 +0000695__isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000696 isl_pw_aff *L = getPwAff(Comp.getLHS());
697 isl_pw_aff *R = getPwAff(Comp.getRHS());
Tobias Grosser75805372011-04-29 06:27:02 +0000698
Tobias Grosserd2795d02011-08-18 07:51:40 +0000699 switch (Comp.getPred()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000700 case ICmpInst::ICMP_EQ:
Tobias Grosser048c8792011-10-23 20:59:20 +0000701 return isl_pw_aff_eq_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000702 case ICmpInst::ICMP_NE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000703 return isl_pw_aff_ne_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000704 case ICmpInst::ICMP_SLT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000705 return isl_pw_aff_lt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000706 case ICmpInst::ICMP_SLE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000707 return isl_pw_aff_le_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000708 case ICmpInst::ICMP_SGT:
Tobias Grosser048c8792011-10-23 20:59:20 +0000709 return isl_pw_aff_gt_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000710 case ICmpInst::ICMP_SGE:
Tobias Grosser048c8792011-10-23 20:59:20 +0000711 return isl_pw_aff_ge_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000712 case ICmpInst::ICMP_ULT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000713 return isl_pw_aff_lt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000714 case ICmpInst::ICMP_UGT:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000715 return isl_pw_aff_gt_set(L, R);
Tobias Grosserd2795d02011-08-18 07:51:40 +0000716 case ICmpInst::ICMP_ULE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000717 return isl_pw_aff_le_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000718 case ICmpInst::ICMP_UGE:
Tobias Grosserbfbc3692015-01-09 00:01:33 +0000719 return isl_pw_aff_ge_set(L, R);
Tobias Grosser75805372011-04-29 06:27:02 +0000720 default:
721 llvm_unreachable("Non integer predicate not supported");
722 }
Tobias Grosser75805372011-04-29 06:27:02 +0000723}
724
Tobias Grossere19661e2011-10-07 08:46:57 +0000725__isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
Tobias Grosser60b54f12011-11-08 15:41:28 +0000726 TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000727 isl_space *Space;
728 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000729
Tobias Grossere19661e2011-10-07 08:46:57 +0000730 Space = isl_set_get_space(Domain);
731 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000732
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000733 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000734 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000735 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000736 isl_pw_aff *IV =
737 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000738
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000739 // 0 <= IV.
740 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
741 Domain = isl_set_intersect(Domain, LowerBound);
742
743 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000744 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000745 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000746 isl_pw_aff *UpperBound = getPwAff(LatchExecutions);
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000747 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
Tobias Grosser75805372011-04-29 06:27:02 +0000748 Domain = isl_set_intersect(Domain, UpperBoundSet);
749 }
750
Tobias Grosserf5338802011-10-06 00:03:35 +0000751 isl_local_space_free(LocalSpace);
Tobias Grossere19661e2011-10-07 08:46:57 +0000752 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000753}
754
Tobias Grossere602a072013-05-07 07:30:56 +0000755__isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
756 TempScop &tempScop,
757 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000758 const Region *TopRegion = tempScop.getMaxRegion().getParent(),
Tobias Grosserd7e58642013-04-10 06:55:45 +0000759 *CurrentRegion = &CurRegion;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000760 const BasicBlock *BranchingBB = BB ? BB : R->getEntry();
Tobias Grosser75805372011-04-29 06:27:02 +0000761
Tobias Grosser75805372011-04-29 06:27:02 +0000762 do {
Tobias Grossere19661e2011-10-07 08:46:57 +0000763 if (BranchingBB != CurrentRegion->getEntry()) {
764 if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
Tobias Grosser083d3d32014-06-28 08:59:45 +0000765 for (const auto &C : *Condition) {
766 isl_set *ConditionSet = buildConditionSet(C);
Tobias Grossere19661e2011-10-07 08:46:57 +0000767 Domain = isl_set_intersect(Domain, ConditionSet);
Tobias Grosser75805372011-04-29 06:27:02 +0000768 }
769 }
Tobias Grossere19661e2011-10-07 08:46:57 +0000770 BranchingBB = CurrentRegion->getEntry();
771 CurrentRegion = CurrentRegion->getParent();
772 } while (TopRegion != CurrentRegion);
Tobias Grosser75805372011-04-29 06:27:02 +0000773
Tobias Grossere19661e2011-10-07 08:46:57 +0000774 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000775}
776
Tobias Grossere602a072013-05-07 07:30:56 +0000777__isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
778 const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000779 isl_space *Space;
780 isl_set *Domain;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000781 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000782
783 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
784
Tobias Grosser084d8f72012-05-29 09:29:44 +0000785 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
786
Tobias Grossere19661e2011-10-07 08:46:57 +0000787 Domain = isl_set_universe(Space);
Tobias Grossere19661e2011-10-07 08:46:57 +0000788 Domain = addLoopBoundsToDomain(Domain, tempScop);
789 Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000790 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grossere19661e2011-10-07 08:46:57 +0000791
792 return Domain;
Tobias Grosser75805372011-04-29 06:27:02 +0000793}
794
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000795void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
796 int Dimension = 0;
797 isl_ctx *Ctx = Parent.getIslCtx();
798 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
799 Type *Ty = GEP->getPointerOperandType();
800 ScalarEvolution &SE = *Parent.getSE();
801
802 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
803 Dimension = 1;
804 Ty = PtrTy->getElementType();
805 }
806
807 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
808 unsigned int Operand = 1 + Dimension;
809
810 if (GEP->getNumOperands() <= Operand)
811 break;
812
813 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
814
815 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000816 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000817 AccessOffset =
818 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
819
820 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
821 isl_local_space_copy(LSpace),
822 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
823
824 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
825 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
826 OutOfBound = isl_set_params(OutOfBound);
827 isl_set *InBound = isl_set_complement(OutOfBound);
828 isl_set *Executed = isl_set_params(getDomain());
829
830 // A => B == !A or B
831 isl_set *InBoundIfExecuted =
832 isl_set_union(isl_set_complement(Executed), InBound);
833
834 Parent.addAssumption(InBoundIfExecuted);
835 }
836
837 Dimension += 1;
838 Ty = ArrayTy->getElementType();
839 }
840
841 isl_local_space_free(LSpace);
842}
843
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000844void ScopStmt::deriveAssumptions(BasicBlock *Block) {
845 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000846 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
847 deriveAssumptionsFromGEP(GEP);
848}
849
Tobias Grosser74394f02013-01-14 22:40:23 +0000850ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000851 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000852 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
853 NestLoops(Nest.size()) {
854 // Setup the induction variables.
855 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
856 NestLoops[i] = Nest[i];
857
Tobias Grosser16c44032015-07-09 07:31:45 +0000858 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000859
860 Domain = buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000861
862 BasicBlock *EntryBB = R.getEntry();
863 for (BasicBlock *Block : R.blocks()) {
864 buildAccesses(tempScop, Block, Block != EntryBB);
865 deriveAssumptions(Block);
866 }
867 checkForReductions();
868}
869
870ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000871 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000872 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
873 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +0000874 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +0000875 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +0000876 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +0000877
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000878 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +0000879
Tobias Grossere19661e2011-10-07 08:46:57 +0000880 Domain = buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000881 buildAccesses(tempScop, BB);
882 deriveAssumptions(BB);
Johannes Doerferte58a0122014-06-27 20:31:28 +0000883 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000884}
885
Johannes Doerferte58a0122014-06-27 20:31:28 +0000886/// @brief Collect loads which might form a reduction chain with @p StoreMA
887///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000888/// Check if the stored value for @p StoreMA is a binary operator with one or
889/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000890/// used only once (by @p StoreMA) and its load operands are also used only
891/// once, we have found a possible reduction chain. It starts at an operand
892/// load and includes the binary operator and @p StoreMA.
893///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000894/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +0000895/// escape this block or into any other store except @p StoreMA.
896void ScopStmt::collectCandiateReductionLoads(
897 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
898 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
899 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000900 return;
901
902 // Skip if there is not one binary operator between the load and the store
903 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +0000904 if (!BinOp)
905 return;
906
907 // Skip if the binary operators has multiple uses
908 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000909 return;
910
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000911 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000912 if (!BinOp->isCommutative() || !BinOp->isAssociative())
913 return;
914
Johannes Doerfert9890a052014-07-01 00:32:29 +0000915 // Skip if the binary operator is outside the current SCoP
916 if (BinOp->getParent() != Store->getParent())
917 return;
918
Johannes Doerfert0ee1f212014-06-17 17:31:36 +0000919 // Skip if it is a multiplicative reduction and we disabled them
920 if (DisableMultiplicativeReductions &&
921 (BinOp->getOpcode() == Instruction::Mul ||
922 BinOp->getOpcode() == Instruction::FMul))
923 return;
924
Johannes Doerferte58a0122014-06-27 20:31:28 +0000925 // Check the binary operator operands for a candidate load
926 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
927 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
928 if (!PossibleLoad0 && !PossibleLoad1)
929 return;
930
931 // A load is only a candidate if it cannot escape (thus has only this use)
932 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000933 if (PossibleLoad0->getParent() == Store->getParent())
934 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000935 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +0000936 if (PossibleLoad1->getParent() == Store->getParent())
937 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +0000938}
939
940/// @brief Check for reductions in this ScopStmt
941///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000942/// Iterate over all store memory accesses and check for valid binary reduction
943/// like chains. For all candidates we check if they have the same base address
944/// and there are no other accesses which overlap with them. The base address
945/// check rules out impossible reductions candidates early. The overlap check,
946/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +0000947/// guarantees that none of the intermediate results will escape during
948/// execution of the loop nest. We basically check here that no other memory
949/// access can access the same memory as the potential reduction.
950void ScopStmt::checkForReductions() {
951 SmallVector<MemoryAccess *, 2> Loads;
952 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
953
Johannes Doerfert6cad9c42015-02-24 16:00:29 +0000954 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +0000955 // stores and collecting possible reduction loads.
956 for (MemoryAccess *StoreMA : MemAccs) {
957 if (StoreMA->isRead())
958 continue;
959
960 Loads.clear();
961 collectCandiateReductionLoads(StoreMA, Loads);
962 for (MemoryAccess *LoadMA : Loads)
963 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
964 }
965
966 // Then check each possible candidate pair.
967 for (const auto &CandidatePair : Candidates) {
968 bool Valid = true;
969 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
970 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
971
972 // Skip those with obviously unequal base addresses.
973 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
974 isl_map_free(LoadAccs);
975 isl_map_free(StoreAccs);
976 continue;
977 }
978
979 // And check if the remaining for overlap with other memory accesses.
980 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
981 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
982 isl_set *AllAccs = isl_map_range(AllAccsRel);
983
984 for (MemoryAccess *MA : MemAccs) {
985 if (MA == CandidatePair.first || MA == CandidatePair.second)
986 continue;
987
988 isl_map *AccRel =
989 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
990 isl_set *Accs = isl_map_range(AccRel);
991
992 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
993 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
994 Valid = Valid && isl_set_is_empty(OverlapAccs);
995 isl_set_free(OverlapAccs);
996 }
997 }
998
999 isl_set_free(AllAccs);
1000 if (!Valid)
1001 continue;
1002
Johannes Doerfertf6183392014-07-01 20:52:51 +00001003 const LoadInst *Load =
1004 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1005 MemoryAccess::ReductionType RT =
1006 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1007
Johannes Doerferte58a0122014-06-27 20:31:28 +00001008 // If no overlapping access was found we mark the load and store as
1009 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001010 CandidatePair.first->markAsReductionLike(RT);
1011 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001012 }
Tobias Grosser75805372011-04-29 06:27:02 +00001013}
1014
Tobias Grosser74394f02013-01-14 22:40:23 +00001015std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001016
Tobias Grosser54839312015-04-21 11:37:25 +00001017std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001018 auto *S = getSchedule();
1019 auto Str = stringFromIslObj(S);
1020 isl_map_free(S);
1021 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001022}
1023
Tobias Grosser74394f02013-01-14 22:40:23 +00001024unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001025
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001026unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001027
Tobias Grosser75805372011-04-29 06:27:02 +00001028const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1029
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001030const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001031 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001032}
1033
Tobias Grosser74394f02013-01-14 22:40:23 +00001034isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001035
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001036__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001037
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001038__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001039 return isl_set_get_space(Domain);
1040}
1041
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001042__isl_give isl_id *ScopStmt::getDomainId() const {
1043 return isl_set_get_tuple_id(Domain);
1044}
Tobias Grossercd95b772012-08-30 11:49:38 +00001045
Tobias Grosser75805372011-04-29 06:27:02 +00001046ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001047 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001048 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001049}
1050
1051void ScopStmt::print(raw_ostream &OS) const {
1052 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001053 OS.indent(12) << "Domain :=\n";
1054
1055 if (Domain) {
1056 OS.indent(16) << getDomainStr() << ";\n";
1057 } else
1058 OS.indent(16) << "n/a\n";
1059
Tobias Grosser54839312015-04-21 11:37:25 +00001060 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001061
1062 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001063 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001064 } else
1065 OS.indent(16) << "n/a\n";
1066
Tobias Grosser083d3d32014-06-28 08:59:45 +00001067 for (MemoryAccess *Access : MemAccs)
1068 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001069}
1070
1071void ScopStmt::dump() const { print(dbgs()); }
1072
1073//===----------------------------------------------------------------------===//
1074/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001075
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001076void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001077 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1078 isl_set_free(Context);
1079 Context = NewContext;
1080}
1081
Tobias Grosserabfbe632013-02-05 12:09:06 +00001082void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001083 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001084 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001085 if (ParameterIds.find(Parameter) != ParameterIds.end())
1086 continue;
1087
1088 int dimension = Parameters.size();
1089
1090 Parameters.push_back(Parameter);
1091 ParameterIds[Parameter] = dimension;
1092 }
1093}
1094
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001095__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1096 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001097
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001098 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001099 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001100
Tobias Grosser8f99c162011-11-15 11:38:55 +00001101 std::string ParameterName;
1102
1103 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1104 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001105 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001106 }
1107
1108 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001109 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001110
Tobias Grosser20532b82014-04-11 17:56:49 +00001111 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1112 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001113}
Tobias Grosser75805372011-04-29 06:27:02 +00001114
Tobias Grosser6be480c2011-11-08 15:41:13 +00001115void Scop::buildContext() {
1116 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001117 Context = isl_set_universe(isl_space_copy(Space));
1118 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001119}
1120
Tobias Grosser18daaca2012-05-22 10:47:27 +00001121void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001122 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001123 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001124
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001125 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001126
Johannes Doerferte7044942015-02-24 11:58:30 +00001127 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001128 }
1129}
1130
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001131void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001132 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001133 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001134
Tobias Grosser083d3d32014-06-28 08:59:45 +00001135 for (const auto &ParamID : ParameterIds) {
1136 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001137 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001138 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001139 }
1140
1141 // Align the parameters of all data structures to the model.
1142 Context = isl_set_align_params(Context, Space);
1143
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001144 for (ScopStmt &Stmt : *this)
1145 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001146}
1147
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001148void Scop::simplifyAssumedContext() {
1149 // The parameter constraints of the iteration domains give us a set of
1150 // constraints that need to hold for all cases where at least a single
1151 // statement iteration is executed in the whole scop. We now simplify the
1152 // assumed context under the assumption that such constraints hold and at
1153 // least a single statement iteration is executed. For cases where no
1154 // statement instances are executed, the assumptions we have taken about
1155 // the executed code do not matter and can be changed.
1156 //
1157 // WARNING: This only holds if the assumptions we have taken do not reduce
1158 // the set of statement instances that are executed. Otherwise we
1159 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001160 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001161 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001162 // performed. In such a case, modifying the run-time conditions and
1163 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001164 // to not be executed.
1165 //
1166 // Example:
1167 //
1168 // When delinearizing the following code:
1169 //
1170 // for (long i = 0; i < 100; i++)
1171 // for (long j = 0; j < m; j++)
1172 // A[i+p][j] = 1.0;
1173 //
1174 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001175 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001176 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1177 AssumedContext =
1178 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001179 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001180}
1181
Johannes Doerfertb164c792014-09-18 11:17:17 +00001182/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001183static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001184 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1185 isl_pw_multi_aff *MinPMA, *MaxPMA;
1186 isl_pw_aff *LastDimAff;
1187 isl_aff *OneAff;
1188 unsigned Pos;
1189
Johannes Doerfert9143d672014-09-27 11:02:39 +00001190 // Restrict the number of parameters involved in the access as the lexmin/
1191 // lexmax computation will take too long if this number is high.
1192 //
1193 // Experiments with a simple test case using an i7 4800MQ:
1194 //
1195 // #Parameters involved | Time (in sec)
1196 // 6 | 0.01
1197 // 7 | 0.04
1198 // 8 | 0.12
1199 // 9 | 0.40
1200 // 10 | 1.54
1201 // 11 | 6.78
1202 // 12 | 30.38
1203 //
1204 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1205 unsigned InvolvedParams = 0;
1206 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1207 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1208 InvolvedParams++;
1209
1210 if (InvolvedParams > RunTimeChecksMaxParameters) {
1211 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001212 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001213 }
1214 }
1215
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001216 Set = isl_set_remove_divs(Set);
1217
Johannes Doerfertb164c792014-09-18 11:17:17 +00001218 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1219 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1220
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001221 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1222 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1223
Johannes Doerfertb164c792014-09-18 11:17:17 +00001224 // Adjust the last dimension of the maximal access by one as we want to
1225 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1226 // we test during code generation might now point after the end of the
1227 // allocated array but we will never dereference it anyway.
1228 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1229 "Assumed at least one output dimension");
1230 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1231 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1232 OneAff = isl_aff_zero_on_domain(
1233 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1234 OneAff = isl_aff_add_constant_si(OneAff, 1);
1235 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1236 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1237
1238 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1239
1240 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001241 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001242}
1243
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001244static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1245 isl_set *Domain = MA->getStatement()->getDomain();
1246 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1247 return isl_set_reset_tuple_id(Domain);
1248}
1249
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001250/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1251static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001252 __isl_take isl_union_set *Domains,
1253 __isl_take isl_set *AssumedContext,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001254 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001255
1256 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1257 isl_union_set *Locations = isl_union_map_range(Accesses);
1258 Locations = isl_union_set_intersect_params(Locations, AssumedContext);
1259 Locations = isl_union_set_coalesce(Locations);
1260 Locations = isl_union_set_detect_equalities(Locations);
1261 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001262 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001263 isl_union_set_free(Locations);
1264 return Valid;
1265}
1266
Johannes Doerfert9143d672014-09-27 11:02:39 +00001267bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001268 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001269 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001270 // for all memory accesses inside the SCoP.
1271 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001272 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001273 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001274 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001275 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001276 // if their access domains intersect, otherwise they are in different
1277 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001278 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001279 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001280 // and maximal accesses to each array of a group in read only and non
1281 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001282 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1283
1284 AliasSetTracker AST(AA);
1285
1286 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001287 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001288 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001289
1290 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001291 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001292 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1293 isl_set_free(StmtDomain);
1294 if (StmtDomainEmpty)
1295 continue;
1296
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001297 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001298 if (MA->isScalar())
1299 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001300 if (!MA->isRead())
1301 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001302 Instruction *Acc = MA->getAccessInstruction();
1303 PtrToAcc[getPointerOperand(*Acc)] = MA;
1304 AST.add(Acc);
1305 }
1306 }
1307
1308 SmallVector<AliasGroupTy, 4> AliasGroups;
1309 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001310 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001311 continue;
1312 AliasGroupTy AG;
1313 for (auto PR : AS)
1314 AG.push_back(PtrToAcc[PR.getValue()]);
1315 assert(AG.size() > 1 &&
1316 "Alias groups should contain at least two accesses");
1317 AliasGroups.push_back(std::move(AG));
1318 }
1319
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001320 // Split the alias groups based on their domain.
1321 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1322 AliasGroupTy NewAG;
1323 AliasGroupTy &AG = AliasGroups[u];
1324 AliasGroupTy::iterator AGI = AG.begin();
1325 isl_set *AGDomain = getAccessDomain(*AGI);
1326 while (AGI != AG.end()) {
1327 MemoryAccess *MA = *AGI;
1328 isl_set *MADomain = getAccessDomain(MA);
1329 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1330 NewAG.push_back(MA);
1331 AGI = AG.erase(AGI);
1332 isl_set_free(MADomain);
1333 } else {
1334 AGDomain = isl_set_union(AGDomain, MADomain);
1335 AGI++;
1336 }
1337 }
1338 if (NewAG.size() > 1)
1339 AliasGroups.push_back(std::move(NewAG));
1340 isl_set_free(AGDomain);
1341 }
1342
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001343 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001344 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1345 for (AliasGroupTy &AG : AliasGroups) {
1346 NonReadOnlyBaseValues.clear();
1347 ReadOnlyPairs.clear();
1348
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001349 if (AG.size() < 2) {
1350 AG.clear();
1351 continue;
1352 }
1353
Johannes Doerfert13771732014-10-01 12:40:46 +00001354 for (auto II = AG.begin(); II != AG.end();) {
1355 Value *BaseAddr = (*II)->getBaseAddr();
1356 if (HasWriteAccess.count(BaseAddr)) {
1357 NonReadOnlyBaseValues.insert(BaseAddr);
1358 II++;
1359 } else {
1360 ReadOnlyPairs[BaseAddr].insert(*II);
1361 II = AG.erase(II);
1362 }
1363 }
1364
1365 // If we don't have read only pointers check if there are at least two
1366 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001367 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001368 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001369 continue;
1370 }
1371
1372 // If we don't have non read only pointers clear the alias group.
1373 if (NonReadOnlyBaseValues.empty()) {
1374 AG.clear();
1375 continue;
1376 }
1377
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001378 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001379 MinMaxAliasGroups.emplace_back();
1380 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1381 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1382 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1383 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001384
1385 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001386
1387 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001388 for (MemoryAccess *MA : AG)
1389 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001390
Tobias Grosserbb853c22015-07-25 12:31:03 +00001391 bool Valid = calculateMinMaxAccess(
1392 Accesses, getDomains(), getAssumedContext(), MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001393
1394 // Bail out if the number of values we need to compare is too large.
1395 // This is important as the number of comparisions grows quadratically with
1396 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001397 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1398 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001399 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001400
1401 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001402 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001403 Accesses = isl_union_map_empty(getParamSpace());
1404
1405 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1406 for (MemoryAccess *MA : ReadOnlyPair.second)
1407 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1408
Tobias Grosserbb853c22015-07-25 12:31:03 +00001409 Valid = calculateMinMaxAccess(Accesses, getDomains(), getAssumedContext(),
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001410 MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001411
1412 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001413 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001414 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001415
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001416 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001417}
1418
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001419static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1420 ScopDetection &SD) {
1421
1422 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1423
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001424 unsigned MinLD = INT_MAX, MaxLD = 0;
1425 for (BasicBlock *BB : R.blocks()) {
1426 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001427 if (!R.contains(L))
1428 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001429 if (BoxedLoops && BoxedLoops->count(L))
1430 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001431 unsigned LD = L->getLoopDepth();
1432 MinLD = std::min(MinLD, LD);
1433 MaxLD = std::max(MaxLD, LD);
1434 }
1435 }
1436
1437 // Handle the case that there is no loop in the SCoP first.
1438 if (MaxLD == 0)
1439 return 1;
1440
1441 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1442 assert(MaxLD >= MinLD &&
1443 "Maximal loop depth was smaller than mininaml loop depth?");
1444 return MaxLD - MinLD + 1;
1445}
1446
Michael Kruse471a5e32015-07-30 19:27:04 +00001447Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, isl_ctx *Context,
1448 unsigned MaxLoopDepth)
1449 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert574182d2015-08-12 10:19:50 +00001450 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001451
Michael Kruse471a5e32015-07-30 19:27:04 +00001452void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI,
1453 ScopDetection &SD) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001454 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001455
Tobias Grosserabfbe632013-02-05 12:09:06 +00001456 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001457
Tobias Grosser54839312015-04-21 11:37:25 +00001458 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001459 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00001460 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00001461 if (!Schedule)
1462 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00001463
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001464 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001465 addParameterBounds();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001466 simplifyAssumedContext();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001467
Tobias Grosser75805372011-04-29 06:27:02 +00001468 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1469}
1470
Michael Kruse471a5e32015-07-30 19:27:04 +00001471Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
1472 ScalarEvolution &SE, ScopDetection &SD,
1473 isl_ctx *ctx) {
1474 auto &R = TempScop.getMaxRegion();
1475 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
1476 auto S = new Scop(R, SE, ctx, MaxLoopDepth);
1477 S->initFromTempScop(TempScop, LI, SD);
1478 return S;
1479}
1480
Tobias Grosser75805372011-04-29 06:27:02 +00001481Scop::~Scop() {
1482 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001483 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00001484 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001485
Johannes Doerfertb164c792014-09-18 11:17:17 +00001486 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001487 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001488 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001489 isl_pw_multi_aff_free(MMA.first);
1490 isl_pw_multi_aff_free(MMA.second);
1491 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001492 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001493 isl_pw_multi_aff_free(MMA.first);
1494 isl_pw_multi_aff_free(MMA.second);
1495 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001496 }
Tobias Grosser75805372011-04-29 06:27:02 +00001497}
1498
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001499const ScopArrayInfo *
1500Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00001501 const SmallVector<const SCEV *, 4> &Sizes,
1502 bool IsPHI) {
1503 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001504 if (!SAI)
Tobias Grosser92245222015-07-28 14:53:44 +00001505 SAI.reset(
1506 new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI));
Tobias Grosserab671442015-05-23 05:58:27 +00001507 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001508}
1509
Tobias Grosser92245222015-07-28 14:53:44 +00001510const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
1511 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001512 assert(SAI && "No ScopArrayInfo available for this base pointer");
1513 return SAI;
1514}
1515
Tobias Grosser74394f02013-01-14 22:40:23 +00001516std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001517std::string Scop::getAssumedContextStr() const {
1518 return stringFromIslObj(AssumedContext);
1519}
Tobias Grosser75805372011-04-29 06:27:02 +00001520
1521std::string Scop::getNameStr() const {
1522 std::string ExitName, EntryName;
1523 raw_string_ostream ExitStr(ExitName);
1524 raw_string_ostream EntryStr(EntryName);
1525
Tobias Grosserf240b482014-01-09 10:42:15 +00001526 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001527 EntryStr.str();
1528
1529 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001530 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001531 ExitStr.str();
1532 } else
1533 ExitName = "FunctionExit";
1534
1535 return EntryName + "---" + ExitName;
1536}
1537
Tobias Grosser74394f02013-01-14 22:40:23 +00001538__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001539__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001540 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001541}
1542
Tobias Grossere86109f2013-10-29 21:05:49 +00001543__isl_give isl_set *Scop::getAssumedContext() const {
1544 return isl_set_copy(AssumedContext);
1545}
1546
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001547void Scop::addAssumption(__isl_take isl_set *Set) {
1548 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001549 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001550}
1551
Tobias Grosser75805372011-04-29 06:27:02 +00001552void Scop::printContext(raw_ostream &OS) const {
1553 OS << "Context:\n";
1554
1555 if (!Context) {
1556 OS.indent(4) << "n/a\n\n";
1557 return;
1558 }
1559
1560 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001561
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001562 OS.indent(4) << "Assumed Context:\n";
1563 if (!AssumedContext) {
1564 OS.indent(4) << "n/a\n\n";
1565 return;
1566 }
1567
1568 OS.indent(4) << getAssumedContextStr() << "\n";
1569
Tobias Grosser083d3d32014-06-28 08:59:45 +00001570 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001571 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001572 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1573 }
Tobias Grosser75805372011-04-29 06:27:02 +00001574}
1575
Johannes Doerfertb164c792014-09-18 11:17:17 +00001576void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001577 int noOfGroups = 0;
1578 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001579 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001580 noOfGroups += 1;
1581 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001582 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001583 }
1584
Tobias Grosserbb853c22015-07-25 12:31:03 +00001585 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00001586 if (MinMaxAliasGroups.empty()) {
1587 OS.indent(8) << "n/a\n";
1588 return;
1589 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001590
Tobias Grosserbb853c22015-07-25 12:31:03 +00001591 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001592
1593 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001594 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001595 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001596 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001597 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1598 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001599 }
1600 OS << " ]]\n";
1601 }
1602
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001603 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001604 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00001605 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001606 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001607 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1608 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001609 }
1610 OS << " ]]\n";
1611 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001612 }
1613}
1614
Tobias Grosser75805372011-04-29 06:27:02 +00001615void Scop::printStatements(raw_ostream &OS) const {
1616 OS << "Statements {\n";
1617
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001618 for (const ScopStmt &Stmt : *this)
1619 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001620
1621 OS.indent(4) << "}\n";
1622}
1623
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001624void Scop::printArrayInfo(raw_ostream &OS) const {
1625 OS << "Arrays {\n";
1626
Tobias Grosserab671442015-05-23 05:58:27 +00001627 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001628 Array.second->print(OS);
1629
1630 OS.indent(4) << "}\n";
1631}
1632
Tobias Grosser75805372011-04-29 06:27:02 +00001633void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00001634 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1635 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00001636 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00001637 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001638 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001639 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00001640 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001641 printStatements(OS.indent(4));
1642}
1643
1644void Scop::dump() const { print(dbgs()); }
1645
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001646isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00001647
Johannes Doerfert574182d2015-08-12 10:19:50 +00001648__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, ScopStmt *Stmt) {
1649 return Affinator.getPwAff(E, Stmt);
1650}
1651
Tobias Grosser808cd692015-07-14 09:33:13 +00001652__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001653 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001654
Tobias Grosser808cd692015-07-14 09:33:13 +00001655 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001656 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00001657
1658 return Domain;
1659}
1660
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001661__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001662 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001663
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001664 for (ScopStmt &Stmt : *this) {
1665 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001666 if (!MA->isMustWrite())
1667 continue;
1668
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001669 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001670 isl_map *AccessDomain = MA->getAccessRelation();
1671 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1672 Write = isl_union_map_add_map(Write, AccessDomain);
1673 }
1674 }
1675 return isl_union_map_coalesce(Write);
1676}
1677
1678__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001679 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001680
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001681 for (ScopStmt &Stmt : *this) {
1682 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001683 if (!MA->isMayWrite())
1684 continue;
1685
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001686 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00001687 isl_map *AccessDomain = MA->getAccessRelation();
1688 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1689 Write = isl_union_map_add_map(Write, AccessDomain);
1690 }
1691 }
1692 return isl_union_map_coalesce(Write);
1693}
1694
Tobias Grosser37eb4222014-02-20 21:43:54 +00001695__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001696 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001697
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001698 for (ScopStmt &Stmt : *this) {
1699 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001700 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001701 continue;
1702
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001703 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001704 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001705 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1706 Write = isl_union_map_add_map(Write, AccessDomain);
1707 }
1708 }
1709 return isl_union_map_coalesce(Write);
1710}
1711
1712__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001713 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001714
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001715 for (ScopStmt &Stmt : *this) {
1716 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001717 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00001718 continue;
1719
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001720 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00001721 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00001722
1723 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1724 Read = isl_union_map_add_map(Read, AccessDomain);
1725 }
1726 }
1727 return isl_union_map_coalesce(Read);
1728}
1729
Tobias Grosser808cd692015-07-14 09:33:13 +00001730__isl_give isl_union_map *Scop::getSchedule() const {
1731 auto Tree = getScheduleTree();
1732 auto S = isl_schedule_get_map(Tree);
1733 isl_schedule_free(Tree);
1734 return S;
1735}
Tobias Grosser37eb4222014-02-20 21:43:54 +00001736
Tobias Grosser808cd692015-07-14 09:33:13 +00001737__isl_give isl_schedule *Scop::getScheduleTree() const {
1738 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
1739 getDomains());
1740}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00001741
Tobias Grosser808cd692015-07-14 09:33:13 +00001742void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
1743 auto *S = isl_schedule_from_domain(getDomains());
1744 S = isl_schedule_insert_partial_schedule(
1745 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
1746 isl_schedule_free(Schedule);
1747 Schedule = S;
1748}
1749
1750void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
1751 isl_schedule_free(Schedule);
1752 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00001753}
1754
1755bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1756 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001757 for (ScopStmt &Stmt : *this) {
1758 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00001759 isl_union_set *NewStmtDomain = isl_union_set_intersect(
1760 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1761
1762 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1763 isl_union_set_free(StmtDomain);
1764 isl_union_set_free(NewStmtDomain);
1765 continue;
1766 }
1767
1768 Changed = true;
1769
1770 isl_union_set_free(StmtDomain);
1771 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1772
1773 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001774 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001775 isl_union_set_free(NewStmtDomain);
1776 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001777 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00001778 }
1779 isl_union_set_free(Domain);
1780 return Changed;
1781}
1782
Tobias Grosser75805372011-04-29 06:27:02 +00001783ScalarEvolution *Scop::getSE() const { return SE; }
1784
1785bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1786 if (tempScop.getAccessFunctions(BB))
1787 return false;
1788
1789 return true;
1790}
1791
Tobias Grosser808cd692015-07-14 09:33:13 +00001792struct MapToDimensionDataTy {
1793 int N;
1794 isl_union_pw_multi_aff *Res;
1795};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001796
Tobias Grosser808cd692015-07-14 09:33:13 +00001797// @brief Create a function that maps the elements of 'Set' to its N-th
1798// dimension.
1799//
1800// The result is added to 'User->Res'.
1801//
1802// @param Set The input set.
1803// @param N The dimension to map to.
1804//
1805// @returns Zero if no error occurred, non-zero otherwise.
1806static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
1807 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
1808 int Dim;
1809 isl_space *Space;
1810 isl_pw_multi_aff *PMA;
1811
1812 Dim = isl_set_dim(Set, isl_dim_set);
1813 Space = isl_set_get_space(Set);
1814 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
1815 Dim - Data->N);
1816 if (Data->N > 1)
1817 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
1818 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
1819
1820 isl_set_free(Set);
1821
1822 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001823}
1824
Tobias Grosser808cd692015-07-14 09:33:13 +00001825// @brief Create a function that maps the elements of Domain to their Nth
1826// dimension.
1827//
1828// @param Domain The set of elements to map.
1829// @param N The dimension to map to.
1830static __isl_give isl_multi_union_pw_aff *
1831mapToDimension(__isl_take isl_union_set *Domain, int N) {
1832 struct MapToDimensionDataTy Data;
1833 isl_space *Space;
1834
1835 Space = isl_union_set_get_space(Domain);
1836 Data.N = N;
1837 Data.Res = isl_union_pw_multi_aff_empty(Space);
1838 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
1839 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
1840
1841 isl_union_set_free(Domain);
1842 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
1843}
1844
1845ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
1846 const Region &CurRegion,
1847 SmallVectorImpl<Loop *> &NestLoops) {
1848 ScopStmt *Stmt;
1849 if (BB) {
1850 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
1851 Stmt = &Stmts.back();
1852 StmtMap[BB] = Stmt;
1853 } else {
1854 assert(R && "Either basic block or a region expected.");
1855 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
1856 Stmt = &Stmts.back();
1857 for (BasicBlock *BB : R->blocks())
1858 StmtMap[BB] = Stmt;
1859 }
1860 return Stmt;
1861}
1862
Michael Kruse046dde42015-08-10 13:01:57 +00001863__isl_give isl_schedule *
1864Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
1865 const Region &CurRegion,
1866 SmallVectorImpl<Loop *> &NestLoops) {
1867 if (isTrivialBB(BB, tempScop))
1868 return nullptr;
1869
1870 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
1871 auto *Domain = Stmt->getDomain();
1872 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
1873}
1874
Tobias Grosser808cd692015-07-14 09:33:13 +00001875__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
1876 const Region &CurRegion,
1877 SmallVectorImpl<Loop *> &NestLoops,
1878 LoopInfo &LI, ScopDetection &SD) {
1879 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
1880 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
1881 tempScop, CurRegion, NestLoops);
1882 auto *Domain = Stmt->getDomain();
1883 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
1884 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001885
Tobias Grosser75805372011-04-29 06:27:02 +00001886 Loop *L = castToLoop(CurRegion, LI);
1887
1888 if (L)
1889 NestLoops.push_back(L);
1890
1891 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00001892 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001893
1894 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00001895 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00001896 I != E; ++I) {
1897 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001898 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00001899 StmtSchedule =
1900 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001901 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00001902 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
1903 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00001904 }
Michael Kruse046dde42015-08-10 13:01:57 +00001905 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00001906 }
Tobias Grosser75805372011-04-29 06:27:02 +00001907
Tobias Grosser808cd692015-07-14 09:33:13 +00001908 if (!L)
1909 return Schedule;
1910
1911 auto *Domain = isl_schedule_get_domain(Schedule);
1912 if (!isl_union_set_is_empty(Domain)) {
1913 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
1914 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
1915 }
1916 isl_union_set_free(Domain);
1917
Tobias Grosser75805372011-04-29 06:27:02 +00001918 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00001919 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00001920}
1921
Johannes Doerfert7c494212014-10-31 23:13:39 +00001922ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00001923 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00001924 if (StmtMapIt == StmtMap.end())
1925 return nullptr;
1926 return StmtMapIt->second;
1927}
1928
Tobias Grosser75805372011-04-29 06:27:02 +00001929//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00001930ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1931 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00001932 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001933}
1934
1935ScopInfo::~ScopInfo() {
1936 clear();
1937 isl_ctx_free(ctx);
1938}
1939
Tobias Grosser75805372011-04-29 06:27:02 +00001940void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00001941 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00001942 AU.addRequired<RegionInfoPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001943 AU.addRequired<ScalarEvolution>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001944 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00001945 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001946 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00001947 AU.setPreservesAll();
1948}
1949
1950bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00001951 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00001952 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001953 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00001954 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1955
1956 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1957
1958 // This region is no Scop.
1959 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00001960 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001961 return false;
1962 }
1963
Michael Kruse471a5e32015-07-30 19:27:04 +00001964 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00001965
Tobias Grosserd6a50b32015-05-30 06:26:21 +00001966 DEBUG(scop->print(dbgs()));
1967
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001968 if (!PollyUseRuntimeAliasChecks) {
1969 // Statistics.
1970 ++ScopFound;
1971 if (scop->getMaxLoopDepth() > 0)
1972 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001973 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001974 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001975
Johannes Doerfert9143d672014-09-27 11:02:39 +00001976 // If a problem occurs while building the alias groups we need to delete
1977 // this SCoP and pretend it wasn't valid in the first place.
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001978 if (scop->buildAliasGroups(AA)) {
1979 // Statistics.
1980 ++ScopFound;
1981 if (scop->getMaxLoopDepth() > 0)
1982 ++RichScopFound;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001983 return false;
Johannes Doerfert21aa3dc2014-11-01 01:30:11 +00001984 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001985
1986 DEBUG(dbgs()
1987 << "\n\nNOTE: Run time checks for " << scop->getNameStr()
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001988 << " could not be created as the number of parameters involved is too "
Johannes Doerfert9143d672014-09-27 11:02:39 +00001989 "high. The SCoP will be "
1990 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust the "
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001991 "maximal number of parameters but be advised that the compile time "
Johannes Doerfert9143d672014-09-27 11:02:39 +00001992 "might increase exponentially.\n\n");
1993
1994 delete scop;
1995 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00001996 return false;
1997}
1998
1999char ScopInfo::ID = 0;
2000
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002001Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2002
Tobias Grosser73600b82011-10-08 00:30:40 +00002003INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2004 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002005 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002006INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002007INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002008INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002009INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002010INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002011INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Tobias Grosser73600b82011-10-08 00:30:40 +00002012INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2013 "Polly - Create polyhedral description of Scops", false,
2014 false)