blob: cf3e2fe7fba502afa5e6c937daf13a218fbd2782 [file] [log] [blame]
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001
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"
Michael Kruse7bf39442015-09-10 12:46:52 +000026#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000028#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000029#include "llvm/ADT/Statistic.h"
Johannes Doerfertecff11d2015-05-22 23:43:58 +000030#include "llvm/ADT/STLExtras.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfert96425c22015-08-30 21:13:53 +000032#include "llvm/ADT/PostOrderIterator.h"
Johannes Doerfertb68cffb2015-09-10 15:27:46 +000033#include "llvm/Analysis/LoopIterator.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000036#include "llvm/Analysis/RegionIterator.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000038#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000039#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000041#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000045#include "isl/schedule.h"
46#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/set.h"
48#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000049#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000050#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000051#include <sstream>
52#include <string>
53#include <vector>
54
55using namespace llvm;
56using namespace polly;
57
Chandler Carruth95fef942014-04-22 03:30:19 +000058#define DEBUG_TYPE "polly-scops"
59
Tobias Grosser74394f02013-01-14 22:40:23 +000060STATISTIC(ScopFound, "Number of valid Scops");
61STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000062
Michael Kruse7bf39442015-09-10 12:46:52 +000063static cl::opt<bool> ModelReadOnlyScalars(
64 "polly-analyze-read-only-scalars",
65 cl::desc("Model read-only scalar values in the scop description"),
66 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
67
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000068// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000069// operations can overflow easily. Additive reductions and bit operations
70// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000071static cl::opt<bool> DisableMultiplicativeReductions(
72 "polly-disable-multiplicative-reductions",
73 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
74 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075
Johannes Doerfert9143d672014-09-27 11:02:39 +000076static cl::opt<unsigned> RunTimeChecksMaxParameters(
77 "polly-rtc-max-parameters",
78 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
79 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
80
Tobias Grosser71500722015-03-28 15:11:14 +000081static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
82 "polly-rtc-max-arrays-per-group",
83 cl::desc("The maximal number of arrays to compare in each alias group."),
84 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000085static cl::opt<std::string> UserContextStr(
86 "polly-context", cl::value_desc("isl parameter set"),
87 cl::desc("Provide additional constraints on the context parameters"),
88 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000089
Tobias Grosserd83b8a82015-08-20 19:08:11 +000090static cl::opt<bool> DetectReductions("polly-detect-reductions",
91 cl::desc("Detect and exploit reductions"),
92 cl::Hidden, cl::ZeroOrMore,
93 cl::init(true), cl::cat(PollyCategory));
94
Michael Kruse7bf39442015-09-10 12:46:52 +000095//===----------------------------------------------------------------------===//
96/// Helper Classes
97
98void Comparison::print(raw_ostream &OS) const {
99 // Not yet implemented.
100}
101
Michael Kruse046dde42015-08-10 13:01:57 +0000102// Create a sequence of two schedules. Either argument may be null and is
103// interpreted as the empty schedule. Can also return null if both schedules are
104// empty.
105static __isl_give isl_schedule *
106combineInSequence(__isl_take isl_schedule *Prev,
107 __isl_take isl_schedule *Succ) {
108 if (!Prev)
109 return Succ;
110 if (!Succ)
111 return Prev;
112
113 return isl_schedule_sequence(Prev, Succ);
114}
115
Johannes Doerferte7044942015-02-24 11:58:30 +0000116static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
117 const ConstantRange &Range,
118 int dim,
119 enum isl_dim_type type) {
120 isl_val *V;
121 isl_ctx *ctx = isl_set_get_ctx(S);
122
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000123 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
124 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000129 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000132 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
133
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000134 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000135 return isl_set_union(SLB, SUB);
136 else
137 return isl_set_intersect(SLB, SUB);
138}
139
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000140static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
141 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
142 if (!BasePtrLI)
143 return nullptr;
144
145 if (!S->getRegion().contains(BasePtrLI))
146 return nullptr;
147
148 ScalarEvolution &SE = *S->getSE();
149
150 auto *OriginBaseSCEV =
151 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
152 if (!OriginBaseSCEV)
153 return nullptr;
154
155 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
156 if (!OriginBaseSCEVUnknown)
157 return nullptr;
158
159 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue());
160}
161
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000162ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Michael Kruse28468772015-09-14 15:45:33 +0000163 ArrayRef<const SCEV *> DimensionSizes, bool IsPHI,
164 Scop *S)
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000165 : BasePtr(BasePtr), ElementType(ElementType),
Michael Kruse28468772015-09-14 15:45:33 +0000166 DimensionSizes(DimensionSizes.begin(), DimensionSizes.end()),
167 IsPHI(IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +0000168 std::string BasePtrName =
169 getIslCompatibleName("MemRef_", BasePtr, IsPHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000170 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000171 for (const SCEV *Expr : DimensionSizes) {
172 isl_pw_aff *Size = S->getPwAff(Expr);
173 DimensionSizesPw.push_back(Size);
174 }
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175
176 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
177 if (BasePtrOriginSAI)
178 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000179}
180
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000181ScopArrayInfo::~ScopArrayInfo() {
182 isl_id_free(Id);
183 for (isl_pw_aff *Size : DimensionSizesPw)
184 isl_pw_aff_free(Size);
185}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000186
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000187std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
188
189int ScopArrayInfo::getElemSizeInBytes() const {
190 return ElementType->getPrimitiveSizeInBits() / 8;
191}
192
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000193isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
194
195void ScopArrayInfo::dump() const { print(errs()); }
196
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000197void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000198 OS.indent(8) << *getElementType() << " " << getName() << "[*]";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000199 for (unsigned u = 0; u < getNumberOfDimensions(); u++) {
200 OS << "[";
201
202 if (SizeAsPwAff)
203 OS << " " << DimensionSizesPw[u] << " ";
204 else
205 OS << *DimensionSizes[u];
206
207 OS << "]";
208 }
209
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000210 if (BasePtrOriginSAI)
211 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
212
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000213 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000214}
215
216const ScopArrayInfo *
217ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
218 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
219 assert(Id && "Output dimension didn't have an ID");
220 return getFromId(Id);
221}
222
223const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
224 void *User = isl_id_get_user(Id);
225 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
226 isl_id_free(Id);
227 return SAI;
228}
229
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000230const std::string
231MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
232 switch (RT) {
233 case MemoryAccess::RT_NONE:
234 llvm_unreachable("Requested a reduction operator string for a memory "
235 "access which isn't a reduction");
236 case MemoryAccess::RT_ADD:
237 return "+";
238 case MemoryAccess::RT_MUL:
239 return "*";
240 case MemoryAccess::RT_BOR:
241 return "|";
242 case MemoryAccess::RT_BXOR:
243 return "^";
244 case MemoryAccess::RT_BAND:
245 return "&";
246 }
247 llvm_unreachable("Unknown reduction type");
248 return "";
249}
250
Johannes Doerfertf6183392014-07-01 20:52:51 +0000251/// @brief Return the reduction type for a given binary operator
252static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
253 const Instruction *Load) {
254 if (!BinOp)
255 return MemoryAccess::RT_NONE;
256 switch (BinOp->getOpcode()) {
257 case Instruction::FAdd:
258 if (!BinOp->hasUnsafeAlgebra())
259 return MemoryAccess::RT_NONE;
260 // Fall through
261 case Instruction::Add:
262 return MemoryAccess::RT_ADD;
263 case Instruction::Or:
264 return MemoryAccess::RT_BOR;
265 case Instruction::Xor:
266 return MemoryAccess::RT_BXOR;
267 case Instruction::And:
268 return MemoryAccess::RT_BAND;
269 case Instruction::FMul:
270 if (!BinOp->hasUnsafeAlgebra())
271 return MemoryAccess::RT_NONE;
272 // Fall through
273 case Instruction::Mul:
274 if (DisableMultiplicativeReductions)
275 return MemoryAccess::RT_NONE;
276 return MemoryAccess::RT_MUL;
277 default:
278 return MemoryAccess::RT_NONE;
279 }
280}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000281
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000282/// @brief Derive the individual index expressions from a GEP instruction
283///
284/// This function optimistically assumes the GEP references into a fixed size
285/// array. If this is actually true, this function returns a list of array
286/// subscript expressions as SCEV as well as a list of integers describing
287/// the size of the individual array dimensions. Both lists have either equal
288/// length of the size list is one element shorter in case there is no known
289/// size available for the outermost array dimension.
290///
291/// @param GEP The GetElementPtr instruction to analyze.
292///
293/// @return A tuple with the subscript expressions and the dimension sizes.
294static std::tuple<std::vector<const SCEV *>, std::vector<int>>
295getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
296 std::vector<const SCEV *> Subscripts;
297 std::vector<int> Sizes;
298
299 Type *Ty = GEP->getPointerOperandType();
300
301 bool DroppedFirstDim = false;
302
Michael Kruse26ed65e2015-09-24 17:32:49 +0000303 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000304
305 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
306
307 if (i == 1) {
308 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
309 Ty = PtrTy->getElementType();
310 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
311 Ty = ArrayTy->getElementType();
312 } else {
313 Subscripts.clear();
314 Sizes.clear();
315 break;
316 }
317 if (auto Const = dyn_cast<SCEVConstant>(Expr))
318 if (Const->getValue()->isZero()) {
319 DroppedFirstDim = true;
320 continue;
321 }
322 Subscripts.push_back(Expr);
323 continue;
324 }
325
326 auto ArrayTy = dyn_cast<ArrayType>(Ty);
327 if (!ArrayTy) {
328 Subscripts.clear();
329 Sizes.clear();
330 break;
331 }
332
333 Subscripts.push_back(Expr);
334 if (!(DroppedFirstDim && i == 2))
335 Sizes.push_back(ArrayTy->getNumElements());
336
337 Ty = ArrayTy->getElementType();
338 }
339
340 return std::make_tuple(Subscripts, Sizes);
341}
342
Tobias Grosser75805372011-04-29 06:27:02 +0000343MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000344 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000345 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000346 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000347}
348
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000349const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
350 isl_id *ArrayId = getArrayId();
351 void *User = isl_id_get_user(ArrayId);
352 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
353 isl_id_free(ArrayId);
354 return SAI;
355}
356
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000357__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000358 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
359}
360
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000361__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
362 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000363 isl_map *Schedule, *ScheduledAccRel;
364 isl_union_set *UDomain;
365
366 UDomain = isl_union_set_from_set(getStatement()->getDomain());
367 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
368 Schedule = isl_map_from_union_map(USchedule);
369 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
370 return isl_pw_multi_aff_from_map(ScheduledAccRel);
371}
372
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000373__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000374 return isl_map_copy(AccessRelation);
375}
376
Johannes Doerferta99130f2014-10-13 12:58:03 +0000377std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000378 return stringFromIslObj(AccessRelation);
379}
380
Johannes Doerferta99130f2014-10-13 12:58:03 +0000381__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000382 return isl_map_get_space(AccessRelation);
383}
384
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000385__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000386 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000387}
388
Tobias Grosser6f730082015-09-05 07:46:47 +0000389std::string MemoryAccess::getNewAccessRelationStr() const {
390 return stringFromIslObj(NewAccessRelation);
391}
392
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000393__isl_give isl_basic_map *
394MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000395 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000396 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000397
Tobias Grosser084d8f72012-05-29 09:29:44 +0000398 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000399 isl_basic_set_universe(Statement->getDomainSpace()),
400 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000401}
402
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000403// Formalize no out-of-bound access assumption
404//
405// When delinearizing array accesses we optimistically assume that the
406// delinearized accesses do not access out of bound locations (the subscript
407// expression of each array evaluates for each statement instance that is
408// executed to a value that is larger than zero and strictly smaller than the
409// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000410// dimension for which we do not need to assume any upper bound. At this point
411// we formalize this assumption to ensure that at code generation time the
412// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000413//
414// To find the set of constraints necessary to avoid out of bound accesses, we
415// first build the set of data locations that are not within array bounds. We
416// then apply the reverse access relation to obtain the set of iterations that
417// may contain invalid accesses and reduce this set of iterations to the ones
418// that are actually executed by intersecting them with the domain of the
419// statement. If we now project out all loop dimensions, we obtain a set of
420// parameters that may cause statement instances to be executed that may
421// possibly yield out of bound memory accesses. The complement of these
422// constraints is the set of constraints that needs to be assumed to ensure such
423// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000424void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000425 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000426 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000427 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000428 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
429 isl_pw_aff *Var =
430 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
431 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
432
433 isl_set *DimOutside;
434
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000435 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000436 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000437
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000438 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
439 Statement->getNumIterators());
440 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
441 isl_space_dim(Space, isl_dim_set));
442 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
443 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000444
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000445 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000446
447 Outside = isl_set_union(Outside, DimOutside);
448 }
449
450 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
451 Outside = isl_set_intersect(Outside, Statement->getDomain());
452 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000453
454 // Remove divs to avoid the construction of overly complicated assumptions.
455 // Doing so increases the set of parameter combinations that are assumed to
456 // not appear. This is always save, but may make the resulting run-time check
457 // bail out more often than strictly necessary.
458 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000459 Outside = isl_set_complement(Outside);
460 Statement->getParent()->addAssumption(Outside);
461 isl_space_free(Space);
462}
463
Johannes Doerferte7044942015-02-24 11:58:30 +0000464void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
465 ScalarEvolution *SE = Statement->getParent()->getSE();
466
467 Value *Ptr = getPointerOperand(*getAccessInstruction());
468 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
469 return;
470
471 auto *PtrSCEV = SE->getSCEV(Ptr);
472 if (isa<SCEVCouldNotCompute>(PtrSCEV))
473 return;
474
475 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
476 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
477 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
478
479 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
480 if (Range.isFullSet())
481 return;
482
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000483 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000484 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000485 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
486 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
487
488 auto Min = LB.sdiv(APInt(BW, ElementSize));
489 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000490
491 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
492 AccessRange =
493 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
494 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
495}
496
Michael Krusee2bccbb2015-09-18 19:59:43 +0000497__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000498 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000499 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000500
501 for (int i = Size - 2; i >= 0; --i) {
502 isl_space *Space;
503 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000504 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000505
506 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
507 isl_pw_aff_free(DimSize);
508 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
509
510 Space = isl_map_get_space(AccessRelation);
511 Space = isl_space_map_from_set(isl_space_range(Space));
512 Space = isl_space_align_params(Space, SpaceSize);
513
514 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
515 isl_id_free(ParamId);
516
517 MapOne = isl_map_universe(isl_space_copy(Space));
518 for (int j = 0; j < Size; ++j)
519 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
520 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
521
522 MapTwo = isl_map_universe(isl_space_copy(Space));
523 for (int j = 0; j < Size; ++j)
524 if (j < i || j > i + 1)
525 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
526
527 isl_local_space *LS = isl_local_space_from_space(Space);
528 isl_constraint *C;
529 C = isl_equality_alloc(isl_local_space_copy(LS));
530 C = isl_constraint_set_constant_si(C, -1);
531 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
532 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
533 MapTwo = isl_map_add_constraint(MapTwo, C);
534 C = isl_equality_alloc(LS);
535 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
536 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
537 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
538 MapTwo = isl_map_add_constraint(MapTwo, C);
539 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
540
541 MapOne = isl_map_union(MapOne, MapTwo);
542 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
543 }
544 return AccessRelation;
545}
546
Michael Krusee2bccbb2015-09-18 19:59:43 +0000547void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
548 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000549
Michael Krusee2bccbb2015-09-18 19:59:43 +0000550 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000551 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000552
Michael Krusee2bccbb2015-09-18 19:59:43 +0000553 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000554 // We overapproximate non-affine accesses with a possible access to the
555 // whole array. For read accesses it does not make a difference, if an
556 // access must or may happen. However, for write accesses it is important to
557 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000558 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000559 AccessRelation =
560 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000561
Michael Krusee2bccbb2015-09-18 19:59:43 +0000562 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000563 return;
564 }
565
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000566 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000567 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000568
Michael Krusee2bccbb2015-09-18 19:59:43 +0000569 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
570 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000571
Sebastian Pop422e33f2014-06-03 18:16:31 +0000572 if (Size == 1) {
573 // For the non delinearized arrays, divide the access function of the last
574 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000575 //
576 // A stride one array access in C expressed as A[i] is expressed in
577 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
578 // two subsequent values of 'i' index two values that are stored next to
579 // each other in memory. By this division we make this characteristic
580 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000581 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000582 Affine = isl_pw_aff_scale_down_val(Affine, v);
583 }
584
585 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
586
Tobias Grosser79baa212014-04-10 08:38:02 +0000587 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000588 }
589
Michael Krusee2bccbb2015-09-18 19:59:43 +0000590 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
591 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000592
Tobias Grosser79baa212014-04-10 08:38:02 +0000593 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000594 AccessRelation = isl_map_set_tuple_id(
595 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000596 AccessRelation =
597 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
598
Michael Krusee2bccbb2015-09-18 19:59:43 +0000599 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000600 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000601 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000602}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000603
Michael Krusee2bccbb2015-09-18 19:59:43 +0000604MemoryAccess::MemoryAccess(Instruction *AccessInst, __isl_take isl_id *Id,
605 AccessType Type, Value *BaseAddress,
Michael Kruse2d0ece92015-09-24 11:41:21 +0000606 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000607 ArrayRef<const SCEV *> Subscripts,
608 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
609 bool IsPHI, StringRef BaseName)
610 : Id(Id), IsPHI(IsPHI), AccType(Type), RedType(RT_NONE), Statement(nullptr),
611 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
612 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
Michael Kruse2d0ece92015-09-24 11:41:21 +0000613 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000614 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
615 NewAccessRelation(nullptr) {}
616
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000617void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000618 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000619 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000620}
621
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000622const std::string MemoryAccess::getReductionOperatorStr() const {
623 return MemoryAccess::getReductionOperatorStr(getReductionType());
624}
625
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000626__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
627
Johannes Doerfertf6183392014-07-01 20:52:51 +0000628raw_ostream &polly::operator<<(raw_ostream &OS,
629 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000630 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000631 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000632 else
633 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000634 return OS;
635}
636
Tobias Grosser75805372011-04-29 06:27:02 +0000637void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000638 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000639 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000640 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000641 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000642 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000643 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000644 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000645 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000646 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000647 break;
648 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000649 OS << "[Reduction Type: " << getReductionType() << "] ";
650 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000651 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000652 if (hasNewAccessRelation())
653 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000654}
655
Tobias Grosser74394f02013-01-14 22:40:23 +0000656void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000657
658// Create a map in the size of the provided set domain, that maps from the
659// one element of the provided set domain to another element of the provided
660// set domain.
661// The mapping is limited to all points that are equal in all but the last
662// dimension and for which the last dimension of the input is strict smaller
663// than the last dimension of the output.
664//
665// getEqualAndLarger(set[i0, i1, ..., iX]):
666//
667// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
668// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
669//
Tobias Grosserf5338802011-10-06 00:03:35 +0000670static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000671 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000672 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000673 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000674
675 // Set all but the last dimension to be equal for the input and output
676 //
677 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
678 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000679 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000680 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000681
682 // Set the last dimension of the input to be strict smaller than the
683 // last dimension of the output.
684 //
685 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000686 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
687 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000688 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000689}
690
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000691__isl_give isl_set *
692MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000693 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000694 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000695 isl_space *Space = isl_space_range(isl_map_get_space(S));
696 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000697
Sebastian Popa00a0292012-12-18 07:46:06 +0000698 S = isl_map_reverse(S);
699 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000700
Sebastian Popa00a0292012-12-18 07:46:06 +0000701 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
702 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
703 NextScatt = isl_map_apply_domain(NextScatt, S);
704 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000705
Sebastian Popa00a0292012-12-18 07:46:06 +0000706 isl_set *Deltas = isl_map_deltas(NextScatt);
707 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000708}
709
Sebastian Popa00a0292012-12-18 07:46:06 +0000710bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000711 int StrideWidth) const {
712 isl_set *Stride, *StrideX;
713 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000714
Sebastian Popa00a0292012-12-18 07:46:06 +0000715 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000716 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000717 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
718 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
719 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
720 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000721 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000722
Tobias Grosser28dd4862012-01-24 16:42:16 +0000723 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000724 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000725
Tobias Grosser28dd4862012-01-24 16:42:16 +0000726 return IsStrideX;
727}
728
Sebastian Popa00a0292012-12-18 07:46:06 +0000729bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
730 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000731}
732
Tobias Grosser79baa212014-04-10 08:38:02 +0000733bool MemoryAccess::isScalar() const {
734 return isl_map_n_out(AccessRelation) == 0;
735}
736
Sebastian Popa00a0292012-12-18 07:46:06 +0000737bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
738 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000739}
740
Tobias Grosser166c4222015-09-05 07:46:40 +0000741void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
742 isl_map_free(NewAccessRelation);
743 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000744}
Tobias Grosser75805372011-04-29 06:27:02 +0000745
746//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000747
Tobias Grosser808cd692015-07-14 09:33:13 +0000748isl_map *ScopStmt::getSchedule() const {
749 isl_set *Domain = getDomain();
750 if (isl_set_is_empty(Domain)) {
751 isl_set_free(Domain);
752 return isl_map_from_aff(
753 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
754 }
755 auto *Schedule = getParent()->getSchedule();
756 Schedule = isl_union_map_intersect_domain(
757 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
758 if (isl_union_map_is_empty(Schedule)) {
759 isl_set_free(Domain);
760 isl_union_map_free(Schedule);
761 return isl_map_from_aff(
762 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
763 }
764 auto *M = isl_map_from_union_map(Schedule);
765 M = isl_map_coalesce(M);
766 M = isl_map_gist_domain(M, Domain);
767 M = isl_map_coalesce(M);
768 return M;
769}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000770
Johannes Doerfert574182d2015-08-12 10:19:50 +0000771__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000772 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
773 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000774}
775
Tobias Grosser37eb4222014-02-20 21:43:54 +0000776void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
777 assert(isl_set_is_subset(NewDomain, Domain) &&
778 "New domain is not a subset of old domain!");
779 isl_set_free(Domain);
780 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000781}
782
Michael Kruse9d080092015-09-11 21:41:48 +0000783void ScopStmt::buildAccesses(BasicBlock *Block, bool isApproximated) {
784 AccFuncSetType *AFS = Parent.getAccessFunctions(Block);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000785 if (!AFS)
786 return;
787
Michael Krusee2bccbb2015-09-18 19:59:43 +0000788 for (auto &Access : *AFS) {
789 Instruction *AccessInst = Access.getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000790 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000791
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000792 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusee2bccbb2015-09-18 19:59:43 +0000793 Access.getBaseAddr(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000794
Michael Krusee2bccbb2015-09-18 19:59:43 +0000795 if (isApproximated && Access.isMustWrite())
796 Access.AccType = MemoryAccess::MAY_WRITE;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000797
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000798 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
799 if (!MAL)
800 MAL = new MemoryAccessList();
Michael Krusee2bccbb2015-09-18 19:59:43 +0000801 Access.setStatement(this);
802 Access.buildAccessRelation(SAI);
803 MAL->emplace_front(&Access);
804 MemAccs.push_back(MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000805 }
806}
807
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000808void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000809 for (MemoryAccess *MA : *this)
810 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000811
812 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000813}
814
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000815/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
816static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
817 void *User) {
818 isl_set **BoundedParts = static_cast<isl_set **>(User);
819 if (isl_basic_set_is_bounded(BSet))
820 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
821 else
822 isl_basic_set_free(BSet);
823 return isl_stat_ok;
824}
825
826/// @brief Return the bounded parts of @p S.
827static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
828 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
829 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
830 isl_set_free(S);
831 return BoundedParts;
832}
833
834/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
835///
836/// @returns A separation of @p S into first an unbounded then a bounded subset,
837/// both with regards to the dimension @p Dim.
838static std::pair<__isl_give isl_set *, __isl_give isl_set *>
839partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
840
841 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000842 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000843
844 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000845 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000846
847 // Remove dimensions that are greater than Dim as they are not interesting.
848 assert(NumDimsS >= Dim + 1);
849 OnlyDimS =
850 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
851
852 // Create artificial parametric upper bounds for dimensions smaller than Dim
853 // as we are not interested in them.
854 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
855 for (unsigned u = 0; u < Dim; u++) {
856 isl_constraint *C = isl_inequality_alloc(
857 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
858 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
859 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
860 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
861 }
862
863 // Collect all bounded parts of OnlyDimS.
864 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
865
866 // Create the dimensions greater than Dim again.
867 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
868 NumDimsS - Dim - 1);
869
870 // Remove the artificial upper bound parameters again.
871 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
872
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000873 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000874 return std::make_pair(UnboundedParts, BoundedParts);
875}
876
Johannes Doerfert96425c22015-08-30 21:13:53 +0000877static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
878 isl_pw_aff *L, isl_pw_aff *R) {
879 switch (Pred) {
880 case ICmpInst::ICMP_EQ:
881 return isl_pw_aff_eq_set(L, R);
882 case ICmpInst::ICMP_NE:
883 return isl_pw_aff_ne_set(L, R);
884 case ICmpInst::ICMP_SLT:
885 return isl_pw_aff_lt_set(L, R);
886 case ICmpInst::ICMP_SLE:
887 return isl_pw_aff_le_set(L, R);
888 case ICmpInst::ICMP_SGT:
889 return isl_pw_aff_gt_set(L, R);
890 case ICmpInst::ICMP_SGE:
891 return isl_pw_aff_ge_set(L, R);
892 case ICmpInst::ICMP_ULT:
893 return isl_pw_aff_lt_set(L, R);
894 case ICmpInst::ICMP_UGT:
895 return isl_pw_aff_gt_set(L, R);
896 case ICmpInst::ICMP_ULE:
897 return isl_pw_aff_le_set(L, R);
898 case ICmpInst::ICMP_UGE:
899 return isl_pw_aff_ge_set(L, R);
900 default:
901 llvm_unreachable("Non integer predicate not supported");
902 }
903}
904
905/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
906///
907/// This will fill @p ConditionSets with the conditions under which control
908/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
909/// have as many elements as @p BI has successors.
910static void
911buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
912 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
913
914 if (BI->isUnconditional()) {
915 ConditionSets.push_back(isl_set_copy(Domain));
916 return;
917 }
918
919 Value *Condition = BI->getCondition();
920
921 isl_set *ConsequenceCondSet = nullptr;
922 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
923 if (CCond->isZero())
924 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
925 else
926 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
927 } else {
928 auto *ICond = dyn_cast<ICmpInst>(Condition);
929 assert(ICond &&
930 "Condition of exiting branch was neither constant nor ICmp!");
931
932 ScalarEvolution &SE = *S.getSE();
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000933 BasicBlock *BB = BI->getParent();
Johannes Doerfert96425c22015-08-30 21:13:53 +0000934 isl_pw_aff *LHS, *RHS;
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000935 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
936 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000937 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000938
939 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
940 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
941 ConsequenceCondSet =
942 isl_set_set_dim_id(ConsequenceCondSet, isl_dim_set, u, DimId);
943 }
Johannes Doerfert96425c22015-08-30 21:13:53 +0000944 }
945
946 assert(ConsequenceCondSet);
947 isl_set *AlternativeCondSet =
948 isl_set_complement(isl_set_copy(ConsequenceCondSet));
949
950 ConditionSets.push_back(isl_set_coalesce(
951 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
952 ConditionSets.push_back(isl_set_coalesce(
953 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
954}
955
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000956void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000957 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000958
Tobias Grosser084d8f72012-05-29 09:29:44 +0000959 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
960
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000961 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000962 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000963}
964
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000965void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000966 isl_ctx *Ctx = Parent.getIslCtx();
967 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
968 Type *Ty = GEP->getPointerOperandType();
969 ScalarEvolution &SE = *Parent.getSE();
970
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000971 std::vector<const SCEV *> Subscripts;
972 std::vector<int> Sizes;
973
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000974 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000975
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000976 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000977 Ty = PtrTy->getElementType();
978 }
979
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000980 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000981
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000982 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000983
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000984 for (size_t i = 0; i < Sizes.size(); i++) {
985 auto Expr = Subscripts[i + IndexOffset];
986 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000987
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000988 if (!isAffineExpr(&Parent.getRegion(), Expr, SE))
989 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000990
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000991 isl_pw_aff *AccessOffset = getPwAff(Expr);
992 AccessOffset =
993 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000994
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000995 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
996 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000997
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000998 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
999 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1000 OutOfBound = isl_set_params(OutOfBound);
1001 isl_set *InBound = isl_set_complement(OutOfBound);
1002 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001003
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001004 // A => B == !A or B
1005 isl_set *InBoundIfExecuted =
1006 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001007
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001008 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001009 }
1010
1011 isl_local_space_free(LSpace);
1012}
1013
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001014void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1015 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001016 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1017 deriveAssumptionsFromGEP(GEP);
1018}
1019
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001020void ScopStmt::collectSurroundingLoops() {
1021 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1022 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1023 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1024 isl_id_free(DimId);
1025 }
1026}
1027
Michael Kruse9d080092015-09-11 21:41:48 +00001028ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001029 : Parent(parent), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001030
Tobias Grosser16c44032015-07-09 07:31:45 +00001031 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001032
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001033 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001034 collectSurroundingLoops();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001035
1036 BasicBlock *EntryBB = R.getEntry();
1037 for (BasicBlock *Block : R.blocks()) {
Michael Kruse9d080092015-09-11 21:41:48 +00001038 buildAccesses(Block, Block != EntryBB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001039 deriveAssumptions(Block);
1040 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001041 if (DetectReductions)
1042 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001043}
1044
Michael Kruse9d080092015-09-11 21:41:48 +00001045ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001046 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001047
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001048 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001049
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001050 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001051 collectSurroundingLoops();
Michael Kruse9d080092015-09-11 21:41:48 +00001052 buildAccesses(BB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001053 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001054 if (DetectReductions)
1055 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001056}
1057
Johannes Doerferte58a0122014-06-27 20:31:28 +00001058/// @brief Collect loads which might form a reduction chain with @p StoreMA
1059///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001060/// Check if the stored value for @p StoreMA is a binary operator with one or
1061/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001062/// used only once (by @p StoreMA) and its load operands are also used only
1063/// once, we have found a possible reduction chain. It starts at an operand
1064/// load and includes the binary operator and @p StoreMA.
1065///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001066/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001067/// escape this block or into any other store except @p StoreMA.
1068void ScopStmt::collectCandiateReductionLoads(
1069 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1070 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1071 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001072 return;
1073
1074 // Skip if there is not one binary operator between the load and the store
1075 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001076 if (!BinOp)
1077 return;
1078
1079 // Skip if the binary operators has multiple uses
1080 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001081 return;
1082
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001083 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001084 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1085 return;
1086
Johannes Doerfert9890a052014-07-01 00:32:29 +00001087 // Skip if the binary operator is outside the current SCoP
1088 if (BinOp->getParent() != Store->getParent())
1089 return;
1090
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001091 // Skip if it is a multiplicative reduction and we disabled them
1092 if (DisableMultiplicativeReductions &&
1093 (BinOp->getOpcode() == Instruction::Mul ||
1094 BinOp->getOpcode() == Instruction::FMul))
1095 return;
1096
Johannes Doerferte58a0122014-06-27 20:31:28 +00001097 // Check the binary operator operands for a candidate load
1098 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1099 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1100 if (!PossibleLoad0 && !PossibleLoad1)
1101 return;
1102
1103 // A load is only a candidate if it cannot escape (thus has only this use)
1104 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001105 if (PossibleLoad0->getParent() == Store->getParent())
1106 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001107 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001108 if (PossibleLoad1->getParent() == Store->getParent())
1109 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001110}
1111
1112/// @brief Check for reductions in this ScopStmt
1113///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001114/// Iterate over all store memory accesses and check for valid binary reduction
1115/// like chains. For all candidates we check if they have the same base address
1116/// and there are no other accesses which overlap with them. The base address
1117/// check rules out impossible reductions candidates early. The overlap check,
1118/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001119/// guarantees that none of the intermediate results will escape during
1120/// execution of the loop nest. We basically check here that no other memory
1121/// access can access the same memory as the potential reduction.
1122void ScopStmt::checkForReductions() {
1123 SmallVector<MemoryAccess *, 2> Loads;
1124 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1125
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001126 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001127 // stores and collecting possible reduction loads.
1128 for (MemoryAccess *StoreMA : MemAccs) {
1129 if (StoreMA->isRead())
1130 continue;
1131
1132 Loads.clear();
1133 collectCandiateReductionLoads(StoreMA, Loads);
1134 for (MemoryAccess *LoadMA : Loads)
1135 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1136 }
1137
1138 // Then check each possible candidate pair.
1139 for (const auto &CandidatePair : Candidates) {
1140 bool Valid = true;
1141 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1142 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1143
1144 // Skip those with obviously unequal base addresses.
1145 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1146 isl_map_free(LoadAccs);
1147 isl_map_free(StoreAccs);
1148 continue;
1149 }
1150
1151 // And check if the remaining for overlap with other memory accesses.
1152 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1153 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1154 isl_set *AllAccs = isl_map_range(AllAccsRel);
1155
1156 for (MemoryAccess *MA : MemAccs) {
1157 if (MA == CandidatePair.first || MA == CandidatePair.second)
1158 continue;
1159
1160 isl_map *AccRel =
1161 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1162 isl_set *Accs = isl_map_range(AccRel);
1163
1164 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1165 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1166 Valid = Valid && isl_set_is_empty(OverlapAccs);
1167 isl_set_free(OverlapAccs);
1168 }
1169 }
1170
1171 isl_set_free(AllAccs);
1172 if (!Valid)
1173 continue;
1174
Johannes Doerfertf6183392014-07-01 20:52:51 +00001175 const LoadInst *Load =
1176 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1177 MemoryAccess::ReductionType RT =
1178 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1179
Johannes Doerferte58a0122014-06-27 20:31:28 +00001180 // If no overlapping access was found we mark the load and store as
1181 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001182 CandidatePair.first->markAsReductionLike(RT);
1183 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001184 }
Tobias Grosser75805372011-04-29 06:27:02 +00001185}
1186
Tobias Grosser74394f02013-01-14 22:40:23 +00001187std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001188
Tobias Grosser54839312015-04-21 11:37:25 +00001189std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001190 auto *S = getSchedule();
1191 auto Str = stringFromIslObj(S);
1192 isl_map_free(S);
1193 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001194}
1195
Tobias Grosser74394f02013-01-14 22:40:23 +00001196unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001197
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001198unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001199
Tobias Grosser75805372011-04-29 06:27:02 +00001200const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1201
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001202const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001203 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001204}
1205
Tobias Grosser74394f02013-01-14 22:40:23 +00001206isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001207
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001208__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001209
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001210__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001211 return isl_set_get_space(Domain);
1212}
1213
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001214__isl_give isl_id *ScopStmt::getDomainId() const {
1215 return isl_set_get_tuple_id(Domain);
1216}
Tobias Grossercd95b772012-08-30 11:49:38 +00001217
Tobias Grosser75805372011-04-29 06:27:02 +00001218ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001219 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001220 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001221}
1222
1223void ScopStmt::print(raw_ostream &OS) const {
1224 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001225 OS.indent(12) << "Domain :=\n";
1226
1227 if (Domain) {
1228 OS.indent(16) << getDomainStr() << ";\n";
1229 } else
1230 OS.indent(16) << "n/a\n";
1231
Tobias Grosser54839312015-04-21 11:37:25 +00001232 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001233
1234 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001235 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001236 } else
1237 OS.indent(16) << "n/a\n";
1238
Tobias Grosser083d3d32014-06-28 08:59:45 +00001239 for (MemoryAccess *Access : MemAccs)
1240 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001241}
1242
1243void ScopStmt::dump() const { print(dbgs()); }
1244
1245//===----------------------------------------------------------------------===//
1246/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001247
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001248void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001249 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1250 isl_set_free(Context);
1251 Context = NewContext;
1252}
1253
Tobias Grosserabfbe632013-02-05 12:09:06 +00001254void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001255 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001256 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001257 if (ParameterIds.find(Parameter) != ParameterIds.end())
1258 continue;
1259
1260 int dimension = Parameters.size();
1261
1262 Parameters.push_back(Parameter);
1263 ParameterIds[Parameter] = dimension;
1264 }
1265}
1266
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001267__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1268 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001269
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001270 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001271 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001272
Tobias Grosser8f99c162011-11-15 11:38:55 +00001273 std::string ParameterName;
1274
1275 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1276 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001277 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001278 }
1279
1280 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001281 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001282
Tobias Grosser20532b82014-04-11 17:56:49 +00001283 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1284 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001285}
Tobias Grosser75805372011-04-29 06:27:02 +00001286
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001287isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1288 isl_set *DomainContext = isl_union_set_params(getDomains());
1289 return isl_set_intersect_params(C, DomainContext);
1290}
1291
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001292void Scop::buildBoundaryContext() {
1293 BoundaryContext = Affinator.getWrappingContext();
1294 BoundaryContext = isl_set_complement(BoundaryContext);
1295 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1296}
1297
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001298void Scop::addUserContext() {
1299 if (UserContextStr.empty())
1300 return;
1301
1302 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1303 isl_space *Space = getParamSpace();
1304 if (isl_space_dim(Space, isl_dim_param) !=
1305 isl_set_dim(UserContext, isl_dim_param)) {
1306 auto SpaceStr = isl_space_to_str(Space);
1307 errs() << "Error: the context provided in -polly-context has not the same "
1308 << "number of dimensions than the computed context. Due to this "
1309 << "mismatch, the -polly-context option is ignored. Please provide "
1310 << "the context in the parameter space: " << SpaceStr << ".\n";
1311 free(SpaceStr);
1312 isl_set_free(UserContext);
1313 isl_space_free(Space);
1314 return;
1315 }
1316
1317 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1318 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1319 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1320
1321 if (strcmp(NameContext, NameUserContext) != 0) {
1322 auto SpaceStr = isl_space_to_str(Space);
1323 errs() << "Error: the name of dimension " << i
1324 << " provided in -polly-context "
1325 << "is '" << NameUserContext << "', but the name in the computed "
1326 << "context is '" << NameContext
1327 << "'. Due to this name mismatch, "
1328 << "the -polly-context option is ignored. Please provide "
1329 << "the context in the parameter space: " << SpaceStr << ".\n";
1330 free(SpaceStr);
1331 isl_set_free(UserContext);
1332 isl_space_free(Space);
1333 return;
1334 }
1335
1336 UserContext =
1337 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1338 isl_space_get_dim_id(Space, isl_dim_param, i));
1339 }
1340
1341 Context = isl_set_intersect(Context, UserContext);
1342 isl_space_free(Space);
1343}
1344
Tobias Grosser6be480c2011-11-08 15:41:13 +00001345void Scop::buildContext() {
1346 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001347 Context = isl_set_universe(isl_space_copy(Space));
1348 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001349}
1350
Tobias Grosser18daaca2012-05-22 10:47:27 +00001351void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001352 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001353 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001354
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001355 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001356
Johannes Doerferte7044942015-02-24 11:58:30 +00001357 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001358 }
1359}
1360
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001361void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001362 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001363 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001364
Tobias Grosser083d3d32014-06-28 08:59:45 +00001365 for (const auto &ParamID : ParameterIds) {
1366 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001367 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001368 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001369 }
1370
1371 // Align the parameters of all data structures to the model.
1372 Context = isl_set_align_params(Context, Space);
1373
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001374 for (ScopStmt &Stmt : *this)
1375 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001376}
1377
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001378static __isl_give isl_set *
1379simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1380 const Scop &S) {
1381 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1382 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1383 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1384 return AssumptionContext;
1385}
1386
1387void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001388 // The parameter constraints of the iteration domains give us a set of
1389 // constraints that need to hold for all cases where at least a single
1390 // statement iteration is executed in the whole scop. We now simplify the
1391 // assumed context under the assumption that such constraints hold and at
1392 // least a single statement iteration is executed. For cases where no
1393 // statement instances are executed, the assumptions we have taken about
1394 // the executed code do not matter and can be changed.
1395 //
1396 // WARNING: This only holds if the assumptions we have taken do not reduce
1397 // the set of statement instances that are executed. Otherwise we
1398 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001399 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001400 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001401 // performed. In such a case, modifying the run-time conditions and
1402 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001403 // to not be executed.
1404 //
1405 // Example:
1406 //
1407 // When delinearizing the following code:
1408 //
1409 // for (long i = 0; i < 100; i++)
1410 // for (long j = 0; j < m; j++)
1411 // A[i+p][j] = 1.0;
1412 //
1413 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001414 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001415 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001416 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1417 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001418}
1419
Johannes Doerfertb164c792014-09-18 11:17:17 +00001420/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001421static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001422 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1423 isl_pw_multi_aff *MinPMA, *MaxPMA;
1424 isl_pw_aff *LastDimAff;
1425 isl_aff *OneAff;
1426 unsigned Pos;
1427
Johannes Doerfert9143d672014-09-27 11:02:39 +00001428 // Restrict the number of parameters involved in the access as the lexmin/
1429 // lexmax computation will take too long if this number is high.
1430 //
1431 // Experiments with a simple test case using an i7 4800MQ:
1432 //
1433 // #Parameters involved | Time (in sec)
1434 // 6 | 0.01
1435 // 7 | 0.04
1436 // 8 | 0.12
1437 // 9 | 0.40
1438 // 10 | 1.54
1439 // 11 | 6.78
1440 // 12 | 30.38
1441 //
1442 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1443 unsigned InvolvedParams = 0;
1444 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1445 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1446 InvolvedParams++;
1447
1448 if (InvolvedParams > RunTimeChecksMaxParameters) {
1449 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001450 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001451 }
1452 }
1453
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001454 Set = isl_set_remove_divs(Set);
1455
Johannes Doerfertb164c792014-09-18 11:17:17 +00001456 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1457 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1458
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001459 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1460 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1461
Johannes Doerfertb164c792014-09-18 11:17:17 +00001462 // Adjust the last dimension of the maximal access by one as we want to
1463 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1464 // we test during code generation might now point after the end of the
1465 // allocated array but we will never dereference it anyway.
1466 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1467 "Assumed at least one output dimension");
1468 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1469 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1470 OneAff = isl_aff_zero_on_domain(
1471 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1472 OneAff = isl_aff_add_constant_si(OneAff, 1);
1473 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1474 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1475
1476 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1477
1478 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001479 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001480}
1481
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001482static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1483 isl_set *Domain = MA->getStatement()->getDomain();
1484 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1485 return isl_set_reset_tuple_id(Domain);
1486}
1487
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001488/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1489static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001490 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001491 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001492
1493 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1494 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001495 Locations = isl_union_set_coalesce(Locations);
1496 Locations = isl_union_set_detect_equalities(Locations);
1497 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001498 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001499 isl_union_set_free(Locations);
1500 return Valid;
1501}
1502
Johannes Doerfert96425c22015-08-30 21:13:53 +00001503/// @brief Helper to treat non-affine regions and basic blocks the same.
1504///
1505///{
1506
1507/// @brief Return the block that is the representing block for @p RN.
1508static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1509 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1510 : RN->getNodeAs<BasicBlock>();
1511}
1512
1513/// @brief Return the @p idx'th block that is executed after @p RN.
1514static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1515 unsigned idx) {
1516 if (RN->isSubRegion()) {
1517 assert(idx == 0);
1518 return RN->getNodeAs<Region>()->getExit();
1519 }
1520 return BI->getSuccessor(idx);
1521}
1522
1523/// @brief Return the smallest loop surrounding @p RN.
1524static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1525 if (!RN->isSubRegion())
1526 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1527
1528 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1529 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1530 while (L && NonAffineSubRegion->contains(L))
1531 L = L->getParentLoop();
1532 return L;
1533}
1534
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001535static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1536 if (!RN->isSubRegion())
1537 return 1;
1538
1539 unsigned NumBlocks = 0;
1540 Region *R = RN->getNodeAs<Region>();
1541 for (auto BB : R->blocks()) {
1542 (void)BB;
1543 NumBlocks++;
1544 }
1545 return NumBlocks;
1546}
1547
Johannes Doerfert96425c22015-08-30 21:13:53 +00001548///}
1549
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001550static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1551 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001552 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001553 isl_id *DimId =
1554 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1555 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1556}
1557
Johannes Doerfert96425c22015-08-30 21:13:53 +00001558isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1559 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1560 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001561 return getDomainConditions(BB);
1562}
1563
1564isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1565 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001566 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001567}
1568
1569void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1570 DominatorTree &DT) {
1571
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001572 auto *EntryBB = R->getEntry();
1573 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1574 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001575
1576 Loop *L = LI.getLoopFor(EntryBB);
1577 while (LD-- >= 0) {
1578 S = addDomainDimId(S, LD + 1, L);
1579 L = L->getParentLoop();
1580 }
1581
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001582 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001583
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001584 if (SD.isNonAffineSubRegion(R, R))
1585 return;
1586
Johannes Doerfert96425c22015-08-30 21:13:53 +00001587 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001588 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001589}
1590
1591void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1592 ScopDetection &SD,
1593 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001594 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001595
1596 // To create the domain for each block in R we iterate over all blocks and
1597 // subregions in R and propagate the conditions under which the current region
1598 // element is executed. To this end we iterate in reverse post order over R as
1599 // it ensures that we first visit all predecessors of a region node (either a
1600 // basic block or a subregion) before we visit the region node itself.
1601 // Initially, only the domain for the SCoP region entry block is set and from
1602 // there we propagate the current domain to all successors, however we add the
1603 // condition that the successor is actually executed next.
1604 // As we are only interested in non-loop carried constraints here we can
1605 // simply skip loop back edges.
1606
1607 ReversePostOrderTraversal<Region *> RTraversal(R);
1608 for (auto *RN : RTraversal) {
1609
1610 // Recurse for affine subregions but go on for basic blocks and non-affine
1611 // subregions.
1612 if (RN->isSubRegion()) {
1613 Region *SubRegion = RN->getNodeAs<Region>();
1614 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1615 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1616 continue;
1617 }
1618 }
1619
1620 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001621 TerminatorInst *TI = BB->getTerminator();
1622
1623 // Unreachable instructions do not have successors so we can skip them.
1624 if (isa<UnreachableInst>(TI)) {
1625 // Assume unreachables only in error blocks.
1626 assert(isErrorBlock(*BB));
1627 continue;
1628 }
1629
Johannes Doerfert96425c22015-08-30 21:13:53 +00001630 isl_set *Domain = DomainMap[BB];
1631 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1632 assert(Domain && "Due to reverse post order traversal of the region all "
1633 "predecessor of the current region node should have been "
1634 "visited and a domain for this region node should have "
1635 "been set.");
1636
1637 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1638 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1639
1640 // Build the condition sets for the successor nodes of the current region
1641 // node. If it is a non-affine subregion we will always execute the single
1642 // exit node, hence the single entry node domain is the condition set. For
1643 // basic blocks we use the helper function buildConditionSets.
1644 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001645 BranchInst *BI = cast<BranchInst>(TI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001646 if (RN->isSubRegion())
1647 ConditionSets.push_back(isl_set_copy(Domain));
1648 else
1649 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1650
1651 // Now iterate over the successors and set their initial domain based on
1652 // their condition set. We skip back edges here and have to be careful when
1653 // we leave a loop not to keep constraints over a dimension that doesn't
1654 // exist anymore.
1655 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1656 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1657 isl_set *CondSet = ConditionSets[u];
1658
1659 // Skip back edges.
1660 if (DT.dominates(SuccBB, BB)) {
1661 isl_set_free(CondSet);
1662 continue;
1663 }
1664
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001665 // Do not adjust the number of dimensions if we enter a boxed loop or are
1666 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001667 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001668 Region *SuccRegion = RI.getRegionFor(SuccBB);
1669 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1670 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1671 SuccRegion->contains(SuccBBLoop))) {
1672
1673 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1674 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1675 // and enter a new one we need to drop the old constraints.
1676 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001677 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001678 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001679 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1680 isl_set_n_dim(CondSet) - LoopDepthDiff,
1681 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001682 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001683 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001684 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001685 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001686 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001687 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001688 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1689 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001690 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001691 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001692 }
1693
1694 // Set the domain for the successor or merge it with an existing domain in
1695 // case there are multiple paths (without loop back edges) to the
1696 // successor block.
1697 isl_set *&SuccDomain = DomainMap[SuccBB];
1698 if (!SuccDomain)
1699 SuccDomain = CondSet;
1700 else
1701 SuccDomain = isl_set_union(SuccDomain, CondSet);
1702
1703 SuccDomain = isl_set_coalesce(SuccDomain);
1704 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1705 << "\n");
1706 }
1707 }
1708}
1709
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001710/// @brief Return the domain for @p BB wrt @p DomainMap.
1711///
1712/// This helper function will lookup @p BB in @p DomainMap but also handle the
1713/// case where @p BB is contained in a non-affine subregion using the region
1714/// tree obtained by @p RI.
1715static __isl_give isl_set *
1716getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1717 RegionInfo &RI) {
1718 auto DIt = DomainMap.find(BB);
1719 if (DIt != DomainMap.end())
1720 return isl_set_copy(DIt->getSecond());
1721
1722 Region *R = RI.getRegionFor(BB);
1723 while (R->getEntry() == BB)
1724 R = R->getParent();
1725 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1726}
1727
Johannes Doerferte114dc02015-09-14 11:15:58 +00001728static bool containsErrorBlock(RegionNode *RN) {
1729 if (!RN->isSubRegion())
1730 return isErrorBlock(*RN->getNodeAs<BasicBlock>());
1731 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
1732 if (isErrorBlock(*BB))
1733 return true;
1734 return false;
1735}
1736
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001737void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1738 ScopDetection &SD, DominatorTree &DT) {
1739 // Iterate over the region R and propagate the domain constrains from the
1740 // predecessors to the current node. In contrast to the
1741 // buildDomainsWithBranchConstraints function, this one will pull the domain
1742 // information from the predecessors instead of pushing it to the successors.
1743 // Additionally, we assume the domains to be already present in the domain
1744 // map here. However, we iterate again in reverse post order so we know all
1745 // predecessors have been visited before a block or non-affine subregion is
1746 // visited.
1747
1748 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1749 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1750
1751 ReversePostOrderTraversal<Region *> RTraversal(R);
1752 for (auto *RN : RTraversal) {
1753
1754 // Recurse for affine subregions but go on for basic blocks and non-affine
1755 // subregions.
1756 if (RN->isSubRegion()) {
1757 Region *SubRegion = RN->getNodeAs<Region>();
1758 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1759 propagateDomainConstraints(SubRegion, LI, SD, DT);
1760 continue;
1761 }
1762 }
1763
1764 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1765 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1766 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1767
1768 isl_set *&Domain = DomainMap[BB];
1769 assert(Domain && "Due to reverse post order traversal of the region all "
1770 "predecessor of the current region node should have been "
1771 "visited and a domain for this region node should have "
1772 "been set.");
1773
1774 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1775 for (auto *PredBB : predecessors(BB)) {
1776
1777 // Skip backedges
1778 if (DT.dominates(BB, PredBB))
1779 continue;
1780
1781 isl_set *PredBBDom = nullptr;
1782
1783 // Handle the SCoP entry block with its outside predecessors.
1784 if (!getRegion().contains(PredBB))
1785 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1786
1787 if (!PredBBDom) {
1788 // Determine the loop depth of the predecessor and adjust its domain to
1789 // the domain of the current block. This can mean we have to:
1790 // o) Drop a dimension if this block is the exit of a loop, not the
1791 // header of a new loop and the predecessor was part of the loop.
1792 // o) Add an unconstrainted new dimension if this block is the header
1793 // of a loop and the predecessor is not part of it.
1794 // o) Drop the information about the innermost loop dimension when the
1795 // predecessor and the current block are surrounded by different
1796 // loops in the same depth.
1797 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1798 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1799 while (BoxedLoops.count(PredBBLoop))
1800 PredBBLoop = PredBBLoop->getParentLoop();
1801
1802 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001803 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001804 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001805 PredBBDom = isl_set_project_out(
1806 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1807 LoopDepthDiff);
1808 else if (PredBBLoopDepth < BBLoopDepth) {
1809 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001810 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001811 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
1812 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001813 PredBBDom = isl_set_drop_constraints_involving_dims(
1814 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001815 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001816 }
1817
1818 PredDom = isl_set_union(PredDom, PredBBDom);
1819 }
1820
1821 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00001822 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001823
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001824 if (BBLoop && BBLoop->getHeader() == BB)
1825 addLoopBoundsToHeaderDomain(BBLoop, LI);
1826
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001827 // Add assumptions for error blocks.
Johannes Doerferte114dc02015-09-14 11:15:58 +00001828 if (containsErrorBlock(RN)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001829 IsOptimized = true;
1830 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
1831 addAssumption(isl_set_complement(DomPar));
1832 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001833 }
1834}
1835
1836/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1837/// is incremented by one and all other dimensions are equal, e.g.,
1838/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1839/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1840static __isl_give isl_map *
1841createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1842 auto *MapSpace = isl_space_map_from_set(SetSpace);
1843 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1844 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1845 if (u != Dim)
1846 NextIterationMap =
1847 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1848 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1849 C = isl_constraint_set_constant_si(C, 1);
1850 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1851 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
1852 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
1853 return NextIterationMap;
1854}
1855
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001856void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
1857 int LoopDepth = getRelativeLoopDepth(L);
1858 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001859
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001860 BasicBlock *HeaderBB = L->getHeader();
1861 assert(DomainMap.count(HeaderBB));
1862 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001863
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001864 isl_map *NextIterationMap =
1865 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001866
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001867 isl_set *UnionBackedgeCondition =
1868 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001869
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001870 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
1871 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001872
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001873 for (BasicBlock *LatchBB : LatchBlocks) {
1874 assert(DomainMap.count(LatchBB));
1875 isl_set *LatchBBDom = DomainMap[LatchBB];
1876 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001877
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001878 BranchInst *BI = cast<BranchInst>(LatchBB->getTerminator());
1879 if (BI->isUnconditional())
1880 BackedgeCondition = isl_set_copy(LatchBBDom);
1881 else {
1882 SmallVector<isl_set *, 2> ConditionSets;
1883 int idx = BI->getSuccessor(0) != HeaderBB;
1884 buildConditionSets(*this, BI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001885
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001886 // Free the non back edge condition set as we do not need it.
1887 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001888
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001889 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00001890 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001891
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001892 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
1893 assert(LatchLoopDepth >= LoopDepth);
1894 BackedgeCondition =
1895 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
1896 LatchLoopDepth - LoopDepth);
1897 UnionBackedgeCondition =
1898 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001899 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001900
1901 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
1902 for (int i = 0; i < LoopDepth; i++)
1903 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
1904
1905 isl_set *UnionBackedgeConditionComplement =
1906 isl_set_complement(UnionBackedgeCondition);
1907 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
1908 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
1909 UnionBackedgeConditionComplement =
1910 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
1911 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
1912 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
1913
1914 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
1915 HeaderBBDom = Parts.second;
1916
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00001917 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
1918 // the bounded assumptions to the context as they are already implied by the
1919 // <nsw> tag.
1920 if (Affinator.hasNSWAddRecForLoop(L)) {
1921 isl_set_free(Parts.first);
1922 return;
1923 }
1924
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001925 isl_set *UnboundedCtx = isl_set_params(Parts.first);
1926 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00001927 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001928}
1929
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001930void Scop::buildAliasChecks(AliasAnalysis &AA) {
1931 if (!PollyUseRuntimeAliasChecks)
1932 return;
1933
1934 if (buildAliasGroups(AA))
1935 return;
1936
1937 // If a problem occurs while building the alias groups we need to delete
1938 // this SCoP and pretend it wasn't valid in the first place. To this end
1939 // we make the assumed context infeasible.
1940 addAssumption(isl_set_empty(getParamSpace()));
1941
1942 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1943 << " could not be created as the number of parameters involved "
1944 "is too high. The SCoP will be "
1945 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1946 "the maximal number of parameters but be advised that the "
1947 "compile time might increase exponentially.\n\n");
1948}
1949
Johannes Doerfert9143d672014-09-27 11:02:39 +00001950bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001951 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001952 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00001953 // for all memory accesses inside the SCoP.
1954 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001955 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00001956 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001957 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001958 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001959 // if their access domains intersect, otherwise they are in different
1960 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001961 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001962 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001963 // and maximal accesses to each array of a group in read only and non
1964 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00001965 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
1966
1967 AliasSetTracker AST(AA);
1968
1969 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00001970 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001971 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001972
1973 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001974 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00001975 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
1976 isl_set_free(StmtDomain);
1977 if (StmtDomainEmpty)
1978 continue;
1979
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001980 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001981 if (MA->isScalar())
1982 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00001983 if (!MA->isRead())
1984 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00001985 Instruction *Acc = MA->getAccessInstruction();
1986 PtrToAcc[getPointerOperand(*Acc)] = MA;
1987 AST.add(Acc);
1988 }
1989 }
1990
1991 SmallVector<AliasGroupTy, 4> AliasGroups;
1992 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00001993 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00001994 continue;
1995 AliasGroupTy AG;
1996 for (auto PR : AS)
1997 AG.push_back(PtrToAcc[PR.getValue()]);
1998 assert(AG.size() > 1 &&
1999 "Alias groups should contain at least two accesses");
2000 AliasGroups.push_back(std::move(AG));
2001 }
2002
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002003 // Split the alias groups based on their domain.
2004 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2005 AliasGroupTy NewAG;
2006 AliasGroupTy &AG = AliasGroups[u];
2007 AliasGroupTy::iterator AGI = AG.begin();
2008 isl_set *AGDomain = getAccessDomain(*AGI);
2009 while (AGI != AG.end()) {
2010 MemoryAccess *MA = *AGI;
2011 isl_set *MADomain = getAccessDomain(MA);
2012 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2013 NewAG.push_back(MA);
2014 AGI = AG.erase(AGI);
2015 isl_set_free(MADomain);
2016 } else {
2017 AGDomain = isl_set_union(AGDomain, MADomain);
2018 AGI++;
2019 }
2020 }
2021 if (NewAG.size() > 1)
2022 AliasGroups.push_back(std::move(NewAG));
2023 isl_set_free(AGDomain);
2024 }
2025
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002026 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002027 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2028 for (AliasGroupTy &AG : AliasGroups) {
2029 NonReadOnlyBaseValues.clear();
2030 ReadOnlyPairs.clear();
2031
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002032 if (AG.size() < 2) {
2033 AG.clear();
2034 continue;
2035 }
2036
Johannes Doerfert13771732014-10-01 12:40:46 +00002037 for (auto II = AG.begin(); II != AG.end();) {
2038 Value *BaseAddr = (*II)->getBaseAddr();
2039 if (HasWriteAccess.count(BaseAddr)) {
2040 NonReadOnlyBaseValues.insert(BaseAddr);
2041 II++;
2042 } else {
2043 ReadOnlyPairs[BaseAddr].insert(*II);
2044 II = AG.erase(II);
2045 }
2046 }
2047
2048 // If we don't have read only pointers check if there are at least two
2049 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002050 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002051 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002052 continue;
2053 }
2054
2055 // If we don't have non read only pointers clear the alias group.
2056 if (NonReadOnlyBaseValues.empty()) {
2057 AG.clear();
2058 continue;
2059 }
2060
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002061 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002062 MinMaxAliasGroups.emplace_back();
2063 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2064 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2065 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2066 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002067
2068 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002069
2070 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002071 for (MemoryAccess *MA : AG)
2072 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002073
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002074 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2075 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002076
2077 // Bail out if the number of values we need to compare is too large.
2078 // This is important as the number of comparisions grows quadratically with
2079 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002080 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2081 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002082 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002083
2084 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002085 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002086 Accesses = isl_union_map_empty(getParamSpace());
2087
2088 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2089 for (MemoryAccess *MA : ReadOnlyPair.second)
2090 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2091
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002092 Valid =
2093 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002094
2095 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002096 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002097 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002098
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002099 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002100}
2101
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002102static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2103 Loop *L = LI.getLoopFor(R.getEntry());
2104 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2105}
2106
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002107static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2108 ScopDetection &SD) {
2109
2110 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2111
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002112 unsigned MinLD = INT_MAX, MaxLD = 0;
2113 for (BasicBlock *BB : R.blocks()) {
2114 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002115 if (!R.contains(L))
2116 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002117 if (BoxedLoops && BoxedLoops->count(L))
2118 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002119 unsigned LD = L->getLoopDepth();
2120 MinLD = std::min(MinLD, LD);
2121 MaxLD = std::max(MaxLD, LD);
2122 }
2123 }
2124
2125 // Handle the case that there is no loop in the SCoP first.
2126 if (MaxLD == 0)
2127 return 1;
2128
2129 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2130 assert(MaxLD >= MinLD &&
2131 "Maximal loop depth was smaller than mininaml loop depth?");
2132 return MaxLD - MinLD + 1;
2133}
2134
Michael Kruse9d080092015-09-11 21:41:48 +00002135Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
2136 ScalarEvolution &ScalarEvolution, DominatorTree &DT,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002137 isl_ctx *Context, unsigned MaxLoopDepth)
Michael Kruse9d080092015-09-11 21:41:48 +00002138 : DT(DT), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
2139 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002140 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this),
2141 BoundaryContext(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002142
Michael Kruse9d080092015-09-11 21:41:48 +00002143void Scop::init(LoopInfo &LI, ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002144 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002145
Johannes Doerfert96425c22015-08-30 21:13:53 +00002146 buildDomains(&R, LI, SD, DT);
2147
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002148 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Tobias Grosser75805372011-04-29 06:27:02 +00002149
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002150 Loop *L = getLoopSurroundingRegion(R, LI);
2151 LoopSchedules[L];
Michael Kruse9d080092015-09-11 21:41:48 +00002152 buildSchedule(&R, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002153 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002154
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002155 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002156 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002157 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002158 buildBoundaryContext();
2159 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002160 buildAliasChecks(AA);
Tobias Grosser75805372011-04-29 06:27:02 +00002161}
2162
2163Scop::~Scop() {
2164 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002165 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002166 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002167 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002168
Johannes Doerfert96425c22015-08-30 21:13:53 +00002169 for (auto It : DomainMap)
2170 isl_set_free(It.second);
2171
Johannes Doerfertb164c792014-09-18 11:17:17 +00002172 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002173 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002174 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002175 isl_pw_multi_aff_free(MMA.first);
2176 isl_pw_multi_aff_free(MMA.second);
2177 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002178 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002179 isl_pw_multi_aff_free(MMA.first);
2180 isl_pw_multi_aff_free(MMA.second);
2181 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002182 }
Tobias Grosser75805372011-04-29 06:27:02 +00002183}
2184
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002185const ScopArrayInfo *
2186Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002187 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002188 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002189 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002190 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2191 this));
Tobias Grosserab671442015-05-23 05:58:27 +00002192 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002193}
2194
Tobias Grosser92245222015-07-28 14:53:44 +00002195const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2196 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002197 assert(SAI && "No ScopArrayInfo available for this base pointer");
2198 return SAI;
2199}
2200
Tobias Grosser74394f02013-01-14 22:40:23 +00002201std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002202std::string Scop::getAssumedContextStr() const {
2203 return stringFromIslObj(AssumedContext);
2204}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002205std::string Scop::getBoundaryContextStr() const {
2206 return stringFromIslObj(BoundaryContext);
2207}
Tobias Grosser75805372011-04-29 06:27:02 +00002208
2209std::string Scop::getNameStr() const {
2210 std::string ExitName, EntryName;
2211 raw_string_ostream ExitStr(ExitName);
2212 raw_string_ostream EntryStr(EntryName);
2213
Tobias Grosserf240b482014-01-09 10:42:15 +00002214 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002215 EntryStr.str();
2216
2217 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002218 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002219 ExitStr.str();
2220 } else
2221 ExitName = "FunctionExit";
2222
2223 return EntryName + "---" + ExitName;
2224}
2225
Tobias Grosser74394f02013-01-14 22:40:23 +00002226__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002227__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002228 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002229}
2230
Tobias Grossere86109f2013-10-29 21:05:49 +00002231__isl_give isl_set *Scop::getAssumedContext() const {
2232 return isl_set_copy(AssumedContext);
2233}
2234
Johannes Doerfert43788c52015-08-20 05:58:56 +00002235__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2236 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002237 RuntimeCheckContext =
2238 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2239 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002240 return RuntimeCheckContext;
2241}
2242
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002243bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002244 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002245 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002246 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2247 isl_set_free(RuntimeCheckContext);
2248 return IsFeasible;
2249}
2250
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002251void Scop::addAssumption(__isl_take isl_set *Set) {
2252 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002253 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002254}
2255
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002256__isl_give isl_set *Scop::getBoundaryContext() const {
2257 return isl_set_copy(BoundaryContext);
2258}
2259
Tobias Grosser75805372011-04-29 06:27:02 +00002260void Scop::printContext(raw_ostream &OS) const {
2261 OS << "Context:\n";
2262
2263 if (!Context) {
2264 OS.indent(4) << "n/a\n\n";
2265 return;
2266 }
2267
2268 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002269
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002270 OS.indent(4) << "Assumed Context:\n";
2271 if (!AssumedContext) {
2272 OS.indent(4) << "n/a\n\n";
2273 return;
2274 }
2275
2276 OS.indent(4) << getAssumedContextStr() << "\n";
2277
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002278 OS.indent(4) << "Boundary Context:\n";
2279 if (!BoundaryContext) {
2280 OS.indent(4) << "n/a\n\n";
2281 return;
2282 }
2283
2284 OS.indent(4) << getBoundaryContextStr() << "\n";
2285
Tobias Grosser083d3d32014-06-28 08:59:45 +00002286 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002287 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002288 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2289 }
Tobias Grosser75805372011-04-29 06:27:02 +00002290}
2291
Johannes Doerfertb164c792014-09-18 11:17:17 +00002292void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002293 int noOfGroups = 0;
2294 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002295 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002296 noOfGroups += 1;
2297 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002298 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002299 }
2300
Tobias Grosserbb853c22015-07-25 12:31:03 +00002301 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002302 if (MinMaxAliasGroups.empty()) {
2303 OS.indent(8) << "n/a\n";
2304 return;
2305 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002306
Tobias Grosserbb853c22015-07-25 12:31:03 +00002307 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002308
2309 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002310 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002311 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002312 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002313 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2314 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002315 }
2316 OS << " ]]\n";
2317 }
2318
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002319 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002320 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002321 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002322 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002323 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2324 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002325 }
2326 OS << " ]]\n";
2327 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002328 }
2329}
2330
Tobias Grosser75805372011-04-29 06:27:02 +00002331void Scop::printStatements(raw_ostream &OS) const {
2332 OS << "Statements {\n";
2333
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002334 for (const ScopStmt &Stmt : *this)
2335 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002336
2337 OS.indent(4) << "}\n";
2338}
2339
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002340void Scop::printArrayInfo(raw_ostream &OS) const {
2341 OS << "Arrays {\n";
2342
Tobias Grosserab671442015-05-23 05:58:27 +00002343 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002344 Array.second->print(OS);
2345
2346 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002347
2348 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2349
2350 for (auto &Array : arrays())
2351 Array.second->print(OS, /* SizeAsPwAff */ true);
2352
2353 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002354}
2355
Tobias Grosser75805372011-04-29 06:27:02 +00002356void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002357 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2358 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002359 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002360 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002361 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002362 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002363 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002364 printStatements(OS.indent(4));
2365}
2366
2367void Scop::dump() const { print(dbgs()); }
2368
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002369isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002370
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002371__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2372 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002373}
2374
Tobias Grosser808cd692015-07-14 09:33:13 +00002375__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002376 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002377
Tobias Grosser808cd692015-07-14 09:33:13 +00002378 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002379 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002380
2381 return Domain;
2382}
2383
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002384__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002385 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002386
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002387 for (ScopStmt &Stmt : *this) {
2388 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002389 if (!MA->isMustWrite())
2390 continue;
2391
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002392 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002393 isl_map *AccessDomain = MA->getAccessRelation();
2394 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2395 Write = isl_union_map_add_map(Write, AccessDomain);
2396 }
2397 }
2398 return isl_union_map_coalesce(Write);
2399}
2400
2401__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002402 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002403
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002404 for (ScopStmt &Stmt : *this) {
2405 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002406 if (!MA->isMayWrite())
2407 continue;
2408
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002409 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002410 isl_map *AccessDomain = MA->getAccessRelation();
2411 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2412 Write = isl_union_map_add_map(Write, AccessDomain);
2413 }
2414 }
2415 return isl_union_map_coalesce(Write);
2416}
2417
Tobias Grosser37eb4222014-02-20 21:43:54 +00002418__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002419 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002420
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002421 for (ScopStmt &Stmt : *this) {
2422 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002423 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002424 continue;
2425
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002426 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002427 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002428 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2429 Write = isl_union_map_add_map(Write, AccessDomain);
2430 }
2431 }
2432 return isl_union_map_coalesce(Write);
2433}
2434
2435__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002436 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002437
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002438 for (ScopStmt &Stmt : *this) {
2439 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002440 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002441 continue;
2442
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002443 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002444 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002445
2446 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2447 Read = isl_union_map_add_map(Read, AccessDomain);
2448 }
2449 }
2450 return isl_union_map_coalesce(Read);
2451}
2452
Tobias Grosser808cd692015-07-14 09:33:13 +00002453__isl_give isl_union_map *Scop::getSchedule() const {
2454 auto Tree = getScheduleTree();
2455 auto S = isl_schedule_get_map(Tree);
2456 isl_schedule_free(Tree);
2457 return S;
2458}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002459
Tobias Grosser808cd692015-07-14 09:33:13 +00002460__isl_give isl_schedule *Scop::getScheduleTree() const {
2461 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2462 getDomains());
2463}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002464
Tobias Grosser808cd692015-07-14 09:33:13 +00002465void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2466 auto *S = isl_schedule_from_domain(getDomains());
2467 S = isl_schedule_insert_partial_schedule(
2468 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2469 isl_schedule_free(Schedule);
2470 Schedule = S;
2471}
2472
2473void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2474 isl_schedule_free(Schedule);
2475 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002476}
2477
2478bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2479 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002480 for (ScopStmt &Stmt : *this) {
2481 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002482 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2483 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2484
2485 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2486 isl_union_set_free(StmtDomain);
2487 isl_union_set_free(NewStmtDomain);
2488 continue;
2489 }
2490
2491 Changed = true;
2492
2493 isl_union_set_free(StmtDomain);
2494 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2495
2496 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002497 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002498 isl_union_set_free(NewStmtDomain);
2499 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002500 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002501 }
2502 isl_union_set_free(Domain);
2503 return Changed;
2504}
2505
Tobias Grosser75805372011-04-29 06:27:02 +00002506ScalarEvolution *Scop::getSE() const { return SE; }
2507
Michael Kruse9d080092015-09-11 21:41:48 +00002508bool Scop::isTrivialBB(BasicBlock *BB) {
2509 if (getAccessFunctions(BB) && !isErrorBlock(*BB))
Tobias Grosser75805372011-04-29 06:27:02 +00002510 return false;
2511
2512 return true;
2513}
2514
Tobias Grosser808cd692015-07-14 09:33:13 +00002515struct MapToDimensionDataTy {
2516 int N;
2517 isl_union_pw_multi_aff *Res;
2518};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002519
Tobias Grosser808cd692015-07-14 09:33:13 +00002520// @brief Create a function that maps the elements of 'Set' to its N-th
2521// dimension.
2522//
2523// The result is added to 'User->Res'.
2524//
2525// @param Set The input set.
2526// @param N The dimension to map to.
2527//
2528// @returns Zero if no error occurred, non-zero otherwise.
2529static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2530 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2531 int Dim;
2532 isl_space *Space;
2533 isl_pw_multi_aff *PMA;
2534
2535 Dim = isl_set_dim(Set, isl_dim_set);
2536 Space = isl_set_get_space(Set);
2537 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2538 Dim - Data->N);
2539 if (Data->N > 1)
2540 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2541 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2542
2543 isl_set_free(Set);
2544
2545 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002546}
2547
Tobias Grosser808cd692015-07-14 09:33:13 +00002548// @brief Create a function that maps the elements of Domain to their Nth
2549// dimension.
2550//
2551// @param Domain The set of elements to map.
2552// @param N The dimension to map to.
2553static __isl_give isl_multi_union_pw_aff *
2554mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002555 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2556 isl_union_set_free(Domain);
2557 return nullptr;
2558 }
2559
Tobias Grosser808cd692015-07-14 09:33:13 +00002560 struct MapToDimensionDataTy Data;
2561 isl_space *Space;
2562
2563 Space = isl_union_set_get_space(Domain);
2564 Data.N = N;
2565 Data.Res = isl_union_pw_multi_aff_empty(Space);
2566 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2567 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2568
2569 isl_union_set_free(Domain);
2570 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2571}
2572
Michael Kruse9d080092015-09-11 21:41:48 +00002573ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002574 ScopStmt *Stmt;
2575 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002576 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002577 Stmt = &Stmts.back();
2578 StmtMap[BB] = Stmt;
2579 } else {
2580 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002581 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002582 Stmt = &Stmts.back();
2583 for (BasicBlock *BB : R->blocks())
2584 StmtMap[BB] = Stmt;
2585 }
2586 return Stmt;
2587}
2588
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002589void Scop::buildSchedule(
Michael Kruse9d080092015-09-11 21:41:48 +00002590 Region *R, LoopInfo &LI, ScopDetection &SD,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002591 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002592
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002593 if (SD.isNonAffineSubRegion(R, &getRegion())) {
2594 auto *Stmt = addScopStmt(nullptr, R);
2595 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2596 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2597 auto &LSchedulePair = LoopSchedules[nullptr];
2598 LSchedulePair.first = StmtSchedule;
2599 return;
2600 }
2601
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002602 ReversePostOrderTraversal<Region *> RTraversal(R);
2603 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00002604
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002605 if (RN->isSubRegion()) {
2606 Region *SubRegion = RN->getNodeAs<Region>();
2607 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Michael Kruse9d080092015-09-11 21:41:48 +00002608 buildSchedule(SubRegion, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002609 continue;
2610 }
Tobias Grosser75805372011-04-29 06:27:02 +00002611 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002612
2613 Loop *L = getRegionNodeLoop(RN, LI);
2614 int LD = getRelativeLoopDepth(L);
2615 auto &LSchedulePair = LoopSchedules[L];
2616 LSchedulePair.second += getNumBlocksInRegionNode(RN);
2617
2618 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse9d080092015-09-11 21:41:48 +00002619 if (RN->isSubRegion() || !isTrivialBB(BB)) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002620
2621 ScopStmt *Stmt;
2622 if (RN->isSubRegion())
Michael Kruse9d080092015-09-11 21:41:48 +00002623 Stmt = addScopStmt(nullptr, RN->getNodeAs<Region>());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002624 else
Michael Kruse9d080092015-09-11 21:41:48 +00002625 Stmt = addScopStmt(BB, nullptr);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002626
2627 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2628 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2629 LSchedulePair.first =
2630 combineInSequence(LSchedulePair.first, StmtSchedule);
2631 }
2632
2633 unsigned NumVisited = LSchedulePair.second;
2634 while (L && NumVisited == L->getNumBlocks()) {
2635 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
2636 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
2637 LSchedulePair.first =
2638 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
2639
2640 auto *PL = L->getParentLoop();
2641 assert(LoopSchedules.count(PL));
2642 auto &PSchedulePair = LoopSchedules[PL];
2643 PSchedulePair.first =
2644 combineInSequence(PSchedulePair.first, LSchedulePair.first);
2645 PSchedulePair.second += NumVisited;
2646
2647 L = PL;
2648 NumVisited = PSchedulePair.second;
2649 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002650 }
Tobias Grosser75805372011-04-29 06:27:02 +00002651}
2652
Johannes Doerfert7c494212014-10-31 23:13:39 +00002653ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002654 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002655 if (StmtMapIt == StmtMap.end())
2656 return nullptr;
2657 return StmtMapIt->second;
2658}
2659
Johannes Doerfert96425c22015-08-30 21:13:53 +00002660int Scop::getRelativeLoopDepth(const Loop *L) const {
2661 Loop *OuterLoop =
2662 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2663 if (!OuterLoop)
2664 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002665 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2666}
2667
Michael Krused868b5d2015-09-10 15:25:24 +00002668void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00002669 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002670
2671 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2672 // true, are not modeled as ordinary PHI nodes as they are not part of the
2673 // region. However, we model the operands in the predecessor blocks that are
2674 // part of the region as regular scalar accesses.
2675
2676 // If we can synthesize a PHI we can skip it, however only if it is in
2677 // the region. If it is not it can only be in the exit block of the region.
2678 // In this case we model the operands but not the PHI itself.
2679 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2680 return;
2681
2682 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2683 // detection. Hence, the PHI is a load of a new memory location in which the
2684 // incoming value was written at the end of the incoming basic block.
2685 bool OnlyNonAffineSubRegionOperands = true;
2686 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2687 Value *Op = PHI->getIncomingValue(u);
2688 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2689
2690 // Do not build scalar dependences inside a non-affine subregion.
2691 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2692 continue;
2693
2694 OnlyNonAffineSubRegionOperands = false;
2695
2696 if (!R.contains(OpBB))
2697 continue;
2698
2699 Instruction *OpI = dyn_cast<Instruction>(Op);
2700 if (OpI) {
2701 BasicBlock *OpIBB = OpI->getParent();
2702 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2703 // we have to insert a scalar dependence from the definition of OpI to
2704 // OpBB if the definition is not in OpBB.
2705 if (OpIBB != OpBB) {
Michael Kruse2d0ece92015-09-24 11:41:21 +00002706 addMemoryAccess(OpBB, PHI, MemoryAccess::READ, OpI, 1, true, OpI);
2707 addMemoryAccess(OpIBB, OpI, MemoryAccess::MUST_WRITE, OpI, 1, true,
Michael Krusee2bccbb2015-09-18 19:59:43 +00002708 OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002709 }
2710 }
2711
2712 // Always use the terminator of the incoming basic block as the access
2713 // instruction.
2714 OpI = OpBB->getTerminator();
2715
Michael Kruse2d0ece92015-09-24 11:41:21 +00002716 addMemoryAccess(OpBB, OpI, MemoryAccess::MUST_WRITE, PHI, 1, true, Op,
2717 /* IsPHI */ !IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002718 }
2719
2720 if (!OnlyNonAffineSubRegionOperands) {
Michael Kruse2d0ece92015-09-24 11:41:21 +00002721 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true,
2722 PHI,
Michael Krusee2bccbb2015-09-18 19:59:43 +00002723 /* IsPHI */ !IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002724 }
2725}
2726
Michael Krused868b5d2015-09-10 15:25:24 +00002727bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2728 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002729 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2730 if (isIgnoredIntrinsic(Inst))
2731 return false;
2732
2733 bool AnyCrossStmtUse = false;
2734 BasicBlock *ParentBB = Inst->getParent();
2735
2736 for (User *U : Inst->users()) {
2737 Instruction *UI = dyn_cast<Instruction>(U);
2738
2739 // Ignore the strange user
2740 if (UI == 0)
2741 continue;
2742
2743 BasicBlock *UseParent = UI->getParent();
2744
2745 // Ignore the users in the same BB (statement)
2746 if (UseParent == ParentBB)
2747 continue;
2748
2749 // Do not build scalar dependences inside a non-affine subregion.
2750 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2751 continue;
2752
2753 // Check whether or not the use is in the SCoP.
2754 if (!R->contains(UseParent)) {
2755 AnyCrossStmtUse = true;
2756 continue;
2757 }
2758
2759 // If the instruction can be synthesized and the user is in the region
2760 // we do not need to add scalar dependences.
2761 if (canSynthesizeInst)
2762 continue;
2763
2764 // No need to translate these scalar dependences into polyhedral form,
2765 // because synthesizable scalars can be generated by the code generator.
2766 if (canSynthesize(UI, LI, SE, R))
2767 continue;
2768
2769 // Skip PHI nodes in the region as they handle their operands on their own.
2770 if (isa<PHINode>(UI))
2771 continue;
2772
2773 // Now U is used in another statement.
2774 AnyCrossStmtUse = true;
2775
2776 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00002777 // Use the def instruction as base address of the MemoryAccess, so that it
2778 // will become the name of the scalar access in the polyhedral form.
Michael Kruse2d0ece92015-09-24 11:41:21 +00002779 addMemoryAccess(UseParent, UI, MemoryAccess::READ, Inst, 1, true, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00002780 }
2781
2782 if (ModelReadOnlyScalars) {
2783 for (Value *Op : Inst->operands()) {
2784 if (canSynthesize(Op, LI, SE, R))
2785 continue;
2786
2787 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
2788 if (R->contains(OpInst))
2789 continue;
2790
2791 if (isa<Constant>(Op))
2792 continue;
2793
Michael Kruse2d0ece92015-09-24 11:41:21 +00002794 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::READ, Op, 1, true,
2795 Op);
Michael Kruse7bf39442015-09-10 12:46:52 +00002796 }
2797 }
2798
2799 return AnyCrossStmtUse;
2800}
2801
2802extern MapInsnToMemAcc InsnToMemAcc;
2803
Michael Krusee2bccbb2015-09-18 19:59:43 +00002804void ScopInfo::buildMemoryAccess(
2805 Instruction *Inst, Loop *L, Region *R,
2806 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002807 unsigned Size;
2808 Type *SizeType;
2809 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00002810 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00002811
2812 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
2813 SizeType = Load->getType();
2814 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002815 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00002816 Val = Load;
2817 } else {
2818 StoreInst *Store = cast<StoreInst>(Inst);
2819 SizeType = Store->getValueOperand()->getType();
2820 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002821 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002822 Val = Store->getValueOperand();
2823 }
2824
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002825 auto Address = getPointerOperand(*Inst);
2826
2827 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00002828 const SCEVUnknown *BasePointer =
2829 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
2830
2831 assert(BasePointer && "Could not find base pointer");
2832 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
2833
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002834 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
2835 auto NewAddress = Address;
2836 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
2837 auto Src = BitCast->getOperand(0);
2838 auto SrcTy = Src->getType();
2839 auto DstTy = BitCast->getType();
2840 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
2841 NewAddress = Src;
2842 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002843
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002844 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
2845 std::vector<const SCEV *> Subscripts;
2846 std::vector<int> Sizes;
2847 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
2848 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002849
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002850 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002851
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002852 bool AllAffineSubcripts = true;
2853 for (auto Subscript : Subscripts)
2854 if (!isAffineExpr(R, Subscript, *SE)) {
2855 AllAffineSubcripts = false;
2856 break;
2857 }
2858
2859 if (AllAffineSubcripts && Sizes.size() > 0) {
2860 for (auto V : Sizes)
2861 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
2862 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002863 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002864 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002865
Michael Krusee2bccbb2015-09-18 19:59:43 +00002866 addMemoryAccess(Inst->getParent(), Inst, Type, BasePointer->getValue(),
Michael Kruse2d0ece92015-09-24 11:41:21 +00002867 Size, true, Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00002868 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002869 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002870 }
2871 }
2872
Michael Kruse7bf39442015-09-10 12:46:52 +00002873 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002874 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
2875 addMemoryAccess(Inst->getParent(), Inst, Type, BasePointer->getValue(),
Michael Kruse2d0ece92015-09-24 11:41:21 +00002876 Size, true, AccItr->second.DelinearizedSubscripts,
Michael Kruse7bf39442015-09-10 12:46:52 +00002877 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002878 return;
2879 }
Michael Kruse7bf39442015-09-10 12:46:52 +00002880
2881 // Check if the access depends on a loop contained in a non-affine subregion.
2882 bool isVariantInNonAffineLoop = false;
2883 if (BoxedLoops) {
2884 SetVector<const Loop *> Loops;
2885 findLoops(AccessFunction, Loops);
2886 for (const Loop *L : Loops)
2887 if (BoxedLoops->count(L))
2888 isVariantInNonAffineLoop = true;
2889 }
2890
2891 bool IsAffine = !isVariantInNonAffineLoop &&
2892 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
2893
2894 SmallVector<const SCEV *, 4> Subscripts, Sizes;
2895 Subscripts.push_back(AccessFunction);
2896 Sizes.push_back(SE->getConstant(ZeroOffset->getType(), Size));
2897
Michael Krusee2bccbb2015-09-18 19:59:43 +00002898 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
2899 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002900
Michael Kruse2d0ece92015-09-24 11:41:21 +00002901 addMemoryAccess(Inst->getParent(), Inst, Type, BasePointer->getValue(), Size,
2902 IsAffine, Subscripts, Sizes, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00002903}
2904
Michael Krused868b5d2015-09-10 15:25:24 +00002905void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002906
2907 if (SD->isNonAffineSubRegion(&SR, &R)) {
2908 for (BasicBlock *BB : SR.blocks())
2909 buildAccessFunctions(R, *BB, &SR);
2910 return;
2911 }
2912
2913 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2914 if (I->isSubRegion())
2915 buildAccessFunctions(R, *I->getNodeAs<Region>());
2916 else
2917 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
2918}
2919
Michael Krused868b5d2015-09-10 15:25:24 +00002920void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
2921 Region *NonAffineSubRegion,
2922 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002923 Loop *L = LI->getLoopFor(&BB);
2924
2925 // The set of loops contained in non-affine subregions that are part of R.
2926 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
2927
2928 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
2929 Instruction *Inst = I;
2930
2931 PHINode *PHI = dyn_cast<PHINode>(Inst);
2932 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00002933 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002934
2935 // For the exit block we stop modeling after the last PHI node.
2936 if (!PHI && IsExitBlock)
2937 break;
2938
2939 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Michael Krusee2bccbb2015-09-18 19:59:43 +00002940 buildMemoryAccess(Inst, L, &R, BoxedLoops);
Michael Kruse7bf39442015-09-10 12:46:52 +00002941
2942 if (isIgnoredIntrinsic(Inst))
2943 continue;
2944
2945 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002946 if (!isa<StoreInst>(Inst))
Michael Kruse2d0ece92015-09-24 11:41:21 +00002947 addMemoryAccess(&BB, Inst, MemoryAccess::MUST_WRITE, Inst, 1, true,
2948 Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00002949 }
2950 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00002951}
Michael Kruse7bf39442015-09-10 12:46:52 +00002952
Michael Kruse2d0ece92015-09-24 11:41:21 +00002953void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
2954 MemoryAccess::AccessType Type,
2955 Value *BaseAddress, unsigned ElemBytes,
2956 bool Affine, Value *AccessValue,
2957 ArrayRef<const SCEV *> Subscripts,
2958 ArrayRef<const SCEV *> Sizes,
2959 bool IsPHI = false) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002960 AccFuncSetType &AccList = AccFuncMap[BB];
2961 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00002962
Michael Krusee2bccbb2015-09-18 19:59:43 +00002963 Value *BaseAddr = BaseAddress;
2964 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
2965
2966 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
2967 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
2968
Michael Kruse2d0ece92015-09-24 11:41:21 +00002969 AccList.emplace_back(Inst, Id, Type, BaseAddress, ElemBytes, Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +00002970 Subscripts, Sizes, AccessValue, IsPHI, BaseName);
Michael Kruse7bf39442015-09-10 12:46:52 +00002971}
2972
Michael Kruse9d080092015-09-11 21:41:48 +00002973Scop *ScopInfo::buildScop(Region &R, DominatorTree &DT) {
2974 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
2975 Scop *S = new Scop(R, AccFuncMap, *SE, DT, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00002976
2977 buildAccessFunctions(R, R);
2978
2979 // In case the region does not have an exiting block we will later (during
2980 // code generation) split the exit block. This will move potential PHI nodes
2981 // from the current exit block into the new region exiting block. Hence, PHI
2982 // nodes that are at this point not part of the region will be.
2983 // To handle these PHI nodes later we will now model their operands as scalar
2984 // accesses. Note that we do not model anything in the exit block if we have
2985 // an exiting block in the region, as there will not be any splitting later.
2986 if (!R.getExitingBlock())
2987 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
2988
Michael Kruse9d080092015-09-11 21:41:48 +00002989 S->init(*LI, *SD, *AA);
2990 return S;
Michael Kruse7bf39442015-09-10 12:46:52 +00002991}
2992
Michael Krused868b5d2015-09-10 15:25:24 +00002993void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00002994 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00002995 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00002996 return;
2997 }
2998
Michael Kruse9d080092015-09-11 21:41:48 +00002999 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003000}
3001
Michael Krused868b5d2015-09-10 15:25:24 +00003002void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003003 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003004 if (scop) {
3005 delete scop;
3006 scop = 0;
3007 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003008}
3009
3010//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003011ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003012 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003013 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003014}
3015
3016ScopInfo::~ScopInfo() {
3017 clear();
3018 isl_ctx_free(ctx);
3019}
3020
Tobias Grosser75805372011-04-29 06:27:02 +00003021void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00003022 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00003023 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003024 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003025 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003026 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3027 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003028 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003029 AU.setPreservesAll();
3030}
3031
3032bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003033 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003034
Michael Krused868b5d2015-09-10 15:25:24 +00003035 if (!SD->isMaxRegionInScop(*R))
3036 return false;
3037
3038 Function *F = R->getEntry()->getParent();
3039 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3040 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3041 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3042 TD = &F->getParent()->getDataLayout();
3043 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3044 ZeroOffset = SE->getConstant(TD->getIntPtrType(F->getContext()), 0);
3045
Michael Kruse9d080092015-09-11 21:41:48 +00003046 scop = buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003047
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003048 DEBUG(scop->print(dbgs()));
3049
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003050 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003051 delete scop;
3052 scop = nullptr;
3053 return false;
3054 }
3055
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003056 // Statistics.
3057 ++ScopFound;
3058 if (scop->getMaxLoopDepth() > 0)
3059 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003060 return false;
3061}
3062
3063char ScopInfo::ID = 0;
3064
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003065Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3066
Tobias Grosser73600b82011-10-08 00:30:40 +00003067INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3068 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003069 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003070INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003071INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003072INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003073INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003074INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003075INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003076INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3077 "Polly - Create polyhedral description of Scops", false,
3078 false)