blob: 1e4b582cb9509b1ecc03bc8cadde1cdb9b366fe0 [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 Doerfert96425c22015-08-30 21:13:53 +000032#include "llvm/ADT/PostOrderIterator.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000035#include "llvm/Analysis/RegionIterator.h"
36#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000037#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000038#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000040#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000042#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000044#include "isl/schedule.h"
45#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/set.h"
47#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000048#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000049#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000050#include <sstream>
51#include <string>
52#include <vector>
53
54using namespace llvm;
55using namespace polly;
56
Chandler Carruth95fef942014-04-22 03:30:19 +000057#define DEBUG_TYPE "polly-scops"
58
Tobias Grosser74394f02013-01-14 22:40:23 +000059STATISTIC(ScopFound, "Number of valid Scops");
60STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000061
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000062// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000063// operations can overflow easily. Additive reductions and bit operations
64// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000065static cl::opt<bool> DisableMultiplicativeReductions(
66 "polly-disable-multiplicative-reductions",
67 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
68 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000069
Johannes Doerfert9143d672014-09-27 11:02:39 +000070static cl::opt<unsigned> RunTimeChecksMaxParameters(
71 "polly-rtc-max-parameters",
72 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
73 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
74
Tobias Grosser71500722015-03-28 15:11:14 +000075static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
76 "polly-rtc-max-arrays-per-group",
77 cl::desc("The maximal number of arrays to compare in each alias group."),
78 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000079static cl::opt<std::string> UserContextStr(
80 "polly-context", cl::value_desc("isl parameter set"),
81 cl::desc("Provide additional constraints on the context parameters"),
82 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000083
Tobias Grosserd83b8a82015-08-20 19:08:11 +000084static cl::opt<bool> DetectReductions("polly-detect-reductions",
85 cl::desc("Detect and exploit reductions"),
86 cl::Hidden, cl::ZeroOrMore,
87 cl::init(true), cl::cat(PollyCategory));
88
Michael Kruse046dde42015-08-10 13:01:57 +000089// Create a sequence of two schedules. Either argument may be null and is
90// interpreted as the empty schedule. Can also return null if both schedules are
91// empty.
92static __isl_give isl_schedule *
93combineInSequence(__isl_take isl_schedule *Prev,
94 __isl_take isl_schedule *Succ) {
95 if (!Prev)
96 return Succ;
97 if (!Succ)
98 return Prev;
99
100 return isl_schedule_sequence(Prev, Succ);
101}
102
Johannes Doerferte7044942015-02-24 11:58:30 +0000103static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
104 const ConstantRange &Range,
105 int dim,
106 enum isl_dim_type type) {
107 isl_val *V;
108 isl_ctx *ctx = isl_set_get_ctx(S);
109
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000110 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
111 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000112 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000113 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
114
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000115 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000116 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000117 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000118 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000119 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
120
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000121 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000122 return isl_set_union(SLB, SUB);
123 else
124 return isl_set_intersect(SLB, SUB);
125}
126
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000127static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
128 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
129 if (!BasePtrLI)
130 return nullptr;
131
132 if (!S->getRegion().contains(BasePtrLI))
133 return nullptr;
134
135 ScalarEvolution &SE = *S->getSE();
136
137 auto *OriginBaseSCEV =
138 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
139 if (!OriginBaseSCEV)
140 return nullptr;
141
142 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
143 if (!OriginBaseSCEVUnknown)
144 return nullptr;
145
146 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
147}
148
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000149ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser92245222015-07-28 14:53:44 +0000150 const SmallVector<const SCEV *, 4> &DimensionSizes,
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000151 bool IsPHI, Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000152 : BasePtr(BasePtr), ElementType(ElementType),
Tobias Grosser92245222015-07-28 14:53:44 +0000153 DimensionSizes(DimensionSizes), IsPHI(IsPHI) {
154 std::string BasePtrName =
155 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000156 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000157 for (const SCEV *Expr : DimensionSizes) {
158 isl_pw_aff *Size = S->getPwAff(Expr);
159 DimensionSizesPw.push_back(Size);
160 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000161
162 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
163 if (BasePtrOriginSAI)
164 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000165}
166
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000167ScopArrayInfo::~ScopArrayInfo() {
168 isl_id_free(Id);
169 for (isl_pw_aff *Size : DimensionSizesPw)
170 isl_pw_aff_free(Size);
171}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000172
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000173std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
174
175int ScopArrayInfo::getElemSizeInBytes() const {
176 return ElementType->getPrimitiveSizeInBits() / 8;
177}
178
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000179isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
180
181void ScopArrayInfo::dump() const { print(errs()); }
182
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000183void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000184 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000185 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
186 OS << "[";
187
188 if (SizeAsPwAff)
189 OS << " " << DimensionSizesPw[u] << " ";
190 else
191 OS << *DimensionSizes[u];
192
193 OS << "]";
194 }
195
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000196 if (BasePtrOriginSAI)
197 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
198
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000199 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000200}
201
202const ScopArrayInfo *
203ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
204 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
205 assert(Id && "Output dimension didn't have an ID");
206 return getFromId(Id);
207}
208
209const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
210 void *User = isl_id_get_user(Id);
211 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
212 isl_id_free(Id);
213 return SAI;
214}
215
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000216const std::string
217MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
218 switch (RT) {
219 case MemoryAccess::RT_NONE:
220 llvm_unreachable("Requested a reduction operator string for a memory "
221 "access which isn't a reduction");
222 case MemoryAccess::RT_ADD:
223 return "+";
224 case MemoryAccess::RT_MUL:
225 return "*";
226 case MemoryAccess::RT_BOR:
227 return "|";
228 case MemoryAccess::RT_BXOR:
229 return "^";
230 case MemoryAccess::RT_BAND:
231 return "&";
232 }
233 llvm_unreachable("Unknown reduction type");
234 return "";
235}
236
Johannes Doerfertf6183392014-07-01 20:52:51 +0000237/// @brief Return the reduction type for a given binary operator
238static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
239 const Instruction *Load) {
240 if (!BinOp)
241 return MemoryAccess::RT_NONE;
242 switch (BinOp->getOpcode()) {
243 case Instruction::FAdd:
244 if (!BinOp->hasUnsafeAlgebra())
245 return MemoryAccess::RT_NONE;
246 // Fall through
247 case Instruction::Add:
248 return MemoryAccess::RT_ADD;
249 case Instruction::Or:
250 return MemoryAccess::RT_BOR;
251 case Instruction::Xor:
252 return MemoryAccess::RT_BXOR;
253 case Instruction::And:
254 return MemoryAccess::RT_BAND;
255 case Instruction::FMul:
256 if (!BinOp->hasUnsafeAlgebra())
257 return MemoryAccess::RT_NONE;
258 // Fall through
259 case Instruction::Mul:
260 if (DisableMultiplicativeReductions)
261 return MemoryAccess::RT_NONE;
262 return MemoryAccess::RT_MUL;
263 default:
264 return MemoryAccess::RT_NONE;
265 }
266}
Tobias Grosser75805372011-04-29 06:27:02 +0000267//===----------------------------------------------------------------------===//
268
269MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000270 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000271 isl_map_free(AccessRelation);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000272 isl_map_free(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000273}
274
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000275static MemoryAccess::AccessType getMemoryAccessType(const IRAccess &Access) {
276 switch (Access.getType()) {
277 case IRAccess::READ:
278 return MemoryAccess::READ;
279 case IRAccess::MUST_WRITE:
280 return MemoryAccess::MUST_WRITE;
281 case IRAccess::MAY_WRITE:
282 return MemoryAccess::MAY_WRITE;
283 }
284 llvm_unreachable("Unknown IRAccess type!");
285}
286
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000287const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
288 isl_id *ArrayId = getArrayId();
289 void *User = isl_id_get_user(ArrayId);
290 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
291 isl_id_free(ArrayId);
292 return SAI;
293}
294
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000295__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000296 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
297}
298
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000299__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
300 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000301 isl_map *Schedule, *ScheduledAccRel;
302 isl_union_set *UDomain;
303
304 UDomain = isl_union_set_from_set(getStatement()->getDomain());
305 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
306 Schedule = isl_map_from_union_map(USchedule);
307 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
308 return isl_pw_multi_aff_from_map(ScheduledAccRel);
309}
310
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000311__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000312 return isl_map_copy(AccessRelation);
313}
314
Johannes Doerferta99130f2014-10-13 12:58:03 +0000315std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000316 return stringFromIslObj(AccessRelation);
317}
318
Johannes Doerferta99130f2014-10-13 12:58:03 +0000319__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000320 return isl_map_get_space(AccessRelation);
321}
322
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000323__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000324 return isl_map_copy(newAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000325}
326
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000327__isl_give isl_basic_map *
328MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000329 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000330 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000331
Tobias Grosser084d8f72012-05-29 09:29:44 +0000332 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000333 isl_basic_set_universe(Statement->getDomainSpace()),
334 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000335}
336
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000337// Formalize no out-of-bound access assumption
338//
339// When delinearizing array accesses we optimistically assume that the
340// delinearized accesses do not access out of bound locations (the subscript
341// expression of each array evaluates for each statement instance that is
342// executed to a value that is larger than zero and strictly smaller than the
343// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000344// dimension for which we do not need to assume any upper bound. At this point
345// we formalize this assumption to ensure that at code generation time the
346// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000347//
348// To find the set of constraints necessary to avoid out of bound accesses, we
349// first build the set of data locations that are not within array bounds. We
350// then apply the reverse access relation to obtain the set of iterations that
351// may contain invalid accesses and reduce this set of iterations to the ones
352// that are actually executed by intersecting them with the domain of the
353// statement. If we now project out all loop dimensions, we obtain a set of
354// parameters that may cause statement instances to be executed that may
355// possibly yield out of bound memory accesses. The complement of these
356// constraints is the set of constraints that needs to be assumed to ensure such
357// statement instances are never executed.
358void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000359 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000360 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000361 for (int i = 1, Size = Access.Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000362 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
363 isl_pw_aff *Var =
364 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
365 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
366
367 isl_set *DimOutside;
368
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000369 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000370 isl_pw_aff *SizeE = Statement->getPwAff(Access.Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000371
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000372 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
373 Statement->getNumIterators());
374 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
375 isl_space_dim(Space, isl_dim_set));
376 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
377 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000378
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000379 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000380
381 Outside = isl_set_union(Outside, DimOutside);
382 }
383
384 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
385 Outside = isl_set_intersect(Outside, Statement->getDomain());
386 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000387
388 // Remove divs to avoid the construction of overly complicated assumptions.
389 // Doing so increases the set of parameter combinations that are assumed to
390 // not appear. This is always save, but may make the resulting run-time check
391 // bail out more often than strictly necessary.
392 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000393 Outside = isl_set_complement(Outside);
394 Statement->getParent()->addAssumption(Outside);
395 isl_space_free(Space);
396}
397
Johannes Doerferte7044942015-02-24 11:58:30 +0000398void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
399 ScalarEvolution *SE = Statement->getParent()->getSE();
400
401 Value *Ptr = getPointerOperand(*getAccessInstruction());
402 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
403 return;
404
405 auto *PtrSCEV = SE->getSCEV(Ptr);
406 if (isa<SCEVCouldNotCompute>(PtrSCEV))
407 return;
408
409 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
410 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
411 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
412
413 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
414 if (Range.isFullSet())
415 return;
416
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000417 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000418 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000419 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
420 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
421
422 auto Min = LB.sdiv(APInt(BW, ElementSize));
423 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000424
425 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
426 AccessRange =
427 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
428 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
429}
430
Tobias Grosser619190d2015-03-30 17:22:28 +0000431__isl_give isl_map *MemoryAccess::foldAccess(const IRAccess &Access,
432 __isl_take isl_map *AccessRelation,
433 ScopStmt *Statement) {
434 int Size = Access.Subscripts.size();
435
436 for (int i = Size - 2; i >= 0; --i) {
437 isl_space *Space;
438 isl_map *MapOne, *MapTwo;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000439 isl_pw_aff *DimSize = Statement->getPwAff(Access.Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000440
441 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
442 isl_pw_aff_free(DimSize);
443 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
444
445 Space = isl_map_get_space(AccessRelation);
446 Space = isl_space_map_from_set(isl_space_range(Space));
447 Space = isl_space_align_params(Space, SpaceSize);
448
449 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
450 isl_id_free(ParamId);
451
452 MapOne = isl_map_universe(isl_space_copy(Space));
453 for (int j = 0; j < Size; ++j)
454 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
455 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
456
457 MapTwo = isl_map_universe(isl_space_copy(Space));
458 for (int j = 0; j < Size; ++j)
459 if (j < i || j > i + 1)
460 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
461
462 isl_local_space *LS = isl_local_space_from_space(Space);
463 isl_constraint *C;
464 C = isl_equality_alloc(isl_local_space_copy(LS));
465 C = isl_constraint_set_constant_si(C, -1);
466 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
467 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
468 MapTwo = isl_map_add_constraint(MapTwo, C);
469 C = isl_equality_alloc(LS);
470 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
471 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
472 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
473 MapTwo = isl_map_add_constraint(MapTwo, C);
474 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
475
476 MapOne = isl_map_union(MapOne, MapTwo);
477 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
478 }
479 return AccessRelation;
480}
481
Johannes Doerfert13c8cf22014-08-10 08:09:38 +0000482MemoryAccess::MemoryAccess(const IRAccess &Access, Instruction *AccInst,
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000483 ScopStmt *Statement, const ScopArrayInfo *SAI,
484 int Identifier)
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000485 : AccType(getMemoryAccessType(Access)), Statement(Statement),
486 AccessInstruction(AccInst), AccessValue(Access.getAccessValue()),
Johannes Doerfert8f7124c2014-09-12 11:00:49 +0000487 newAccessRelation(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +0000488
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000489 isl_ctx *Ctx = Statement->getIslCtx();
Tobias Grosser9759f852011-11-10 12:44:55 +0000490 BaseAddr = Access.getBase();
Johannes Doerfert79fc23f2014-07-24 23:48:02 +0000491 BaseName = getIslCompatibleName("MemRef_", getBaseAddr(), "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000492
493 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000494
Tobias Grosserac3a95f2015-08-03 17:53:21 +0000495 auto IdName = "__polly_array_ref_" + std::to_string(Identifier);
Tobias Grossere29d31c2015-05-15 12:24:09 +0000496 Id = isl_id_alloc(Ctx, IdName.c_str(), nullptr);
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000497
Tobias Grossera1879642011-12-20 10:43:14 +0000498 if (!Access.isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000499 // We overapproximate non-affine accesses with a possible access to the
500 // whole array. For read accesses it does not make a difference, if an
501 // access must or may happen. However, for write accesses it is important to
502 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000503 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000504 AccessRelation =
505 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000506
507 computeBoundsOnAccessRelation(Access.getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000508 return;
509 }
510
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000511 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000512 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000513
Tobias Grosser79baa212014-04-10 08:38:02 +0000514 for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000515 isl_pw_aff *Affine = Statement->getPwAff(Access.Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000516
Sebastian Pop422e33f2014-06-03 18:16:31 +0000517 if (Size == 1) {
518 // For the non delinearized arrays, divide the access function of the last
519 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000520 //
521 // A stride one array access in C expressed as A[i] is expressed in
522 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
523 // two subsequent values of 'i' index two values that are stored next to
524 // each other in memory. By this division we make this characteristic
525 // obvious again.
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000526 isl_val *v = isl_val_int_from_si(Ctx, Access.getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000527 Affine = isl_pw_aff_scale_down_val(Affine, v);
528 }
529
530 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
531
Tobias Grosser79baa212014-04-10 08:38:02 +0000532 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000533 }
534
Tobias Grosser619190d2015-03-30 17:22:28 +0000535 AccessRelation = foldAccess(Access, AccessRelation, Statement);
536
Tobias Grosser79baa212014-04-10 08:38:02 +0000537 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000538 AccessRelation = isl_map_set_tuple_id(
539 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000540 AccessRelation =
541 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
542
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000543 assumeNoOutOfBound(Access);
Tobias Grosseraa660a92015-03-30 00:07:50 +0000544 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000545 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000546}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000547
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000548void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000549 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000550 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000551}
552
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000553const std::string MemoryAccess::getReductionOperatorStr() const {
554 return MemoryAccess::getReductionOperatorStr(getReductionType());
555}
556
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000557__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
558
Johannes Doerfertf6183392014-07-01 20:52:51 +0000559raw_ostream &polly::operator<<(raw_ostream &OS,
560 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000561 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000562 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000563 else
564 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000565 return OS;
566}
567
Tobias Grosser75805372011-04-29 06:27:02 +0000568void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000569 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000570 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000571 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000572 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000573 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000574 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000575 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000576 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000577 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000578 break;
579 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000580 OS << "[Reduction Type: " << getReductionType() << "] ";
581 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000582 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000583}
584
Tobias Grosser74394f02013-01-14 22:40:23 +0000585void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000586
587// Create a map in the size of the provided set domain, that maps from the
588// one element of the provided set domain to another element of the provided
589// set domain.
590// The mapping is limited to all points that are equal in all but the last
591// dimension and for which the last dimension of the input is strict smaller
592// than the last dimension of the output.
593//
594// getEqualAndLarger(set[i0, i1, ..., iX]):
595//
596// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
597// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
598//
Tobias Grosserf5338802011-10-06 00:03:35 +0000599static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000600 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000601 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000602 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000603
604 // Set all but the last dimension to be equal for the input and output
605 //
606 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
607 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000608 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000609 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000610
611 // Set the last dimension of the input to be strict smaller than the
612 // last dimension of the output.
613 //
614 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000615 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
616 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000617 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000618}
619
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000620__isl_give isl_set *
621MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000622 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000623 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000624 isl_space *Space = isl_space_range(isl_map_get_space(S));
625 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000626
Sebastian Popa00a0292012-12-18 07:46:06 +0000627 S = isl_map_reverse(S);
628 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000629
Sebastian Popa00a0292012-12-18 07:46:06 +0000630 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
631 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
632 NextScatt = isl_map_apply_domain(NextScatt, S);
633 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000634
Sebastian Popa00a0292012-12-18 07:46:06 +0000635 isl_set *Deltas = isl_map_deltas(NextScatt);
636 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000637}
638
Sebastian Popa00a0292012-12-18 07:46:06 +0000639bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000640 int StrideWidth) const {
641 isl_set *Stride, *StrideX;
642 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000643
Sebastian Popa00a0292012-12-18 07:46:06 +0000644 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000645 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000646 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
647 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
648 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
649 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000650 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000651
Tobias Grosser28dd4862012-01-24 16:42:16 +0000652 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000653 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000654
Tobias Grosser28dd4862012-01-24 16:42:16 +0000655 return IsStrideX;
656}
657
Sebastian Popa00a0292012-12-18 07:46:06 +0000658bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
659 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000660}
661
Tobias Grosser79baa212014-04-10 08:38:02 +0000662bool MemoryAccess::isScalar() const {
663 return isl_map_n_out(AccessRelation) == 0;
664}
665
Sebastian Popa00a0292012-12-18 07:46:06 +0000666bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
667 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000668}
669
Tobias Grosser5d453812011-10-06 00:04:11 +0000670void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
Tobias Grosserb76f38532011-08-20 11:11:25 +0000671 isl_map_free(newAccessRelation);
Raghesh Aloor7a04f4f2011-08-03 13:47:59 +0000672 newAccessRelation = newAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000673}
Tobias Grosser75805372011-04-29 06:27:02 +0000674
675//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000676
Tobias Grosser808cd692015-07-14 09:33:13 +0000677isl_map *ScopStmt::getSchedule() const {
678 isl_set *Domain = getDomain();
679 if (isl_set_is_empty(Domain)) {
680 isl_set_free(Domain);
681 return isl_map_from_aff(
682 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
683 }
684 auto *Schedule = getParent()->getSchedule();
685 Schedule = isl_union_map_intersect_domain(
686 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
687 if (isl_union_map_is_empty(Schedule)) {
688 isl_set_free(Domain);
689 isl_union_map_free(Schedule);
690 return isl_map_from_aff(
691 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
692 }
693 auto *M = isl_map_from_union_map(Schedule);
694 M = isl_map_coalesce(M);
695 M = isl_map_gist_domain(M, Domain);
696 M = isl_map_coalesce(M);
697 return M;
698}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000699
Johannes Doerfert574182d2015-08-12 10:19:50 +0000700__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertb409fdc2015-08-28 09:24:35 +0000701 return getParent()->getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +0000702}
703
Tobias Grosser37eb4222014-02-20 21:43:54 +0000704void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
705 assert(isl_set_is_subset(NewDomain, Domain) &&
706 "New domain is not a subset of old domain!");
707 isl_set_free(Domain);
708 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000709}
710
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000711void ScopStmt::buildAccesses(TempScop &tempScop, BasicBlock *Block,
712 bool isApproximated) {
713 AccFuncSetType *AFS = tempScop.getAccessFunctions(Block);
714 if (!AFS)
715 return;
716
717 for (auto &AccessPair : *AFS) {
718 IRAccess &Access = AccessPair.first;
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000719 Instruction *AccessInst = AccessPair.second;
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000720 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000721
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000722 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser92245222015-07-28 14:53:44 +0000723 Access.getBase(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000724
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000725 if (isApproximated && Access.isWrite())
726 Access.setMayWrite();
727
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000728 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
729 if (!MAL)
730 MAL = new MemoryAccessList();
731 MAL->emplace_front(Access, AccessInst, this, SAI, MemAccs.size());
732 MemAccs.push_back(&MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000733 }
734}
735
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000736void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000737 for (MemoryAccess *MA : *this)
738 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000739
740 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000741}
742
Johannes Doerfert96425c22015-08-30 21:13:53 +0000743static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
744 isl_pw_aff *L, isl_pw_aff *R) {
745 switch (Pred) {
746 case ICmpInst::ICMP_EQ:
747 return isl_pw_aff_eq_set(L, R);
748 case ICmpInst::ICMP_NE:
749 return isl_pw_aff_ne_set(L, R);
750 case ICmpInst::ICMP_SLT:
751 return isl_pw_aff_lt_set(L, R);
752 case ICmpInst::ICMP_SLE:
753 return isl_pw_aff_le_set(L, R);
754 case ICmpInst::ICMP_SGT:
755 return isl_pw_aff_gt_set(L, R);
756 case ICmpInst::ICMP_SGE:
757 return isl_pw_aff_ge_set(L, R);
758 case ICmpInst::ICMP_ULT:
759 return isl_pw_aff_lt_set(L, R);
760 case ICmpInst::ICMP_UGT:
761 return isl_pw_aff_gt_set(L, R);
762 case ICmpInst::ICMP_ULE:
763 return isl_pw_aff_le_set(L, R);
764 case ICmpInst::ICMP_UGE:
765 return isl_pw_aff_ge_set(L, R);
766 default:
767 llvm_unreachable("Non integer predicate not supported");
768 }
769}
770
771/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
772///
773/// This will fill @p ConditionSets with the conditions under which control
774/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
775/// have as many elements as @p BI has successors.
776static void
777buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
778 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
779
780 if (BI->isUnconditional()) {
781 ConditionSets.push_back(isl_set_copy(Domain));
782 return;
783 }
784
785 Value *Condition = BI->getCondition();
786
787 isl_set *ConsequenceCondSet = nullptr;
788 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
789 if (CCond->isZero())
790 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
791 else
792 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
793 } else {
794 auto *ICond = dyn_cast<ICmpInst>(Condition);
795 assert(ICond &&
796 "Condition of exiting branch was neither constant nor ICmp!");
797
798 ScalarEvolution &SE = *S.getSE();
799 isl_pw_aff *LHS, *RHS;
800 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), Domain);
801 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), Domain);
802 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
803 }
804
805 assert(ConsequenceCondSet);
806 isl_set *AlternativeCondSet =
807 isl_set_complement(isl_set_copy(ConsequenceCondSet));
808
809 ConditionSets.push_back(isl_set_coalesce(
810 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
811 ConditionSets.push_back(isl_set_coalesce(
812 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
813}
814
Johannes Doerfertd020b772015-08-27 06:53:52 +0000815void ScopStmt::addLoopTripCountToDomain(const Loop *L) {
816
Johannes Doerfert96425c22015-08-30 21:13:53 +0000817 int RelativeLoopDimension = getParent()->getRelativeLoopDepth(L);
818 assert(RelativeLoopDimension >= 0 &&
819 "Expected relative loop depth of L to be non-negative");
820 unsigned loopDimension = RelativeLoopDimension;
821
Johannes Doerfertd020b772015-08-27 06:53:52 +0000822 ScalarEvolution *SE = getParent()->getSE();
823 isl_space *DomSpace = isl_set_get_space(Domain);
824
825 isl_space *MapSpace = isl_space_map_from_set(isl_space_copy(DomSpace));
826 isl_multi_aff *LoopMAff = isl_multi_aff_identity(MapSpace);
827 isl_aff *LoopAff = isl_multi_aff_get_aff(LoopMAff, loopDimension);
828 LoopAff = isl_aff_add_constant_si(LoopAff, 1);
829 LoopMAff = isl_multi_aff_set_aff(LoopMAff, loopDimension, LoopAff);
830 isl_map *TranslationMap = isl_map_from_multi_aff(LoopMAff);
831
832 BasicBlock *ExitingBB = L->getExitingBlock();
833 assert(ExitingBB && "Loop has more than one exiting block");
834
835 BranchInst *Term = dyn_cast<BranchInst>(ExitingBB->getTerminator());
836 assert(Term && Term->isConditional() && "Terminator is not conditional");
837
838 const SCEV *LHS = nullptr;
839 const SCEV *RHS = nullptr;
840 Value *Cond = Term->getCondition();
841 CmpInst::Predicate Pred = CmpInst::Predicate::BAD_ICMP_PREDICATE;
842
843 ICmpInst *CondICmpInst = dyn_cast<ICmpInst>(Cond);
844 ConstantInt *CondConstant = dyn_cast<ConstantInt>(Cond);
845 if (CondICmpInst) {
846 LHS = SE->getSCEVAtScope(CondICmpInst->getOperand(0), L);
847 RHS = SE->getSCEVAtScope(CondICmpInst->getOperand(1), L);
848 Pred = CondICmpInst->getPredicate();
849 } else if (CondConstant) {
850 LHS = SE->getConstant(CondConstant);
851 RHS = SE->getConstant(ConstantInt::getTrue(SE->getContext()));
852 Pred = CmpInst::Predicate::ICMP_EQ;
853 } else {
854 llvm_unreachable("Condition is neither a ConstantInt nor a ICmpInst");
855 }
856
857 if (!L->contains(Term->getSuccessor(0)))
858 Pred = ICmpInst::getInversePredicate(Pred);
859 Comparison Comp(LHS, RHS, Pred);
860
Johannes Doerfert96425c22015-08-30 21:13:53 +0000861 isl_pw_aff *LPWA = getPwAff(Comp.getLHS());
862 isl_pw_aff *RPWA = getPwAff(Comp.getRHS());
863
864 isl_set *CondSet = buildConditionSet(Comp.getPred(), LPWA, RPWA);
Johannes Doerfertd020b772015-08-27 06:53:52 +0000865 isl_map *ForwardMap = isl_map_lex_le(isl_space_copy(DomSpace));
866 for (unsigned i = 0; i < isl_set_n_dim(Domain); i++)
867 if (i != loopDimension)
868 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
869
870 ForwardMap = isl_map_apply_range(ForwardMap, isl_map_copy(TranslationMap));
871 isl_set *CondDom = isl_set_subtract(isl_set_copy(Domain), CondSet);
872 isl_set *ForwardCond = isl_set_apply(CondDom, isl_map_copy(ForwardMap));
873 isl_set *ForwardDomain = isl_set_apply(isl_set_copy(Domain), ForwardMap);
874 ForwardCond = isl_set_gist(ForwardCond, ForwardDomain);
875 Domain = isl_set_subtract(Domain, ForwardCond);
876
877 isl_map_free(TranslationMap);
878 isl_space_free(DomSpace);
879}
880
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000881void ScopStmt::addLoopBoundsToDomain(TempScop &tempScop) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000882 isl_space *Space;
883 isl_local_space *LocalSpace;
Tobias Grosser75805372011-04-29 06:27:02 +0000884
Tobias Grossere19661e2011-10-07 08:46:57 +0000885 Space = isl_set_get_space(Domain);
886 LocalSpace = isl_local_space_from_space(Space);
Tobias Grosserf5338802011-10-06 00:03:35 +0000887
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000888 ScalarEvolution *SE = getParent()->getSE();
Tobias Grosser75805372011-04-29 06:27:02 +0000889 for (int i = 0, e = getNumIterators(); i != e; ++i) {
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000890 isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
Tobias Grosserabfbe632013-02-05 12:09:06 +0000891 isl_pw_aff *IV =
892 isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
Tobias Grosser75805372011-04-29 06:27:02 +0000893
Tobias Grosser9b13d3d2011-10-06 22:32:58 +0000894 // 0 <= IV.
895 isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
896 Domain = isl_set_intersect(Domain, LowerBound);
897
898 // IV <= LatchExecutions.
Hongbin Zheng27f3afb2011-04-30 03:26:51 +0000899 const Loop *L = getLoopForDimension(i);
Johannes Doerfert5ad8a6a2014-11-01 01:14:56 +0000900 const SCEV *LatchExecutions = SE->getBackedgeTakenCount(L);
Johannes Doerfertd020b772015-08-27 06:53:52 +0000901 if (!isa<SCEVCouldNotCompute>(LatchExecutions)) {
902 isl_pw_aff *UpperBound = getPwAff(LatchExecutions);
903 isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
904 Domain = isl_set_intersect(Domain, UpperBoundSet);
905 } else {
Johannes Doerfert5f912d32015-08-31 19:58:24 +0000906 // If SCEV cannot provide a loop trip count, we compute it with ISL. If
907 // the domain remains unbounded, make the assumed context infeasible
908 // as code generation currently does not expect unbounded loops.
Johannes Doerfertd020b772015-08-27 06:53:52 +0000909 addLoopTripCountToDomain(L);
910 isl_pw_aff_free(IV);
Johannes Doerfert5f912d32015-08-31 19:58:24 +0000911 if (!isl_set_dim_has_upper_bound(Domain, isl_dim_set, i))
912 Parent.addAssumption(isl_set_empty(Parent.getParamSpace()));
Johannes Doerfertd020b772015-08-27 06:53:52 +0000913 }
Tobias Grosser75805372011-04-29 06:27:02 +0000914 }
915
Tobias Grosserf5338802011-10-06 00:03:35 +0000916 isl_local_space_free(LocalSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000917}
918
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000919void ScopStmt::buildDomain(TempScop &tempScop, const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000920 isl_space *Space;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000921 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000922
923 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
924
Tobias Grosser084d8f72012-05-29 09:29:44 +0000925 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
926
Tobias Grossere19661e2011-10-07 08:46:57 +0000927 Domain = isl_set_universe(Space);
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000928 addLoopBoundsToDomain(tempScop);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000929 Domain = isl_set_intersect(Domain, getParent()->getDomainConditions(this));
930 Domain = isl_set_coalesce(Domain);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000931 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000932}
933
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000934void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
935 int Dimension = 0;
936 isl_ctx *Ctx = Parent.getIslCtx();
937 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
938 Type *Ty = GEP->getPointerOperandType();
939 ScalarEvolution &SE = *Parent.getSE();
940
941 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
942 Dimension = 1;
943 Ty = PtrTy->getElementType();
944 }
945
946 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
947 unsigned int Operand = 1 + Dimension;
948
949 if (GEP->getNumOperands() <= Operand)
950 break;
951
952 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
953
954 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000955 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000956 AccessOffset =
957 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
958
959 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
960 isl_local_space_copy(LSpace),
961 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
962
963 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
964 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
965 OutOfBound = isl_set_params(OutOfBound);
966 isl_set *InBound = isl_set_complement(OutOfBound);
967 isl_set *Executed = isl_set_params(getDomain());
968
969 // A => B == !A or B
970 isl_set *InBoundIfExecuted =
971 isl_set_union(isl_set_complement(Executed), InBound);
972
973 Parent.addAssumption(InBoundIfExecuted);
974 }
975
976 Dimension += 1;
977 Ty = ArrayTy->getElementType();
978 }
979
980 isl_local_space_free(LSpace);
981}
982
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000983void ScopStmt::deriveAssumptions(BasicBlock *Block) {
984 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000985 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
986 deriveAssumptionsFromGEP(GEP);
987}
988
Tobias Grosser74394f02013-01-14 22:40:23 +0000989ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000990 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000991 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
992 NestLoops(Nest.size()) {
993 // Setup the induction variables.
994 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
995 NestLoops[i] = Nest[i];
996
Tobias Grosser16c44032015-07-09 07:31:45 +0000997 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000998
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000999 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001000
1001 BasicBlock *EntryBB = R.getEntry();
1002 for (BasicBlock *Block : R.blocks()) {
1003 buildAccesses(tempScop, Block, Block != EntryBB);
1004 deriveAssumptions(Block);
1005 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001006 if (DetectReductions)
1007 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001008}
1009
1010ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +00001011 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001012 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
1013 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +00001014 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +00001015 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +00001016 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +00001017
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001018 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001019
Johannes Doerfert45545ff2015-08-16 14:36:01 +00001020 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001021 buildAccesses(tempScop, BB);
1022 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001023 if (DetectReductions)
1024 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001025}
1026
Johannes Doerferte58a0122014-06-27 20:31:28 +00001027/// @brief Collect loads which might form a reduction chain with @p StoreMA
1028///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001029/// Check if the stored value for @p StoreMA is a binary operator with one or
1030/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001031/// used only once (by @p StoreMA) and its load operands are also used only
1032/// once, we have found a possible reduction chain. It starts at an operand
1033/// load and includes the binary operator and @p StoreMA.
1034///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001035/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001036/// escape this block or into any other store except @p StoreMA.
1037void ScopStmt::collectCandiateReductionLoads(
1038 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1039 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1040 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001041 return;
1042
1043 // Skip if there is not one binary operator between the load and the store
1044 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001045 if (!BinOp)
1046 return;
1047
1048 // Skip if the binary operators has multiple uses
1049 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001050 return;
1051
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001052 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001053 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1054 return;
1055
Johannes Doerfert9890a052014-07-01 00:32:29 +00001056 // Skip if the binary operator is outside the current SCoP
1057 if (BinOp->getParent() != Store->getParent())
1058 return;
1059
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001060 // Skip if it is a multiplicative reduction and we disabled them
1061 if (DisableMultiplicativeReductions &&
1062 (BinOp->getOpcode() == Instruction::Mul ||
1063 BinOp->getOpcode() == Instruction::FMul))
1064 return;
1065
Johannes Doerferte58a0122014-06-27 20:31:28 +00001066 // Check the binary operator operands for a candidate load
1067 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1068 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1069 if (!PossibleLoad0 && !PossibleLoad1)
1070 return;
1071
1072 // A load is only a candidate if it cannot escape (thus has only this use)
1073 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001074 if (PossibleLoad0->getParent() == Store->getParent())
1075 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001076 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001077 if (PossibleLoad1->getParent() == Store->getParent())
1078 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001079}
1080
1081/// @brief Check for reductions in this ScopStmt
1082///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001083/// Iterate over all store memory accesses and check for valid binary reduction
1084/// like chains. For all candidates we check if they have the same base address
1085/// and there are no other accesses which overlap with them. The base address
1086/// check rules out impossible reductions candidates early. The overlap check,
1087/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001088/// guarantees that none of the intermediate results will escape during
1089/// execution of the loop nest. We basically check here that no other memory
1090/// access can access the same memory as the potential reduction.
1091void ScopStmt::checkForReductions() {
1092 SmallVector<MemoryAccess *, 2> Loads;
1093 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1094
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001095 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001096 // stores and collecting possible reduction loads.
1097 for (MemoryAccess *StoreMA : MemAccs) {
1098 if (StoreMA->isRead())
1099 continue;
1100
1101 Loads.clear();
1102 collectCandiateReductionLoads(StoreMA, Loads);
1103 for (MemoryAccess *LoadMA : Loads)
1104 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1105 }
1106
1107 // Then check each possible candidate pair.
1108 for (const auto &CandidatePair : Candidates) {
1109 bool Valid = true;
1110 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1111 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1112
1113 // Skip those with obviously unequal base addresses.
1114 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1115 isl_map_free(LoadAccs);
1116 isl_map_free(StoreAccs);
1117 continue;
1118 }
1119
1120 // And check if the remaining for overlap with other memory accesses.
1121 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1122 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1123 isl_set *AllAccs = isl_map_range(AllAccsRel);
1124
1125 for (MemoryAccess *MA : MemAccs) {
1126 if (MA == CandidatePair.first || MA == CandidatePair.second)
1127 continue;
1128
1129 isl_map *AccRel =
1130 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1131 isl_set *Accs = isl_map_range(AccRel);
1132
1133 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1134 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1135 Valid = Valid && isl_set_is_empty(OverlapAccs);
1136 isl_set_free(OverlapAccs);
1137 }
1138 }
1139
1140 isl_set_free(AllAccs);
1141 if (!Valid)
1142 continue;
1143
Johannes Doerfertf6183392014-07-01 20:52:51 +00001144 const LoadInst *Load =
1145 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1146 MemoryAccess::ReductionType RT =
1147 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1148
Johannes Doerferte58a0122014-06-27 20:31:28 +00001149 // If no overlapping access was found we mark the load and store as
1150 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001151 CandidatePair.first->markAsReductionLike(RT);
1152 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001153 }
Tobias Grosser75805372011-04-29 06:27:02 +00001154}
1155
Tobias Grosser74394f02013-01-14 22:40:23 +00001156std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001157
Tobias Grosser54839312015-04-21 11:37:25 +00001158std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001159 auto *S = getSchedule();
1160 auto Str = stringFromIslObj(S);
1161 isl_map_free(S);
1162 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001163}
1164
Tobias Grosser74394f02013-01-14 22:40:23 +00001165unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001166
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001167unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001168
Tobias Grosser75805372011-04-29 06:27:02 +00001169const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1170
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001171const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001172 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001173}
1174
Tobias Grosser74394f02013-01-14 22:40:23 +00001175isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001176
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001177__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001178
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001179__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001180 return isl_set_get_space(Domain);
1181}
1182
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001183__isl_give isl_id *ScopStmt::getDomainId() const {
1184 return isl_set_get_tuple_id(Domain);
1185}
Tobias Grossercd95b772012-08-30 11:49:38 +00001186
Tobias Grosser75805372011-04-29 06:27:02 +00001187ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001188 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001189 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001190}
1191
1192void ScopStmt::print(raw_ostream &OS) const {
1193 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001194 OS.indent(12) << "Domain :=\n";
1195
1196 if (Domain) {
1197 OS.indent(16) << getDomainStr() << ";\n";
1198 } else
1199 OS.indent(16) << "n/a\n";
1200
Tobias Grosser54839312015-04-21 11:37:25 +00001201 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001202
1203 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001204 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001205 } else
1206 OS.indent(16) << "n/a\n";
1207
Tobias Grosser083d3d32014-06-28 08:59:45 +00001208 for (MemoryAccess *Access : MemAccs)
1209 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001210}
1211
1212void ScopStmt::dump() const { print(dbgs()); }
1213
1214//===----------------------------------------------------------------------===//
1215/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001216
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001217void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001218 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1219 isl_set_free(Context);
1220 Context = NewContext;
1221}
1222
Tobias Grosserabfbe632013-02-05 12:09:06 +00001223void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001224 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001225 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001226 if (ParameterIds.find(Parameter) != ParameterIds.end())
1227 continue;
1228
1229 int dimension = Parameters.size();
1230
1231 Parameters.push_back(Parameter);
1232 ParameterIds[Parameter] = dimension;
1233 }
1234}
1235
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001236__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1237 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001238
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001239 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001240 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001241
Tobias Grosser8f99c162011-11-15 11:38:55 +00001242 std::string ParameterName;
1243
1244 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1245 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001246 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001247 }
1248
1249 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001250 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001251
Tobias Grosser20532b82014-04-11 17:56:49 +00001252 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1253 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001254}
Tobias Grosser75805372011-04-29 06:27:02 +00001255
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001256isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1257 isl_set *DomainContext = isl_union_set_params(getDomains());
1258 return isl_set_intersect_params(C, DomainContext);
1259}
1260
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001261void Scop::addUserContext() {
1262 if (UserContextStr.empty())
1263 return;
1264
1265 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1266 isl_space *Space = getParamSpace();
1267 if (isl_space_dim(Space, isl_dim_param) !=
1268 isl_set_dim(UserContext, isl_dim_param)) {
1269 auto SpaceStr = isl_space_to_str(Space);
1270 errs() << "Error: the context provided in -polly-context has not the same "
1271 << "number of dimensions than the computed context. Due to this "
1272 << "mismatch, the -polly-context option is ignored. Please provide "
1273 << "the context in the parameter space: " << SpaceStr << ".\n";
1274 free(SpaceStr);
1275 isl_set_free(UserContext);
1276 isl_space_free(Space);
1277 return;
1278 }
1279
1280 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1281 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1282 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1283
1284 if (strcmp(NameContext, NameUserContext) != 0) {
1285 auto SpaceStr = isl_space_to_str(Space);
1286 errs() << "Error: the name of dimension " << i
1287 << " provided in -polly-context "
1288 << "is '" << NameUserContext << "', but the name in the computed "
1289 << "context is '" << NameContext
1290 << "'. Due to this name mismatch, "
1291 << "the -polly-context option is ignored. Please provide "
1292 << "the context in the parameter space: " << SpaceStr << ".\n";
1293 free(SpaceStr);
1294 isl_set_free(UserContext);
1295 isl_space_free(Space);
1296 return;
1297 }
1298
1299 UserContext =
1300 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1301 isl_space_get_dim_id(Space, isl_dim_param, i));
1302 }
1303
1304 Context = isl_set_intersect(Context, UserContext);
1305 isl_space_free(Space);
1306}
1307
Tobias Grosser6be480c2011-11-08 15:41:13 +00001308void Scop::buildContext() {
1309 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001310 Context = isl_set_universe(isl_space_copy(Space));
1311 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001312}
1313
Tobias Grosser18daaca2012-05-22 10:47:27 +00001314void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001315 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001316 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001317
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001318 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001319
Johannes Doerferte7044942015-02-24 11:58:30 +00001320 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001321 }
1322}
1323
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001324void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001325 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001326 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001327
Tobias Grosser083d3d32014-06-28 08:59:45 +00001328 for (const auto &ParamID : ParameterIds) {
1329 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001330 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001331 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001332 }
1333
1334 // Align the parameters of all data structures to the model.
1335 Context = isl_set_align_params(Context, Space);
1336
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001337 for (ScopStmt &Stmt : *this)
1338 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001339}
1340
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001341void Scop::simplifyAssumedContext() {
1342 // The parameter constraints of the iteration domains give us a set of
1343 // constraints that need to hold for all cases where at least a single
1344 // statement iteration is executed in the whole scop. We now simplify the
1345 // assumed context under the assumption that such constraints hold and at
1346 // least a single statement iteration is executed. For cases where no
1347 // statement instances are executed, the assumptions we have taken about
1348 // the executed code do not matter and can be changed.
1349 //
1350 // WARNING: This only holds if the assumptions we have taken do not reduce
1351 // the set of statement instances that are executed. Otherwise we
1352 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001353 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001354 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001355 // performed. In such a case, modifying the run-time conditions and
1356 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001357 // to not be executed.
1358 //
1359 // Example:
1360 //
1361 // When delinearizing the following code:
1362 //
1363 // for (long i = 0; i < 100; i++)
1364 // for (long j = 0; j < m; j++)
1365 // A[i+p][j] = 1.0;
1366 //
1367 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001368 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001369 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1370 AssumedContext =
1371 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001372 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001373}
1374
Johannes Doerfertb164c792014-09-18 11:17:17 +00001375/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001376static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001377 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1378 isl_pw_multi_aff *MinPMA, *MaxPMA;
1379 isl_pw_aff *LastDimAff;
1380 isl_aff *OneAff;
1381 unsigned Pos;
1382
Johannes Doerfert9143d672014-09-27 11:02:39 +00001383 // Restrict the number of parameters involved in the access as the lexmin/
1384 // lexmax computation will take too long if this number is high.
1385 //
1386 // Experiments with a simple test case using an i7 4800MQ:
1387 //
1388 // #Parameters involved | Time (in sec)
1389 // 6 | 0.01
1390 // 7 | 0.04
1391 // 8 | 0.12
1392 // 9 | 0.40
1393 // 10 | 1.54
1394 // 11 | 6.78
1395 // 12 | 30.38
1396 //
1397 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1398 unsigned InvolvedParams = 0;
1399 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1400 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1401 InvolvedParams++;
1402
1403 if (InvolvedParams > RunTimeChecksMaxParameters) {
1404 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001405 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001406 }
1407 }
1408
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001409 Set = isl_set_remove_divs(Set);
1410
Johannes Doerfertb164c792014-09-18 11:17:17 +00001411 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1412 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1413
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001414 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1415 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1416
Johannes Doerfertb164c792014-09-18 11:17:17 +00001417 // Adjust the last dimension of the maximal access by one as we want to
1418 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1419 // we test during code generation might now point after the end of the
1420 // allocated array but we will never dereference it anyway.
1421 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1422 "Assumed at least one output dimension");
1423 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1424 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1425 OneAff = isl_aff_zero_on_domain(
1426 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1427 OneAff = isl_aff_add_constant_si(OneAff, 1);
1428 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1429 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1430
1431 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1432
1433 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001434 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001435}
1436
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001437static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1438 isl_set *Domain = MA->getStatement()->getDomain();
1439 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1440 return isl_set_reset_tuple_id(Domain);
1441}
1442
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001443/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1444static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001445 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001446 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001447
1448 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1449 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001450 Locations = isl_union_set_coalesce(Locations);
1451 Locations = isl_union_set_detect_equalities(Locations);
1452 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001453 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001454 isl_union_set_free(Locations);
1455 return Valid;
1456}
1457
Johannes Doerfert96425c22015-08-30 21:13:53 +00001458/// @brief Helper to treat non-affine regions and basic blocks the same.
1459///
1460///{
1461
1462/// @brief Return the block that is the representing block for @p RN.
1463static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1464 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1465 : RN->getNodeAs<BasicBlock>();
1466}
1467
1468/// @brief Return the @p idx'th block that is executed after @p RN.
1469static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1470 unsigned idx) {
1471 if (RN->isSubRegion()) {
1472 assert(idx == 0);
1473 return RN->getNodeAs<Region>()->getExit();
1474 }
1475 return BI->getSuccessor(idx);
1476}
1477
1478/// @brief Return the smallest loop surrounding @p RN.
1479static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1480 if (!RN->isSubRegion())
1481 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1482
1483 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1484 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1485 while (L && NonAffineSubRegion->contains(L))
1486 L = L->getParentLoop();
1487 return L;
1488}
1489
1490///}
1491
1492isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1493 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1494 : Stmt->getRegion()->getEntry();
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001495 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001496}
1497
1498void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1499 DominatorTree &DT) {
1500
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001501 auto *EntryBB = R->getEntry();
1502 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1503 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
1504 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001505
1506 buildDomainsWithBranchConstraints(R, LI, SD, DT);
1507}
1508
1509void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1510 ScopDetection &SD,
1511 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001512 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001513
1514 // To create the domain for each block in R we iterate over all blocks and
1515 // subregions in R and propagate the conditions under which the current region
1516 // element is executed. To this end we iterate in reverse post order over R as
1517 // it ensures that we first visit all predecessors of a region node (either a
1518 // basic block or a subregion) before we visit the region node itself.
1519 // Initially, only the domain for the SCoP region entry block is set and from
1520 // there we propagate the current domain to all successors, however we add the
1521 // condition that the successor is actually executed next.
1522 // As we are only interested in non-loop carried constraints here we can
1523 // simply skip loop back edges.
1524
1525 ReversePostOrderTraversal<Region *> RTraversal(R);
1526 for (auto *RN : RTraversal) {
1527
1528 // Recurse for affine subregions but go on for basic blocks and non-affine
1529 // subregions.
1530 if (RN->isSubRegion()) {
1531 Region *SubRegion = RN->getNodeAs<Region>();
1532 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1533 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1534 continue;
1535 }
1536 }
1537
1538 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1539 isl_set *Domain = DomainMap[BB];
1540 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1541 assert(Domain && "Due to reverse post order traversal of the region all "
1542 "predecessor of the current region node should have been "
1543 "visited and a domain for this region node should have "
1544 "been set.");
1545
1546 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1547 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1548
1549 // Build the condition sets for the successor nodes of the current region
1550 // node. If it is a non-affine subregion we will always execute the single
1551 // exit node, hence the single entry node domain is the condition set. For
1552 // basic blocks we use the helper function buildConditionSets.
1553 SmallVector<isl_set *, 2> ConditionSets;
1554 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1555 if (RN->isSubRegion())
1556 ConditionSets.push_back(isl_set_copy(Domain));
1557 else
1558 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1559
1560 // Now iterate over the successors and set their initial domain based on
1561 // their condition set. We skip back edges here and have to be careful when
1562 // we leave a loop not to keep constraints over a dimension that doesn't
1563 // exist anymore.
1564 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1565 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1566 isl_set *CondSet = ConditionSets[u];
1567
1568 // Skip back edges.
1569 if (DT.dominates(SuccBB, BB)) {
1570 isl_set_free(CondSet);
1571 continue;
1572 }
1573
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001574 // Do not adjust the number of dimensions if we enter a boxed loop or are
1575 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001576 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001577 Region *SuccRegion = RI.getRegionFor(SuccBB);
1578 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1579 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1580 SuccRegion->contains(SuccBBLoop))) {
1581
1582 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1583 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1584 // and enter a new one we need to drop the old constraints.
1585 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
1586 assert(std::abs(BBLoopDepth - SuccBBLoopDepth) <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001587 if (BBLoopDepth > SuccBBLoopDepth) {
1588 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1589 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001590 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001591 } else if (BBLoopDepth >= 0) {
1592 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1593 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
1594 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001595 }
1596
1597 // Set the domain for the successor or merge it with an existing domain in
1598 // case there are multiple paths (without loop back edges) to the
1599 // successor block.
1600 isl_set *&SuccDomain = DomainMap[SuccBB];
1601 if (!SuccDomain)
1602 SuccDomain = CondSet;
1603 else
1604 SuccDomain = isl_set_union(SuccDomain, CondSet);
1605
1606 SuccDomain = isl_set_coalesce(SuccDomain);
1607 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1608 << "\n");
1609 }
1610 }
1611}
1612
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001613void Scop::buildAliasChecks(AliasAnalysis &AA) {
1614 if (!PollyUseRuntimeAliasChecks)
1615 return;
1616
1617 if (buildAliasGroups(AA))
1618 return;
1619
1620 // If a problem occurs while building the alias groups we need to delete
1621 // this SCoP and pretend it wasn't valid in the first place. To this end
1622 // we make the assumed context infeasible.
1623 addAssumption(isl_set_empty(getParamSpace()));
1624
1625 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1626 << " could not be created as the number of parameters involved "
1627 "is too high. The SCoP will be "
1628 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1629 "the maximal number of parameters but be advised that the "
1630 "compile time might increase exponentially.\n\n");
1631}
1632
Johannes Doerfert9143d672014-09-27 11:02:39 +00001633bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001634 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001635 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001636 // for all memory accesses inside the SCoP.
1637 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001638 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001639 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001640 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001641 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001642 // if their access domains intersect, otherwise they are in different
1643 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001644 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001645 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001646 // and maximal accesses to each array of a group in read only and non
1647 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001648 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1649
1650 AliasSetTracker AST(AA);
1651
1652 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001653 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001654 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001655
1656 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001657 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001658 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1659 isl_set_free(StmtDomain);
1660 if (StmtDomainEmpty)
1661 continue;
1662
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001663 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001664 if (MA->isScalar())
1665 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001666 if (!MA->isRead())
1667 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001668 Instruction *Acc = MA->getAccessInstruction();
1669 PtrToAcc[getPointerOperand(*Acc)] = MA;
1670 AST.add(Acc);
1671 }
1672 }
1673
1674 SmallVector<AliasGroupTy, 4> AliasGroups;
1675 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001676 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001677 continue;
1678 AliasGroupTy AG;
1679 for (auto PR : AS)
1680 AG.push_back(PtrToAcc[PR.getValue()]);
1681 assert(AG.size() > 1 &&
1682 "Alias groups should contain at least two accesses");
1683 AliasGroups.push_back(std::move(AG));
1684 }
1685
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001686 // Split the alias groups based on their domain.
1687 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1688 AliasGroupTy NewAG;
1689 AliasGroupTy &AG = AliasGroups[u];
1690 AliasGroupTy::iterator AGI = AG.begin();
1691 isl_set *AGDomain = getAccessDomain(*AGI);
1692 while (AGI != AG.end()) {
1693 MemoryAccess *MA = *AGI;
1694 isl_set *MADomain = getAccessDomain(MA);
1695 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1696 NewAG.push_back(MA);
1697 AGI = AG.erase(AGI);
1698 isl_set_free(MADomain);
1699 } else {
1700 AGDomain = isl_set_union(AGDomain, MADomain);
1701 AGI++;
1702 }
1703 }
1704 if (NewAG.size() > 1)
1705 AliasGroups.push_back(std::move(NewAG));
1706 isl_set_free(AGDomain);
1707 }
1708
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001709 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001710 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1711 for (AliasGroupTy &AG : AliasGroups) {
1712 NonReadOnlyBaseValues.clear();
1713 ReadOnlyPairs.clear();
1714
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001715 if (AG.size() < 2) {
1716 AG.clear();
1717 continue;
1718 }
1719
Johannes Doerfert13771732014-10-01 12:40:46 +00001720 for (auto II = AG.begin(); II != AG.end();) {
1721 Value *BaseAddr = (*II)->getBaseAddr();
1722 if (HasWriteAccess.count(BaseAddr)) {
1723 NonReadOnlyBaseValues.insert(BaseAddr);
1724 II++;
1725 } else {
1726 ReadOnlyPairs[BaseAddr].insert(*II);
1727 II = AG.erase(II);
1728 }
1729 }
1730
1731 // If we don't have read only pointers check if there are at least two
1732 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001733 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001734 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001735 continue;
1736 }
1737
1738 // If we don't have non read only pointers clear the alias group.
1739 if (NonReadOnlyBaseValues.empty()) {
1740 AG.clear();
1741 continue;
1742 }
1743
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001744 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001745 MinMaxAliasGroups.emplace_back();
1746 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1747 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1748 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1749 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001750
1751 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001752
1753 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001754 for (MemoryAccess *MA : AG)
1755 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001756
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001757 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
1758 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001759
1760 // Bail out if the number of values we need to compare is too large.
1761 // This is important as the number of comparisions grows quadratically with
1762 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001763 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1764 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001765 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001766
1767 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001768 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001769 Accesses = isl_union_map_empty(getParamSpace());
1770
1771 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1772 for (MemoryAccess *MA : ReadOnlyPair.second)
1773 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1774
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001775 Valid =
1776 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001777
1778 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001779 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001780 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001781
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001782 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001783}
1784
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001785static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1786 ScopDetection &SD) {
1787
1788 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1789
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001790 unsigned MinLD = INT_MAX, MaxLD = 0;
1791 for (BasicBlock *BB : R.blocks()) {
1792 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001793 if (!R.contains(L))
1794 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001795 if (BoxedLoops && BoxedLoops->count(L))
1796 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001797 unsigned LD = L->getLoopDepth();
1798 MinLD = std::min(MinLD, LD);
1799 MaxLD = std::max(MaxLD, LD);
1800 }
1801 }
1802
1803 // Handle the case that there is no loop in the SCoP first.
1804 if (MaxLD == 0)
1805 return 1;
1806
1807 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1808 assert(MaxLD >= MinLD &&
1809 "Maximal loop depth was smaller than mininaml loop depth?");
1810 return MaxLD - MinLD + 1;
1811}
1812
Johannes Doerfert96425c22015-08-30 21:13:53 +00001813Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, DominatorTree &DT,
1814 isl_ctx *Context, unsigned MaxLoopDepth)
1815 : DT(DT), SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert574182d2015-08-12 10:19:50 +00001816 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001817
Tobias Grosser40985012015-08-20 19:08:05 +00001818void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI, ScopDetection &SD,
1819 AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001820 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001821
Johannes Doerfert96425c22015-08-30 21:13:53 +00001822 buildDomains(&R, LI, SD, DT);
1823
Tobias Grosserabfbe632013-02-05 12:09:06 +00001824 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001825
Tobias Grosser54839312015-04-21 11:37:25 +00001826 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001827 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00001828 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00001829 if (!Schedule)
1830 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00001831
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001832 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001833 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001834 addUserContext();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001835 simplifyAssumedContext();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001836 buildAliasChecks(AA);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001837
Tobias Grosser75805372011-04-29 06:27:02 +00001838 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1839}
1840
Michael Kruse471a5e32015-07-30 19:27:04 +00001841Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
1842 ScalarEvolution &SE, ScopDetection &SD,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001843 AliasAnalysis &AA, DominatorTree &DT,
1844 isl_ctx *ctx) {
Michael Kruse471a5e32015-07-30 19:27:04 +00001845 auto &R = TempScop.getMaxRegion();
1846 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001847 auto S = new Scop(R, SE, DT, ctx, MaxLoopDepth);
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001848 S->initFromTempScop(TempScop, LI, SD, AA);
1849
Michael Kruse471a5e32015-07-30 19:27:04 +00001850 return S;
1851}
1852
Tobias Grosser75805372011-04-29 06:27:02 +00001853Scop::~Scop() {
1854 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001855 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00001856 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001857
Johannes Doerfert96425c22015-08-30 21:13:53 +00001858 for (auto It : DomainMap)
1859 isl_set_free(It.second);
1860
Johannes Doerfertb164c792014-09-18 11:17:17 +00001861 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001862 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001863 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001864 isl_pw_multi_aff_free(MMA.first);
1865 isl_pw_multi_aff_free(MMA.second);
1866 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001867 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001868 isl_pw_multi_aff_free(MMA.first);
1869 isl_pw_multi_aff_free(MMA.second);
1870 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001871 }
Tobias Grosser75805372011-04-29 06:27:02 +00001872}
1873
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001874const ScopArrayInfo *
1875Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00001876 const SmallVector<const SCEV *, 4> &Sizes,
1877 bool IsPHI) {
1878 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001879 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001880 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
1881 this));
Tobias Grosserab671442015-05-23 05:58:27 +00001882 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001883}
1884
Tobias Grosser92245222015-07-28 14:53:44 +00001885const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
1886 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001887 assert(SAI && "No ScopArrayInfo available for this base pointer");
1888 return SAI;
1889}
1890
Tobias Grosser74394f02013-01-14 22:40:23 +00001891std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001892std::string Scop::getAssumedContextStr() const {
1893 return stringFromIslObj(AssumedContext);
1894}
Tobias Grosser75805372011-04-29 06:27:02 +00001895
1896std::string Scop::getNameStr() const {
1897 std::string ExitName, EntryName;
1898 raw_string_ostream ExitStr(ExitName);
1899 raw_string_ostream EntryStr(EntryName);
1900
Tobias Grosserf240b482014-01-09 10:42:15 +00001901 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001902 EntryStr.str();
1903
1904 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001905 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001906 ExitStr.str();
1907 } else
1908 ExitName = "FunctionExit";
1909
1910 return EntryName + "---" + ExitName;
1911}
1912
Tobias Grosser74394f02013-01-14 22:40:23 +00001913__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001914__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001915 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001916}
1917
Tobias Grossere86109f2013-10-29 21:05:49 +00001918__isl_give isl_set *Scop::getAssumedContext() const {
1919 return isl_set_copy(AssumedContext);
1920}
1921
Johannes Doerfert43788c52015-08-20 05:58:56 +00001922__isl_give isl_set *Scop::getRuntimeCheckContext() const {
1923 isl_set *RuntimeCheckContext = getAssumedContext();
1924 return RuntimeCheckContext;
1925}
1926
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001927bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00001928 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001929 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00001930 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
1931 isl_set_free(RuntimeCheckContext);
1932 return IsFeasible;
1933}
1934
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001935void Scop::addAssumption(__isl_take isl_set *Set) {
1936 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001937 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001938}
1939
Tobias Grosser75805372011-04-29 06:27:02 +00001940void Scop::printContext(raw_ostream &OS) const {
1941 OS << "Context:\n";
1942
1943 if (!Context) {
1944 OS.indent(4) << "n/a\n\n";
1945 return;
1946 }
1947
1948 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001949
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001950 OS.indent(4) << "Assumed Context:\n";
1951 if (!AssumedContext) {
1952 OS.indent(4) << "n/a\n\n";
1953 return;
1954 }
1955
1956 OS.indent(4) << getAssumedContextStr() << "\n";
1957
Tobias Grosser083d3d32014-06-28 08:59:45 +00001958 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001959 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001960 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1961 }
Tobias Grosser75805372011-04-29 06:27:02 +00001962}
1963
Johannes Doerfertb164c792014-09-18 11:17:17 +00001964void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001965 int noOfGroups = 0;
1966 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001967 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001968 noOfGroups += 1;
1969 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001970 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001971 }
1972
Tobias Grosserbb853c22015-07-25 12:31:03 +00001973 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00001974 if (MinMaxAliasGroups.empty()) {
1975 OS.indent(8) << "n/a\n";
1976 return;
1977 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001978
Tobias Grosserbb853c22015-07-25 12:31:03 +00001979 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001980
1981 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001982 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001983 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001984 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001985 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1986 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001987 }
1988 OS << " ]]\n";
1989 }
1990
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001991 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001992 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00001993 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001994 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001995 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1996 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001997 }
1998 OS << " ]]\n";
1999 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002000 }
2001}
2002
Tobias Grosser75805372011-04-29 06:27:02 +00002003void Scop::printStatements(raw_ostream &OS) const {
2004 OS << "Statements {\n";
2005
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002006 for (const ScopStmt &Stmt : *this)
2007 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002008
2009 OS.indent(4) << "}\n";
2010}
2011
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002012void Scop::printArrayInfo(raw_ostream &OS) const {
2013 OS << "Arrays {\n";
2014
Tobias Grosserab671442015-05-23 05:58:27 +00002015 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002016 Array.second->print(OS);
2017
2018 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002019
2020 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2021
2022 for (auto &Array : arrays())
2023 Array.second->print(OS, /* SizeAsPwAff */ true);
2024
2025 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002026}
2027
Tobias Grosser75805372011-04-29 06:27:02 +00002028void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002029 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2030 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002031 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002032 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002033 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002034 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002035 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002036 printStatements(OS.indent(4));
2037}
2038
2039void Scop::dump() const { print(dbgs()); }
2040
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002041isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002042
Johannes Doerfertb409fdc2015-08-28 09:24:35 +00002043__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, isl_set *Domain) {
2044 return Affinator.getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002045}
2046
Tobias Grosser808cd692015-07-14 09:33:13 +00002047__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002048 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002049
Tobias Grosser808cd692015-07-14 09:33:13 +00002050 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002051 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002052
2053 return Domain;
2054}
2055
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002056__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002057 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002058
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002059 for (ScopStmt &Stmt : *this) {
2060 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002061 if (!MA->isMustWrite())
2062 continue;
2063
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002064 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002065 isl_map *AccessDomain = MA->getAccessRelation();
2066 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2067 Write = isl_union_map_add_map(Write, AccessDomain);
2068 }
2069 }
2070 return isl_union_map_coalesce(Write);
2071}
2072
2073__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002074 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002075
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002076 for (ScopStmt &Stmt : *this) {
2077 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002078 if (!MA->isMayWrite())
2079 continue;
2080
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002081 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002082 isl_map *AccessDomain = MA->getAccessRelation();
2083 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2084 Write = isl_union_map_add_map(Write, AccessDomain);
2085 }
2086 }
2087 return isl_union_map_coalesce(Write);
2088}
2089
Tobias Grosser37eb4222014-02-20 21:43:54 +00002090__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002091 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002092
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002093 for (ScopStmt &Stmt : *this) {
2094 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002095 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002096 continue;
2097
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002098 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002099 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002100 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2101 Write = isl_union_map_add_map(Write, AccessDomain);
2102 }
2103 }
2104 return isl_union_map_coalesce(Write);
2105}
2106
2107__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002108 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002109
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002110 for (ScopStmt &Stmt : *this) {
2111 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002112 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002113 continue;
2114
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002115 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002116 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002117
2118 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2119 Read = isl_union_map_add_map(Read, AccessDomain);
2120 }
2121 }
2122 return isl_union_map_coalesce(Read);
2123}
2124
Tobias Grosser808cd692015-07-14 09:33:13 +00002125__isl_give isl_union_map *Scop::getSchedule() const {
2126 auto Tree = getScheduleTree();
2127 auto S = isl_schedule_get_map(Tree);
2128 isl_schedule_free(Tree);
2129 return S;
2130}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002131
Tobias Grosser808cd692015-07-14 09:33:13 +00002132__isl_give isl_schedule *Scop::getScheduleTree() const {
2133 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2134 getDomains());
2135}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002136
Tobias Grosser808cd692015-07-14 09:33:13 +00002137void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2138 auto *S = isl_schedule_from_domain(getDomains());
2139 S = isl_schedule_insert_partial_schedule(
2140 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2141 isl_schedule_free(Schedule);
2142 Schedule = S;
2143}
2144
2145void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2146 isl_schedule_free(Schedule);
2147 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002148}
2149
2150bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2151 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002152 for (ScopStmt &Stmt : *this) {
2153 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002154 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2155 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2156
2157 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2158 isl_union_set_free(StmtDomain);
2159 isl_union_set_free(NewStmtDomain);
2160 continue;
2161 }
2162
2163 Changed = true;
2164
2165 isl_union_set_free(StmtDomain);
2166 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2167
2168 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002169 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002170 isl_union_set_free(NewStmtDomain);
2171 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002172 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002173 }
2174 isl_union_set_free(Domain);
2175 return Changed;
2176}
2177
Tobias Grosser75805372011-04-29 06:27:02 +00002178ScalarEvolution *Scop::getSE() const { return SE; }
2179
2180bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
2181 if (tempScop.getAccessFunctions(BB))
2182 return false;
2183
2184 return true;
2185}
2186
Tobias Grosser808cd692015-07-14 09:33:13 +00002187struct MapToDimensionDataTy {
2188 int N;
2189 isl_union_pw_multi_aff *Res;
2190};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002191
Tobias Grosser808cd692015-07-14 09:33:13 +00002192// @brief Create a function that maps the elements of 'Set' to its N-th
2193// dimension.
2194//
2195// The result is added to 'User->Res'.
2196//
2197// @param Set The input set.
2198// @param N The dimension to map to.
2199//
2200// @returns Zero if no error occurred, non-zero otherwise.
2201static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2202 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2203 int Dim;
2204 isl_space *Space;
2205 isl_pw_multi_aff *PMA;
2206
2207 Dim = isl_set_dim(Set, isl_dim_set);
2208 Space = isl_set_get_space(Set);
2209 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2210 Dim - Data->N);
2211 if (Data->N > 1)
2212 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2213 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2214
2215 isl_set_free(Set);
2216
2217 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002218}
2219
Tobias Grosser808cd692015-07-14 09:33:13 +00002220// @brief Create a function that maps the elements of Domain to their Nth
2221// dimension.
2222//
2223// @param Domain The set of elements to map.
2224// @param N The dimension to map to.
2225static __isl_give isl_multi_union_pw_aff *
2226mapToDimension(__isl_take isl_union_set *Domain, int N) {
2227 struct MapToDimensionDataTy Data;
2228 isl_space *Space;
2229
2230 Space = isl_union_set_get_space(Domain);
2231 Data.N = N;
2232 Data.Res = isl_union_pw_multi_aff_empty(Space);
2233 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2234 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2235
2236 isl_union_set_free(Domain);
2237 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2238}
2239
2240ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
2241 const Region &CurRegion,
2242 SmallVectorImpl<Loop *> &NestLoops) {
2243 ScopStmt *Stmt;
2244 if (BB) {
2245 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
2246 Stmt = &Stmts.back();
2247 StmtMap[BB] = Stmt;
2248 } else {
2249 assert(R && "Either basic block or a region expected.");
2250 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
2251 Stmt = &Stmts.back();
2252 for (BasicBlock *BB : R->blocks())
2253 StmtMap[BB] = Stmt;
2254 }
2255 return Stmt;
2256}
2257
Michael Kruse046dde42015-08-10 13:01:57 +00002258__isl_give isl_schedule *
2259Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
2260 const Region &CurRegion,
2261 SmallVectorImpl<Loop *> &NestLoops) {
2262 if (isTrivialBB(BB, tempScop))
2263 return nullptr;
2264
2265 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
2266 auto *Domain = Stmt->getDomain();
2267 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2268}
2269
Tobias Grosser808cd692015-07-14 09:33:13 +00002270__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
2271 const Region &CurRegion,
2272 SmallVectorImpl<Loop *> &NestLoops,
2273 LoopInfo &LI, ScopDetection &SD) {
2274 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
2275 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
2276 tempScop, CurRegion, NestLoops);
2277 auto *Domain = Stmt->getDomain();
2278 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2279 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002280
Tobias Grosser75805372011-04-29 06:27:02 +00002281 Loop *L = castToLoop(CurRegion, LI);
2282
2283 if (L)
2284 NestLoops.push_back(L);
2285
2286 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00002287 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002288
2289 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002290 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00002291 I != E; ++I) {
2292 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002293 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002294 StmtSchedule =
2295 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002296 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00002297 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
2298 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00002299 }
Michael Kruse046dde42015-08-10 13:01:57 +00002300 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00002301 }
Tobias Grosser75805372011-04-29 06:27:02 +00002302
Tobias Grosser808cd692015-07-14 09:33:13 +00002303 if (!L)
2304 return Schedule;
2305
2306 auto *Domain = isl_schedule_get_domain(Schedule);
2307 if (!isl_union_set_is_empty(Domain)) {
2308 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
2309 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
2310 }
2311 isl_union_set_free(Domain);
2312
Tobias Grosser75805372011-04-29 06:27:02 +00002313 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00002314 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00002315}
2316
Johannes Doerfert7c494212014-10-31 23:13:39 +00002317ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002318 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002319 if (StmtMapIt == StmtMap.end())
2320 return nullptr;
2321 return StmtMapIt->second;
2322}
2323
Johannes Doerfert96425c22015-08-30 21:13:53 +00002324int Scop::getRelativeLoopDepth(const Loop *L) const {
2325 Loop *OuterLoop =
2326 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2327 if (!OuterLoop)
2328 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002329 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2330}
2331
Tobias Grosser75805372011-04-29 06:27:02 +00002332//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002333ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2334 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002335 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002336}
2337
2338ScopInfo::~ScopInfo() {
2339 clear();
2340 isl_ctx_free(ctx);
2341}
2342
Tobias Grosser75805372011-04-29 06:27:02 +00002343void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002344 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002345 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002346 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002347 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002348 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002349 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002350 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002351 AU.setPreservesAll();
2352}
2353
2354bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002355 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002356 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002357 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002358 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002359 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00002360
Michael Kruse82a1c7d2015-08-14 20:10:27 +00002361 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop();
Tobias Grosser75805372011-04-29 06:27:02 +00002362
2363 // This region is no Scop.
2364 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002365 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002366 return false;
2367 }
2368
Johannes Doerfert96425c22015-08-30 21:13:53 +00002369 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, AA, DT, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002370
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002371 DEBUG(scop->print(dbgs()));
2372
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002373 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002374 delete scop;
2375 scop = nullptr;
2376 return false;
2377 }
2378
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002379 // Statistics.
2380 ++ScopFound;
2381 if (scop->getMaxLoopDepth() > 0)
2382 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00002383 return false;
2384}
2385
2386char ScopInfo::ID = 0;
2387
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002388Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2389
Tobias Grosser73600b82011-10-08 00:30:40 +00002390INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2391 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002392 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002393INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002394INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002395INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002396INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002397INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002398INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002399INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00002400INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2401 "Polly - Create polyhedral description of Scops", false,
2402 false)