blob: 9ef804d3b204d419036ce2f67c538496d655568a [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
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"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000026#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000027#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000029#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000034#include "llvm/Analysis/LoopIterator.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
Michael Kruse7bf39442015-09-10 12:46:52 +000062static cl::opt<bool> ModelReadOnlyScalars(
63 "polly-analyze-read-only-scalars",
64 cl::desc("Model read-only scalar values in the scop description"),
65 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
66
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000067// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068// operations can overflow easily. Additive reductions and bit operations
69// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000070static cl::opt<bool> DisableMultiplicativeReductions(
71 "polly-disable-multiplicative-reductions",
72 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
73 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000074
Johannes Doerfert9143d672014-09-27 11:02:39 +000075static cl::opt<unsigned> RunTimeChecksMaxParameters(
76 "polly-rtc-max-parameters",
77 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
78 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
79
Tobias Grosser71500722015-03-28 15:11:14 +000080static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
81 "polly-rtc-max-arrays-per-group",
82 cl::desc("The maximal number of arrays to compare in each alias group."),
83 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000084static cl::opt<std::string> UserContextStr(
85 "polly-context", cl::value_desc("isl parameter set"),
86 cl::desc("Provide additional constraints on the context parameters"),
87 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000088
Tobias Grosserd83b8a82015-08-20 19:08:11 +000089static cl::opt<bool> DetectReductions("polly-detect-reductions",
90 cl::desc("Detect and exploit reductions"),
91 cl::Hidden, cl::ZeroOrMore,
92 cl::init(true), cl::cat(PollyCategory));
93
Michael Kruse7bf39442015-09-10 12:46:52 +000094//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +000095
Michael Kruse046dde42015-08-10 13:01:57 +000096// Create a sequence of two schedules. Either argument may be null and is
97// interpreted as the empty schedule. Can also return null if both schedules are
98// empty.
99static __isl_give isl_schedule *
100combineInSequence(__isl_take isl_schedule *Prev,
101 __isl_take isl_schedule *Succ) {
102 if (!Prev)
103 return Succ;
104 if (!Succ)
105 return Prev;
106
107 return isl_schedule_sequence(Prev, Succ);
108}
109
Johannes Doerferte7044942015-02-24 11:58:30 +0000110static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
111 const ConstantRange &Range,
112 int dim,
113 enum isl_dim_type type) {
114 isl_val *V;
115 isl_ctx *ctx = isl_set_get_ctx(S);
116
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000117 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
118 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000119 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000120 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
121
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000122 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000123 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000124 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000129 return isl_set_union(SLB, SUB);
130 else
131 return isl_set_intersect(SLB, SUB);
132}
133
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000134static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
135 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
136 if (!BasePtrLI)
137 return nullptr;
138
139 if (!S->getRegion().contains(BasePtrLI))
140 return nullptr;
141
142 ScalarEvolution &SE = *S->getSE();
143
144 auto *OriginBaseSCEV =
145 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
146 if (!OriginBaseSCEV)
147 return nullptr;
148
149 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
150 if (!OriginBaseSCEVUnknown)
151 return nullptr;
152
Johannes Doerferta7686242015-11-08 19:12:05 +0000153 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(), false);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000154}
155
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000156ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000157 ArrayRef<const SCEV *> Sizes, bool IsPHI, Scop *S)
158 : BasePtr(BasePtr), ElementType(ElementType), IsPHI(IsPHI), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000159 std::string BasePtrName =
160 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000161 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000162
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000163 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000164 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
165 if (BasePtrOriginSAI)
166 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000167}
168
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000169__isl_give isl_space *ScopArrayInfo::getSpace() const {
170 auto Space =
171 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
172 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
173 return Space;
174}
175
Tobias Grosser8286b832015-11-02 11:29:32 +0000176bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000177 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
178 int ExtraDimsNew = NewSizes.size() - SharedDims;
179 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000180 for (int i = 0; i < SharedDims; i++)
181 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
182 return false;
183
184 if (DimensionSizes.size() >= NewSizes.size())
185 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000186
187 DimensionSizes.clear();
188 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
189 NewSizes.end());
190 for (isl_pw_aff *Size : DimensionSizesPw)
191 isl_pw_aff_free(Size);
192 DimensionSizesPw.clear();
193 for (const SCEV *Expr : DimensionSizes) {
194 isl_pw_aff *Size = S.getPwAff(Expr);
195 DimensionSizesPw.push_back(Size);
196 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000197 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000198}
199
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000200ScopArrayInfo::~ScopArrayInfo() {
201 isl_id_free(Id);
202 for (isl_pw_aff *Size : DimensionSizesPw)
203 isl_pw_aff_free(Size);
204}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000205
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000206std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
207
208int ScopArrayInfo::getElemSizeInBytes() const {
209 return ElementType->getPrimitiveSizeInBits() / 8;
210}
211
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000212isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
213
214void ScopArrayInfo::dump() const { print(errs()); }
215
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000216void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000217 OS.indent(8) << *getElementType() << " " << getName();
218 if (getNumberOfDimensions() > 0)
219 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000220 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000221 OS << "[";
222
Tobias Grosser26253842015-11-10 14:24:21 +0000223 if (SizeAsPwAff) {
224 auto Size = getDimensionSizePw(u);
225 OS << " " << Size << " ";
226 isl_pw_aff_free(Size);
227 } else {
228 OS << *getDimensionSize(u);
229 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000230
231 OS << "]";
232 }
233
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000234 OS << ";";
235
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000236 if (BasePtrOriginSAI)
237 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
238
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000239 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000240}
241
242const ScopArrayInfo *
243ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
244 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
245 assert(Id && "Output dimension didn't have an ID");
246 return getFromId(Id);
247}
248
249const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
250 void *User = isl_id_get_user(Id);
251 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
252 isl_id_free(Id);
253 return SAI;
254}
255
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000256void MemoryAccess::updateDimensionality() {
257 auto ArraySpace = getScopArrayInfo()->getSpace();
258 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
259
260 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
261 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
262 auto DimsMissing = DimsArray - DimsAccess;
263
264 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
265 isl_set_universe(ArraySpace));
266
267 for (unsigned i = 0; i < DimsMissing; i++)
268 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
269
270 for (unsigned i = DimsMissing; i < DimsArray; i++)
271 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
272
273 AccessRelation = isl_map_apply_range(AccessRelation, Map);
274}
275
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000276const std::string
277MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
278 switch (RT) {
279 case MemoryAccess::RT_NONE:
280 llvm_unreachable("Requested a reduction operator string for a memory "
281 "access which isn't a reduction");
282 case MemoryAccess::RT_ADD:
283 return "+";
284 case MemoryAccess::RT_MUL:
285 return "*";
286 case MemoryAccess::RT_BOR:
287 return "|";
288 case MemoryAccess::RT_BXOR:
289 return "^";
290 case MemoryAccess::RT_BAND:
291 return "&";
292 }
293 llvm_unreachable("Unknown reduction type");
294 return "";
295}
296
Johannes Doerfertf6183392014-07-01 20:52:51 +0000297/// @brief Return the reduction type for a given binary operator
298static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
299 const Instruction *Load) {
300 if (!BinOp)
301 return MemoryAccess::RT_NONE;
302 switch (BinOp->getOpcode()) {
303 case Instruction::FAdd:
304 if (!BinOp->hasUnsafeAlgebra())
305 return MemoryAccess::RT_NONE;
306 // Fall through
307 case Instruction::Add:
308 return MemoryAccess::RT_ADD;
309 case Instruction::Or:
310 return MemoryAccess::RT_BOR;
311 case Instruction::Xor:
312 return MemoryAccess::RT_BXOR;
313 case Instruction::And:
314 return MemoryAccess::RT_BAND;
315 case Instruction::FMul:
316 if (!BinOp->hasUnsafeAlgebra())
317 return MemoryAccess::RT_NONE;
318 // Fall through
319 case Instruction::Mul:
320 if (DisableMultiplicativeReductions)
321 return MemoryAccess::RT_NONE;
322 return MemoryAccess::RT_MUL;
323 default:
324 return MemoryAccess::RT_NONE;
325 }
326}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000327
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000328/// @brief Derive the individual index expressions from a GEP instruction
329///
330/// This function optimistically assumes the GEP references into a fixed size
331/// array. If this is actually true, this function returns a list of array
332/// subscript expressions as SCEV as well as a list of integers describing
333/// the size of the individual array dimensions. Both lists have either equal
334/// length of the size list is one element shorter in case there is no known
335/// size available for the outermost array dimension.
336///
337/// @param GEP The GetElementPtr instruction to analyze.
338///
339/// @return A tuple with the subscript expressions and the dimension sizes.
340static std::tuple<std::vector<const SCEV *>, std::vector<int>>
341getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
342 std::vector<const SCEV *> Subscripts;
343 std::vector<int> Sizes;
344
345 Type *Ty = GEP->getPointerOperandType();
346
347 bool DroppedFirstDim = false;
348
Michael Kruse26ed65e2015-09-24 17:32:49 +0000349 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000350
351 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
352
353 if (i == 1) {
354 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
355 Ty = PtrTy->getElementType();
356 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
357 Ty = ArrayTy->getElementType();
358 } else {
359 Subscripts.clear();
360 Sizes.clear();
361 break;
362 }
363 if (auto Const = dyn_cast<SCEVConstant>(Expr))
364 if (Const->getValue()->isZero()) {
365 DroppedFirstDim = true;
366 continue;
367 }
368 Subscripts.push_back(Expr);
369 continue;
370 }
371
372 auto ArrayTy = dyn_cast<ArrayType>(Ty);
373 if (!ArrayTy) {
374 Subscripts.clear();
375 Sizes.clear();
376 break;
377 }
378
379 Subscripts.push_back(Expr);
380 if (!(DroppedFirstDim && i == 2))
381 Sizes.push_back(ArrayTy->getNumElements());
382
383 Ty = ArrayTy->getElementType();
384 }
385
386 return std::make_tuple(Subscripts, Sizes);
387}
388
Tobias Grosser75805372011-04-29 06:27:02 +0000389MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000390 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000391 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000392 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000393}
394
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000395const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
396 isl_id *ArrayId = getArrayId();
397 void *User = isl_id_get_user(ArrayId);
398 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
399 isl_id_free(ArrayId);
400 return SAI;
401}
402
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000403__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000404 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
405}
406
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000407__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
408 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000409 isl_map *Schedule, *ScheduledAccRel;
410 isl_union_set *UDomain;
411
412 UDomain = isl_union_set_from_set(getStatement()->getDomain());
413 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
414 Schedule = isl_map_from_union_map(USchedule);
415 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
416 return isl_pw_multi_aff_from_map(ScheduledAccRel);
417}
418
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000419__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000420 return isl_map_copy(AccessRelation);
421}
422
Johannes Doerferta99130f2014-10-13 12:58:03 +0000423std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000424 return stringFromIslObj(AccessRelation);
425}
426
Johannes Doerferta99130f2014-10-13 12:58:03 +0000427__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000428 return isl_map_get_space(AccessRelation);
429}
430
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000431__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000432 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000433}
434
Tobias Grosser6f730082015-09-05 07:46:47 +0000435std::string MemoryAccess::getNewAccessRelationStr() const {
436 return stringFromIslObj(NewAccessRelation);
437}
438
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000439__isl_give isl_basic_map *
440MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000441 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000442 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000443
Tobias Grosser084d8f72012-05-29 09:29:44 +0000444 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000445 isl_basic_set_universe(Statement->getDomainSpace()),
446 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000447}
448
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000449// Formalize no out-of-bound access assumption
450//
451// When delinearizing array accesses we optimistically assume that the
452// delinearized accesses do not access out of bound locations (the subscript
453// expression of each array evaluates for each statement instance that is
454// executed to a value that is larger than zero and strictly smaller than the
455// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000456// dimension for which we do not need to assume any upper bound. At this point
457// we formalize this assumption to ensure that at code generation time the
458// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000459//
460// To find the set of constraints necessary to avoid out of bound accesses, we
461// first build the set of data locations that are not within array bounds. We
462// then apply the reverse access relation to obtain the set of iterations that
463// may contain invalid accesses and reduce this set of iterations to the ones
464// that are actually executed by intersecting them with the domain of the
465// statement. If we now project out all loop dimensions, we obtain a set of
466// parameters that may cause statement instances to be executed that may
467// possibly yield out of bound memory accesses. The complement of these
468// constraints is the set of constraints that needs to be assumed to ensure such
469// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000470void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000471 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000472 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000473 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000474 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
475 isl_pw_aff *Var =
476 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
477 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
478
479 isl_set *DimOutside;
480
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000481 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000482 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000483
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000484 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
485 Statement->getNumIterators());
486 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
487 isl_space_dim(Space, isl_dim_set));
488 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
489 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000490
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000491 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000492
493 Outside = isl_set_union(Outside, DimOutside);
494 }
495
496 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
497 Outside = isl_set_intersect(Outside, Statement->getDomain());
498 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000499
500 // Remove divs to avoid the construction of overly complicated assumptions.
501 // Doing so increases the set of parameter combinations that are assumed to
502 // not appear. This is always save, but may make the resulting run-time check
503 // bail out more often than strictly necessary.
504 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000505 Outside = isl_set_complement(Outside);
506 Statement->getParent()->addAssumption(Outside);
507 isl_space_free(Space);
508}
509
Johannes Doerferte7044942015-02-24 11:58:30 +0000510void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
511 ScalarEvolution *SE = Statement->getParent()->getSE();
512
513 Value *Ptr = getPointerOperand(*getAccessInstruction());
514 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
515 return;
516
517 auto *PtrSCEV = SE->getSCEV(Ptr);
518 if (isa<SCEVCouldNotCompute>(PtrSCEV))
519 return;
520
521 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
522 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
523 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
524
525 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
526 if (Range.isFullSet())
527 return;
528
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000529 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000530 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000531 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
532 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
533
534 auto Min = LB.sdiv(APInt(BW, ElementSize));
535 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000536
537 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
538 AccessRange =
539 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
540 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
541}
542
Michael Krusee2bccbb2015-09-18 19:59:43 +0000543__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000544 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000545 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000546
547 for (int i = Size - 2; i >= 0; --i) {
548 isl_space *Space;
549 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000550 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000551
552 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
553 isl_pw_aff_free(DimSize);
554 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
555
556 Space = isl_map_get_space(AccessRelation);
557 Space = isl_space_map_from_set(isl_space_range(Space));
558 Space = isl_space_align_params(Space, SpaceSize);
559
560 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
561 isl_id_free(ParamId);
562
563 MapOne = isl_map_universe(isl_space_copy(Space));
564 for (int j = 0; j < Size; ++j)
565 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
566 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
567
568 MapTwo = isl_map_universe(isl_space_copy(Space));
569 for (int j = 0; j < Size; ++j)
570 if (j < i || j > i + 1)
571 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
572
573 isl_local_space *LS = isl_local_space_from_space(Space);
574 isl_constraint *C;
575 C = isl_equality_alloc(isl_local_space_copy(LS));
576 C = isl_constraint_set_constant_si(C, -1);
577 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
578 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
579 MapTwo = isl_map_add_constraint(MapTwo, C);
580 C = isl_equality_alloc(LS);
581 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
582 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
583 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
584 MapTwo = isl_map_add_constraint(MapTwo, C);
585 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
586
587 MapOne = isl_map_union(MapOne, MapTwo);
588 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
589 }
590 return AccessRelation;
591}
592
Michael Krusee2bccbb2015-09-18 19:59:43 +0000593void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
594 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000595
Michael Krusee2bccbb2015-09-18 19:59:43 +0000596 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000597 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000598
Michael Krusee2bccbb2015-09-18 19:59:43 +0000599 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000600 // We overapproximate non-affine accesses with a possible access to the
601 // whole array. For read accesses it does not make a difference, if an
602 // access must or may happen. However, for write accesses it is important to
603 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000604 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000605 AccessRelation =
606 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000607
Michael Krusee2bccbb2015-09-18 19:59:43 +0000608 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000609 return;
610 }
611
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000612 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000613 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000614
Michael Krusee2bccbb2015-09-18 19:59:43 +0000615 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
616 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000617
Sebastian Pop422e33f2014-06-03 18:16:31 +0000618 if (Size == 1) {
619 // For the non delinearized arrays, divide the access function of the last
620 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000621 //
622 // A stride one array access in C expressed as A[i] is expressed in
623 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
624 // two subsequent values of 'i' index two values that are stored next to
625 // each other in memory. By this division we make this characteristic
626 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000627 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000628 Affine = isl_pw_aff_scale_down_val(Affine, v);
629 }
630
631 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
632
Tobias Grosser79baa212014-04-10 08:38:02 +0000633 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000634 }
635
Michael Krusee2bccbb2015-09-18 19:59:43 +0000636 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
637 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000638
Tobias Grosser79baa212014-04-10 08:38:02 +0000639 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000640 AccessRelation = isl_map_set_tuple_id(
641 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000642 AccessRelation =
643 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
644
Michael Krusee2bccbb2015-09-18 19:59:43 +0000645 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000646 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000647 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000648}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000649
Michael Krusecac948e2015-10-02 13:53:07 +0000650MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000651 AccessType Type, Value *BaseAddress,
652 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000653 ArrayRef<const SCEV *> Subscripts,
654 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000655 AccessOrigin Origin, StringRef BaseName)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000656 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000657 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
658 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
659 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000660 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000661 NewAccessRelation(nullptr) {
662
663 std::string IdName = "__polly_array_ref";
664 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
665}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000666
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000667void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000668 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000669 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000670}
671
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000672const std::string MemoryAccess::getReductionOperatorStr() const {
673 return MemoryAccess::getReductionOperatorStr(getReductionType());
674}
675
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000676__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
677
Johannes Doerfertf6183392014-07-01 20:52:51 +0000678raw_ostream &polly::operator<<(raw_ostream &OS,
679 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000680 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000681 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000682 else
683 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000684 return OS;
685}
686
Tobias Grosser75805372011-04-29 06:27:02 +0000687void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000688 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000689 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000690 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000691 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000692 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000693 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000694 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000695 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000696 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000697 break;
698 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000699 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000700 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000701 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000702 if (hasNewAccessRelation())
703 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000704}
705
Tobias Grosser74394f02013-01-14 22:40:23 +0000706void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000707
708// Create a map in the size of the provided set domain, that maps from the
709// one element of the provided set domain to another element of the provided
710// set domain.
711// The mapping is limited to all points that are equal in all but the last
712// dimension and for which the last dimension of the input is strict smaller
713// than the last dimension of the output.
714//
715// getEqualAndLarger(set[i0, i1, ..., iX]):
716//
717// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
718// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
719//
Tobias Grosserf5338802011-10-06 00:03:35 +0000720static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000721 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000722 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000723 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000724
725 // Set all but the last dimension to be equal for the input and output
726 //
727 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
728 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000729 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000730 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000731
732 // Set the last dimension of the input to be strict smaller than the
733 // last dimension of the output.
734 //
735 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000736 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
737 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000738 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000739}
740
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000741__isl_give isl_set *
742MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000743 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000744 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000745 isl_space *Space = isl_space_range(isl_map_get_space(S));
746 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000747
Sebastian Popa00a0292012-12-18 07:46:06 +0000748 S = isl_map_reverse(S);
749 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000750
Sebastian Popa00a0292012-12-18 07:46:06 +0000751 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
752 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
753 NextScatt = isl_map_apply_domain(NextScatt, S);
754 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000755
Sebastian Popa00a0292012-12-18 07:46:06 +0000756 isl_set *Deltas = isl_map_deltas(NextScatt);
757 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000758}
759
Sebastian Popa00a0292012-12-18 07:46:06 +0000760bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000761 int StrideWidth) const {
762 isl_set *Stride, *StrideX;
763 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000764
Sebastian Popa00a0292012-12-18 07:46:06 +0000765 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000766 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000767 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
768 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
769 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
770 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000771 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000772
Tobias Grosser28dd4862012-01-24 16:42:16 +0000773 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000774 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000775
Tobias Grosser28dd4862012-01-24 16:42:16 +0000776 return IsStrideX;
777}
778
Sebastian Popa00a0292012-12-18 07:46:06 +0000779bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
780 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000781}
782
Sebastian Popa00a0292012-12-18 07:46:06 +0000783bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
784 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000785}
786
Tobias Grosser166c4222015-09-05 07:46:40 +0000787void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
788 isl_map_free(NewAccessRelation);
789 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000790}
Tobias Grosser75805372011-04-29 06:27:02 +0000791
792//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000793
Tobias Grosser808cd692015-07-14 09:33:13 +0000794isl_map *ScopStmt::getSchedule() const {
795 isl_set *Domain = getDomain();
796 if (isl_set_is_empty(Domain)) {
797 isl_set_free(Domain);
798 return isl_map_from_aff(
799 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
800 }
801 auto *Schedule = getParent()->getSchedule();
802 Schedule = isl_union_map_intersect_domain(
803 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
804 if (isl_union_map_is_empty(Schedule)) {
805 isl_set_free(Domain);
806 isl_union_map_free(Schedule);
807 return isl_map_from_aff(
808 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
809 }
810 auto *M = isl_map_from_union_map(Schedule);
811 M = isl_map_coalesce(M);
812 M = isl_map_gist_domain(M, Domain);
813 M = isl_map_coalesce(M);
814 return M;
815}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000816
Johannes Doerfert574182d2015-08-12 10:19:50 +0000817__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000818 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
819 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000820}
821
Tobias Grosser37eb4222014-02-20 21:43:54 +0000822void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
823 assert(isl_set_is_subset(NewDomain, Domain) &&
824 "New domain is not a subset of old domain!");
825 isl_set_free(Domain);
826 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000827}
828
Michael Krusecac948e2015-10-02 13:53:07 +0000829void ScopStmt::buildAccessRelations() {
830 for (MemoryAccess *Access : MemAccs) {
831 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000832
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000833 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusecac948e2015-10-02 13:53:07 +0000834 Access->getBaseAddr(), ElementType, Access->Sizes, Access->isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000835
Michael Krusecac948e2015-10-02 13:53:07 +0000836 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000837 }
838}
839
Michael Krusecac948e2015-10-02 13:53:07 +0000840void ScopStmt::addAccess(MemoryAccess *Access) {
841 Instruction *AccessInst = Access->getAccessInstruction();
842
843 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
844 if (!MAL)
845 MAL = new MemoryAccessList();
846 MAL->emplace_front(Access);
847 MemAccs.push_back(MAL->front());
848}
849
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000850void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000851 for (MemoryAccess *MA : *this)
852 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000853
854 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000855}
856
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000857/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
858static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
859 void *User) {
860 isl_set **BoundedParts = static_cast<isl_set **>(User);
861 if (isl_basic_set_is_bounded(BSet))
862 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
863 else
864 isl_basic_set_free(BSet);
865 return isl_stat_ok;
866}
867
868/// @brief Return the bounded parts of @p S.
869static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
870 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
871 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
872 isl_set_free(S);
873 return BoundedParts;
874}
875
876/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
877///
878/// @returns A separation of @p S into first an unbounded then a bounded subset,
879/// both with regards to the dimension @p Dim.
880static std::pair<__isl_give isl_set *, __isl_give isl_set *>
881partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
882
883 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000884 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000885
886 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000887 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000888
889 // Remove dimensions that are greater than Dim as they are not interesting.
890 assert(NumDimsS >= Dim + 1);
891 OnlyDimS =
892 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
893
894 // Create artificial parametric upper bounds for dimensions smaller than Dim
895 // as we are not interested in them.
896 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
897 for (unsigned u = 0; u < Dim; u++) {
898 isl_constraint *C = isl_inequality_alloc(
899 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
900 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
901 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
902 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
903 }
904
905 // Collect all bounded parts of OnlyDimS.
906 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
907
908 // Create the dimensions greater than Dim again.
909 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
910 NumDimsS - Dim - 1);
911
912 // Remove the artificial upper bound parameters again.
913 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
914
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000915 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000916 return std::make_pair(UnboundedParts, BoundedParts);
917}
918
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000919/// @brief Set the dimension Ids from @p From in @p To.
920static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
921 __isl_take isl_set *To) {
922 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
923 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
924 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
925 }
926 return To;
927}
928
929/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000930static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000931 __isl_take isl_pw_aff *L,
932 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000933 switch (Pred) {
934 case ICmpInst::ICMP_EQ:
935 return isl_pw_aff_eq_set(L, R);
936 case ICmpInst::ICMP_NE:
937 return isl_pw_aff_ne_set(L, R);
938 case ICmpInst::ICMP_SLT:
939 return isl_pw_aff_lt_set(L, R);
940 case ICmpInst::ICMP_SLE:
941 return isl_pw_aff_le_set(L, R);
942 case ICmpInst::ICMP_SGT:
943 return isl_pw_aff_gt_set(L, R);
944 case ICmpInst::ICMP_SGE:
945 return isl_pw_aff_ge_set(L, R);
946 case ICmpInst::ICMP_ULT:
947 return isl_pw_aff_lt_set(L, R);
948 case ICmpInst::ICMP_UGT:
949 return isl_pw_aff_gt_set(L, R);
950 case ICmpInst::ICMP_ULE:
951 return isl_pw_aff_le_set(L, R);
952 case ICmpInst::ICMP_UGE:
953 return isl_pw_aff_ge_set(L, R);
954 default:
955 llvm_unreachable("Non integer predicate not supported");
956 }
957}
958
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000959/// @brief Create the conditions under which @p L @p Pred @p R is true.
960///
961/// Helper function that will make sure the dimensions of the result have the
962/// same isl_id's as the @p Domain.
963static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
964 __isl_take isl_pw_aff *L,
965 __isl_take isl_pw_aff *R,
966 __isl_keep isl_set *Domain) {
967 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
968 return setDimensionIds(Domain, ConsequenceCondSet);
969}
970
971/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000972///
973/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000974/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
975/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000976static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000977buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000978 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
979
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000980 Value *Condition = getConditionFromTerminator(SI);
981 assert(Condition && "No condition for switch");
982
983 ScalarEvolution &SE = *S.getSE();
984 BasicBlock *BB = SI->getParent();
985 isl_pw_aff *LHS, *RHS;
986 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
987
988 unsigned NumSuccessors = SI->getNumSuccessors();
989 ConditionSets.resize(NumSuccessors);
990 for (auto &Case : SI->cases()) {
991 unsigned Idx = Case.getSuccessorIndex();
992 ConstantInt *CaseValue = Case.getCaseValue();
993
994 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
995 isl_set *CaseConditionSet =
996 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
997 ConditionSets[Idx] = isl_set_coalesce(
998 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
999 }
1000
1001 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1002 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1003 for (unsigned u = 2; u < NumSuccessors; u++)
1004 ConditionSetUnion =
1005 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1006 ConditionSets[0] = setDimensionIds(
1007 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1008
1009 S.markAsOptimized();
1010 isl_pw_aff_free(LHS);
1011}
1012
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001013/// @brief Build the conditions sets for the branch condition @p Condition in
1014/// the @p Domain.
1015///
1016/// This will fill @p ConditionSets with the conditions under which control
1017/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1018/// have as many elements as @p TI has successors.
1019static void
1020buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1021 __isl_keep isl_set *Domain,
1022 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1023
1024 isl_set *ConsequenceCondSet = nullptr;
1025 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1026 if (CCond->isZero())
1027 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1028 else
1029 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1030 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1031 auto Opcode = BinOp->getOpcode();
1032 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1033
1034 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1035 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1036
1037 isl_set_free(ConditionSets.pop_back_val());
1038 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1039 isl_set_free(ConditionSets.pop_back_val());
1040 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1041
1042 if (Opcode == Instruction::And)
1043 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1044 else
1045 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1046 } else {
1047 auto *ICond = dyn_cast<ICmpInst>(Condition);
1048 assert(ICond &&
1049 "Condition of exiting branch was neither constant nor ICmp!");
1050
1051 ScalarEvolution &SE = *S.getSE();
1052 BasicBlock *BB = TI->getParent();
1053 isl_pw_aff *LHS, *RHS;
1054 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1055 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1056 ConsequenceCondSet =
1057 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1058 }
1059
1060 assert(ConsequenceCondSet);
1061 isl_set *AlternativeCondSet =
1062 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1063
1064 ConditionSets.push_back(isl_set_coalesce(
1065 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1066 ConditionSets.push_back(isl_set_coalesce(
1067 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1068}
1069
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001070/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1071///
1072/// This will fill @p ConditionSets with the conditions under which control
1073/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1074/// have as many elements as @p TI has successors.
1075static void
1076buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1077 __isl_keep isl_set *Domain,
1078 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1079
1080 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1081 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1082
1083 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1084
1085 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001086 ConditionSets.push_back(isl_set_copy(Domain));
1087 return;
1088 }
1089
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001090 Value *Condition = getConditionFromTerminator(TI);
1091 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001092
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001093 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001094}
1095
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001096void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001097 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001098
Tobias Grosser084d8f72012-05-29 09:29:44 +00001099 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1100
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001101 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001102 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001103}
1104
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001105void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001106 isl_ctx *Ctx = Parent.getIslCtx();
1107 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1108 Type *Ty = GEP->getPointerOperandType();
1109 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001110 ScopDetection &SD = Parent.getSD();
1111
1112 // The set of loads that are required to be invariant.
1113 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001114
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001115 std::vector<const SCEV *> Subscripts;
1116 std::vector<int> Sizes;
1117
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001118 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001119
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001120 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001121 Ty = PtrTy->getElementType();
1122 }
1123
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001124 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001125
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001126 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001127
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001128 for (size_t i = 0; i < Sizes.size(); i++) {
1129 auto Expr = Subscripts[i + IndexOffset];
1130 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001131
Johannes Doerfert09e36972015-10-07 20:17:36 +00001132 InvariantLoadsSetTy AccessILS;
1133 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1134 continue;
1135
1136 bool NonAffine = false;
1137 for (LoadInst *LInst : AccessILS)
1138 if (!ScopRIL.count(LInst))
1139 NonAffine = true;
1140
1141 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001142 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001143
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001144 isl_pw_aff *AccessOffset = getPwAff(Expr);
1145 AccessOffset =
1146 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001147
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001148 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1149 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001150
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001151 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1152 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1153 OutOfBound = isl_set_params(OutOfBound);
1154 isl_set *InBound = isl_set_complement(OutOfBound);
1155 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001156
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001157 // A => B == !A or B
1158 isl_set *InBoundIfExecuted =
1159 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001160
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001161 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001162 }
1163
1164 isl_local_space_free(LSpace);
1165}
1166
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001167void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1168 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001169 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1170 deriveAssumptionsFromGEP(GEP);
1171}
1172
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001173void ScopStmt::collectSurroundingLoops() {
1174 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1175 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1176 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1177 isl_id_free(DimId);
1178 }
1179}
1180
Michael Kruse9d080092015-09-11 21:41:48 +00001181ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001182 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001183
Tobias Grosser16c44032015-07-09 07:31:45 +00001184 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001185}
1186
Michael Kruse9d080092015-09-11 21:41:48 +00001187ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001188 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001189
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001190 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001191}
1192
1193void ScopStmt::init() {
1194 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001195
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001196 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001197 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001198 buildAccessRelations();
1199
1200 if (BB) {
1201 deriveAssumptions(BB);
1202 } else {
1203 for (BasicBlock *Block : R->blocks()) {
1204 deriveAssumptions(Block);
1205 }
1206 }
1207
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001208 if (DetectReductions)
1209 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001210}
1211
Johannes Doerferte58a0122014-06-27 20:31:28 +00001212/// @brief Collect loads which might form a reduction chain with @p StoreMA
1213///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001214/// Check if the stored value for @p StoreMA is a binary operator with one or
1215/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001216/// used only once (by @p StoreMA) and its load operands are also used only
1217/// once, we have found a possible reduction chain. It starts at an operand
1218/// load and includes the binary operator and @p StoreMA.
1219///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001220/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001221/// escape this block or into any other store except @p StoreMA.
1222void ScopStmt::collectCandiateReductionLoads(
1223 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1224 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1225 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001226 return;
1227
1228 // Skip if there is not one binary operator between the load and the store
1229 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001230 if (!BinOp)
1231 return;
1232
1233 // Skip if the binary operators has multiple uses
1234 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001235 return;
1236
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001237 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001238 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1239 return;
1240
Johannes Doerfert9890a052014-07-01 00:32:29 +00001241 // Skip if the binary operator is outside the current SCoP
1242 if (BinOp->getParent() != Store->getParent())
1243 return;
1244
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001245 // Skip if it is a multiplicative reduction and we disabled them
1246 if (DisableMultiplicativeReductions &&
1247 (BinOp->getOpcode() == Instruction::Mul ||
1248 BinOp->getOpcode() == Instruction::FMul))
1249 return;
1250
Johannes Doerferte58a0122014-06-27 20:31:28 +00001251 // Check the binary operator operands for a candidate load
1252 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1253 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1254 if (!PossibleLoad0 && !PossibleLoad1)
1255 return;
1256
1257 // A load is only a candidate if it cannot escape (thus has only this use)
1258 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001259 if (PossibleLoad0->getParent() == Store->getParent())
1260 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001261 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001262 if (PossibleLoad1->getParent() == Store->getParent())
1263 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001264}
1265
1266/// @brief Check for reductions in this ScopStmt
1267///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001268/// Iterate over all store memory accesses and check for valid binary reduction
1269/// like chains. For all candidates we check if they have the same base address
1270/// and there are no other accesses which overlap with them. The base address
1271/// check rules out impossible reductions candidates early. The overlap check,
1272/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001273/// guarantees that none of the intermediate results will escape during
1274/// execution of the loop nest. We basically check here that no other memory
1275/// access can access the same memory as the potential reduction.
1276void ScopStmt::checkForReductions() {
1277 SmallVector<MemoryAccess *, 2> Loads;
1278 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1279
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001280 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001281 // stores and collecting possible reduction loads.
1282 for (MemoryAccess *StoreMA : MemAccs) {
1283 if (StoreMA->isRead())
1284 continue;
1285
1286 Loads.clear();
1287 collectCandiateReductionLoads(StoreMA, Loads);
1288 for (MemoryAccess *LoadMA : Loads)
1289 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1290 }
1291
1292 // Then check each possible candidate pair.
1293 for (const auto &CandidatePair : Candidates) {
1294 bool Valid = true;
1295 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1296 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1297
1298 // Skip those with obviously unequal base addresses.
1299 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1300 isl_map_free(LoadAccs);
1301 isl_map_free(StoreAccs);
1302 continue;
1303 }
1304
1305 // And check if the remaining for overlap with other memory accesses.
1306 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1307 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1308 isl_set *AllAccs = isl_map_range(AllAccsRel);
1309
1310 for (MemoryAccess *MA : MemAccs) {
1311 if (MA == CandidatePair.first || MA == CandidatePair.second)
1312 continue;
1313
1314 isl_map *AccRel =
1315 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1316 isl_set *Accs = isl_map_range(AccRel);
1317
1318 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1319 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1320 Valid = Valid && isl_set_is_empty(OverlapAccs);
1321 isl_set_free(OverlapAccs);
1322 }
1323 }
1324
1325 isl_set_free(AllAccs);
1326 if (!Valid)
1327 continue;
1328
Johannes Doerfertf6183392014-07-01 20:52:51 +00001329 const LoadInst *Load =
1330 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1331 MemoryAccess::ReductionType RT =
1332 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1333
Johannes Doerferte58a0122014-06-27 20:31:28 +00001334 // If no overlapping access was found we mark the load and store as
1335 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001336 CandidatePair.first->markAsReductionLike(RT);
1337 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001338 }
Tobias Grosser75805372011-04-29 06:27:02 +00001339}
1340
Tobias Grosser74394f02013-01-14 22:40:23 +00001341std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001342
Tobias Grosser54839312015-04-21 11:37:25 +00001343std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001344 auto *S = getSchedule();
1345 auto Str = stringFromIslObj(S);
1346 isl_map_free(S);
1347 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001348}
1349
Tobias Grosser74394f02013-01-14 22:40:23 +00001350unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001351
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001352unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001353
Tobias Grosser75805372011-04-29 06:27:02 +00001354const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1355
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001356const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001357 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001358}
1359
Tobias Grosser74394f02013-01-14 22:40:23 +00001360isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001361
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001362__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001363
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001364__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001365 return isl_set_get_space(Domain);
1366}
1367
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001368__isl_give isl_id *ScopStmt::getDomainId() const {
1369 return isl_set_get_tuple_id(Domain);
1370}
Tobias Grossercd95b772012-08-30 11:49:38 +00001371
Tobias Grosser75805372011-04-29 06:27:02 +00001372ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001373 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001374 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001375}
1376
1377void ScopStmt::print(raw_ostream &OS) const {
1378 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001379 OS.indent(12) << "Domain :=\n";
1380
1381 if (Domain) {
1382 OS.indent(16) << getDomainStr() << ";\n";
1383 } else
1384 OS.indent(16) << "n/a\n";
1385
Tobias Grosser54839312015-04-21 11:37:25 +00001386 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001387
1388 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001389 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001390 } else
1391 OS.indent(16) << "n/a\n";
1392
Tobias Grosser083d3d32014-06-28 08:59:45 +00001393 for (MemoryAccess *Access : MemAccs)
1394 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001395}
1396
1397void ScopStmt::dump() const { print(dbgs()); }
1398
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001399void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001400
1401 // Remove all memory accesses in @p InvMAs from this statement together
1402 // with all scalar accesses that were caused by them. The tricky iteration
1403 // order uses is needed because the MemAccs is a vector and the order in
1404 // which the accesses of each memory access list (MAL) are stored in this
1405 // vector is reversed.
1406 for (MemoryAccess *MA : InvMAs) {
1407 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1408 MAL.reverse();
1409
1410 auto MALIt = MAL.begin();
1411 auto MALEnd = MAL.end();
1412 auto MemAccsIt = MemAccs.begin();
1413 while (MALIt != MALEnd) {
1414 while (*MemAccsIt != *MALIt)
1415 MemAccsIt++;
1416
1417 MALIt++;
1418 MemAccs.erase(MemAccsIt);
1419 }
1420
1421 InstructionToAccess.erase(MA->getAccessInstruction());
1422 delete &MAL;
1423 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001424}
1425
Tobias Grosser75805372011-04-29 06:27:02 +00001426//===----------------------------------------------------------------------===//
1427/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001428
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001429void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001430 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1431 isl_set_free(Context);
1432 Context = NewContext;
1433}
1434
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001435/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1436struct SCEVSensitiveParameterRewriter
1437 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1438 ValueToValueMap &VMap;
1439 ScalarEvolution &SE;
1440
1441public:
1442 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1443 : VMap(VMap), SE(SE) {}
1444
1445 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1446 ValueToValueMap &VMap) {
1447 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1448 return SSPR.visit(E);
1449 }
1450
1451 const SCEV *visit(const SCEV *E) {
1452 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1453 }
1454
1455 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1456
1457 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1458 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1459 }
1460
1461 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1462 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1463 }
1464
1465 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1466 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1467 }
1468
1469 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1470 SmallVector<const SCEV *, 4> Operands;
1471 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1472 Operands.push_back(visit(E->getOperand(i)));
1473 return SE.getAddExpr(Operands);
1474 }
1475
1476 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1477 SmallVector<const SCEV *, 4> Operands;
1478 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1479 Operands.push_back(visit(E->getOperand(i)));
1480 return SE.getMulExpr(Operands);
1481 }
1482
1483 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1484 SmallVector<const SCEV *, 4> Operands;
1485 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1486 Operands.push_back(visit(E->getOperand(i)));
1487 return SE.getSMaxExpr(Operands);
1488 }
1489
1490 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1491 SmallVector<const SCEV *, 4> Operands;
1492 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1493 Operands.push_back(visit(E->getOperand(i)));
1494 return SE.getUMaxExpr(Operands);
1495 }
1496
1497 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1498 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1499 }
1500
1501 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1502 auto *Start = visit(E->getStart());
1503 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1504 visit(E->getStepRecurrence(SE)),
1505 E->getLoop(), SCEV::FlagAnyWrap);
1506 return SE.getAddExpr(Start, AddRec);
1507 }
1508
1509 const SCEV *visitUnknown(const SCEVUnknown *E) {
1510 if (auto *NewValue = VMap.lookup(E->getValue()))
1511 return SE.getUnknown(NewValue);
1512 return E;
1513 }
1514};
1515
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001516const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001517 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001518}
1519
Tobias Grosserabfbe632013-02-05 12:09:06 +00001520void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001521 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001522 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001523
1524 // Normalize the SCEV to get the representing element for an invariant load.
1525 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1526
Tobias Grosser60b54f12011-11-08 15:41:28 +00001527 if (ParameterIds.find(Parameter) != ParameterIds.end())
1528 continue;
1529
1530 int dimension = Parameters.size();
1531
1532 Parameters.push_back(Parameter);
1533 ParameterIds[Parameter] = dimension;
1534 }
1535}
1536
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001537__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001538 // Normalize the SCEV to get the representing element for an invariant load.
1539 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1540
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001541 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001542
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001543 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001544 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001545
Tobias Grosser8f99c162011-11-15 11:38:55 +00001546 std::string ParameterName;
1547
1548 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1549 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001550 ParameterName = Val->getName();
Johannes Doerferte071f6d2015-11-03 16:49:59 +00001551 if (!Val->hasName())
1552 if (LoadInst *LI = dyn_cast<LoadInst>(Val))
1553 ParameterName =
1554 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001555 }
1556
1557 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001558 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001559
Tobias Grosser20532b82014-04-11 17:56:49 +00001560 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1561 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001562}
Tobias Grosser75805372011-04-29 06:27:02 +00001563
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001564isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1565 isl_set *DomainContext = isl_union_set_params(getDomains());
1566 return isl_set_intersect_params(C, DomainContext);
1567}
1568
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001569void Scop::buildBoundaryContext() {
1570 BoundaryContext = Affinator.getWrappingContext();
1571 BoundaryContext = isl_set_complement(BoundaryContext);
1572 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1573}
1574
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001575void Scop::addUserContext() {
1576 if (UserContextStr.empty())
1577 return;
1578
1579 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1580 isl_space *Space = getParamSpace();
1581 if (isl_space_dim(Space, isl_dim_param) !=
1582 isl_set_dim(UserContext, isl_dim_param)) {
1583 auto SpaceStr = isl_space_to_str(Space);
1584 errs() << "Error: the context provided in -polly-context has not the same "
1585 << "number of dimensions than the computed context. Due to this "
1586 << "mismatch, the -polly-context option is ignored. Please provide "
1587 << "the context in the parameter space: " << SpaceStr << ".\n";
1588 free(SpaceStr);
1589 isl_set_free(UserContext);
1590 isl_space_free(Space);
1591 return;
1592 }
1593
1594 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1595 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1596 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1597
1598 if (strcmp(NameContext, NameUserContext) != 0) {
1599 auto SpaceStr = isl_space_to_str(Space);
1600 errs() << "Error: the name of dimension " << i
1601 << " provided in -polly-context "
1602 << "is '" << NameUserContext << "', but the name in the computed "
1603 << "context is '" << NameContext
1604 << "'. Due to this name mismatch, "
1605 << "the -polly-context option is ignored. Please provide "
1606 << "the context in the parameter space: " << SpaceStr << ".\n";
1607 free(SpaceStr);
1608 isl_set_free(UserContext);
1609 isl_space_free(Space);
1610 return;
1611 }
1612
1613 UserContext =
1614 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1615 isl_space_get_dim_id(Space, isl_dim_param, i));
1616 }
1617
1618 Context = isl_set_intersect(Context, UserContext);
1619 isl_space_free(Space);
1620}
1621
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001622void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001623 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1624
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001625 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001626 for (LoadInst *LInst : RIL) {
1627 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1628
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001629 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
1630 if (!ClassRep)
1631 ClassRep = LInst;
1632 else
1633 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001634 }
1635}
1636
Tobias Grosser6be480c2011-11-08 15:41:13 +00001637void Scop::buildContext() {
1638 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001639 Context = isl_set_universe(isl_space_copy(Space));
1640 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001641}
1642
Tobias Grosser18daaca2012-05-22 10:47:27 +00001643void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001644 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001645 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001646
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001647 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001648
Johannes Doerferte7044942015-02-24 11:58:30 +00001649 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001650 }
1651}
1652
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001653void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001654 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001655 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001656
Tobias Grosser083d3d32014-06-28 08:59:45 +00001657 for (const auto &ParamID : ParameterIds) {
1658 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001659 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001660 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001661 }
1662
1663 // Align the parameters of all data structures to the model.
1664 Context = isl_set_align_params(Context, Space);
1665
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001666 for (ScopStmt &Stmt : *this)
1667 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001668}
1669
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001670static __isl_give isl_set *
1671simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1672 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001673 // If we modelt all blocks in the SCoP that have side effects we can simplify
1674 // the context with the constraints that are needed for anything to be
1675 // executed at all. However, if we have error blocks in the SCoP we already
1676 // assumed some parameter combinations cannot occure and removed them from the
1677 // domains, thus we cannot use the remaining domain to simplify the
1678 // assumptions.
1679 if (!S.hasErrorBlock()) {
1680 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1681 AssumptionContext =
1682 isl_set_gist_params(AssumptionContext, DomainParameters);
1683 }
1684
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001685 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1686 return AssumptionContext;
1687}
1688
1689void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001690 // The parameter constraints of the iteration domains give us a set of
1691 // constraints that need to hold for all cases where at least a single
1692 // statement iteration is executed in the whole scop. We now simplify the
1693 // assumed context under the assumption that such constraints hold and at
1694 // least a single statement iteration is executed. For cases where no
1695 // statement instances are executed, the assumptions we have taken about
1696 // the executed code do not matter and can be changed.
1697 //
1698 // WARNING: This only holds if the assumptions we have taken do not reduce
1699 // the set of statement instances that are executed. Otherwise we
1700 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001701 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001702 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001703 // performed. In such a case, modifying the run-time conditions and
1704 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001705 // to not be executed.
1706 //
1707 // Example:
1708 //
1709 // When delinearizing the following code:
1710 //
1711 // for (long i = 0; i < 100; i++)
1712 // for (long j = 0; j < m; j++)
1713 // A[i+p][j] = 1.0;
1714 //
1715 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001716 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001717 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001718 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1719 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001720}
1721
Johannes Doerfertb164c792014-09-18 11:17:17 +00001722/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001723static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001724 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1725 isl_pw_multi_aff *MinPMA, *MaxPMA;
1726 isl_pw_aff *LastDimAff;
1727 isl_aff *OneAff;
1728 unsigned Pos;
1729
Johannes Doerfert9143d672014-09-27 11:02:39 +00001730 // Restrict the number of parameters involved in the access as the lexmin/
1731 // lexmax computation will take too long if this number is high.
1732 //
1733 // Experiments with a simple test case using an i7 4800MQ:
1734 //
1735 // #Parameters involved | Time (in sec)
1736 // 6 | 0.01
1737 // 7 | 0.04
1738 // 8 | 0.12
1739 // 9 | 0.40
1740 // 10 | 1.54
1741 // 11 | 6.78
1742 // 12 | 30.38
1743 //
1744 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1745 unsigned InvolvedParams = 0;
1746 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1747 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1748 InvolvedParams++;
1749
1750 if (InvolvedParams > RunTimeChecksMaxParameters) {
1751 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001752 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001753 }
1754 }
1755
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001756 Set = isl_set_remove_divs(Set);
1757
Johannes Doerfertb164c792014-09-18 11:17:17 +00001758 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1759 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1760
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001761 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1762 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1763
Johannes Doerfertb164c792014-09-18 11:17:17 +00001764 // Adjust the last dimension of the maximal access by one as we want to
1765 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1766 // we test during code generation might now point after the end of the
1767 // allocated array but we will never dereference it anyway.
1768 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1769 "Assumed at least one output dimension");
1770 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1771 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1772 OneAff = isl_aff_zero_on_domain(
1773 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1774 OneAff = isl_aff_add_constant_si(OneAff, 1);
1775 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1776 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1777
1778 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1779
1780 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001781 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001782}
1783
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001784static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1785 isl_set *Domain = MA->getStatement()->getDomain();
1786 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1787 return isl_set_reset_tuple_id(Domain);
1788}
1789
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001790/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1791static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001792 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001793 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001794
1795 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1796 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001797 Locations = isl_union_set_coalesce(Locations);
1798 Locations = isl_union_set_detect_equalities(Locations);
1799 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001800 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001801 isl_union_set_free(Locations);
1802 return Valid;
1803}
1804
Johannes Doerfert96425c22015-08-30 21:13:53 +00001805/// @brief Helper to treat non-affine regions and basic blocks the same.
1806///
1807///{
1808
1809/// @brief Return the block that is the representing block for @p RN.
1810static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1811 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1812 : RN->getNodeAs<BasicBlock>();
1813}
1814
1815/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001816static inline BasicBlock *
1817getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001818 if (RN->isSubRegion()) {
1819 assert(idx == 0);
1820 return RN->getNodeAs<Region>()->getExit();
1821 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001822 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001823}
1824
1825/// @brief Return the smallest loop surrounding @p RN.
1826static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1827 if (!RN->isSubRegion())
1828 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1829
1830 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1831 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1832 while (L && NonAffineSubRegion->contains(L))
1833 L = L->getParentLoop();
1834 return L;
1835}
1836
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001837static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1838 if (!RN->isSubRegion())
1839 return 1;
1840
1841 unsigned NumBlocks = 0;
1842 Region *R = RN->getNodeAs<Region>();
1843 for (auto BB : R->blocks()) {
1844 (void)BB;
1845 NumBlocks++;
1846 }
1847 return NumBlocks;
1848}
1849
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001850static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1851 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001852 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001853 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001854 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001855 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001856 return true;
1857 return false;
1858}
1859
Johannes Doerfert96425c22015-08-30 21:13:53 +00001860///}
1861
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001862static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1863 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001864 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001865 isl_id *DimId =
1866 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1867 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1868}
1869
Johannes Doerfert96425c22015-08-30 21:13:53 +00001870isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1871 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1872 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001873 return getDomainConditions(BB);
1874}
1875
1876isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1877 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001878 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001879}
1880
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001881void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001882
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001883 auto *EntryBB = R->getEntry();
1884 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1885 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001886
1887 Loop *L = LI.getLoopFor(EntryBB);
1888 while (LD-- >= 0) {
1889 S = addDomainDimId(S, LD + 1, L);
1890 L = L->getParentLoop();
1891 }
1892
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001893 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001894
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001895 if (SD.isNonAffineSubRegion(R, R))
1896 return;
1897
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001898 buildDomainsWithBranchConstraints(R);
1899 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001900}
1901
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001902void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001903 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001904
1905 // To create the domain for each block in R we iterate over all blocks and
1906 // subregions in R and propagate the conditions under which the current region
1907 // element is executed. To this end we iterate in reverse post order over R as
1908 // it ensures that we first visit all predecessors of a region node (either a
1909 // basic block or a subregion) before we visit the region node itself.
1910 // Initially, only the domain for the SCoP region entry block is set and from
1911 // there we propagate the current domain to all successors, however we add the
1912 // condition that the successor is actually executed next.
1913 // As we are only interested in non-loop carried constraints here we can
1914 // simply skip loop back edges.
1915
1916 ReversePostOrderTraversal<Region *> RTraversal(R);
1917 for (auto *RN : RTraversal) {
1918
1919 // Recurse for affine subregions but go on for basic blocks and non-affine
1920 // subregions.
1921 if (RN->isSubRegion()) {
1922 Region *SubRegion = RN->getNodeAs<Region>();
1923 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001924 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001925 continue;
1926 }
1927 }
1928
Johannes Doerfertf5673802015-10-01 23:48:18 +00001929 // Error blocks are assumed not to be executed. Therefor they are not
1930 // checked properly in the ScopDetection. Any attempt to generate control
1931 // conditions from them might result in a crash. However, this is only true
1932 // for the first step of the domain generation (this function) where we
1933 // push the control conditions of a block to the successors. In the second
1934 // step (propagateDomainConstraints) we only receive domain constraints from
1935 // the predecessors and can therefor look at the domain of a error block.
1936 // That allows us to generate the assumptions needed for them not to be
1937 // executed at runtime.
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001938 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
1939 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00001940 continue;
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001941 }
Johannes Doerfertf5673802015-10-01 23:48:18 +00001942
Johannes Doerfert96425c22015-08-30 21:13:53 +00001943 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001944 TerminatorInst *TI = BB->getTerminator();
1945
Johannes Doerfertf5673802015-10-01 23:48:18 +00001946 isl_set *Domain = DomainMap.lookup(BB);
1947 if (!Domain) {
1948 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1949 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001950 continue;
1951 }
1952
Johannes Doerfert96425c22015-08-30 21:13:53 +00001953 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001954
1955 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1956 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1957
1958 // Build the condition sets for the successor nodes of the current region
1959 // node. If it is a non-affine subregion we will always execute the single
1960 // exit node, hence the single entry node domain is the condition set. For
1961 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001962 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001963 if (RN->isSubRegion())
1964 ConditionSets.push_back(isl_set_copy(Domain));
1965 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001966 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001967
1968 // Now iterate over the successors and set their initial domain based on
1969 // their condition set. We skip back edges here and have to be careful when
1970 // we leave a loop not to keep constraints over a dimension that doesn't
1971 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001972 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00001973 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001974 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001975 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001976
1977 // Skip back edges.
1978 if (DT.dominates(SuccBB, BB)) {
1979 isl_set_free(CondSet);
1980 continue;
1981 }
1982
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001983 // Do not adjust the number of dimensions if we enter a boxed loop or are
1984 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001985 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001986 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00001987 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
1988 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
1989 SuccBBLoop = SuccBBLoop->getParentLoop();
1990
1991 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001992
1993 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1994 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1995 // and enter a new one we need to drop the old constraints.
1996 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001997 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001998 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001999 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2000 isl_set_n_dim(CondSet) - LoopDepthDiff,
2001 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002002 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002003 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002004 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002005 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002006 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002007 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002008 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2009 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002010 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002011 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002012 }
2013
2014 // Set the domain for the successor or merge it with an existing domain in
2015 // case there are multiple paths (without loop back edges) to the
2016 // successor block.
2017 isl_set *&SuccDomain = DomainMap[SuccBB];
2018 if (!SuccDomain)
2019 SuccDomain = CondSet;
2020 else
2021 SuccDomain = isl_set_union(SuccDomain, CondSet);
2022
2023 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002024 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2025 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002026 }
2027 }
2028}
2029
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002030/// @brief Return the domain for @p BB wrt @p DomainMap.
2031///
2032/// This helper function will lookup @p BB in @p DomainMap but also handle the
2033/// case where @p BB is contained in a non-affine subregion using the region
2034/// tree obtained by @p RI.
2035static __isl_give isl_set *
2036getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2037 RegionInfo &RI) {
2038 auto DIt = DomainMap.find(BB);
2039 if (DIt != DomainMap.end())
2040 return isl_set_copy(DIt->getSecond());
2041
2042 Region *R = RI.getRegionFor(BB);
2043 while (R->getEntry() == BB)
2044 R = R->getParent();
2045 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2046}
2047
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002048void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002049 // Iterate over the region R and propagate the domain constrains from the
2050 // predecessors to the current node. In contrast to the
2051 // buildDomainsWithBranchConstraints function, this one will pull the domain
2052 // information from the predecessors instead of pushing it to the successors.
2053 // Additionally, we assume the domains to be already present in the domain
2054 // map here. However, we iterate again in reverse post order so we know all
2055 // predecessors have been visited before a block or non-affine subregion is
2056 // visited.
2057
2058 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2059 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2060
2061 ReversePostOrderTraversal<Region *> RTraversal(R);
2062 for (auto *RN : RTraversal) {
2063
2064 // Recurse for affine subregions but go on for basic blocks and non-affine
2065 // subregions.
2066 if (RN->isSubRegion()) {
2067 Region *SubRegion = RN->getNodeAs<Region>();
2068 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002069 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002070 continue;
2071 }
2072 }
2073
Johannes Doerfertf5673802015-10-01 23:48:18 +00002074 // Get the domain for the current block and check if it was initialized or
2075 // not. The only way it was not is if this block is only reachable via error
2076 // blocks, thus will not be executed under the assumptions we make. Such
2077 // blocks have to be skipped as their predecessors might not have domains
2078 // either. It would not benefit us to compute the domain anyway, only the
2079 // domains of the error blocks that are reachable from non-error blocks
2080 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002081 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002082 isl_set *&Domain = DomainMap[BB];
2083 if (!Domain) {
2084 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2085 << ", it is only reachable from error blocks.\n");
2086 DomainMap.erase(BB);
2087 continue;
2088 }
2089 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2090
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002091 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2092 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2093
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002094 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2095 for (auto *PredBB : predecessors(BB)) {
2096
2097 // Skip backedges
2098 if (DT.dominates(BB, PredBB))
2099 continue;
2100
2101 isl_set *PredBBDom = nullptr;
2102
2103 // Handle the SCoP entry block with its outside predecessors.
2104 if (!getRegion().contains(PredBB))
2105 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2106
2107 if (!PredBBDom) {
2108 // Determine the loop depth of the predecessor and adjust its domain to
2109 // the domain of the current block. This can mean we have to:
2110 // o) Drop a dimension if this block is the exit of a loop, not the
2111 // header of a new loop and the predecessor was part of the loop.
2112 // o) Add an unconstrainted new dimension if this block is the header
2113 // of a loop and the predecessor is not part of it.
2114 // o) Drop the information about the innermost loop dimension when the
2115 // predecessor and the current block are surrounded by different
2116 // loops in the same depth.
2117 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2118 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2119 while (BoxedLoops.count(PredBBLoop))
2120 PredBBLoop = PredBBLoop->getParentLoop();
2121
2122 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002123 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002124 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002125 PredBBDom = isl_set_project_out(
2126 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2127 LoopDepthDiff);
2128 else if (PredBBLoopDepth < BBLoopDepth) {
2129 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002130 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002131 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2132 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002133 PredBBDom = isl_set_drop_constraints_involving_dims(
2134 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002135 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002136 }
2137
2138 PredDom = isl_set_union(PredDom, PredBBDom);
2139 }
2140
2141 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002142 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002143
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002144 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002145 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002146
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002147 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002148 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002149 IsOptimized = true;
2150 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2151 addAssumption(isl_set_complement(DomPar));
2152 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002153 }
2154}
2155
2156/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2157/// is incremented by one and all other dimensions are equal, e.g.,
2158/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2159/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2160static __isl_give isl_map *
2161createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2162 auto *MapSpace = isl_space_map_from_set(SetSpace);
2163 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2164 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2165 if (u != Dim)
2166 NextIterationMap =
2167 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2168 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2169 C = isl_constraint_set_constant_si(C, 1);
2170 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2171 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2172 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2173 return NextIterationMap;
2174}
2175
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002176void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002177 int LoopDepth = getRelativeLoopDepth(L);
2178 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002179
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002180 BasicBlock *HeaderBB = L->getHeader();
2181 assert(DomainMap.count(HeaderBB));
2182 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002183
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002184 isl_map *NextIterationMap =
2185 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002186
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002187 isl_set *UnionBackedgeCondition =
2188 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002189
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002190 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2191 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002192
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002193 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002194
2195 // If the latch is only reachable via error statements we skip it.
2196 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2197 if (!LatchBBDom)
2198 continue;
2199
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002200 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002201
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002202 TerminatorInst *TI = LatchBB->getTerminator();
2203 BranchInst *BI = dyn_cast<BranchInst>(TI);
2204 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002205 BackedgeCondition = isl_set_copy(LatchBBDom);
2206 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002207 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002208 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002209 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002210
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002211 // Free the non back edge condition set as we do not need it.
2212 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002213
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002214 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002215 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002216
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002217 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2218 assert(LatchLoopDepth >= LoopDepth);
2219 BackedgeCondition =
2220 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2221 LatchLoopDepth - LoopDepth);
2222 UnionBackedgeCondition =
2223 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002224 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002225
2226 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2227 for (int i = 0; i < LoopDepth; i++)
2228 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2229
2230 isl_set *UnionBackedgeConditionComplement =
2231 isl_set_complement(UnionBackedgeCondition);
2232 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2233 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2234 UnionBackedgeConditionComplement =
2235 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2236 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2237 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2238
2239 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2240 HeaderBBDom = Parts.second;
2241
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002242 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2243 // the bounded assumptions to the context as they are already implied by the
2244 // <nsw> tag.
2245 if (Affinator.hasNSWAddRecForLoop(L)) {
2246 isl_set_free(Parts.first);
2247 return;
2248 }
2249
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002250 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2251 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002252 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002253}
2254
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002255void Scop::buildAliasChecks(AliasAnalysis &AA) {
2256 if (!PollyUseRuntimeAliasChecks)
2257 return;
2258
2259 if (buildAliasGroups(AA))
2260 return;
2261
2262 // If a problem occurs while building the alias groups we need to delete
2263 // this SCoP and pretend it wasn't valid in the first place. To this end
2264 // we make the assumed context infeasible.
2265 addAssumption(isl_set_empty(getParamSpace()));
2266
2267 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2268 << " could not be created as the number of parameters involved "
2269 "is too high. The SCoP will be "
2270 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2271 "the maximal number of parameters but be advised that the "
2272 "compile time might increase exponentially.\n\n");
2273}
2274
Johannes Doerfert9143d672014-09-27 11:02:39 +00002275bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002276 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002277 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002278 // for all memory accesses inside the SCoP.
2279 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002280 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002281 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002282 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002283 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002284 // if their access domains intersect, otherwise they are in different
2285 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002286 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002287 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002288 // and maximal accesses to each array of a group in read only and non
2289 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002290 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2291
2292 AliasSetTracker AST(AA);
2293
2294 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002295 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002296 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002297
2298 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002299 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002300 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2301 isl_set_free(StmtDomain);
2302 if (StmtDomainEmpty)
2303 continue;
2304
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002305 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002306 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002307 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002308 if (!MA->isRead())
2309 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002310 Instruction *Acc = MA->getAccessInstruction();
2311 PtrToAcc[getPointerOperand(*Acc)] = MA;
2312 AST.add(Acc);
2313 }
2314 }
2315
2316 SmallVector<AliasGroupTy, 4> AliasGroups;
2317 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002318 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002319 continue;
2320 AliasGroupTy AG;
2321 for (auto PR : AS)
2322 AG.push_back(PtrToAcc[PR.getValue()]);
2323 assert(AG.size() > 1 &&
2324 "Alias groups should contain at least two accesses");
2325 AliasGroups.push_back(std::move(AG));
2326 }
2327
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002328 // Split the alias groups based on their domain.
2329 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2330 AliasGroupTy NewAG;
2331 AliasGroupTy &AG = AliasGroups[u];
2332 AliasGroupTy::iterator AGI = AG.begin();
2333 isl_set *AGDomain = getAccessDomain(*AGI);
2334 while (AGI != AG.end()) {
2335 MemoryAccess *MA = *AGI;
2336 isl_set *MADomain = getAccessDomain(MA);
2337 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2338 NewAG.push_back(MA);
2339 AGI = AG.erase(AGI);
2340 isl_set_free(MADomain);
2341 } else {
2342 AGDomain = isl_set_union(AGDomain, MADomain);
2343 AGI++;
2344 }
2345 }
2346 if (NewAG.size() > 1)
2347 AliasGroups.push_back(std::move(NewAG));
2348 isl_set_free(AGDomain);
2349 }
2350
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002351 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002352 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2353 for (AliasGroupTy &AG : AliasGroups) {
2354 NonReadOnlyBaseValues.clear();
2355 ReadOnlyPairs.clear();
2356
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002357 if (AG.size() < 2) {
2358 AG.clear();
2359 continue;
2360 }
2361
Johannes Doerfert13771732014-10-01 12:40:46 +00002362 for (auto II = AG.begin(); II != AG.end();) {
2363 Value *BaseAddr = (*II)->getBaseAddr();
2364 if (HasWriteAccess.count(BaseAddr)) {
2365 NonReadOnlyBaseValues.insert(BaseAddr);
2366 II++;
2367 } else {
2368 ReadOnlyPairs[BaseAddr].insert(*II);
2369 II = AG.erase(II);
2370 }
2371 }
2372
2373 // If we don't have read only pointers check if there are at least two
2374 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002375 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002376 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002377 continue;
2378 }
2379
2380 // If we don't have non read only pointers clear the alias group.
2381 if (NonReadOnlyBaseValues.empty()) {
2382 AG.clear();
2383 continue;
2384 }
2385
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002386 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002387 MinMaxAliasGroups.emplace_back();
2388 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2389 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2390 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2391 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002392
2393 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002394
2395 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002396 for (MemoryAccess *MA : AG)
2397 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002398
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002399 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2400 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002401
2402 // Bail out if the number of values we need to compare is too large.
2403 // This is important as the number of comparisions grows quadratically with
2404 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002405 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2406 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002407 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002408
2409 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002410 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002411 Accesses = isl_union_map_empty(getParamSpace());
2412
2413 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2414 for (MemoryAccess *MA : ReadOnlyPair.second)
2415 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2416
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002417 Valid =
2418 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002419
2420 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002421 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002422 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002423
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002424 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002425}
2426
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002427static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2428 Loop *L = LI.getLoopFor(R.getEntry());
2429 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2430}
2431
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002432static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2433 ScopDetection &SD) {
2434
2435 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2436
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002437 unsigned MinLD = INT_MAX, MaxLD = 0;
2438 for (BasicBlock *BB : R.blocks()) {
2439 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002440 if (!R.contains(L))
2441 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002442 if (BoxedLoops && BoxedLoops->count(L))
2443 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002444 unsigned LD = L->getLoopDepth();
2445 MinLD = std::min(MinLD, LD);
2446 MaxLD = std::max(MaxLD, LD);
2447 }
2448 }
2449
2450 // Handle the case that there is no loop in the SCoP first.
2451 if (MaxLD == 0)
2452 return 1;
2453
2454 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2455 assert(MaxLD >= MinLD &&
2456 "Maximal loop depth was smaller than mininaml loop depth?");
2457 return MaxLD - MinLD + 1;
2458}
2459
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002460Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002461 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002462 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002463 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2464 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002465 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2466 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2467 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2468 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002469
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002470void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002471 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002472 buildInvariantEquivalenceClasses();
2473
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002474 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002475
Michael Krusecac948e2015-10-02 13:53:07 +00002476 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002477 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002478 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002479 if (Stmts.empty())
2480 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002481
Michael Krusecac948e2015-10-02 13:53:07 +00002482 // The ScopStmts now have enough information to initialize themselves.
2483 for (ScopStmt &Stmt : Stmts)
2484 Stmt.init();
2485
2486 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002487 Loop *L = getLoopSurroundingRegion(R, LI);
2488 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002489 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002490 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002491
Tobias Grosser8286b832015-11-02 11:29:32 +00002492 if (isl_set_is_empty(AssumedContext))
2493 return;
2494
2495 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002496 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002497 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002498 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002499 buildBoundaryContext();
2500 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002501 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002502
2503 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002504 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002505}
2506
2507Scop::~Scop() {
2508 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002509 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002510 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002511 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002512
Johannes Doerfert96425c22015-08-30 21:13:53 +00002513 for (auto It : DomainMap)
2514 isl_set_free(It.second);
2515
Johannes Doerfertb164c792014-09-18 11:17:17 +00002516 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002517 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002518 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002519 isl_pw_multi_aff_free(MMA.first);
2520 isl_pw_multi_aff_free(MMA.second);
2521 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002522 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002523 isl_pw_multi_aff_free(MMA.first);
2524 isl_pw_multi_aff_free(MMA.second);
2525 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002526 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002527
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002528 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002529 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002530}
2531
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002532void Scop::updateAccessDimensionality() {
2533 for (auto &Stmt : *this)
2534 for (auto &Access : Stmt)
2535 Access->updateDimensionality();
2536}
2537
Michael Krusecac948e2015-10-02 13:53:07 +00002538void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002539 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2540 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002541 RegionNode *RN = Stmt.isRegionStmt()
2542 ? Stmt.getRegion()->getNode()
2543 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002544
Johannes Doerferteca9e892015-11-03 16:54:49 +00002545 bool RemoveStmt = StmtIt->isEmpty();
2546 if (!RemoveStmt)
2547 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2548 if (!RemoveStmt)
2549 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002550
Johannes Doerferteca9e892015-11-03 16:54:49 +00002551 // Remove read only statements only after invariant loop hoisting.
2552 if (!RemoveStmt && !RemoveIgnoredStmts) {
2553 bool OnlyRead = true;
2554 for (MemoryAccess *MA : Stmt) {
2555 if (MA->isRead())
2556 continue;
2557
2558 OnlyRead = false;
2559 break;
2560 }
2561
2562 RemoveStmt = OnlyRead;
2563 }
2564
2565 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002566 // Remove the statement because it is unnecessary.
2567 if (Stmt.isRegionStmt())
2568 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2569 StmtMap.erase(BB);
2570 else
2571 StmtMap.erase(Stmt.getBasicBlock());
2572
2573 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002574 continue;
2575 }
2576
Michael Krusecac948e2015-10-02 13:53:07 +00002577 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002578 }
2579}
2580
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002581const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2582 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2583 if (!LInst)
2584 return nullptr;
2585
2586 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2587 LInst = cast<LoadInst>(Rep);
2588
2589 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2590 for (auto &IAClass : InvariantEquivClasses)
2591 if (PointerSCEV == std::get<0>(IAClass))
2592 return &IAClass;
2593
2594 return nullptr;
2595}
2596
2597void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2598
2599 // Get the context under which the statement is executed.
2600 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2601 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2602 DomainCtx = isl_set_detect_equalities(DomainCtx);
2603 DomainCtx = isl_set_coalesce(DomainCtx);
2604
2605 // Project out all parameters that relate to loads in the statement. Otherwise
2606 // we could have cyclic dependences on the constraints under which the
2607 // hoisted loads are executed and we could not determine an order in which to
2608 // pre-load them. This happens because not only lower bounds are part of the
2609 // domain but also upper bounds.
2610 for (MemoryAccess *MA : InvMAs) {
2611 Instruction *AccInst = MA->getAccessInstruction();
2612 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002613 SetVector<Value *> Values;
2614 for (const SCEV *Parameter : Parameters) {
2615 Values.clear();
2616 findValues(Parameter, Values);
2617 if (!Values.count(AccInst))
2618 continue;
2619
2620 if (isl_id *ParamId = getIdForParam(Parameter)) {
2621 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2622 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2623 isl_id_free(ParamId);
2624 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002625 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002626 }
2627 }
2628
2629 for (MemoryAccess *MA : InvMAs) {
2630 // Check for another invariant access that accesses the same location as
2631 // MA and if found consolidate them. Otherwise create a new equivalence
2632 // class at the end of InvariantEquivClasses.
2633 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2634 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2635
2636 bool Consolidated = false;
2637 for (auto &IAClass : InvariantEquivClasses) {
2638 if (PointerSCEV != std::get<0>(IAClass))
2639 continue;
2640
2641 Consolidated = true;
2642
2643 // Add MA to the list of accesses that are in this class.
2644 auto &MAs = std::get<1>(IAClass);
2645 MAs.push_front(MA);
2646
2647 // Unify the execution context of the class and this statement.
2648 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
2649 IAClassDomainCtx = isl_set_coalesce(
2650 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2651 break;
2652 }
2653
2654 if (Consolidated)
2655 continue;
2656
2657 // If we did not consolidate MA, thus did not find an equivalence class
2658 // for it, we create a new one.
2659 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2660 isl_set_copy(DomainCtx));
2661 }
2662
2663 isl_set_free(DomainCtx);
2664}
2665
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002666void Scop::hoistInvariantLoads() {
2667 isl_union_map *Writes = getWrites();
2668 for (ScopStmt &Stmt : *this) {
2669
2670 // TODO: Loads that are not loop carried, hence are in a statement with
2671 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002672 // currently "hoist" them anyway. This is necessary because we allow
2673 // them to be treated as parameters (e.g., in conditions) and our code
2674 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002675
Johannes Doerfert8930f482015-10-02 14:51:00 +00002676 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2677 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002678 isl_set *Domain = Stmt.getDomain();
2679 MemoryAccessList InvMAs;
2680
2681 for (MemoryAccess *MA : Stmt) {
2682 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2683 continue;
2684
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002685 // Skip accesses that have an invariant base pointer which is defined but
2686 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2687 // returns a pointer that is used as a base address. However, as we want
2688 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002689 // the region if it is also a memory access. Each ScopArrayInfo object
2690 // that has a base pointer origin has a base pointer that is loaded and
2691 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002692 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002693 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002694 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002695 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2696 SAI = BasePtrOriginSAI;
2697
2698 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2699 if (R.contains(BasePtrInst))
2700 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002701
Johannes Doerfert8930f482015-10-02 14:51:00 +00002702 // Skip accesses in non-affine subregions as they might not be executed
2703 // under the same condition as the entry of the non-affine subregion.
2704 if (BB != MA->getAccessInstruction()->getParent())
2705 continue;
2706
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002707 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002708
2709 // Skip accesses that have an empty access relation. These can be caused
2710 // by multiple offsets with a type cast in-between that cause the overall
2711 // byte offset to be not divisible by the new types sizes.
2712 if (isl_map_is_empty(AccessRelation)) {
2713 isl_map_free(AccessRelation);
2714 continue;
2715 }
2716
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002717 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2718 Stmt.getNumIterators())) {
2719 isl_map_free(AccessRelation);
2720 continue;
2721 }
2722
2723 AccessRelation =
2724 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2725 isl_set *AccessRange = isl_map_range(AccessRelation);
2726
2727 isl_union_map *Written = isl_union_map_intersect_range(
2728 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2729 bool IsWritten = !isl_union_map_is_empty(Written);
2730 isl_union_map_free(Written);
2731
2732 if (IsWritten)
2733 continue;
2734
2735 InvMAs.push_front(MA);
2736 }
2737
2738 // We inserted invariant accesses always in the front but need them to be
2739 // sorted in a "natural order". The statements are already sorted in reverse
2740 // post order and that suffices for the accesses too. The reason we require
2741 // an order in the first place is the dependences between invariant loads
2742 // that can be caused by indirect loads.
2743 InvMAs.reverse();
2744
2745 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002746 Stmt.removeMemoryAccesses(InvMAs);
2747 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002748
2749 isl_set_free(Domain);
2750 }
2751 isl_union_map_free(Writes);
2752
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002753 if (!InvariantEquivClasses.empty())
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002754 IsOptimized = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00002755
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002756 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002757 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002758 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002759 assert(LI && getRegion().contains(LI));
2760 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2761 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2762 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2763 << ") is required to be invariant but was not marked as "
2764 "such. SCoP for "
2765 << getRegion() << " will be dropped\n\n");
2766 addAssumption(isl_set_empty(getParamSpace()));
2767 return;
2768 }
2769 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002770}
2771
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002772const ScopArrayInfo *
2773Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002774 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Johannes Doerferta7686242015-11-08 19:12:05 +00002775 bool IsScalar = Sizes.empty();
2776 auto ScalarTypePair = std::make_pair(IsScalar, IsPHI);
2777 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, ScalarTypePair)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002778 if (!SAI) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002779 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2780 this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002781 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002782 // In case of mismatching array sizes, we bail out by setting the run-time
2783 // context to false.
2784 if (!SAI->updateSizes(Sizes))
2785 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002786 }
Tobias Grosserab671442015-05-23 05:58:27 +00002787 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002788}
2789
Johannes Doerferta7686242015-11-08 19:12:05 +00002790const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsScalar,
2791 bool IsPHI) {
2792 auto ScalarTypePair = std::make_pair(IsScalar, IsPHI);
2793 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, ScalarTypePair)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002794 assert(SAI && "No ScopArrayInfo available for this base pointer");
2795 return SAI;
2796}
2797
Tobias Grosser74394f02013-01-14 22:40:23 +00002798std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002799std::string Scop::getAssumedContextStr() const {
2800 return stringFromIslObj(AssumedContext);
2801}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002802std::string Scop::getBoundaryContextStr() const {
2803 return stringFromIslObj(BoundaryContext);
2804}
Tobias Grosser75805372011-04-29 06:27:02 +00002805
2806std::string Scop::getNameStr() const {
2807 std::string ExitName, EntryName;
2808 raw_string_ostream ExitStr(ExitName);
2809 raw_string_ostream EntryStr(EntryName);
2810
Tobias Grosserf240b482014-01-09 10:42:15 +00002811 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002812 EntryStr.str();
2813
2814 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002815 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002816 ExitStr.str();
2817 } else
2818 ExitName = "FunctionExit";
2819
2820 return EntryName + "---" + ExitName;
2821}
2822
Tobias Grosser74394f02013-01-14 22:40:23 +00002823__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002824__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002825 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002826}
2827
Tobias Grossere86109f2013-10-29 21:05:49 +00002828__isl_give isl_set *Scop::getAssumedContext() const {
2829 return isl_set_copy(AssumedContext);
2830}
2831
Johannes Doerfert43788c52015-08-20 05:58:56 +00002832__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2833 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002834 RuntimeCheckContext =
2835 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2836 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002837 return RuntimeCheckContext;
2838}
2839
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002840bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002841 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002842 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002843 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2844 isl_set_free(RuntimeCheckContext);
2845 return IsFeasible;
2846}
2847
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002848void Scop::addAssumption(__isl_take isl_set *Set) {
2849 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002850 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002851}
2852
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002853__isl_give isl_set *Scop::getBoundaryContext() const {
2854 return isl_set_copy(BoundaryContext);
2855}
2856
Tobias Grosser75805372011-04-29 06:27:02 +00002857void Scop::printContext(raw_ostream &OS) const {
2858 OS << "Context:\n";
2859
2860 if (!Context) {
2861 OS.indent(4) << "n/a\n\n";
2862 return;
2863 }
2864
2865 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002866
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002867 OS.indent(4) << "Assumed Context:\n";
2868 if (!AssumedContext) {
2869 OS.indent(4) << "n/a\n\n";
2870 return;
2871 }
2872
2873 OS.indent(4) << getAssumedContextStr() << "\n";
2874
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002875 OS.indent(4) << "Boundary Context:\n";
2876 if (!BoundaryContext) {
2877 OS.indent(4) << "n/a\n\n";
2878 return;
2879 }
2880
2881 OS.indent(4) << getBoundaryContextStr() << "\n";
2882
Tobias Grosser083d3d32014-06-28 08:59:45 +00002883 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002884 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002885 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2886 }
Tobias Grosser75805372011-04-29 06:27:02 +00002887}
2888
Johannes Doerfertb164c792014-09-18 11:17:17 +00002889void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002890 int noOfGroups = 0;
2891 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002892 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002893 noOfGroups += 1;
2894 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002895 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002896 }
2897
Tobias Grosserbb853c22015-07-25 12:31:03 +00002898 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002899 if (MinMaxAliasGroups.empty()) {
2900 OS.indent(8) << "n/a\n";
2901 return;
2902 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002903
Tobias Grosserbb853c22015-07-25 12:31:03 +00002904 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002905
2906 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002907 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002908 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002909 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002910 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2911 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002912 }
2913 OS << " ]]\n";
2914 }
2915
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002916 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002917 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002918 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002919 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002920 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2921 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002922 }
2923 OS << " ]]\n";
2924 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002925 }
2926}
2927
Tobias Grosser75805372011-04-29 06:27:02 +00002928void Scop::printStatements(raw_ostream &OS) const {
2929 OS << "Statements {\n";
2930
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002931 for (const ScopStmt &Stmt : *this)
2932 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002933
2934 OS.indent(4) << "}\n";
2935}
2936
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002937void Scop::printArrayInfo(raw_ostream &OS) const {
2938 OS << "Arrays {\n";
2939
Tobias Grosserab671442015-05-23 05:58:27 +00002940 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002941 Array.second->print(OS);
2942
2943 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002944
2945 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2946
2947 for (auto &Array : arrays())
2948 Array.second->print(OS, /* SizeAsPwAff */ true);
2949
2950 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002951}
2952
Tobias Grosser75805372011-04-29 06:27:02 +00002953void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002954 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2955 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002956 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002957 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002958 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002959 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002960 const auto &MAs = std::get<1>(IAClass);
2961 if (MAs.empty()) {
2962 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002963 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002964 MAs.front()->print(OS);
2965 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002966 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002967 }
2968 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002969 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002970 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002971 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002972 printStatements(OS.indent(4));
2973}
2974
2975void Scop::dump() const { print(dbgs()); }
2976
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002977isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002978
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002979__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2980 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002981}
2982
Tobias Grosser808cd692015-07-14 09:33:13 +00002983__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002984 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002985
Tobias Grosser808cd692015-07-14 09:33:13 +00002986 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002987 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002988
2989 return Domain;
2990}
2991
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002992__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002993 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002994
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002995 for (ScopStmt &Stmt : *this) {
2996 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002997 if (!MA->isMustWrite())
2998 continue;
2999
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003000 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003001 isl_map *AccessDomain = MA->getAccessRelation();
3002 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3003 Write = isl_union_map_add_map(Write, AccessDomain);
3004 }
3005 }
3006 return isl_union_map_coalesce(Write);
3007}
3008
3009__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003010 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003011
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003012 for (ScopStmt &Stmt : *this) {
3013 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003014 if (!MA->isMayWrite())
3015 continue;
3016
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003017 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003018 isl_map *AccessDomain = MA->getAccessRelation();
3019 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3020 Write = isl_union_map_add_map(Write, AccessDomain);
3021 }
3022 }
3023 return isl_union_map_coalesce(Write);
3024}
3025
Tobias Grosser37eb4222014-02-20 21:43:54 +00003026__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003027 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003028
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003029 for (ScopStmt &Stmt : *this) {
3030 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003031 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003032 continue;
3033
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003034 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003035 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003036 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3037 Write = isl_union_map_add_map(Write, AccessDomain);
3038 }
3039 }
3040 return isl_union_map_coalesce(Write);
3041}
3042
3043__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003044 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003045
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003046 for (ScopStmt &Stmt : *this) {
3047 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003048 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003049 continue;
3050
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003051 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003052 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003053
3054 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3055 Read = isl_union_map_add_map(Read, AccessDomain);
3056 }
3057 }
3058 return isl_union_map_coalesce(Read);
3059}
3060
Tobias Grosser808cd692015-07-14 09:33:13 +00003061__isl_give isl_union_map *Scop::getSchedule() const {
3062 auto Tree = getScheduleTree();
3063 auto S = isl_schedule_get_map(Tree);
3064 isl_schedule_free(Tree);
3065 return S;
3066}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003067
Tobias Grosser808cd692015-07-14 09:33:13 +00003068__isl_give isl_schedule *Scop::getScheduleTree() const {
3069 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3070 getDomains());
3071}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003072
Tobias Grosser808cd692015-07-14 09:33:13 +00003073void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3074 auto *S = isl_schedule_from_domain(getDomains());
3075 S = isl_schedule_insert_partial_schedule(
3076 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3077 isl_schedule_free(Schedule);
3078 Schedule = S;
3079}
3080
3081void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3082 isl_schedule_free(Schedule);
3083 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003084}
3085
3086bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3087 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003088 for (ScopStmt &Stmt : *this) {
3089 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003090 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3091 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3092
3093 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3094 isl_union_set_free(StmtDomain);
3095 isl_union_set_free(NewStmtDomain);
3096 continue;
3097 }
3098
3099 Changed = true;
3100
3101 isl_union_set_free(StmtDomain);
3102 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3103
3104 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003105 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003106 isl_union_set_free(NewStmtDomain);
3107 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003108 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003109 }
3110 isl_union_set_free(Domain);
3111 return Changed;
3112}
3113
Tobias Grosser75805372011-04-29 06:27:02 +00003114ScalarEvolution *Scop::getSE() const { return SE; }
3115
Johannes Doerfertf5673802015-10-01 23:48:18 +00003116bool Scop::isIgnored(RegionNode *RN) {
3117 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003118
Johannes Doerfertf5673802015-10-01 23:48:18 +00003119 // Check if there are accesses contained.
3120 bool ContainsAccesses = false;
3121 if (!RN->isSubRegion())
3122 ContainsAccesses = getAccessFunctions(BB);
3123 else
3124 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3125 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3126 if (!ContainsAccesses)
3127 return true;
3128
3129 // Check for reachability via non-error blocks.
3130 if (!DomainMap.count(BB))
3131 return true;
3132
3133 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003134 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003135 return true;
3136
3137 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003138}
3139
Tobias Grosser808cd692015-07-14 09:33:13 +00003140struct MapToDimensionDataTy {
3141 int N;
3142 isl_union_pw_multi_aff *Res;
3143};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003144
Tobias Grosser808cd692015-07-14 09:33:13 +00003145// @brief Create a function that maps the elements of 'Set' to its N-th
3146// dimension.
3147//
3148// The result is added to 'User->Res'.
3149//
3150// @param Set The input set.
3151// @param N The dimension to map to.
3152//
3153// @returns Zero if no error occurred, non-zero otherwise.
3154static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3155 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3156 int Dim;
3157 isl_space *Space;
3158 isl_pw_multi_aff *PMA;
3159
3160 Dim = isl_set_dim(Set, isl_dim_set);
3161 Space = isl_set_get_space(Set);
3162 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3163 Dim - Data->N);
3164 if (Data->N > 1)
3165 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3166 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3167
3168 isl_set_free(Set);
3169
3170 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003171}
3172
Tobias Grosser808cd692015-07-14 09:33:13 +00003173// @brief Create a function that maps the elements of Domain to their Nth
3174// dimension.
3175//
3176// @param Domain The set of elements to map.
3177// @param N The dimension to map to.
3178static __isl_give isl_multi_union_pw_aff *
3179mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003180 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3181 isl_union_set_free(Domain);
3182 return nullptr;
3183 }
3184
Tobias Grosser808cd692015-07-14 09:33:13 +00003185 struct MapToDimensionDataTy Data;
3186 isl_space *Space;
3187
3188 Space = isl_union_set_get_space(Domain);
3189 Data.N = N;
3190 Data.Res = isl_union_pw_multi_aff_empty(Space);
3191 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3192 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3193
3194 isl_union_set_free(Domain);
3195 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3196}
3197
Michael Kruse9d080092015-09-11 21:41:48 +00003198ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003199 ScopStmt *Stmt;
3200 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003201 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003202 Stmt = &Stmts.back();
3203 StmtMap[BB] = Stmt;
3204 } else {
3205 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003206 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003207 Stmt = &Stmts.back();
3208 for (BasicBlock *BB : R->blocks())
3209 StmtMap[BB] = Stmt;
3210 }
3211 return Stmt;
3212}
3213
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003214void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003215 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003216 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003217
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003218 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003219 Loop *L = getLoopSurroundingRegion(*R, LI);
3220 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003221 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003222 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003223 auto *UDomain = isl_union_set_from_set(Domain);
3224 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003225 LSchedulePair.first = StmtSchedule;
3226 return;
3227 }
3228
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003229 ReversePostOrderTraversal<Region *> RTraversal(R);
3230 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003231
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003232 if (RN->isSubRegion()) {
3233 Region *SubRegion = RN->getNodeAs<Region>();
3234 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003235 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003236 continue;
3237 }
Tobias Grosser75805372011-04-29 06:27:02 +00003238 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003239
3240 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003241 if (!getRegion().contains(L))
3242 L = getLoopSurroundingRegion(getRegion(), LI);
3243
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003244 int LD = getRelativeLoopDepth(L);
3245 auto &LSchedulePair = LoopSchedules[L];
3246 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3247
Michael Krusecac948e2015-10-02 13:53:07 +00003248 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3249 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3250 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003251 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3252 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3253 LSchedulePair.first =
3254 combineInSequence(LSchedulePair.first, StmtSchedule);
3255 }
3256
3257 unsigned NumVisited = LSchedulePair.second;
3258 while (L && NumVisited == L->getNumBlocks()) {
3259 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3260 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3261 LSchedulePair.first =
3262 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3263
3264 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003265
3266 // Either we have a proper loop and we also build a schedule for the
3267 // parent loop or we have a infinite loop that does not have a proper
3268 // parent loop. In the former case this conditional will be skipped, in
3269 // the latter case however we will break here as we do not build a domain
3270 // nor a schedule for a infinite loop.
3271 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3272 if (!LoopSchedules.count(PL))
3273 break;
3274
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003275 auto &PSchedulePair = LoopSchedules[PL];
3276 PSchedulePair.first =
3277 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3278 PSchedulePair.second += NumVisited;
3279
3280 L = PL;
3281 NumVisited = PSchedulePair.second;
3282 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003283 }
Tobias Grosser75805372011-04-29 06:27:02 +00003284}
3285
Johannes Doerfert7c494212014-10-31 23:13:39 +00003286ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003287 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003288 if (StmtMapIt == StmtMap.end())
3289 return nullptr;
3290 return StmtMapIt->second;
3291}
3292
Johannes Doerfert96425c22015-08-30 21:13:53 +00003293int Scop::getRelativeLoopDepth(const Loop *L) const {
3294 Loop *OuterLoop =
3295 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3296 if (!OuterLoop)
3297 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003298 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3299}
3300
Michael Krused868b5d2015-09-10 15:25:24 +00003301void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003302 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003303
3304 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3305 // true, are not modeled as ordinary PHI nodes as they are not part of the
3306 // region. However, we model the operands in the predecessor blocks that are
3307 // part of the region as regular scalar accesses.
3308
3309 // If we can synthesize a PHI we can skip it, however only if it is in
3310 // the region. If it is not it can only be in the exit block of the region.
3311 // In this case we model the operands but not the PHI itself.
3312 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3313 return;
3314
3315 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3316 // detection. Hence, the PHI is a load of a new memory location in which the
3317 // incoming value was written at the end of the incoming basic block.
3318 bool OnlyNonAffineSubRegionOperands = true;
3319 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3320 Value *Op = PHI->getIncomingValue(u);
3321 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3322
3323 // Do not build scalar dependences inside a non-affine subregion.
3324 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3325 continue;
3326
3327 OnlyNonAffineSubRegionOperands = false;
3328
3329 if (!R.contains(OpBB))
3330 continue;
3331
3332 Instruction *OpI = dyn_cast<Instruction>(Op);
3333 if (OpI) {
3334 BasicBlock *OpIBB = OpI->getParent();
3335 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3336 // we have to insert a scalar dependence from the definition of OpI to
3337 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003338 if (scop->getStmtForBasicBlock(OpIBB) !=
3339 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003340 addScalarReadAccess(OpI, PHI, OpBB);
3341 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003342 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003343 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003344 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003345 }
3346
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003347 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003348 }
3349
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003350 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3351 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003352 }
3353}
3354
Michael Krused868b5d2015-09-10 15:25:24 +00003355bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3356 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003357 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3358 if (isIgnoredIntrinsic(Inst))
3359 return false;
3360
3361 bool AnyCrossStmtUse = false;
3362 BasicBlock *ParentBB = Inst->getParent();
3363
3364 for (User *U : Inst->users()) {
3365 Instruction *UI = dyn_cast<Instruction>(U);
3366
3367 // Ignore the strange user
3368 if (UI == 0)
3369 continue;
3370
3371 BasicBlock *UseParent = UI->getParent();
3372
Tobias Grosserbaffa092015-10-24 20:55:27 +00003373 // Ignore basic block local uses. A value that is defined in a scop, but
3374 // used in a PHI node in the same basic block does not count as basic block
3375 // local, as for such cases a control flow edge is passed between definition
3376 // and use.
3377 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003378 continue;
3379
Michael Krusef714d472015-11-05 13:18:43 +00003380 // Uses by PHI nodes in the entry node count as external uses in case the
3381 // use is through an incoming block that is itself not contained in the
3382 // region.
3383 if (R->getEntry() == UseParent) {
3384 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3385 bool ExternalUse = false;
3386 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3387 if (PHI->getIncomingValue(i) == Inst &&
3388 !R->contains(PHI->getIncomingBlock(i))) {
3389 ExternalUse = true;
3390 break;
3391 }
3392 }
3393
3394 if (ExternalUse) {
3395 AnyCrossStmtUse = true;
3396 continue;
3397 }
3398 }
3399 }
3400
Michael Kruse7bf39442015-09-10 12:46:52 +00003401 // Do not build scalar dependences inside a non-affine subregion.
3402 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3403 continue;
3404
Michael Kruse01cb3792015-10-17 21:07:08 +00003405 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003406 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003407 //
3408 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003409 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3410 // the control flow a different value will be assigned to the PHI node. In
3411 // case this is the case, there is no need to create an additional normal
3412 // scalar dependence. Hence, bail out before we register an "out-of-region"
3413 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003414 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3415 !R->getExitingBlock())
3416 continue;
3417
Michael Kruse7bf39442015-09-10 12:46:52 +00003418 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003419 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003420 AnyCrossStmtUse = true;
3421 continue;
3422 }
3423
3424 // If the instruction can be synthesized and the user is in the region
3425 // we do not need to add scalar dependences.
3426 if (canSynthesizeInst)
3427 continue;
3428
3429 // No need to translate these scalar dependences into polyhedral form,
3430 // because synthesizable scalars can be generated by the code generator.
3431 if (canSynthesize(UI, LI, SE, R))
3432 continue;
3433
3434 // Skip PHI nodes in the region as they handle their operands on their own.
3435 if (isa<PHINode>(UI))
3436 continue;
3437
3438 // Now U is used in another statement.
3439 AnyCrossStmtUse = true;
3440
3441 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003442 // Use the def instruction as base address of the MemoryAccess, so that it
3443 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003444 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003445 }
3446
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003447 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003448 for (Value *Op : Inst->operands()) {
3449 if (canSynthesize(Op, LI, SE, R))
3450 continue;
3451
3452 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3453 if (R->contains(OpInst))
3454 continue;
3455
3456 if (isa<Constant>(Op))
3457 continue;
3458
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003459 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003460 }
3461 }
3462
3463 return AnyCrossStmtUse;
3464}
3465
3466extern MapInsnToMemAcc InsnToMemAcc;
3467
Michael Krusee2bccbb2015-09-18 19:59:43 +00003468void ScopInfo::buildMemoryAccess(
3469 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003470 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3471 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003472 unsigned Size;
3473 Type *SizeType;
3474 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003475 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003476
3477 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3478 SizeType = Load->getType();
3479 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003480 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003481 Val = Load;
3482 } else {
3483 StoreInst *Store = cast<StoreInst>(Inst);
3484 SizeType = Store->getValueOperand()->getType();
3485 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003486 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003487 Val = Store->getValueOperand();
3488 }
3489
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003490 auto Address = getPointerOperand(*Inst);
3491
3492 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003493 const SCEVUnknown *BasePointer =
3494 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3495
3496 assert(BasePointer && "Could not find base pointer");
3497 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3498
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003499 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3500 auto NewAddress = Address;
3501 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3502 auto Src = BitCast->getOperand(0);
3503 auto SrcTy = Src->getType();
3504 auto DstTy = BitCast->getType();
3505 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3506 NewAddress = Src;
3507 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003508
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003509 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3510 std::vector<const SCEV *> Subscripts;
3511 std::vector<int> Sizes;
3512 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3513 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003514
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003515 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003516
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003517 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003518 for (auto Subscript : Subscripts) {
3519 InvariantLoadsSetTy AccessILS;
3520 AllAffineSubcripts =
3521 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3522
3523 for (LoadInst *LInst : AccessILS)
3524 if (!ScopRIL.count(LInst))
3525 AllAffineSubcripts = false;
3526
3527 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003528 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003529 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003530
3531 if (AllAffineSubcripts && Sizes.size() > 0) {
3532 for (auto V : Sizes)
3533 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3534 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003535 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003536 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003537
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003538 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3539 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003540 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003541 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003542 }
3543 }
3544
Michael Kruse7bf39442015-09-10 12:46:52 +00003545 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003546 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003547 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3548 AccItr->second.DelinearizedSubscripts,
3549 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003550 return;
3551 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003552
3553 // Check if the access depends on a loop contained in a non-affine subregion.
3554 bool isVariantInNonAffineLoop = false;
3555 if (BoxedLoops) {
3556 SetVector<const Loop *> Loops;
3557 findLoops(AccessFunction, Loops);
3558 for (const Loop *L : Loops)
3559 if (BoxedLoops->count(L))
3560 isVariantInNonAffineLoop = true;
3561 }
3562
Johannes Doerfert09e36972015-10-07 20:17:36 +00003563 InvariantLoadsSetTy AccessILS;
3564 bool IsAffine =
3565 !isVariantInNonAffineLoop &&
3566 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3567
3568 for (LoadInst *LInst : AccessILS)
3569 if (!ScopRIL.count(LInst))
3570 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003571
Michael Krusecaac2b62015-09-26 15:51:44 +00003572 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003573 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003574 const SCEV *SizeSCEV =
3575 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003576
Michael Krusee2bccbb2015-09-18 19:59:43 +00003577 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3578 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003579
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003580 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3581 ArrayRef<const SCEV *>(AccessFunction),
3582 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003583}
3584
Michael Krused868b5d2015-09-10 15:25:24 +00003585void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003586
3587 if (SD->isNonAffineSubRegion(&SR, &R)) {
3588 for (BasicBlock *BB : SR.blocks())
3589 buildAccessFunctions(R, *BB, &SR);
3590 return;
3591 }
3592
3593 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3594 if (I->isSubRegion())
3595 buildAccessFunctions(R, *I->getNodeAs<Region>());
3596 else
3597 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3598}
3599
Michael Krusecac948e2015-10-02 13:53:07 +00003600void ScopInfo::buildStmts(Region &SR) {
3601 Region *R = getRegion();
3602
3603 if (SD->isNonAffineSubRegion(&SR, R)) {
3604 scop->addScopStmt(nullptr, &SR);
3605 return;
3606 }
3607
3608 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3609 if (I->isSubRegion())
3610 buildStmts(*I->getNodeAs<Region>());
3611 else
3612 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3613}
3614
Michael Krused868b5d2015-09-10 15:25:24 +00003615void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3616 Region *NonAffineSubRegion,
3617 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003618 Loop *L = LI->getLoopFor(&BB);
3619
3620 // The set of loops contained in non-affine subregions that are part of R.
3621 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3622
Johannes Doerfert09e36972015-10-07 20:17:36 +00003623 // The set of loads that are required to be invariant.
3624 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3625
Michael Kruse7bf39442015-09-10 12:46:52 +00003626 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003627 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003628
3629 PHINode *PHI = dyn_cast<PHINode>(Inst);
3630 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003631 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003632
3633 // For the exit block we stop modeling after the last PHI node.
3634 if (!PHI && IsExitBlock)
3635 break;
3636
Johannes Doerfert09e36972015-10-07 20:17:36 +00003637 // TODO: At this point we only know that elements of ScopRIL have to be
3638 // invariant and will be hoisted for the SCoP to be processed. Though,
3639 // there might be other invariant accesses that will be hoisted and
3640 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003641 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003642 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003643
3644 if (isIgnoredIntrinsic(Inst))
3645 continue;
3646
Johannes Doerfert09e36972015-10-07 20:17:36 +00003647 // Do not build scalar dependences for required invariant loads as we will
3648 // hoist them later on anyway or drop the SCoP if we cannot.
3649 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3650 continue;
3651
Michael Kruse7bf39442015-09-10 12:46:52 +00003652 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003653 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003654 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003655 }
3656 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003657}
Michael Kruse7bf39442015-09-10 12:46:52 +00003658
Michael Kruse2d0ece92015-09-24 11:41:21 +00003659void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3660 MemoryAccess::AccessType Type,
3661 Value *BaseAddress, unsigned ElemBytes,
3662 bool Affine, Value *AccessValue,
3663 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003664 ArrayRef<const SCEV *> Sizes,
3665 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003666 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3667
3668 // Do not create a memory access for anything not in the SCoP. It would be
3669 // ignored anyway.
3670 if (!Stmt)
3671 return;
3672
Michael Krusee2bccbb2015-09-18 19:59:43 +00003673 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003674 Value *BaseAddr = BaseAddress;
3675 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3676
Michael Krusecac948e2015-10-02 13:53:07 +00003677 bool isApproximated =
3678 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3679 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3680 Type = MemoryAccess::MAY_WRITE;
3681
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003682 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003683 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003684 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003685}
3686
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003687void ScopInfo::addExplicitAccess(
3688 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3689 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3690 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3691 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3692 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3693 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003694 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3695 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003696}
3697void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3698 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3699 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003700 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003701}
3702void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3703 assert(!isa<PHINode>(User));
3704 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3705 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003706 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003707}
3708void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3709 BasicBlock *UserBB) {
3710 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003711 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3712 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003713}
3714void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3715 Value *IncomingValue, bool IsExitBlock) {
3716 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3717 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3718 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003719 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003720}
3721void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3722 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003723 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3724 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003725}
3726
Michael Kruse76e924d2015-09-30 09:16:07 +00003727void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003728 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003729 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003730
Michael Krusecac948e2015-10-02 13:53:07 +00003731 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003732 buildAccessFunctions(R, R);
3733
3734 // In case the region does not have an exiting block we will later (during
3735 // code generation) split the exit block. This will move potential PHI nodes
3736 // from the current exit block into the new region exiting block. Hence, PHI
3737 // nodes that are at this point not part of the region will be.
3738 // To handle these PHI nodes later we will now model their operands as scalar
3739 // accesses. Note that we do not model anything in the exit block if we have
3740 // an exiting block in the region, as there will not be any splitting later.
3741 if (!R.getExitingBlock())
3742 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3743
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003744 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003745}
3746
Michael Krused868b5d2015-09-10 15:25:24 +00003747void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003748 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003749 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003750 return;
3751 }
3752
Michael Kruse9d080092015-09-11 21:41:48 +00003753 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003754}
3755
Michael Krused868b5d2015-09-10 15:25:24 +00003756void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003757 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003758 if (scop) {
3759 delete scop;
3760 scop = 0;
3761 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003762}
3763
3764//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003765ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003766 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003767 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003768}
3769
3770ScopInfo::~ScopInfo() {
3771 clear();
3772 isl_ctx_free(ctx);
3773}
3774
Tobias Grosser75805372011-04-29 06:27:02 +00003775void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003776 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003777 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003778 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003779 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3780 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003781 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003782 AU.setPreservesAll();
3783}
3784
3785bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003786 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003787
Michael Krused868b5d2015-09-10 15:25:24 +00003788 if (!SD->isMaxRegionInScop(*R))
3789 return false;
3790
3791 Function *F = R->getEntry()->getParent();
3792 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3793 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3794 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3795 TD = &F->getParent()->getDataLayout();
3796 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003797
Michael Kruse76e924d2015-09-30 09:16:07 +00003798 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003799
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003800 DEBUG(scop->print(dbgs()));
3801
Michael Kruseafe06702015-10-02 16:33:27 +00003802 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003803 delete scop;
3804 scop = nullptr;
3805 return false;
3806 }
3807
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003808 // Statistics.
3809 ++ScopFound;
3810 if (scop->getMaxLoopDepth() > 0)
3811 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003812 return false;
3813}
3814
3815char ScopInfo::ID = 0;
3816
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003817Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3818
Tobias Grosser73600b82011-10-08 00:30:40 +00003819INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3820 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003821 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003822INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003823INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003824INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003825INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003826INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003827INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003828INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3829 "Polly - Create polyhedral description of Scops", false,
3830 false)