blob: b209c3576ef494bde37e9040bb1e4bf79ba173fa [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 {
906 // If SCEV cannot provide a loop trip count we compute it with ISL.
907 addLoopTripCountToDomain(L);
908 isl_pw_aff_free(IV);
909 }
Tobias Grosser75805372011-04-29 06:27:02 +0000910 }
911
Tobias Grosserf5338802011-10-06 00:03:35 +0000912 isl_local_space_free(LocalSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000913}
914
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000915void ScopStmt::buildDomain(TempScop &tempScop, const Region &CurRegion) {
Tobias Grossere19661e2011-10-07 08:46:57 +0000916 isl_space *Space;
Tobias Grosser084d8f72012-05-29 09:29:44 +0000917 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000918
919 Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
920
Tobias Grosser084d8f72012-05-29 09:29:44 +0000921 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
922
Tobias Grossere19661e2011-10-07 08:46:57 +0000923 Domain = isl_set_universe(Space);
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000924 addLoopBoundsToDomain(tempScop);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000925 Domain = isl_set_intersect(Domain, getParent()->getDomainConditions(this));
926 Domain = isl_set_coalesce(Domain);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000927 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000928}
929
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000930void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
931 int Dimension = 0;
932 isl_ctx *Ctx = Parent.getIslCtx();
933 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
934 Type *Ty = GEP->getPointerOperandType();
935 ScalarEvolution &SE = *Parent.getSE();
936
937 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
938 Dimension = 1;
939 Ty = PtrTy->getElementType();
940 }
941
942 while (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
943 unsigned int Operand = 1 + Dimension;
944
945 if (GEP->getNumOperands() <= Operand)
946 break;
947
948 const SCEV *Expr = SE.getSCEV(GEP->getOperand(Operand));
949
950 if (isAffineExpr(&Parent.getRegion(), Expr, SE)) {
Johannes Doerfert574182d2015-08-12 10:19:50 +0000951 isl_pw_aff *AccessOffset = getPwAff(Expr);
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000952 AccessOffset =
953 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
954
955 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
956 isl_local_space_copy(LSpace),
957 isl_val_int_from_si(Ctx, ArrayTy->getNumElements())));
958
959 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
960 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
961 OutOfBound = isl_set_params(OutOfBound);
962 isl_set *InBound = isl_set_complement(OutOfBound);
963 isl_set *Executed = isl_set_params(getDomain());
964
965 // A => B == !A or B
966 isl_set *InBoundIfExecuted =
967 isl_set_union(isl_set_complement(Executed), InBound);
968
969 Parent.addAssumption(InBoundIfExecuted);
970 }
971
972 Dimension += 1;
973 Ty = ArrayTy->getElementType();
974 }
975
976 isl_local_space_free(LSpace);
977}
978
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000979void ScopStmt::deriveAssumptions(BasicBlock *Block) {
980 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000981 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
982 deriveAssumptionsFromGEP(GEP);
983}
984
Tobias Grosser74394f02013-01-14 22:40:23 +0000985ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +0000986 Region &R, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000987 : Parent(parent), BB(nullptr), R(&R), Build(nullptr),
988 NestLoops(Nest.size()) {
989 // Setup the induction variables.
990 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
991 NestLoops[i] = Nest[i];
992
Tobias Grosser16c44032015-07-09 07:31:45 +0000993 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000994
Johannes Doerfert45545ff2015-08-16 14:36:01 +0000995 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000996
997 BasicBlock *EntryBB = R.getEntry();
998 for (BasicBlock *Block : R.blocks()) {
999 buildAccesses(tempScop, Block, Block != EntryBB);
1000 deriveAssumptions(Block);
1001 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001002 if (DetectReductions)
1003 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001004}
1005
1006ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
Tobias Grosser808cd692015-07-14 09:33:13 +00001007 BasicBlock &bb, SmallVectorImpl<Loop *> &Nest)
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001008 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr),
1009 NestLoops(Nest.size()) {
Tobias Grosser75805372011-04-29 06:27:02 +00001010 // Setup the induction variables.
Tobias Grosser683b8e42014-11-30 14:33:31 +00001011 for (unsigned i = 0, e = Nest.size(); i < e; ++i)
Sebastian Pop860e0212013-02-15 21:26:44 +00001012 NestLoops[i] = Nest[i];
Tobias Grosser75805372011-04-29 06:27:02 +00001013
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001014 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001015
Johannes Doerfert45545ff2015-08-16 14:36:01 +00001016 buildDomain(tempScop, CurRegion);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001017 buildAccesses(tempScop, BB);
1018 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001019 if (DetectReductions)
1020 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001021}
1022
Johannes Doerferte58a0122014-06-27 20:31:28 +00001023/// @brief Collect loads which might form a reduction chain with @p StoreMA
1024///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001025/// Check if the stored value for @p StoreMA is a binary operator with one or
1026/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001027/// used only once (by @p StoreMA) and its load operands are also used only
1028/// once, we have found a possible reduction chain. It starts at an operand
1029/// load and includes the binary operator and @p StoreMA.
1030///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001031/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001032/// escape this block or into any other store except @p StoreMA.
1033void ScopStmt::collectCandiateReductionLoads(
1034 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1035 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1036 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001037 return;
1038
1039 // Skip if there is not one binary operator between the load and the store
1040 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001041 if (!BinOp)
1042 return;
1043
1044 // Skip if the binary operators has multiple uses
1045 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001046 return;
1047
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001048 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001049 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1050 return;
1051
Johannes Doerfert9890a052014-07-01 00:32:29 +00001052 // Skip if the binary operator is outside the current SCoP
1053 if (BinOp->getParent() != Store->getParent())
1054 return;
1055
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001056 // Skip if it is a multiplicative reduction and we disabled them
1057 if (DisableMultiplicativeReductions &&
1058 (BinOp->getOpcode() == Instruction::Mul ||
1059 BinOp->getOpcode() == Instruction::FMul))
1060 return;
1061
Johannes Doerferte58a0122014-06-27 20:31:28 +00001062 // Check the binary operator operands for a candidate load
1063 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1064 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1065 if (!PossibleLoad0 && !PossibleLoad1)
1066 return;
1067
1068 // A load is only a candidate if it cannot escape (thus has only this use)
1069 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001070 if (PossibleLoad0->getParent() == Store->getParent())
1071 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001072 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001073 if (PossibleLoad1->getParent() == Store->getParent())
1074 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001075}
1076
1077/// @brief Check for reductions in this ScopStmt
1078///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001079/// Iterate over all store memory accesses and check for valid binary reduction
1080/// like chains. For all candidates we check if they have the same base address
1081/// and there are no other accesses which overlap with them. The base address
1082/// check rules out impossible reductions candidates early. The overlap check,
1083/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001084/// guarantees that none of the intermediate results will escape during
1085/// execution of the loop nest. We basically check here that no other memory
1086/// access can access the same memory as the potential reduction.
1087void ScopStmt::checkForReductions() {
1088 SmallVector<MemoryAccess *, 2> Loads;
1089 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1090
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001091 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001092 // stores and collecting possible reduction loads.
1093 for (MemoryAccess *StoreMA : MemAccs) {
1094 if (StoreMA->isRead())
1095 continue;
1096
1097 Loads.clear();
1098 collectCandiateReductionLoads(StoreMA, Loads);
1099 for (MemoryAccess *LoadMA : Loads)
1100 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1101 }
1102
1103 // Then check each possible candidate pair.
1104 for (const auto &CandidatePair : Candidates) {
1105 bool Valid = true;
1106 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1107 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1108
1109 // Skip those with obviously unequal base addresses.
1110 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1111 isl_map_free(LoadAccs);
1112 isl_map_free(StoreAccs);
1113 continue;
1114 }
1115
1116 // And check if the remaining for overlap with other memory accesses.
1117 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1118 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1119 isl_set *AllAccs = isl_map_range(AllAccsRel);
1120
1121 for (MemoryAccess *MA : MemAccs) {
1122 if (MA == CandidatePair.first || MA == CandidatePair.second)
1123 continue;
1124
1125 isl_map *AccRel =
1126 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1127 isl_set *Accs = isl_map_range(AccRel);
1128
1129 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1130 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1131 Valid = Valid && isl_set_is_empty(OverlapAccs);
1132 isl_set_free(OverlapAccs);
1133 }
1134 }
1135
1136 isl_set_free(AllAccs);
1137 if (!Valid)
1138 continue;
1139
Johannes Doerfertf6183392014-07-01 20:52:51 +00001140 const LoadInst *Load =
1141 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1142 MemoryAccess::ReductionType RT =
1143 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1144
Johannes Doerferte58a0122014-06-27 20:31:28 +00001145 // If no overlapping access was found we mark the load and store as
1146 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001147 CandidatePair.first->markAsReductionLike(RT);
1148 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001149 }
Tobias Grosser75805372011-04-29 06:27:02 +00001150}
1151
Tobias Grosser74394f02013-01-14 22:40:23 +00001152std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001153
Tobias Grosser54839312015-04-21 11:37:25 +00001154std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001155 auto *S = getSchedule();
1156 auto Str = stringFromIslObj(S);
1157 isl_map_free(S);
1158 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001159}
1160
Tobias Grosser74394f02013-01-14 22:40:23 +00001161unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001162
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001163unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001164
Tobias Grosser75805372011-04-29 06:27:02 +00001165const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1166
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001167const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001168 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001169}
1170
Tobias Grosser74394f02013-01-14 22:40:23 +00001171isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001172
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001173__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001174
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001175__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001176 return isl_set_get_space(Domain);
1177}
1178
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001179__isl_give isl_id *ScopStmt::getDomainId() const {
1180 return isl_set_get_tuple_id(Domain);
1181}
Tobias Grossercd95b772012-08-30 11:49:38 +00001182
Tobias Grosser75805372011-04-29 06:27:02 +00001183ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001184 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001185 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001186}
1187
1188void ScopStmt::print(raw_ostream &OS) const {
1189 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001190 OS.indent(12) << "Domain :=\n";
1191
1192 if (Domain) {
1193 OS.indent(16) << getDomainStr() << ";\n";
1194 } else
1195 OS.indent(16) << "n/a\n";
1196
Tobias Grosser54839312015-04-21 11:37:25 +00001197 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001198
1199 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001200 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001201 } else
1202 OS.indent(16) << "n/a\n";
1203
Tobias Grosser083d3d32014-06-28 08:59:45 +00001204 for (MemoryAccess *Access : MemAccs)
1205 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001206}
1207
1208void ScopStmt::dump() const { print(dbgs()); }
1209
1210//===----------------------------------------------------------------------===//
1211/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001212
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001213void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001214 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1215 isl_set_free(Context);
1216 Context = NewContext;
1217}
1218
Tobias Grosserabfbe632013-02-05 12:09:06 +00001219void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001220 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001221 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001222 if (ParameterIds.find(Parameter) != ParameterIds.end())
1223 continue;
1224
1225 int dimension = Parameters.size();
1226
1227 Parameters.push_back(Parameter);
1228 ParameterIds[Parameter] = dimension;
1229 }
1230}
1231
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001232__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1233 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001234
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001235 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001236 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001237
Tobias Grosser8f99c162011-11-15 11:38:55 +00001238 std::string ParameterName;
1239
1240 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1241 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001242 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001243 }
1244
1245 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001246 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001247
Tobias Grosser20532b82014-04-11 17:56:49 +00001248 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1249 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001250}
Tobias Grosser75805372011-04-29 06:27:02 +00001251
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001252isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1253 isl_set *DomainContext = isl_union_set_params(getDomains());
1254 return isl_set_intersect_params(C, DomainContext);
1255}
1256
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001257void Scop::addUserContext() {
1258 if (UserContextStr.empty())
1259 return;
1260
1261 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1262 isl_space *Space = getParamSpace();
1263 if (isl_space_dim(Space, isl_dim_param) !=
1264 isl_set_dim(UserContext, isl_dim_param)) {
1265 auto SpaceStr = isl_space_to_str(Space);
1266 errs() << "Error: the context provided in -polly-context has not the same "
1267 << "number of dimensions than the computed context. Due to this "
1268 << "mismatch, the -polly-context option is ignored. Please provide "
1269 << "the context in the parameter space: " << SpaceStr << ".\n";
1270 free(SpaceStr);
1271 isl_set_free(UserContext);
1272 isl_space_free(Space);
1273 return;
1274 }
1275
1276 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1277 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1278 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1279
1280 if (strcmp(NameContext, NameUserContext) != 0) {
1281 auto SpaceStr = isl_space_to_str(Space);
1282 errs() << "Error: the name of dimension " << i
1283 << " provided in -polly-context "
1284 << "is '" << NameUserContext << "', but the name in the computed "
1285 << "context is '" << NameContext
1286 << "'. Due to this name mismatch, "
1287 << "the -polly-context option is ignored. Please provide "
1288 << "the context in the parameter space: " << SpaceStr << ".\n";
1289 free(SpaceStr);
1290 isl_set_free(UserContext);
1291 isl_space_free(Space);
1292 return;
1293 }
1294
1295 UserContext =
1296 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1297 isl_space_get_dim_id(Space, isl_dim_param, i));
1298 }
1299
1300 Context = isl_set_intersect(Context, UserContext);
1301 isl_space_free(Space);
1302}
1303
Tobias Grosser6be480c2011-11-08 15:41:13 +00001304void Scop::buildContext() {
1305 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001306 Context = isl_set_universe(isl_space_copy(Space));
1307 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001308}
1309
Tobias Grosser18daaca2012-05-22 10:47:27 +00001310void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001311 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001312 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001313
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001314 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001315
Johannes Doerferte7044942015-02-24 11:58:30 +00001316 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001317 }
1318}
1319
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001320void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001321 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001322 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001323
Tobias Grosser083d3d32014-06-28 08:59:45 +00001324 for (const auto &ParamID : ParameterIds) {
1325 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001326 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001327 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001328 }
1329
1330 // Align the parameters of all data structures to the model.
1331 Context = isl_set_align_params(Context, Space);
1332
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001333 for (ScopStmt &Stmt : *this)
1334 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001335}
1336
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001337void Scop::simplifyAssumedContext() {
1338 // The parameter constraints of the iteration domains give us a set of
1339 // constraints that need to hold for all cases where at least a single
1340 // statement iteration is executed in the whole scop. We now simplify the
1341 // assumed context under the assumption that such constraints hold and at
1342 // least a single statement iteration is executed. For cases where no
1343 // statement instances are executed, the assumptions we have taken about
1344 // the executed code do not matter and can be changed.
1345 //
1346 // WARNING: This only holds if the assumptions we have taken do not reduce
1347 // the set of statement instances that are executed. Otherwise we
1348 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001349 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001350 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001351 // performed. In such a case, modifying the run-time conditions and
1352 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001353 // to not be executed.
1354 //
1355 // Example:
1356 //
1357 // When delinearizing the following code:
1358 //
1359 // for (long i = 0; i < 100; i++)
1360 // for (long j = 0; j < m; j++)
1361 // A[i+p][j] = 1.0;
1362 //
1363 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001364 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001365 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
1366 AssumedContext =
1367 isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001368 AssumedContext = isl_set_gist_params(AssumedContext, getContext());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001369}
1370
Johannes Doerfertb164c792014-09-18 11:17:17 +00001371/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001372static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001373 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1374 isl_pw_multi_aff *MinPMA, *MaxPMA;
1375 isl_pw_aff *LastDimAff;
1376 isl_aff *OneAff;
1377 unsigned Pos;
1378
Johannes Doerfert9143d672014-09-27 11:02:39 +00001379 // Restrict the number of parameters involved in the access as the lexmin/
1380 // lexmax computation will take too long if this number is high.
1381 //
1382 // Experiments with a simple test case using an i7 4800MQ:
1383 //
1384 // #Parameters involved | Time (in sec)
1385 // 6 | 0.01
1386 // 7 | 0.04
1387 // 8 | 0.12
1388 // 9 | 0.40
1389 // 10 | 1.54
1390 // 11 | 6.78
1391 // 12 | 30.38
1392 //
1393 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1394 unsigned InvolvedParams = 0;
1395 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1396 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1397 InvolvedParams++;
1398
1399 if (InvolvedParams > RunTimeChecksMaxParameters) {
1400 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001401 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001402 }
1403 }
1404
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001405 Set = isl_set_remove_divs(Set);
1406
Johannes Doerfertb164c792014-09-18 11:17:17 +00001407 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1408 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1409
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001410 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1411 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1412
Johannes Doerfertb164c792014-09-18 11:17:17 +00001413 // Adjust the last dimension of the maximal access by one as we want to
1414 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1415 // we test during code generation might now point after the end of the
1416 // allocated array but we will never dereference it anyway.
1417 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1418 "Assumed at least one output dimension");
1419 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1420 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1421 OneAff = isl_aff_zero_on_domain(
1422 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1423 OneAff = isl_aff_add_constant_si(OneAff, 1);
1424 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1425 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1426
1427 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1428
1429 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001430 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001431}
1432
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001433static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1434 isl_set *Domain = MA->getStatement()->getDomain();
1435 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1436 return isl_set_reset_tuple_id(Domain);
1437}
1438
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001439/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1440static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001441 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001442 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001443
1444 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1445 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001446 Locations = isl_union_set_coalesce(Locations);
1447 Locations = isl_union_set_detect_equalities(Locations);
1448 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001449 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001450 isl_union_set_free(Locations);
1451 return Valid;
1452}
1453
Johannes Doerfert96425c22015-08-30 21:13:53 +00001454/// @brief Helper to treat non-affine regions and basic blocks the same.
1455///
1456///{
1457
1458/// @brief Return the block that is the representing block for @p RN.
1459static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1460 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1461 : RN->getNodeAs<BasicBlock>();
1462}
1463
1464/// @brief Return the @p idx'th block that is executed after @p RN.
1465static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1466 unsigned idx) {
1467 if (RN->isSubRegion()) {
1468 assert(idx == 0);
1469 return RN->getNodeAs<Region>()->getExit();
1470 }
1471 return BI->getSuccessor(idx);
1472}
1473
1474/// @brief Return the smallest loop surrounding @p RN.
1475static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1476 if (!RN->isSubRegion())
1477 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1478
1479 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1480 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1481 while (L && NonAffineSubRegion->contains(L))
1482 L = L->getParentLoop();
1483 return L;
1484}
1485
1486///}
1487
1488isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1489 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1490 : Stmt->getRegion()->getEntry();
1491 isl_set *Domain = isl_set_copy(DomainMap[BB]);
1492
1493 unsigned NumDims = Stmt->getNumIterators();
1494 Domain = isl_set_remove_dims(Domain, isl_dim_set, NumDims,
1495 getMaxLoopDepth() - NumDims);
1496 return Domain;
1497}
1498
1499void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1500 DominatorTree &DT) {
1501
1502 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, MaxLoopDepth));
1503 DomainMap[R->getEntry()] = S;
1504
1505 buildDomainsWithBranchConstraints(R, LI, SD, DT);
1506}
1507
1508void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1509 ScopDetection &SD,
1510 DominatorTree &DT) {
1511
1512 // To create the domain for each block in R we iterate over all blocks and
1513 // subregions in R and propagate the conditions under which the current region
1514 // element is executed. To this end we iterate in reverse post order over R as
1515 // it ensures that we first visit all predecessors of a region node (either a
1516 // basic block or a subregion) before we visit the region node itself.
1517 // Initially, only the domain for the SCoP region entry block is set and from
1518 // there we propagate the current domain to all successors, however we add the
1519 // condition that the successor is actually executed next.
1520 // As we are only interested in non-loop carried constraints here we can
1521 // simply skip loop back edges.
1522
1523 ReversePostOrderTraversal<Region *> RTraversal(R);
1524 for (auto *RN : RTraversal) {
1525
1526 // Recurse for affine subregions but go on for basic blocks and non-affine
1527 // subregions.
1528 if (RN->isSubRegion()) {
1529 Region *SubRegion = RN->getNodeAs<Region>();
1530 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1531 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1532 continue;
1533 }
1534 }
1535
1536 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1537 isl_set *Domain = DomainMap[BB];
1538 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1539 assert(Domain && "Due to reverse post order traversal of the region all "
1540 "predecessor of the current region node should have been "
1541 "visited and a domain for this region node should have "
1542 "been set.");
1543
1544 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1545 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1546
1547 // Build the condition sets for the successor nodes of the current region
1548 // node. If it is a non-affine subregion we will always execute the single
1549 // exit node, hence the single entry node domain is the condition set. For
1550 // basic blocks we use the helper function buildConditionSets.
1551 SmallVector<isl_set *, 2> ConditionSets;
1552 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1553 if (RN->isSubRegion())
1554 ConditionSets.push_back(isl_set_copy(Domain));
1555 else
1556 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1557
1558 // Now iterate over the successors and set their initial domain based on
1559 // their condition set. We skip back edges here and have to be careful when
1560 // we leave a loop not to keep constraints over a dimension that doesn't
1561 // exist anymore.
1562 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1563 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1564 isl_set *CondSet = ConditionSets[u];
1565
1566 // Skip back edges.
1567 if (DT.dominates(SuccBB, BB)) {
1568 isl_set_free(CondSet);
1569 continue;
1570 }
1571
1572 // Check if the edge to SuccBB is a loop exit edge. If so drop the
1573 // constrains on the loop/dimension we leave.
1574 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
1575 if (SuccBBLoop != BBLoop &&
1576 BBLoopDepth > getRelativeLoopDepth(SuccBBLoop)) {
1577 assert(BBLoopDepth >= 0 &&
1578 "Can only remove a dimension if we exit a loop");
1579 CondSet = isl_set_drop_constraints_involving_dims(CondSet, isl_dim_set,
1580 BBLoopDepth, 1);
1581 }
1582
1583 // Set the domain for the successor or merge it with an existing domain in
1584 // case there are multiple paths (without loop back edges) to the
1585 // successor block.
1586 isl_set *&SuccDomain = DomainMap[SuccBB];
1587 if (!SuccDomain)
1588 SuccDomain = CondSet;
1589 else
1590 SuccDomain = isl_set_union(SuccDomain, CondSet);
1591
1592 SuccDomain = isl_set_coalesce(SuccDomain);
1593 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1594 << "\n");
1595 }
1596 }
1597}
1598
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001599void Scop::buildAliasChecks(AliasAnalysis &AA) {
1600 if (!PollyUseRuntimeAliasChecks)
1601 return;
1602
1603 if (buildAliasGroups(AA))
1604 return;
1605
1606 // If a problem occurs while building the alias groups we need to delete
1607 // this SCoP and pretend it wasn't valid in the first place. To this end
1608 // we make the assumed context infeasible.
1609 addAssumption(isl_set_empty(getParamSpace()));
1610
1611 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1612 << " could not be created as the number of parameters involved "
1613 "is too high. The SCoP will be "
1614 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1615 "the maximal number of parameters but be advised that the "
1616 "compile time might increase exponentially.\n\n");
1617}
1618
Johannes Doerfert9143d672014-09-27 11:02:39 +00001619bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001620 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001621 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001622 // for all memory accesses inside the SCoP.
1623 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001624 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001625 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001626 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001627 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001628 // if their access domains intersect, otherwise they are in different
1629 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001630 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001631 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001632 // and maximal accesses to each array of a group in read only and non
1633 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001634 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1635
1636 AliasSetTracker AST(AA);
1637
1638 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001639 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001640 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001641
1642 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001643 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001644 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1645 isl_set_free(StmtDomain);
1646 if (StmtDomainEmpty)
1647 continue;
1648
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001649 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001650 if (MA->isScalar())
1651 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001652 if (!MA->isRead())
1653 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001654 Instruction *Acc = MA->getAccessInstruction();
1655 PtrToAcc[getPointerOperand(*Acc)] = MA;
1656 AST.add(Acc);
1657 }
1658 }
1659
1660 SmallVector<AliasGroupTy, 4> AliasGroups;
1661 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001662 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001663 continue;
1664 AliasGroupTy AG;
1665 for (auto PR : AS)
1666 AG.push_back(PtrToAcc[PR.getValue()]);
1667 assert(AG.size() > 1 &&
1668 "Alias groups should contain at least two accesses");
1669 AliasGroups.push_back(std::move(AG));
1670 }
1671
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001672 // Split the alias groups based on their domain.
1673 for (unsigned u = 0; u < AliasGroups.size(); u++) {
1674 AliasGroupTy NewAG;
1675 AliasGroupTy &AG = AliasGroups[u];
1676 AliasGroupTy::iterator AGI = AG.begin();
1677 isl_set *AGDomain = getAccessDomain(*AGI);
1678 while (AGI != AG.end()) {
1679 MemoryAccess *MA = *AGI;
1680 isl_set *MADomain = getAccessDomain(MA);
1681 if (isl_set_is_disjoint(AGDomain, MADomain)) {
1682 NewAG.push_back(MA);
1683 AGI = AG.erase(AGI);
1684 isl_set_free(MADomain);
1685 } else {
1686 AGDomain = isl_set_union(AGDomain, MADomain);
1687 AGI++;
1688 }
1689 }
1690 if (NewAG.size() > 1)
1691 AliasGroups.push_back(std::move(NewAG));
1692 isl_set_free(AGDomain);
1693 }
1694
Tobias Grosserf4c24b22015-04-05 13:11:54 +00001695 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00001696 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
1697 for (AliasGroupTy &AG : AliasGroups) {
1698 NonReadOnlyBaseValues.clear();
1699 ReadOnlyPairs.clear();
1700
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001701 if (AG.size() < 2) {
1702 AG.clear();
1703 continue;
1704 }
1705
Johannes Doerfert13771732014-10-01 12:40:46 +00001706 for (auto II = AG.begin(); II != AG.end();) {
1707 Value *BaseAddr = (*II)->getBaseAddr();
1708 if (HasWriteAccess.count(BaseAddr)) {
1709 NonReadOnlyBaseValues.insert(BaseAddr);
1710 II++;
1711 } else {
1712 ReadOnlyPairs[BaseAddr].insert(*II);
1713 II = AG.erase(II);
1714 }
1715 }
1716
1717 // If we don't have read only pointers check if there are at least two
1718 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00001719 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001720 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00001721 continue;
1722 }
1723
1724 // If we don't have non read only pointers clear the alias group.
1725 if (NonReadOnlyBaseValues.empty()) {
1726 AG.clear();
1727 continue;
1728 }
1729
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001730 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001731 MinMaxAliasGroups.emplace_back();
1732 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
1733 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
1734 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
1735 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001736
1737 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001738
1739 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001740 for (MemoryAccess *MA : AG)
1741 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001742
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001743 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
1744 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001745
1746 // Bail out if the number of values we need to compare is too large.
1747 // This is important as the number of comparisions grows quadratically with
1748 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001749 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
1750 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001751 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001752
1753 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001754 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001755 Accesses = isl_union_map_empty(getParamSpace());
1756
1757 for (const auto &ReadOnlyPair : ReadOnlyPairs)
1758 for (MemoryAccess *MA : ReadOnlyPair.second)
1759 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
1760
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00001761 Valid =
1762 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00001763
1764 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001765 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001766 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00001767
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00001768 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001769}
1770
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001771static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
1772 ScopDetection &SD) {
1773
1774 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
1775
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001776 unsigned MinLD = INT_MAX, MaxLD = 0;
1777 for (BasicBlock *BB : R.blocks()) {
1778 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00001779 if (!R.contains(L))
1780 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00001781 if (BoxedLoops && BoxedLoops->count(L))
1782 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00001783 unsigned LD = L->getLoopDepth();
1784 MinLD = std::min(MinLD, LD);
1785 MaxLD = std::max(MaxLD, LD);
1786 }
1787 }
1788
1789 // Handle the case that there is no loop in the SCoP first.
1790 if (MaxLD == 0)
1791 return 1;
1792
1793 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
1794 assert(MaxLD >= MinLD &&
1795 "Maximal loop depth was smaller than mininaml loop depth?");
1796 return MaxLD - MinLD + 1;
1797}
1798
Johannes Doerfert96425c22015-08-30 21:13:53 +00001799Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, DominatorTree &DT,
1800 isl_ctx *Context, unsigned MaxLoopDepth)
1801 : DT(DT), SE(&ScalarEvolution), R(R), IsOptimized(false),
Johannes Doerfert574182d2015-08-12 10:19:50 +00001802 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001803
Tobias Grosser40985012015-08-20 19:08:05 +00001804void Scop::initFromTempScop(TempScop &TempScop, LoopInfo &LI, ScopDetection &SD,
1805 AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001806 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00001807
Johannes Doerfert96425c22015-08-30 21:13:53 +00001808 buildDomains(&R, LI, SD, DT);
1809
Tobias Grosserabfbe632013-02-05 12:09:06 +00001810 SmallVector<Loop *, 8> NestLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001811
Tobias Grosser54839312015-04-21 11:37:25 +00001812 // Build the iteration domain, access functions and schedule functions
Tobias Grosser75805372011-04-29 06:27:02 +00001813 // traversing the region tree.
Michael Kruse471a5e32015-07-30 19:27:04 +00001814 Schedule = buildScop(TempScop, getRegion(), NestLoops, LI, SD);
Tobias Grosser808cd692015-07-14 09:33:13 +00001815 if (!Schedule)
1816 Schedule = isl_schedule_empty(getParamSpace());
Tobias Grosser75805372011-04-29 06:27:02 +00001817
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001818 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00001819 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001820 addUserContext();
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001821 simplifyAssumedContext();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001822 buildAliasChecks(AA);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001823
Tobias Grosser75805372011-04-29 06:27:02 +00001824 assert(NestLoops.empty() && "NestLoops not empty at top level!");
1825}
1826
Michael Kruse471a5e32015-07-30 19:27:04 +00001827Scop *Scop::createFromTempScop(TempScop &TempScop, LoopInfo &LI,
1828 ScalarEvolution &SE, ScopDetection &SD,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001829 AliasAnalysis &AA, DominatorTree &DT,
1830 isl_ctx *ctx) {
Michael Kruse471a5e32015-07-30 19:27:04 +00001831 auto &R = TempScop.getMaxRegion();
1832 auto MaxLoopDepth = getMaxLoopDepthInRegion(R, LI, SD);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001833 auto S = new Scop(R, SE, DT, ctx, MaxLoopDepth);
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001834 S->initFromTempScop(TempScop, LI, SD, AA);
1835
Michael Kruse471a5e32015-07-30 19:27:04 +00001836 return S;
1837}
1838
Tobias Grosser75805372011-04-29 06:27:02 +00001839Scop::~Scop() {
1840 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00001841 isl_set_free(AssumedContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00001842 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00001843
Johannes Doerfert96425c22015-08-30 21:13:53 +00001844 for (auto It : DomainMap)
1845 isl_set_free(It.second);
1846
Johannes Doerfertb164c792014-09-18 11:17:17 +00001847 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001848 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001849 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001850 isl_pw_multi_aff_free(MMA.first);
1851 isl_pw_multi_aff_free(MMA.second);
1852 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001853 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001854 isl_pw_multi_aff_free(MMA.first);
1855 isl_pw_multi_aff_free(MMA.second);
1856 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001857 }
Tobias Grosser75805372011-04-29 06:27:02 +00001858}
1859
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001860const ScopArrayInfo *
1861Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser92245222015-07-28 14:53:44 +00001862 const SmallVector<const SCEV *, 4> &Sizes,
1863 bool IsPHI) {
1864 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00001865 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00001866 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
1867 this));
Tobias Grosserab671442015-05-23 05:58:27 +00001868 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001869}
1870
Tobias Grosser92245222015-07-28 14:53:44 +00001871const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
1872 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001873 assert(SAI && "No ScopArrayInfo available for this base pointer");
1874 return SAI;
1875}
1876
Tobias Grosser74394f02013-01-14 22:40:23 +00001877std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001878std::string Scop::getAssumedContextStr() const {
1879 return stringFromIslObj(AssumedContext);
1880}
Tobias Grosser75805372011-04-29 06:27:02 +00001881
1882std::string Scop::getNameStr() const {
1883 std::string ExitName, EntryName;
1884 raw_string_ostream ExitStr(ExitName);
1885 raw_string_ostream EntryStr(EntryName);
1886
Tobias Grosserf240b482014-01-09 10:42:15 +00001887 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001888 EntryStr.str();
1889
1890 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00001891 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00001892 ExitStr.str();
1893 } else
1894 ExitName = "FunctionExit";
1895
1896 return EntryName + "---" + ExitName;
1897}
1898
Tobias Grosser74394f02013-01-14 22:40:23 +00001899__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00001900__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00001901 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00001902}
1903
Tobias Grossere86109f2013-10-29 21:05:49 +00001904__isl_give isl_set *Scop::getAssumedContext() const {
1905 return isl_set_copy(AssumedContext);
1906}
1907
Johannes Doerfert43788c52015-08-20 05:58:56 +00001908__isl_give isl_set *Scop::getRuntimeCheckContext() const {
1909 isl_set *RuntimeCheckContext = getAssumedContext();
1910 return RuntimeCheckContext;
1911}
1912
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001913bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00001914 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001915 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00001916 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
1917 isl_set_free(RuntimeCheckContext);
1918 return IsFeasible;
1919}
1920
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001921void Scop::addAssumption(__isl_take isl_set *Set) {
1922 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001923 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001924}
1925
Tobias Grosser75805372011-04-29 06:27:02 +00001926void Scop::printContext(raw_ostream &OS) const {
1927 OS << "Context:\n";
1928
1929 if (!Context) {
1930 OS.indent(4) << "n/a\n\n";
1931 return;
1932 }
1933
1934 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00001935
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001936 OS.indent(4) << "Assumed Context:\n";
1937 if (!AssumedContext) {
1938 OS.indent(4) << "n/a\n\n";
1939 return;
1940 }
1941
1942 OS.indent(4) << getAssumedContextStr() << "\n";
1943
Tobias Grosser083d3d32014-06-28 08:59:45 +00001944 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00001945 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001946 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1947 }
Tobias Grosser75805372011-04-29 06:27:02 +00001948}
1949
Johannes Doerfertb164c792014-09-18 11:17:17 +00001950void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001951 int noOfGroups = 0;
1952 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001953 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001954 noOfGroups += 1;
1955 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001956 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001957 }
1958
Tobias Grosserbb853c22015-07-25 12:31:03 +00001959 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00001960 if (MinMaxAliasGroups.empty()) {
1961 OS.indent(8) << "n/a\n";
1962 return;
1963 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001964
Tobias Grosserbb853c22015-07-25 12:31:03 +00001965 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001966
1967 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001968 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001969 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001970 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001971 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1972 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001973 }
1974 OS << " ]]\n";
1975 }
1976
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001977 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001978 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00001979 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001980 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00001981 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
1982 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001983 }
1984 OS << " ]]\n";
1985 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00001986 }
1987}
1988
Tobias Grosser75805372011-04-29 06:27:02 +00001989void Scop::printStatements(raw_ostream &OS) const {
1990 OS << "Statements {\n";
1991
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001992 for (const ScopStmt &Stmt : *this)
1993 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00001994
1995 OS.indent(4) << "}\n";
1996}
1997
Tobias Grosser49ad36c2015-05-20 08:05:31 +00001998void Scop::printArrayInfo(raw_ostream &OS) const {
1999 OS << "Arrays {\n";
2000
Tobias Grosserab671442015-05-23 05:58:27 +00002001 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002002 Array.second->print(OS);
2003
2004 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002005
2006 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2007
2008 for (auto &Array : arrays())
2009 Array.second->print(OS, /* SizeAsPwAff */ true);
2010
2011 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002012}
2013
Tobias Grosser75805372011-04-29 06:27:02 +00002014void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002015 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2016 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002017 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002018 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002019 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002020 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002021 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002022 printStatements(OS.indent(4));
2023}
2024
2025void Scop::dump() const { print(dbgs()); }
2026
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002027isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002028
Johannes Doerfertb409fdc2015-08-28 09:24:35 +00002029__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, isl_set *Domain) {
2030 return Affinator.getPwAff(E, Domain);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002031}
2032
Tobias Grosser808cd692015-07-14 09:33:13 +00002033__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002034 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002035
Tobias Grosser808cd692015-07-14 09:33:13 +00002036 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002037 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002038
2039 return Domain;
2040}
2041
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002042__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002043 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002044
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002045 for (ScopStmt &Stmt : *this) {
2046 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002047 if (!MA->isMustWrite())
2048 continue;
2049
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002050 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002051 isl_map *AccessDomain = MA->getAccessRelation();
2052 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2053 Write = isl_union_map_add_map(Write, AccessDomain);
2054 }
2055 }
2056 return isl_union_map_coalesce(Write);
2057}
2058
2059__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002060 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002061
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002062 for (ScopStmt &Stmt : *this) {
2063 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002064 if (!MA->isMayWrite())
2065 continue;
2066
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002067 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002068 isl_map *AccessDomain = MA->getAccessRelation();
2069 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2070 Write = isl_union_map_add_map(Write, AccessDomain);
2071 }
2072 }
2073 return isl_union_map_coalesce(Write);
2074}
2075
Tobias Grosser37eb4222014-02-20 21:43:54 +00002076__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002077 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002078
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002079 for (ScopStmt &Stmt : *this) {
2080 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002081 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002082 continue;
2083
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002084 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002085 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002086 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2087 Write = isl_union_map_add_map(Write, AccessDomain);
2088 }
2089 }
2090 return isl_union_map_coalesce(Write);
2091}
2092
2093__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002094 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002095
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002096 for (ScopStmt &Stmt : *this) {
2097 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002098 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002099 continue;
2100
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002101 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002102 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002103
2104 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2105 Read = isl_union_map_add_map(Read, AccessDomain);
2106 }
2107 }
2108 return isl_union_map_coalesce(Read);
2109}
2110
Tobias Grosser808cd692015-07-14 09:33:13 +00002111__isl_give isl_union_map *Scop::getSchedule() const {
2112 auto Tree = getScheduleTree();
2113 auto S = isl_schedule_get_map(Tree);
2114 isl_schedule_free(Tree);
2115 return S;
2116}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002117
Tobias Grosser808cd692015-07-14 09:33:13 +00002118__isl_give isl_schedule *Scop::getScheduleTree() const {
2119 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2120 getDomains());
2121}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002122
Tobias Grosser808cd692015-07-14 09:33:13 +00002123void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2124 auto *S = isl_schedule_from_domain(getDomains());
2125 S = isl_schedule_insert_partial_schedule(
2126 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2127 isl_schedule_free(Schedule);
2128 Schedule = S;
2129}
2130
2131void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2132 isl_schedule_free(Schedule);
2133 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002134}
2135
2136bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2137 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002138 for (ScopStmt &Stmt : *this) {
2139 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002140 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2141 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2142
2143 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2144 isl_union_set_free(StmtDomain);
2145 isl_union_set_free(NewStmtDomain);
2146 continue;
2147 }
2148
2149 Changed = true;
2150
2151 isl_union_set_free(StmtDomain);
2152 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2153
2154 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002155 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002156 isl_union_set_free(NewStmtDomain);
2157 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002158 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002159 }
2160 isl_union_set_free(Domain);
2161 return Changed;
2162}
2163
Tobias Grosser75805372011-04-29 06:27:02 +00002164ScalarEvolution *Scop::getSE() const { return SE; }
2165
2166bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
2167 if (tempScop.getAccessFunctions(BB))
2168 return false;
2169
2170 return true;
2171}
2172
Tobias Grosser808cd692015-07-14 09:33:13 +00002173struct MapToDimensionDataTy {
2174 int N;
2175 isl_union_pw_multi_aff *Res;
2176};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002177
Tobias Grosser808cd692015-07-14 09:33:13 +00002178// @brief Create a function that maps the elements of 'Set' to its N-th
2179// dimension.
2180//
2181// The result is added to 'User->Res'.
2182//
2183// @param Set The input set.
2184// @param N The dimension to map to.
2185//
2186// @returns Zero if no error occurred, non-zero otherwise.
2187static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2188 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2189 int Dim;
2190 isl_space *Space;
2191 isl_pw_multi_aff *PMA;
2192
2193 Dim = isl_set_dim(Set, isl_dim_set);
2194 Space = isl_set_get_space(Set);
2195 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2196 Dim - Data->N);
2197 if (Data->N > 1)
2198 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2199 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2200
2201 isl_set_free(Set);
2202
2203 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002204}
2205
Tobias Grosser808cd692015-07-14 09:33:13 +00002206// @brief Create a function that maps the elements of Domain to their Nth
2207// dimension.
2208//
2209// @param Domain The set of elements to map.
2210// @param N The dimension to map to.
2211static __isl_give isl_multi_union_pw_aff *
2212mapToDimension(__isl_take isl_union_set *Domain, int N) {
2213 struct MapToDimensionDataTy Data;
2214 isl_space *Space;
2215
2216 Space = isl_union_set_get_space(Domain);
2217 Data.N = N;
2218 Data.Res = isl_union_pw_multi_aff_empty(Space);
2219 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2220 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2221
2222 isl_union_set_free(Domain);
2223 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2224}
2225
2226ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R, TempScop &tempScop,
2227 const Region &CurRegion,
2228 SmallVectorImpl<Loop *> &NestLoops) {
2229 ScopStmt *Stmt;
2230 if (BB) {
2231 Stmts.emplace_back(*this, tempScop, CurRegion, *BB, NestLoops);
2232 Stmt = &Stmts.back();
2233 StmtMap[BB] = Stmt;
2234 } else {
2235 assert(R && "Either basic block or a region expected.");
2236 Stmts.emplace_back(*this, tempScop, CurRegion, *R, NestLoops);
2237 Stmt = &Stmts.back();
2238 for (BasicBlock *BB : R->blocks())
2239 StmtMap[BB] = Stmt;
2240 }
2241 return Stmt;
2242}
2243
Michael Kruse046dde42015-08-10 13:01:57 +00002244__isl_give isl_schedule *
2245Scop::buildBBScopStmt(BasicBlock *BB, TempScop &tempScop,
2246 const Region &CurRegion,
2247 SmallVectorImpl<Loop *> &NestLoops) {
2248 if (isTrivialBB(BB, tempScop))
2249 return nullptr;
2250
2251 auto *Stmt = addScopStmt(BB, nullptr, tempScop, CurRegion, NestLoops);
2252 auto *Domain = Stmt->getDomain();
2253 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2254}
2255
Tobias Grosser808cd692015-07-14 09:33:13 +00002256__isl_give isl_schedule *Scop::buildScop(TempScop &tempScop,
2257 const Region &CurRegion,
2258 SmallVectorImpl<Loop *> &NestLoops,
2259 LoopInfo &LI, ScopDetection &SD) {
2260 if (SD.isNonAffineSubRegion(&CurRegion, &getRegion())) {
2261 auto *Stmt = addScopStmt(nullptr, const_cast<Region *>(&CurRegion),
2262 tempScop, CurRegion, NestLoops);
2263 auto *Domain = Stmt->getDomain();
2264 return isl_schedule_from_domain(isl_union_set_from_set(Domain));
2265 }
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002266
Tobias Grosser75805372011-04-29 06:27:02 +00002267 Loop *L = castToLoop(CurRegion, LI);
2268
2269 if (L)
2270 NestLoops.push_back(L);
2271
2272 unsigned loopDepth = NestLoops.size();
Tobias Grosser808cd692015-07-14 09:33:13 +00002273 isl_schedule *Schedule = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002274
2275 for (Region::const_element_iterator I = CurRegion.element_begin(),
Tobias Grosserabfbe632013-02-05 12:09:06 +00002276 E = CurRegion.element_end();
Tobias Grosser808cd692015-07-14 09:33:13 +00002277 I != E; ++I) {
2278 isl_schedule *StmtSchedule = nullptr;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002279 if (I->isSubRegion()) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002280 StmtSchedule =
2281 buildScop(tempScop, *I->getNodeAs<Region>(), NestLoops, LI, SD);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002282 } else {
Michael Kruse046dde42015-08-10 13:01:57 +00002283 StmtSchedule = buildBBScopStmt(I->getNodeAs<BasicBlock>(), tempScop,
2284 CurRegion, NestLoops);
Tobias Grosser75805372011-04-29 06:27:02 +00002285 }
Michael Kruse046dde42015-08-10 13:01:57 +00002286 Schedule = combineInSequence(Schedule, StmtSchedule);
Tobias Grosser808cd692015-07-14 09:33:13 +00002287 }
Tobias Grosser75805372011-04-29 06:27:02 +00002288
Tobias Grosser808cd692015-07-14 09:33:13 +00002289 if (!L)
2290 return Schedule;
2291
2292 auto *Domain = isl_schedule_get_domain(Schedule);
2293 if (!isl_union_set_is_empty(Domain)) {
2294 auto *MUPA = mapToDimension(isl_union_set_copy(Domain), loopDepth);
2295 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
2296 }
2297 isl_union_set_free(Domain);
2298
Tobias Grosser75805372011-04-29 06:27:02 +00002299 NestLoops.pop_back();
Tobias Grosser808cd692015-07-14 09:33:13 +00002300 return Schedule;
Tobias Grosser75805372011-04-29 06:27:02 +00002301}
2302
Johannes Doerfert7c494212014-10-31 23:13:39 +00002303ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002304 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002305 if (StmtMapIt == StmtMap.end())
2306 return nullptr;
2307 return StmtMapIt->second;
2308}
2309
Johannes Doerfert96425c22015-08-30 21:13:53 +00002310int Scop::getRelativeLoopDepth(const Loop *L) const {
2311 Loop *OuterLoop =
2312 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2313 if (!OuterLoop)
2314 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002315 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2316}
2317
Tobias Grosser75805372011-04-29 06:27:02 +00002318//===----------------------------------------------------------------------===//
Tobias Grosserb76f38532011-08-20 11:11:25 +00002319ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
2320 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00002321 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00002322}
2323
2324ScopInfo::~ScopInfo() {
2325 clear();
2326 isl_ctx_free(ctx);
2327}
2328
Tobias Grosser75805372011-04-29 06:27:02 +00002329void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00002330 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00002331 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002332 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002333 AU.addRequired<ScalarEvolutionWrapperPass>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002334 AU.addRequired<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00002335 AU.addRequired<TempScopInfo>();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002336 AU.addRequired<AliasAnalysis>();
Tobias Grosser75805372011-04-29 06:27:02 +00002337 AU.setPreservesAll();
2338}
2339
2340bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Chandler Carruthf5579872015-01-17 14:16:56 +00002341 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Johannes Doerfertb164c792014-09-18 11:17:17 +00002342 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002343 ScopDetection &SD = getAnalysis<ScopDetection>();
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002344 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002345 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosser75805372011-04-29 06:27:02 +00002346
Michael Kruse82a1c7d2015-08-14 20:10:27 +00002347 TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop();
Tobias Grosser75805372011-04-29 06:27:02 +00002348
2349 // This region is no Scop.
2350 if (!tempScop) {
Tobias Grosserc98a8fc2014-11-14 11:12:31 +00002351 scop = nullptr;
Tobias Grosser75805372011-04-29 06:27:02 +00002352 return false;
2353 }
2354
Johannes Doerfert96425c22015-08-30 21:13:53 +00002355 scop = Scop::createFromTempScop(*tempScop, LI, SE, SD, AA, DT, ctx);
Tobias Grosser75805372011-04-29 06:27:02 +00002356
Tobias Grosserd6a50b32015-05-30 06:26:21 +00002357 DEBUG(scop->print(dbgs()));
2358
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002359 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002360 delete scop;
2361 scop = nullptr;
2362 return false;
2363 }
2364
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002365 // Statistics.
2366 ++ScopFound;
2367 if (scop->getMaxLoopDepth() > 0)
2368 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00002369 return false;
2370}
2371
2372char ScopInfo::ID = 0;
2373
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002374Pass *polly::createScopInfoPass() { return new ScopInfo(); }
2375
Tobias Grosser73600b82011-10-08 00:30:40 +00002376INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
2377 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002378 false);
Johannes Doerfertb164c792014-09-18 11:17:17 +00002379INITIALIZE_AG_DEPENDENCY(AliasAnalysis);
Chandler Carruthf5579872015-01-17 14:16:56 +00002380INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00002381INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00002382INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002383INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00002384INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002385INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00002386INITIALIZE_PASS_END(ScopInfo, "polly-scops",
2387 "Polly - Create polyhedral description of Scops", false,
2388 false)