blob: 1aafe621f3e62d623c57fbac884effa2a841b84d [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
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
Michael Krusee2bccbb2015-09-18 19:59:43 +0000230void MemoryAccess::printIR(raw_ostream &OS) const {
Michael Kruse7bf39442015-09-10 12:46:52 +0000231 if (isRead())
232 OS << "Read ";
233 else {
234 if (isMayWrite())
235 OS << "May";
236 OS << "Write ";
237 }
Michael Krusee2bccbb2015-09-18 19:59:43 +0000238 OS << BaseAddr->getName() << '[' << *Offset << "]\n";
Michael Kruse7bf39442015-09-10 12:46:52 +0000239}
240
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000241const std::string
242MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
243 switch (RT) {
244 case MemoryAccess::RT_NONE:
245 llvm_unreachable("Requested a reduction operator string for a memory "
246 "access which isn't a reduction");
247 case MemoryAccess::RT_ADD:
248 return "+";
249 case MemoryAccess::RT_MUL:
250 return "*";
251 case MemoryAccess::RT_BOR:
252 return "|";
253 case MemoryAccess::RT_BXOR:
254 return "^";
255 case MemoryAccess::RT_BAND:
256 return "&";
257 }
258 llvm_unreachable("Unknown reduction type");
259 return "";
260}
261
Johannes Doerfertf6183392014-07-01 20:52:51 +0000262/// @brief Return the reduction type for a given binary operator
263static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
264 const Instruction *Load) {
265 if (!BinOp)
266 return MemoryAccess::RT_NONE;
267 switch (BinOp->getOpcode()) {
268 case Instruction::FAdd:
269 if (!BinOp->hasUnsafeAlgebra())
270 return MemoryAccess::RT_NONE;
271 // Fall through
272 case Instruction::Add:
273 return MemoryAccess::RT_ADD;
274 case Instruction::Or:
275 return MemoryAccess::RT_BOR;
276 case Instruction::Xor:
277 return MemoryAccess::RT_BXOR;
278 case Instruction::And:
279 return MemoryAccess::RT_BAND;
280 case Instruction::FMul:
281 if (!BinOp->hasUnsafeAlgebra())
282 return MemoryAccess::RT_NONE;
283 // Fall through
284 case Instruction::Mul:
285 if (DisableMultiplicativeReductions)
286 return MemoryAccess::RT_NONE;
287 return MemoryAccess::RT_MUL;
288 default:
289 return MemoryAccess::RT_NONE;
290 }
291}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000292
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000293/// @brief Derive the individual index expressions from a GEP instruction
294///
295/// This function optimistically assumes the GEP references into a fixed size
296/// array. If this is actually true, this function returns a list of array
297/// subscript expressions as SCEV as well as a list of integers describing
298/// the size of the individual array dimensions. Both lists have either equal
299/// length of the size list is one element shorter in case there is no known
300/// size available for the outermost array dimension.
301///
302/// @param GEP The GetElementPtr instruction to analyze.
303///
304/// @return A tuple with the subscript expressions and the dimension sizes.
305static std::tuple<std::vector<const SCEV *>, std::vector<int>>
306getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
307 std::vector<const SCEV *> Subscripts;
308 std::vector<int> Sizes;
309
310 Type *Ty = GEP->getPointerOperandType();
311
312 bool DroppedFirstDim = false;
313
314 for (long i = 1; i < GEP->getNumOperands(); i++) {
315
316 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
317
318 if (i == 1) {
319 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
320 Ty = PtrTy->getElementType();
321 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
322 Ty = ArrayTy->getElementType();
323 } else {
324 Subscripts.clear();
325 Sizes.clear();
326 break;
327 }
328 if (auto Const = dyn_cast<SCEVConstant>(Expr))
329 if (Const->getValue()->isZero()) {
330 DroppedFirstDim = true;
331 continue;
332 }
333 Subscripts.push_back(Expr);
334 continue;
335 }
336
337 auto ArrayTy = dyn_cast<ArrayType>(Ty);
338 if (!ArrayTy) {
339 Subscripts.clear();
340 Sizes.clear();
341 break;
342 }
343
344 Subscripts.push_back(Expr);
345 if (!(DroppedFirstDim && i == 2))
346 Sizes.push_back(ArrayTy->getNumElements());
347
348 Ty = ArrayTy->getElementType();
349 }
350
351 return std::make_tuple(Subscripts, Sizes);
352}
353
Tobias Grosser75805372011-04-29 06:27:02 +0000354MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000355 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000356 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000357 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000358}
359
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000360const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
361 isl_id *ArrayId = getArrayId();
362 void *User = isl_id_get_user(ArrayId);
363 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
364 isl_id_free(ArrayId);
365 return SAI;
366}
367
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000368__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000369 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
370}
371
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000372__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
373 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000374 isl_map *Schedule, *ScheduledAccRel;
375 isl_union_set *UDomain;
376
377 UDomain = isl_union_set_from_set(getStatement()->getDomain());
378 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
379 Schedule = isl_map_from_union_map(USchedule);
380 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
381 return isl_pw_multi_aff_from_map(ScheduledAccRel);
382}
383
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000384__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000385 return isl_map_copy(AccessRelation);
386}
387
Johannes Doerferta99130f2014-10-13 12:58:03 +0000388std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000389 return stringFromIslObj(AccessRelation);
390}
391
Johannes Doerferta99130f2014-10-13 12:58:03 +0000392__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000393 return isl_map_get_space(AccessRelation);
394}
395
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000396__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000397 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000398}
399
Tobias Grosser6f730082015-09-05 07:46:47 +0000400std::string MemoryAccess::getNewAccessRelationStr() const {
401 return stringFromIslObj(NewAccessRelation);
402}
403
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000404__isl_give isl_basic_map *
405MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000406 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000407 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000408
Tobias Grosser084d8f72012-05-29 09:29:44 +0000409 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000410 isl_basic_set_universe(Statement->getDomainSpace()),
411 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000412}
413
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000414// Formalize no out-of-bound access assumption
415//
416// When delinearizing array accesses we optimistically assume that the
417// delinearized accesses do not access out of bound locations (the subscript
418// expression of each array evaluates for each statement instance that is
419// executed to a value that is larger than zero and strictly smaller than the
420// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000421// dimension for which we do not need to assume any upper bound. At this point
422// we formalize this assumption to ensure that at code generation time the
423// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000424//
425// To find the set of constraints necessary to avoid out of bound accesses, we
426// first build the set of data locations that are not within array bounds. We
427// then apply the reverse access relation to obtain the set of iterations that
428// may contain invalid accesses and reduce this set of iterations to the ones
429// that are actually executed by intersecting them with the domain of the
430// statement. If we now project out all loop dimensions, we obtain a set of
431// parameters that may cause statement instances to be executed that may
432// possibly yield out of bound memory accesses. The complement of these
433// constraints is the set of constraints that needs to be assumed to ensure such
434// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000435void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000436 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000437 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000438 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000439 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
440 isl_pw_aff *Var =
441 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
442 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
443
444 isl_set *DimOutside;
445
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000446 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000447 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000448
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000449 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
450 Statement->getNumIterators());
451 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
452 isl_space_dim(Space, isl_dim_set));
453 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
454 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000455
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000456 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000457
458 Outside = isl_set_union(Outside, DimOutside);
459 }
460
461 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
462 Outside = isl_set_intersect(Outside, Statement->getDomain());
463 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000464
465 // Remove divs to avoid the construction of overly complicated assumptions.
466 // Doing so increases the set of parameter combinations that are assumed to
467 // not appear. This is always save, but may make the resulting run-time check
468 // bail out more often than strictly necessary.
469 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000470 Outside = isl_set_complement(Outside);
471 Statement->getParent()->addAssumption(Outside);
472 isl_space_free(Space);
473}
474
Johannes Doerferte7044942015-02-24 11:58:30 +0000475void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
476 ScalarEvolution *SE = Statement->getParent()->getSE();
477
478 Value *Ptr = getPointerOperand(*getAccessInstruction());
479 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
480 return;
481
482 auto *PtrSCEV = SE->getSCEV(Ptr);
483 if (isa<SCEVCouldNotCompute>(PtrSCEV))
484 return;
485
486 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
487 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
488 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
489
490 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
491 if (Range.isFullSet())
492 return;
493
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000494 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000495 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000496 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
497 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
498
499 auto Min = LB.sdiv(APInt(BW, ElementSize));
500 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000501
502 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
503 AccessRange =
504 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
505 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
506}
507
Michael Krusee2bccbb2015-09-18 19:59:43 +0000508__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000509 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000510 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000511
512 for (int i = Size - 2; i >= 0; --i) {
513 isl_space *Space;
514 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000515 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000516
517 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
518 isl_pw_aff_free(DimSize);
519 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
520
521 Space = isl_map_get_space(AccessRelation);
522 Space = isl_space_map_from_set(isl_space_range(Space));
523 Space = isl_space_align_params(Space, SpaceSize);
524
525 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
526 isl_id_free(ParamId);
527
528 MapOne = isl_map_universe(isl_space_copy(Space));
529 for (int j = 0; j < Size; ++j)
530 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
531 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
532
533 MapTwo = isl_map_universe(isl_space_copy(Space));
534 for (int j = 0; j < Size; ++j)
535 if (j < i || j > i + 1)
536 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
537
538 isl_local_space *LS = isl_local_space_from_space(Space);
539 isl_constraint *C;
540 C = isl_equality_alloc(isl_local_space_copy(LS));
541 C = isl_constraint_set_constant_si(C, -1);
542 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
543 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
544 MapTwo = isl_map_add_constraint(MapTwo, C);
545 C = isl_equality_alloc(LS);
546 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
547 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
548 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
549 MapTwo = isl_map_add_constraint(MapTwo, C);
550 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
551
552 MapOne = isl_map_union(MapOne, MapTwo);
553 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
554 }
555 return AccessRelation;
556}
557
Michael Krusee2bccbb2015-09-18 19:59:43 +0000558void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
559 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000560
Michael Krusee2bccbb2015-09-18 19:59:43 +0000561 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000562 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000563
Michael Krusee2bccbb2015-09-18 19:59:43 +0000564 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000565 // We overapproximate non-affine accesses with a possible access to the
566 // whole array. For read accesses it does not make a difference, if an
567 // access must or may happen. However, for write accesses it is important to
568 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000569 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000570 AccessRelation =
571 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000572
Michael Krusee2bccbb2015-09-18 19:59:43 +0000573 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000574 return;
575 }
576
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000577 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000578 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000579
Michael Krusee2bccbb2015-09-18 19:59:43 +0000580 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
581 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000582
Sebastian Pop422e33f2014-06-03 18:16:31 +0000583 if (Size == 1) {
584 // For the non delinearized arrays, divide the access function of the last
585 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000586 //
587 // A stride one array access in C expressed as A[i] is expressed in
588 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
589 // two subsequent values of 'i' index two values that are stored next to
590 // each other in memory. By this division we make this characteristic
591 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000592 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000593 Affine = isl_pw_aff_scale_down_val(Affine, v);
594 }
595
596 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
597
Tobias Grosser79baa212014-04-10 08:38:02 +0000598 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000599 }
600
Michael Krusee2bccbb2015-09-18 19:59:43 +0000601 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
602 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000603
Tobias Grosser79baa212014-04-10 08:38:02 +0000604 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000605 AccessRelation = isl_map_set_tuple_id(
606 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000607 AccessRelation =
608 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
609
Michael Krusee2bccbb2015-09-18 19:59:43 +0000610 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000611 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000612 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000613}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000614
Michael Krusee2bccbb2015-09-18 19:59:43 +0000615MemoryAccess::MemoryAccess(Instruction *AccessInst, __isl_take isl_id *Id,
616 AccessType Type, Value *BaseAddress,
617 const SCEV *Offset, unsigned ElemBytes, bool Affine,
618 ArrayRef<const SCEV *> Subscripts,
619 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
620 bool IsPHI, StringRef BaseName)
621 : Id(Id), IsPHI(IsPHI), AccType(Type), RedType(RT_NONE), Statement(nullptr),
622 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
623 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
624 AccessValue(AccessValue), Offset(Offset), IsAffine(Affine),
625 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
626 NewAccessRelation(nullptr) {}
627
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000628void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000629 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000630 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000631}
632
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000633const std::string MemoryAccess::getReductionOperatorStr() const {
634 return MemoryAccess::getReductionOperatorStr(getReductionType());
635}
636
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000637__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
638
Johannes Doerfertf6183392014-07-01 20:52:51 +0000639raw_ostream &polly::operator<<(raw_ostream &OS,
640 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000641 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000642 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000643 else
644 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000645 return OS;
646}
647
Tobias Grosser75805372011-04-29 06:27:02 +0000648void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000649 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000650 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000651 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000652 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000653 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000654 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000655 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000656 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000657 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000658 break;
659 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000660 OS << "[Reduction Type: " << getReductionType() << "] ";
661 OS << "[Scalar: " << isScalar() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000662 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000663 if (hasNewAccessRelation())
664 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000665}
666
Tobias Grosser74394f02013-01-14 22:40:23 +0000667void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000668
669// Create a map in the size of the provided set domain, that maps from the
670// one element of the provided set domain to another element of the provided
671// set domain.
672// The mapping is limited to all points that are equal in all but the last
673// dimension and for which the last dimension of the input is strict smaller
674// than the last dimension of the output.
675//
676// getEqualAndLarger(set[i0, i1, ..., iX]):
677//
678// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
679// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
680//
Tobias Grosserf5338802011-10-06 00:03:35 +0000681static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000682 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000683 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000684 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000685
686 // Set all but the last dimension to be equal for the input and output
687 //
688 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
689 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000690 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000691 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000692
693 // Set the last dimension of the input to be strict smaller than the
694 // last dimension of the output.
695 //
696 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000697 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
698 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000699 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000700}
701
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000702__isl_give isl_set *
703MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000704 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000705 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000706 isl_space *Space = isl_space_range(isl_map_get_space(S));
707 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000708
Sebastian Popa00a0292012-12-18 07:46:06 +0000709 S = isl_map_reverse(S);
710 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000711
Sebastian Popa00a0292012-12-18 07:46:06 +0000712 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
713 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
714 NextScatt = isl_map_apply_domain(NextScatt, S);
715 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000716
Sebastian Popa00a0292012-12-18 07:46:06 +0000717 isl_set *Deltas = isl_map_deltas(NextScatt);
718 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000719}
720
Sebastian Popa00a0292012-12-18 07:46:06 +0000721bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000722 int StrideWidth) const {
723 isl_set *Stride, *StrideX;
724 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000725
Sebastian Popa00a0292012-12-18 07:46:06 +0000726 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000727 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000728 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
729 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
730 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
731 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000732 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000733
Tobias Grosser28dd4862012-01-24 16:42:16 +0000734 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000735 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000736
Tobias Grosser28dd4862012-01-24 16:42:16 +0000737 return IsStrideX;
738}
739
Sebastian Popa00a0292012-12-18 07:46:06 +0000740bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
741 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000742}
743
Tobias Grosser79baa212014-04-10 08:38:02 +0000744bool MemoryAccess::isScalar() const {
745 return isl_map_n_out(AccessRelation) == 0;
746}
747
Sebastian Popa00a0292012-12-18 07:46:06 +0000748bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
749 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000750}
751
Tobias Grosser166c4222015-09-05 07:46:40 +0000752void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
753 isl_map_free(NewAccessRelation);
754 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000755}
Tobias Grosser75805372011-04-29 06:27:02 +0000756
757//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000758
Tobias Grosser808cd692015-07-14 09:33:13 +0000759isl_map *ScopStmt::getSchedule() const {
760 isl_set *Domain = getDomain();
761 if (isl_set_is_empty(Domain)) {
762 isl_set_free(Domain);
763 return isl_map_from_aff(
764 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
765 }
766 auto *Schedule = getParent()->getSchedule();
767 Schedule = isl_union_map_intersect_domain(
768 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
769 if (isl_union_map_is_empty(Schedule)) {
770 isl_set_free(Domain);
771 isl_union_map_free(Schedule);
772 return isl_map_from_aff(
773 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
774 }
775 auto *M = isl_map_from_union_map(Schedule);
776 M = isl_map_coalesce(M);
777 M = isl_map_gist_domain(M, Domain);
778 M = isl_map_coalesce(M);
779 return M;
780}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000781
Johannes Doerfert574182d2015-08-12 10:19:50 +0000782__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000783 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
784 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000785}
786
Tobias Grosser37eb4222014-02-20 21:43:54 +0000787void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
788 assert(isl_set_is_subset(NewDomain, Domain) &&
789 "New domain is not a subset of old domain!");
790 isl_set_free(Domain);
791 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000792}
793
Michael Kruse9d080092015-09-11 21:41:48 +0000794void ScopStmt::buildAccesses(BasicBlock *Block, bool isApproximated) {
795 AccFuncSetType *AFS = Parent.getAccessFunctions(Block);
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000796 if (!AFS)
797 return;
798
Michael Krusee2bccbb2015-09-18 19:59:43 +0000799 for (auto &Access : *AFS) {
800 Instruction *AccessInst = Access.getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000801 Type *ElementType = Access.getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000802
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000803 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Michael Krusee2bccbb2015-09-18 19:59:43 +0000804 Access.getBaseAddr(), ElementType, Access.Sizes, Access.isPHI());
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000805
Michael Krusee2bccbb2015-09-18 19:59:43 +0000806 if (isApproximated && Access.isMustWrite())
807 Access.AccType = MemoryAccess::MAY_WRITE;
Johannes Doerfertff9d1982015-02-24 12:00:50 +0000808
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000809 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
810 if (!MAL)
811 MAL = new MemoryAccessList();
Michael Krusee2bccbb2015-09-18 19:59:43 +0000812 Access.setStatement(this);
813 Access.buildAccessRelation(SAI);
814 MAL->emplace_front(&Access);
815 MemAccs.push_back(MAL->front());
Tobias Grosser75805372011-04-29 06:27:02 +0000816 }
817}
818
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000819void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000820 for (MemoryAccess *MA : *this)
821 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000822
823 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000824}
825
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000826/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
827static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
828 void *User) {
829 isl_set **BoundedParts = static_cast<isl_set **>(User);
830 if (isl_basic_set_is_bounded(BSet))
831 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
832 else
833 isl_basic_set_free(BSet);
834 return isl_stat_ok;
835}
836
837/// @brief Return the bounded parts of @p S.
838static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
839 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
840 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
841 isl_set_free(S);
842 return BoundedParts;
843}
844
845/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
846///
847/// @returns A separation of @p S into first an unbounded then a bounded subset,
848/// both with regards to the dimension @p Dim.
849static std::pair<__isl_give isl_set *, __isl_give isl_set *>
850partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
851
852 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000853 S = isl_set_lower_bound_si(S, isl_dim_set, u, u == Dim ? -1 : 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000854
855 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000856 isl_set *OnlyDimS = S;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000857
858 // Remove dimensions that are greater than Dim as they are not interesting.
859 assert(NumDimsS >= Dim + 1);
860 OnlyDimS =
861 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
862
863 // Create artificial parametric upper bounds for dimensions smaller than Dim
864 // as we are not interested in them.
865 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
866 for (unsigned u = 0; u < Dim; u++) {
867 isl_constraint *C = isl_inequality_alloc(
868 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
869 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
870 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
871 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
872 }
873
874 // Collect all bounded parts of OnlyDimS.
875 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
876
877 // Create the dimensions greater than Dim again.
878 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
879 NumDimsS - Dim - 1);
880
881 // Remove the artificial upper bound parameters again.
882 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
883
Johannes Doerfertca1e38f2015-09-14 11:12:52 +0000884 isl_set *UnboundedParts = isl_set_complement(isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000885 return std::make_pair(UnboundedParts, BoundedParts);
886}
887
Johannes Doerfert96425c22015-08-30 21:13:53 +0000888static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
889 isl_pw_aff *L, isl_pw_aff *R) {
890 switch (Pred) {
891 case ICmpInst::ICMP_EQ:
892 return isl_pw_aff_eq_set(L, R);
893 case ICmpInst::ICMP_NE:
894 return isl_pw_aff_ne_set(L, R);
895 case ICmpInst::ICMP_SLT:
896 return isl_pw_aff_lt_set(L, R);
897 case ICmpInst::ICMP_SLE:
898 return isl_pw_aff_le_set(L, R);
899 case ICmpInst::ICMP_SGT:
900 return isl_pw_aff_gt_set(L, R);
901 case ICmpInst::ICMP_SGE:
902 return isl_pw_aff_ge_set(L, R);
903 case ICmpInst::ICMP_ULT:
904 return isl_pw_aff_lt_set(L, R);
905 case ICmpInst::ICMP_UGT:
906 return isl_pw_aff_gt_set(L, R);
907 case ICmpInst::ICMP_ULE:
908 return isl_pw_aff_le_set(L, R);
909 case ICmpInst::ICMP_UGE:
910 return isl_pw_aff_ge_set(L, R);
911 default:
912 llvm_unreachable("Non integer predicate not supported");
913 }
914}
915
916/// @brief Build the conditions sets for the branch @p BI in the @p Domain.
917///
918/// This will fill @p ConditionSets with the conditions under which control
919/// will be moved from @p BI to its successors. Hence, @p ConditionSets will
920/// have as many elements as @p BI has successors.
921static void
922buildConditionSets(Scop &S, BranchInst *BI, Loop *L, __isl_keep isl_set *Domain,
923 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
924
925 if (BI->isUnconditional()) {
926 ConditionSets.push_back(isl_set_copy(Domain));
927 return;
928 }
929
930 Value *Condition = BI->getCondition();
931
932 isl_set *ConsequenceCondSet = nullptr;
933 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
934 if (CCond->isZero())
935 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
936 else
937 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
938 } else {
939 auto *ICond = dyn_cast<ICmpInst>(Condition);
940 assert(ICond &&
941 "Condition of exiting branch was neither constant nor ICmp!");
942
943 ScalarEvolution &SE = *S.getSE();
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000944 BasicBlock *BB = BI->getParent();
Johannes Doerfert96425c22015-08-30 21:13:53 +0000945 isl_pw_aff *LHS, *RHS;
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000946 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
947 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
Johannes Doerfert96425c22015-08-30 21:13:53 +0000948 ConsequenceCondSet = buildConditionSet(ICond->getPredicate(), LHS, RHS);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +0000949
950 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
951 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
952 ConsequenceCondSet =
953 isl_set_set_dim_id(ConsequenceCondSet, isl_dim_set, u, DimId);
954 }
Johannes Doerfert96425c22015-08-30 21:13:53 +0000955 }
956
957 assert(ConsequenceCondSet);
958 isl_set *AlternativeCondSet =
959 isl_set_complement(isl_set_copy(ConsequenceCondSet));
960
961 ConditionSets.push_back(isl_set_coalesce(
962 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
963 ConditionSets.push_back(isl_set_coalesce(
964 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
965}
966
Johannes Doerfert32ae76e2015-09-10 13:12:02 +0000967void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000968 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +0000969
Tobias Grosser084d8f72012-05-29 09:29:44 +0000970 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
971
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000972 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +0000973 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +0000974}
975
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000976void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
977 int Dimension = 0;
978 isl_ctx *Ctx = Parent.getIslCtx();
979 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
980 Type *Ty = GEP->getPointerOperandType();
981 ScalarEvolution &SE = *Parent.getSE();
982
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000983 std::vector<const SCEV *> Subscripts;
984 std::vector<int> Sizes;
985
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000986 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000987
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000988 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
989 Dimension = 1;
990 Ty = PtrTy->getElementType();
991 }
992
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000993 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000994
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000995 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +0000996
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +0000997 for (size_t i = 0; i < Sizes.size(); i++) {
998 auto Expr = Subscripts[i + IndexOffset];
999 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001000
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001001 if (!isAffineExpr(&Parent.getRegion(), Expr, SE))
1002 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001003
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001004 isl_pw_aff *AccessOffset = getPwAff(Expr);
1005 AccessOffset =
1006 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001007
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001008 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1009 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001010
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001011 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1012 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1013 OutOfBound = isl_set_params(OutOfBound);
1014 isl_set *InBound = isl_set_complement(OutOfBound);
1015 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001016
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001017 // A => B == !A or B
1018 isl_set *InBoundIfExecuted =
1019 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001020
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001021 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001022 }
1023
1024 isl_local_space_free(LSpace);
1025}
1026
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001027void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1028 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001029 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1030 deriveAssumptionsFromGEP(GEP);
1031}
1032
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001033void ScopStmt::collectSurroundingLoops() {
1034 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1035 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1036 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1037 isl_id_free(DimId);
1038 }
1039}
1040
Michael Kruse9d080092015-09-11 21:41:48 +00001041ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001042 : Parent(parent), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001043
Tobias Grosser16c44032015-07-09 07:31:45 +00001044 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001045
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001046 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001047 collectSurroundingLoops();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001048
1049 BasicBlock *EntryBB = R.getEntry();
1050 for (BasicBlock *Block : R.blocks()) {
Michael Kruse9d080092015-09-11 21:41:48 +00001051 buildAccesses(Block, Block != EntryBB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001052 deriveAssumptions(Block);
1053 }
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001054 if (DetectReductions)
1055 checkForReductions();
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001056}
1057
Michael Kruse9d080092015-09-11 21:41:48 +00001058ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001059 : Parent(parent), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001060
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001061 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Tobias Grosser75805372011-04-29 06:27:02 +00001062
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001063 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001064 collectSurroundingLoops();
Michael Kruse9d080092015-09-11 21:41:48 +00001065 buildAccesses(BB);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001066 deriveAssumptions(BB);
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001067 if (DetectReductions)
1068 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001069}
1070
Johannes Doerferte58a0122014-06-27 20:31:28 +00001071/// @brief Collect loads which might form a reduction chain with @p StoreMA
1072///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001073/// Check if the stored value for @p StoreMA is a binary operator with one or
1074/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001075/// used only once (by @p StoreMA) and its load operands are also used only
1076/// once, we have found a possible reduction chain. It starts at an operand
1077/// load and includes the binary operator and @p StoreMA.
1078///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001079/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001080/// escape this block or into any other store except @p StoreMA.
1081void ScopStmt::collectCandiateReductionLoads(
1082 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1083 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1084 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001085 return;
1086
1087 // Skip if there is not one binary operator between the load and the store
1088 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001089 if (!BinOp)
1090 return;
1091
1092 // Skip if the binary operators has multiple uses
1093 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001094 return;
1095
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001096 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001097 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1098 return;
1099
Johannes Doerfert9890a052014-07-01 00:32:29 +00001100 // Skip if the binary operator is outside the current SCoP
1101 if (BinOp->getParent() != Store->getParent())
1102 return;
1103
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001104 // Skip if it is a multiplicative reduction and we disabled them
1105 if (DisableMultiplicativeReductions &&
1106 (BinOp->getOpcode() == Instruction::Mul ||
1107 BinOp->getOpcode() == Instruction::FMul))
1108 return;
1109
Johannes Doerferte58a0122014-06-27 20:31:28 +00001110 // Check the binary operator operands for a candidate load
1111 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1112 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1113 if (!PossibleLoad0 && !PossibleLoad1)
1114 return;
1115
1116 // A load is only a candidate if it cannot escape (thus has only this use)
1117 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001118 if (PossibleLoad0->getParent() == Store->getParent())
1119 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001120 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001121 if (PossibleLoad1->getParent() == Store->getParent())
1122 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001123}
1124
1125/// @brief Check for reductions in this ScopStmt
1126///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001127/// Iterate over all store memory accesses and check for valid binary reduction
1128/// like chains. For all candidates we check if they have the same base address
1129/// and there are no other accesses which overlap with them. The base address
1130/// check rules out impossible reductions candidates early. The overlap check,
1131/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001132/// guarantees that none of the intermediate results will escape during
1133/// execution of the loop nest. We basically check here that no other memory
1134/// access can access the same memory as the potential reduction.
1135void ScopStmt::checkForReductions() {
1136 SmallVector<MemoryAccess *, 2> Loads;
1137 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1138
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001139 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001140 // stores and collecting possible reduction loads.
1141 for (MemoryAccess *StoreMA : MemAccs) {
1142 if (StoreMA->isRead())
1143 continue;
1144
1145 Loads.clear();
1146 collectCandiateReductionLoads(StoreMA, Loads);
1147 for (MemoryAccess *LoadMA : Loads)
1148 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1149 }
1150
1151 // Then check each possible candidate pair.
1152 for (const auto &CandidatePair : Candidates) {
1153 bool Valid = true;
1154 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1155 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1156
1157 // Skip those with obviously unequal base addresses.
1158 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1159 isl_map_free(LoadAccs);
1160 isl_map_free(StoreAccs);
1161 continue;
1162 }
1163
1164 // And check if the remaining for overlap with other memory accesses.
1165 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1166 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1167 isl_set *AllAccs = isl_map_range(AllAccsRel);
1168
1169 for (MemoryAccess *MA : MemAccs) {
1170 if (MA == CandidatePair.first || MA == CandidatePair.second)
1171 continue;
1172
1173 isl_map *AccRel =
1174 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1175 isl_set *Accs = isl_map_range(AccRel);
1176
1177 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1178 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1179 Valid = Valid && isl_set_is_empty(OverlapAccs);
1180 isl_set_free(OverlapAccs);
1181 }
1182 }
1183
1184 isl_set_free(AllAccs);
1185 if (!Valid)
1186 continue;
1187
Johannes Doerfertf6183392014-07-01 20:52:51 +00001188 const LoadInst *Load =
1189 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1190 MemoryAccess::ReductionType RT =
1191 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1192
Johannes Doerferte58a0122014-06-27 20:31:28 +00001193 // If no overlapping access was found we mark the load and store as
1194 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001195 CandidatePair.first->markAsReductionLike(RT);
1196 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001197 }
Tobias Grosser75805372011-04-29 06:27:02 +00001198}
1199
Tobias Grosser74394f02013-01-14 22:40:23 +00001200std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001201
Tobias Grosser54839312015-04-21 11:37:25 +00001202std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001203 auto *S = getSchedule();
1204 auto Str = stringFromIslObj(S);
1205 isl_map_free(S);
1206 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001207}
1208
Tobias Grosser74394f02013-01-14 22:40:23 +00001209unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001210
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001211unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001212
Tobias Grosser75805372011-04-29 06:27:02 +00001213const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1214
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001215const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001216 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001217}
1218
Tobias Grosser74394f02013-01-14 22:40:23 +00001219isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001220
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001221__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001222
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001223__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001224 return isl_set_get_space(Domain);
1225}
1226
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001227__isl_give isl_id *ScopStmt::getDomainId() const {
1228 return isl_set_get_tuple_id(Domain);
1229}
Tobias Grossercd95b772012-08-30 11:49:38 +00001230
Tobias Grosser75805372011-04-29 06:27:02 +00001231ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001232 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001233 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001234}
1235
1236void ScopStmt::print(raw_ostream &OS) const {
1237 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001238 OS.indent(12) << "Domain :=\n";
1239
1240 if (Domain) {
1241 OS.indent(16) << getDomainStr() << ";\n";
1242 } else
1243 OS.indent(16) << "n/a\n";
1244
Tobias Grosser54839312015-04-21 11:37:25 +00001245 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001246
1247 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001248 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001249 } else
1250 OS.indent(16) << "n/a\n";
1251
Tobias Grosser083d3d32014-06-28 08:59:45 +00001252 for (MemoryAccess *Access : MemAccs)
1253 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001254}
1255
1256void ScopStmt::dump() const { print(dbgs()); }
1257
1258//===----------------------------------------------------------------------===//
1259/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001260
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001261void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001262 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1263 isl_set_free(Context);
1264 Context = NewContext;
1265}
1266
Tobias Grosserabfbe632013-02-05 12:09:06 +00001267void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001268 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001269 Parameter = extractConstantFactor(Parameter, *SE).second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00001270 if (ParameterIds.find(Parameter) != ParameterIds.end())
1271 continue;
1272
1273 int dimension = Parameters.size();
1274
1275 Parameters.push_back(Parameter);
1276 ParameterIds[Parameter] = dimension;
1277 }
1278}
1279
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001280__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1281 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001282
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001283 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001284 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001285
Tobias Grosser8f99c162011-11-15 11:38:55 +00001286 std::string ParameterName;
1287
1288 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1289 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001290 ParameterName = Val->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001291 }
1292
1293 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001294 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001295
Tobias Grosser20532b82014-04-11 17:56:49 +00001296 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1297 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001298}
Tobias Grosser75805372011-04-29 06:27:02 +00001299
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001300isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1301 isl_set *DomainContext = isl_union_set_params(getDomains());
1302 return isl_set_intersect_params(C, DomainContext);
1303}
1304
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001305void Scop::buildBoundaryContext() {
1306 BoundaryContext = Affinator.getWrappingContext();
1307 BoundaryContext = isl_set_complement(BoundaryContext);
1308 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1309}
1310
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001311void Scop::addUserContext() {
1312 if (UserContextStr.empty())
1313 return;
1314
1315 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1316 isl_space *Space = getParamSpace();
1317 if (isl_space_dim(Space, isl_dim_param) !=
1318 isl_set_dim(UserContext, isl_dim_param)) {
1319 auto SpaceStr = isl_space_to_str(Space);
1320 errs() << "Error: the context provided in -polly-context has not the same "
1321 << "number of dimensions than the computed context. Due to this "
1322 << "mismatch, the -polly-context option is ignored. Please provide "
1323 << "the context in the parameter space: " << SpaceStr << ".\n";
1324 free(SpaceStr);
1325 isl_set_free(UserContext);
1326 isl_space_free(Space);
1327 return;
1328 }
1329
1330 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1331 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1332 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1333
1334 if (strcmp(NameContext, NameUserContext) != 0) {
1335 auto SpaceStr = isl_space_to_str(Space);
1336 errs() << "Error: the name of dimension " << i
1337 << " provided in -polly-context "
1338 << "is '" << NameUserContext << "', but the name in the computed "
1339 << "context is '" << NameContext
1340 << "'. Due to this name mismatch, "
1341 << "the -polly-context option is ignored. Please provide "
1342 << "the context in the parameter space: " << SpaceStr << ".\n";
1343 free(SpaceStr);
1344 isl_set_free(UserContext);
1345 isl_space_free(Space);
1346 return;
1347 }
1348
1349 UserContext =
1350 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1351 isl_space_get_dim_id(Space, isl_dim_param, i));
1352 }
1353
1354 Context = isl_set_intersect(Context, UserContext);
1355 isl_space_free(Space);
1356}
1357
Tobias Grosser6be480c2011-11-08 15:41:13 +00001358void Scop::buildContext() {
1359 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001360 Context = isl_set_universe(isl_space_copy(Space));
1361 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001362}
1363
Tobias Grosser18daaca2012-05-22 10:47:27 +00001364void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001365 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001366 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001367
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001368 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001369
Johannes Doerferte7044942015-02-24 11:58:30 +00001370 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001371 }
1372}
1373
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001374void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001375 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001376 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001377
Tobias Grosser083d3d32014-06-28 08:59:45 +00001378 for (const auto &ParamID : ParameterIds) {
1379 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001380 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001381 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001382 }
1383
1384 // Align the parameters of all data structures to the model.
1385 Context = isl_set_align_params(Context, Space);
1386
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001387 for (ScopStmt &Stmt : *this)
1388 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001389}
1390
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001391static __isl_give isl_set *
1392simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1393 const Scop &S) {
1394 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1395 AssumptionContext = isl_set_gist_params(AssumptionContext, DomainParameters);
1396 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1397 return AssumptionContext;
1398}
1399
1400void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001401 // The parameter constraints of the iteration domains give us a set of
1402 // constraints that need to hold for all cases where at least a single
1403 // statement iteration is executed in the whole scop. We now simplify the
1404 // assumed context under the assumption that such constraints hold and at
1405 // least a single statement iteration is executed. For cases where no
1406 // statement instances are executed, the assumptions we have taken about
1407 // the executed code do not matter and can be changed.
1408 //
1409 // WARNING: This only holds if the assumptions we have taken do not reduce
1410 // the set of statement instances that are executed. Otherwise we
1411 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001412 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001413 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001414 // performed. In such a case, modifying the run-time conditions and
1415 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001416 // to not be executed.
1417 //
1418 // Example:
1419 //
1420 // When delinearizing the following code:
1421 //
1422 // for (long i = 0; i < 100; i++)
1423 // for (long j = 0; j < m; j++)
1424 // A[i+p][j] = 1.0;
1425 //
1426 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001427 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001428 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001429 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1430 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001431}
1432
Johannes Doerfertb164c792014-09-18 11:17:17 +00001433/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001434static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001435 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1436 isl_pw_multi_aff *MinPMA, *MaxPMA;
1437 isl_pw_aff *LastDimAff;
1438 isl_aff *OneAff;
1439 unsigned Pos;
1440
Johannes Doerfert9143d672014-09-27 11:02:39 +00001441 // Restrict the number of parameters involved in the access as the lexmin/
1442 // lexmax computation will take too long if this number is high.
1443 //
1444 // Experiments with a simple test case using an i7 4800MQ:
1445 //
1446 // #Parameters involved | Time (in sec)
1447 // 6 | 0.01
1448 // 7 | 0.04
1449 // 8 | 0.12
1450 // 9 | 0.40
1451 // 10 | 1.54
1452 // 11 | 6.78
1453 // 12 | 30.38
1454 //
1455 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1456 unsigned InvolvedParams = 0;
1457 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1458 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1459 InvolvedParams++;
1460
1461 if (InvolvedParams > RunTimeChecksMaxParameters) {
1462 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001463 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001464 }
1465 }
1466
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001467 Set = isl_set_remove_divs(Set);
1468
Johannes Doerfertb164c792014-09-18 11:17:17 +00001469 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1470 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1471
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001472 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1473 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1474
Johannes Doerfertb164c792014-09-18 11:17:17 +00001475 // Adjust the last dimension of the maximal access by one as we want to
1476 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1477 // we test during code generation might now point after the end of the
1478 // allocated array but we will never dereference it anyway.
1479 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1480 "Assumed at least one output dimension");
1481 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1482 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1483 OneAff = isl_aff_zero_on_domain(
1484 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1485 OneAff = isl_aff_add_constant_si(OneAff, 1);
1486 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1487 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1488
1489 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1490
1491 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001492 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001493}
1494
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001495static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1496 isl_set *Domain = MA->getStatement()->getDomain();
1497 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1498 return isl_set_reset_tuple_id(Domain);
1499}
1500
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001501/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1502static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001503 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001504 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001505
1506 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1507 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001508 Locations = isl_union_set_coalesce(Locations);
1509 Locations = isl_union_set_detect_equalities(Locations);
1510 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001511 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001512 isl_union_set_free(Locations);
1513 return Valid;
1514}
1515
Johannes Doerfert96425c22015-08-30 21:13:53 +00001516/// @brief Helper to treat non-affine regions and basic blocks the same.
1517///
1518///{
1519
1520/// @brief Return the block that is the representing block for @p RN.
1521static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1522 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1523 : RN->getNodeAs<BasicBlock>();
1524}
1525
1526/// @brief Return the @p idx'th block that is executed after @p RN.
1527static inline BasicBlock *getRegionNodeSuccessor(RegionNode *RN, BranchInst *BI,
1528 unsigned idx) {
1529 if (RN->isSubRegion()) {
1530 assert(idx == 0);
1531 return RN->getNodeAs<Region>()->getExit();
1532 }
1533 return BI->getSuccessor(idx);
1534}
1535
1536/// @brief Return the smallest loop surrounding @p RN.
1537static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1538 if (!RN->isSubRegion())
1539 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1540
1541 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1542 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1543 while (L && NonAffineSubRegion->contains(L))
1544 L = L->getParentLoop();
1545 return L;
1546}
1547
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001548static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1549 if (!RN->isSubRegion())
1550 return 1;
1551
1552 unsigned NumBlocks = 0;
1553 Region *R = RN->getNodeAs<Region>();
1554 for (auto BB : R->blocks()) {
1555 (void)BB;
1556 NumBlocks++;
1557 }
1558 return NumBlocks;
1559}
1560
Johannes Doerfert96425c22015-08-30 21:13:53 +00001561///}
1562
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001563static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1564 unsigned Dim, Loop *L) {
1565 isl_id *DimId =
1566 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1567 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1568}
1569
Johannes Doerfert96425c22015-08-30 21:13:53 +00001570isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1571 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1572 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001573 return getDomainConditions(BB);
1574}
1575
1576isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1577 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001578 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001579}
1580
1581void Scop::buildDomains(Region *R, LoopInfo &LI, ScopDetection &SD,
1582 DominatorTree &DT) {
1583
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001584 auto *EntryBB = R->getEntry();
1585 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1586 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001587
1588 Loop *L = LI.getLoopFor(EntryBB);
1589 while (LD-- >= 0) {
1590 S = addDomainDimId(S, LD + 1, L);
1591 L = L->getParentLoop();
1592 }
1593
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001594 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001595
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001596 if (SD.isNonAffineSubRegion(R, R))
1597 return;
1598
Johannes Doerfert96425c22015-08-30 21:13:53 +00001599 buildDomainsWithBranchConstraints(R, LI, SD, DT);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001600 addLoopBoundsToHeaderDomains(LI, SD, DT);
1601 propagateDomainConstraints(R, LI, SD, DT);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001602}
1603
1604void Scop::buildDomainsWithBranchConstraints(Region *R, LoopInfo &LI,
1605 ScopDetection &SD,
1606 DominatorTree &DT) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001607 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001608
1609 // To create the domain for each block in R we iterate over all blocks and
1610 // subregions in R and propagate the conditions under which the current region
1611 // element is executed. To this end we iterate in reverse post order over R as
1612 // it ensures that we first visit all predecessors of a region node (either a
1613 // basic block or a subregion) before we visit the region node itself.
1614 // Initially, only the domain for the SCoP region entry block is set and from
1615 // there we propagate the current domain to all successors, however we add the
1616 // condition that the successor is actually executed next.
1617 // As we are only interested in non-loop carried constraints here we can
1618 // simply skip loop back edges.
1619
1620 ReversePostOrderTraversal<Region *> RTraversal(R);
1621 for (auto *RN : RTraversal) {
1622
1623 // Recurse for affine subregions but go on for basic blocks and non-affine
1624 // subregions.
1625 if (RN->isSubRegion()) {
1626 Region *SubRegion = RN->getNodeAs<Region>();
1627 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1628 buildDomainsWithBranchConstraints(SubRegion, LI, SD, DT);
1629 continue;
1630 }
1631 }
1632
1633 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001634 TerminatorInst *TI = BB->getTerminator();
1635
1636 // Unreachable instructions do not have successors so we can skip them.
1637 if (isa<UnreachableInst>(TI)) {
1638 // Assume unreachables only in error blocks.
1639 assert(isErrorBlock(*BB));
1640 continue;
1641 }
1642
Johannes Doerfert96425c22015-08-30 21:13:53 +00001643 isl_set *Domain = DomainMap[BB];
1644 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
1645 assert(Domain && "Due to reverse post order traversal of the region all "
1646 "predecessor of the current region node should have been "
1647 "visited and a domain for this region node should have "
1648 "been set.");
1649
1650 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1651 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1652
1653 // Build the condition sets for the successor nodes of the current region
1654 // node. If it is a non-affine subregion we will always execute the single
1655 // exit node, hence the single entry node domain is the condition set. For
1656 // basic blocks we use the helper function buildConditionSets.
1657 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001658 BranchInst *BI = cast<BranchInst>(TI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001659 if (RN->isSubRegion())
1660 ConditionSets.push_back(isl_set_copy(Domain));
1661 else
1662 buildConditionSets(*this, BI, BBLoop, Domain, ConditionSets);
1663
1664 // Now iterate over the successors and set their initial domain based on
1665 // their condition set. We skip back edges here and have to be careful when
1666 // we leave a loop not to keep constraints over a dimension that doesn't
1667 // exist anymore.
1668 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
1669 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, BI, u);
1670 isl_set *CondSet = ConditionSets[u];
1671
1672 // Skip back edges.
1673 if (DT.dominates(SuccBB, BB)) {
1674 isl_set_free(CondSet);
1675 continue;
1676 }
1677
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001678 // Do not adjust the number of dimensions if we enter a boxed loop or are
1679 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001680 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001681 Region *SuccRegion = RI.getRegionFor(SuccBB);
1682 if (BBLoop != SuccBBLoop && !RN->isSubRegion() &&
1683 !(SD.isNonAffineSubRegion(SuccRegion, &getRegion()) &&
1684 SuccRegion->contains(SuccBBLoop))) {
1685
1686 // Check if the edge to SuccBB is a loop entry or exit edge. If so
1687 // adjust the dimensionality accordingly. Lastly, if we leave a loop
1688 // and enter a new one we need to drop the old constraints.
1689 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001690 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001691 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001692 CondSet = isl_set_project_out(CondSet, isl_dim_set,
1693 isl_set_n_dim(CondSet) - LoopDepthDiff,
1694 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001695 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001696 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001697 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001698 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001699 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001700 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001701 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
1702 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001703 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00001704 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00001705 }
1706
1707 // Set the domain for the successor or merge it with an existing domain in
1708 // case there are multiple paths (without loop back edges) to the
1709 // successor block.
1710 isl_set *&SuccDomain = DomainMap[SuccBB];
1711 if (!SuccDomain)
1712 SuccDomain = CondSet;
1713 else
1714 SuccDomain = isl_set_union(SuccDomain, CondSet);
1715
1716 SuccDomain = isl_set_coalesce(SuccDomain);
1717 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : " << Domain
1718 << "\n");
1719 }
1720 }
1721}
1722
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001723/// @brief Return the domain for @p BB wrt @p DomainMap.
1724///
1725/// This helper function will lookup @p BB in @p DomainMap but also handle the
1726/// case where @p BB is contained in a non-affine subregion using the region
1727/// tree obtained by @p RI.
1728static __isl_give isl_set *
1729getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
1730 RegionInfo &RI) {
1731 auto DIt = DomainMap.find(BB);
1732 if (DIt != DomainMap.end())
1733 return isl_set_copy(DIt->getSecond());
1734
1735 Region *R = RI.getRegionFor(BB);
1736 while (R->getEntry() == BB)
1737 R = R->getParent();
1738 return getDomainForBlock(R->getEntry(), DomainMap, RI);
1739}
1740
Johannes Doerferte114dc02015-09-14 11:15:58 +00001741static bool containsErrorBlock(RegionNode *RN) {
1742 if (!RN->isSubRegion())
1743 return isErrorBlock(*RN->getNodeAs<BasicBlock>());
1744 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
1745 if (isErrorBlock(*BB))
1746 return true;
1747 return false;
1748}
1749
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001750void Scop::propagateDomainConstraints(Region *R, LoopInfo &LI,
1751 ScopDetection &SD, DominatorTree &DT) {
1752 // Iterate over the region R and propagate the domain constrains from the
1753 // predecessors to the current node. In contrast to the
1754 // buildDomainsWithBranchConstraints function, this one will pull the domain
1755 // information from the predecessors instead of pushing it to the successors.
1756 // Additionally, we assume the domains to be already present in the domain
1757 // map here. However, we iterate again in reverse post order so we know all
1758 // predecessors have been visited before a block or non-affine subregion is
1759 // visited.
1760
1761 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
1762 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
1763
1764 ReversePostOrderTraversal<Region *> RTraversal(R);
1765 for (auto *RN : RTraversal) {
1766
1767 // Recurse for affine subregions but go on for basic blocks and non-affine
1768 // subregions.
1769 if (RN->isSubRegion()) {
1770 Region *SubRegion = RN->getNodeAs<Region>();
1771 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
1772 propagateDomainConstraints(SubRegion, LI, SD, DT);
1773 continue;
1774 }
1775 }
1776
1777 BasicBlock *BB = getRegionNodeBasicBlock(RN);
1778 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1779 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1780
1781 isl_set *&Domain = DomainMap[BB];
1782 assert(Domain && "Due to reverse post order traversal of the region all "
1783 "predecessor of the current region node should have been "
1784 "visited and a domain for this region node should have "
1785 "been set.");
1786
1787 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
1788 for (auto *PredBB : predecessors(BB)) {
1789
1790 // Skip backedges
1791 if (DT.dominates(BB, PredBB))
1792 continue;
1793
1794 isl_set *PredBBDom = nullptr;
1795
1796 // Handle the SCoP entry block with its outside predecessors.
1797 if (!getRegion().contains(PredBB))
1798 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
1799
1800 if (!PredBBDom) {
1801 // Determine the loop depth of the predecessor and adjust its domain to
1802 // the domain of the current block. This can mean we have to:
1803 // o) Drop a dimension if this block is the exit of a loop, not the
1804 // header of a new loop and the predecessor was part of the loop.
1805 // o) Add an unconstrainted new dimension if this block is the header
1806 // of a loop and the predecessor is not part of it.
1807 // o) Drop the information about the innermost loop dimension when the
1808 // predecessor and the current block are surrounded by different
1809 // loops in the same depth.
1810 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
1811 Loop *PredBBLoop = LI.getLoopFor(PredBB);
1812 while (BoxedLoops.count(PredBBLoop))
1813 PredBBLoop = PredBBLoop->getParentLoop();
1814
1815 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001816 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001817 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001818 PredBBDom = isl_set_project_out(
1819 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
1820 LoopDepthDiff);
1821 else if (PredBBLoopDepth < BBLoopDepth) {
1822 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001823 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001824 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
1825 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001826 PredBBDom = isl_set_drop_constraints_involving_dims(
1827 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00001828 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001829 }
1830
1831 PredDom = isl_set_union(PredDom, PredBBDom);
1832 }
1833
1834 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00001835 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001836
1837 // Add assumptions for error blocks.
Johannes Doerferte114dc02015-09-14 11:15:58 +00001838 if (containsErrorBlock(RN)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001839 IsOptimized = true;
1840 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
1841 addAssumption(isl_set_complement(DomPar));
1842 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001843 }
1844}
1845
1846/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
1847/// is incremented by one and all other dimensions are equal, e.g.,
1848/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
1849/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
1850static __isl_give isl_map *
1851createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
1852 auto *MapSpace = isl_space_map_from_set(SetSpace);
1853 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
1854 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
1855 if (u != Dim)
1856 NextIterationMap =
1857 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
1858 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
1859 C = isl_constraint_set_constant_si(C, 1);
1860 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
1861 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
1862 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
1863 return NextIterationMap;
1864}
1865
1866/// @brief Add @p L & all children to @p Loops if they are not in @p BoxedLoops.
1867static inline void
1868addLoopAndSubloops(Loop *L, SmallVectorImpl<Loop *> &Loops,
1869 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1870 if (BoxedLoops.count(L))
1871 return;
1872
1873 Loops.push_back(L);
1874 for (Loop *Subloop : *L)
1875 addLoopAndSubloops(Subloop, Loops, BoxedLoops);
1876}
1877
1878/// @brief Add loops in @p R to @p RegionLoops if they are not in @p BoxedLoops.
1879static inline void
1880collectLoopsInRegion(Region &R, LoopInfo &LI,
1881 SmallVector<Loop *, 8> &RegionLoops,
1882 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
1883
1884 SmallVector<Loop *, 8> Loops(LI.begin(), LI.end());
1885 while (!Loops.empty()) {
1886 Loop *L = Loops.pop_back_val();
1887
1888 if (R.contains(L))
1889 addLoopAndSubloops(L, RegionLoops, BoxedLoops);
1890 else if (L->contains(R.getEntry()))
1891 Loops.append(L->begin(), L->end());
1892 }
1893}
1894
1895/// @brief Create a set from @p Space with @p Dim fixed to 0.
1896static __isl_give isl_set *
1897createFirstIterationDomain(__isl_take isl_space *Space, unsigned Dim) {
1898 auto *Domain = isl_set_universe(Space);
1899 Domain = isl_set_fix_si(Domain, isl_dim_set, Dim, 0);
1900 return Domain;
1901}
1902
1903void Scop::addLoopBoundsToHeaderDomains(LoopInfo &LI, ScopDetection &SD,
1904 DominatorTree &DT) {
1905 // We iterate over all loops in the SCoP, create the condition set under which
1906 // we will take the back edge, and then apply these restrictions to the
1907 // header.
1908
1909 Region &R = getRegion();
1910 SmallVector<Loop *, 8> RegionLoops;
1911 collectLoopsInRegion(R, LI, RegionLoops, *SD.getBoxedLoops(&R));
1912
1913 while (!RegionLoops.empty()) {
1914 Loop *L = RegionLoops.pop_back_val();
1915 int LoopDepth = getRelativeLoopDepth(L);
1916 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
1917
1918 BasicBlock *LatchBB = L->getLoopLatch();
1919 assert(LatchBB && "TODO implement multiple exit loop handling");
1920
1921 isl_set *LatchBBDom = DomainMap[LatchBB];
1922 isl_set *BackedgeCondition = nullptr;
1923
1924 BasicBlock *HeaderBB = L->getHeader();
1925
1926 BranchInst *BI = cast<BranchInst>(LatchBB->getTerminator());
1927 if (BI->isUnconditional())
1928 BackedgeCondition = isl_set_copy(LatchBBDom);
1929 else {
1930 SmallVector<isl_set *, 2> ConditionSets;
1931 int idx = BI->getSuccessor(0) != HeaderBB;
1932 buildConditionSets(*this, BI, L, LatchBBDom, ConditionSets);
1933
1934 // Free the non back edge condition set as we do not need it.
1935 isl_set_free(ConditionSets[1 - idx]);
1936
1937 BackedgeCondition = ConditionSets[idx];
1938 }
1939
1940 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
1941 isl_set *FirstIteration =
1942 createFirstIterationDomain(isl_set_get_space(HeaderBBDom), LoopDepth);
1943
1944 isl_map *NextIterationMap =
1945 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
1946
1947 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
1948 assert(LatchLoopDepth >= LoopDepth);
1949 BackedgeCondition =
1950 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
1951 LatchLoopDepth - LoopDepth);
1952
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001953 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
1954 for (int i = 0; i < LoopDepth; i++)
1955 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
1956
1957 isl_set *BackedgeConditionComplement =
1958 isl_set_complement(BackedgeCondition);
1959 BackedgeConditionComplement = isl_set_lower_bound_si(
1960 BackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
1961 BackedgeConditionComplement =
1962 isl_set_apply(BackedgeConditionComplement, ForwardMap);
1963 HeaderBBDom = isl_set_subtract(HeaderBBDom, BackedgeConditionComplement);
1964
1965 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001966
1967 // If a loop has an unbounded back edge condition part (here Parts.first)
1968 // we do not want to assume the header will even be executed for the first
1969 // iteration of an execution that will lead to an infinite loop. While it
1970 // would not be wrong to do so, it does not seem helpful.
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001971 // TODO: Use the unbounded part to build runtime assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001972 FirstIteration = isl_set_subtract(FirstIteration, Parts.first);
1973
Johannes Doerfertca1e38f2015-09-14 11:12:52 +00001974 HeaderBBDom = isl_set_apply(Parts.second, NextIterationMap);
1975 HeaderBBDom = isl_set_coalesce(isl_set_union(HeaderBBDom, FirstIteration));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001976 }
1977}
1978
Johannes Doerfert120de4b2015-08-20 18:30:08 +00001979void Scop::buildAliasChecks(AliasAnalysis &AA) {
1980 if (!PollyUseRuntimeAliasChecks)
1981 return;
1982
1983 if (buildAliasGroups(AA))
1984 return;
1985
1986 // If a problem occurs while building the alias groups we need to delete
1987 // this SCoP and pretend it wasn't valid in the first place. To this end
1988 // we make the assumed context infeasible.
1989 addAssumption(isl_set_empty(getParamSpace()));
1990
1991 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
1992 << " could not be created as the number of parameters involved "
1993 "is too high. The SCoP will be "
1994 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
1995 "the maximal number of parameters but be advised that the "
1996 "compile time might increase exponentially.\n\n");
1997}
1998
Johannes Doerfert9143d672014-09-27 11:02:39 +00001999bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002000 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002001 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002002 // for all memory accesses inside the SCoP.
2003 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002004 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002005 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002006 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002007 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002008 // if their access domains intersect, otherwise they are in different
2009 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002010 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002011 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002012 // and maximal accesses to each array of a group in read only and non
2013 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002014 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2015
2016 AliasSetTracker AST(AA);
2017
2018 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002019 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002020 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002021
2022 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002023 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002024 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2025 isl_set_free(StmtDomain);
2026 if (StmtDomainEmpty)
2027 continue;
2028
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002029 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002030 if (MA->isScalar())
2031 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002032 if (!MA->isRead())
2033 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002034 Instruction *Acc = MA->getAccessInstruction();
2035 PtrToAcc[getPointerOperand(*Acc)] = MA;
2036 AST.add(Acc);
2037 }
2038 }
2039
2040 SmallVector<AliasGroupTy, 4> AliasGroups;
2041 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002042 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002043 continue;
2044 AliasGroupTy AG;
2045 for (auto PR : AS)
2046 AG.push_back(PtrToAcc[PR.getValue()]);
2047 assert(AG.size() > 1 &&
2048 "Alias groups should contain at least two accesses");
2049 AliasGroups.push_back(std::move(AG));
2050 }
2051
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002052 // Split the alias groups based on their domain.
2053 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2054 AliasGroupTy NewAG;
2055 AliasGroupTy &AG = AliasGroups[u];
2056 AliasGroupTy::iterator AGI = AG.begin();
2057 isl_set *AGDomain = getAccessDomain(*AGI);
2058 while (AGI != AG.end()) {
2059 MemoryAccess *MA = *AGI;
2060 isl_set *MADomain = getAccessDomain(MA);
2061 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2062 NewAG.push_back(MA);
2063 AGI = AG.erase(AGI);
2064 isl_set_free(MADomain);
2065 } else {
2066 AGDomain = isl_set_union(AGDomain, MADomain);
2067 AGI++;
2068 }
2069 }
2070 if (NewAG.size() > 1)
2071 AliasGroups.push_back(std::move(NewAG));
2072 isl_set_free(AGDomain);
2073 }
2074
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002075 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002076 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2077 for (AliasGroupTy &AG : AliasGroups) {
2078 NonReadOnlyBaseValues.clear();
2079 ReadOnlyPairs.clear();
2080
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002081 if (AG.size() < 2) {
2082 AG.clear();
2083 continue;
2084 }
2085
Johannes Doerfert13771732014-10-01 12:40:46 +00002086 for (auto II = AG.begin(); II != AG.end();) {
2087 Value *BaseAddr = (*II)->getBaseAddr();
2088 if (HasWriteAccess.count(BaseAddr)) {
2089 NonReadOnlyBaseValues.insert(BaseAddr);
2090 II++;
2091 } else {
2092 ReadOnlyPairs[BaseAddr].insert(*II);
2093 II = AG.erase(II);
2094 }
2095 }
2096
2097 // If we don't have read only pointers check if there are at least two
2098 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002099 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002100 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002101 continue;
2102 }
2103
2104 // If we don't have non read only pointers clear the alias group.
2105 if (NonReadOnlyBaseValues.empty()) {
2106 AG.clear();
2107 continue;
2108 }
2109
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002110 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002111 MinMaxAliasGroups.emplace_back();
2112 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2113 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2114 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2115 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002116
2117 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002118
2119 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002120 for (MemoryAccess *MA : AG)
2121 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002122
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002123 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2124 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002125
2126 // Bail out if the number of values we need to compare is too large.
2127 // This is important as the number of comparisions grows quadratically with
2128 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002129 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2130 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002131 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002132
2133 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002134 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002135 Accesses = isl_union_map_empty(getParamSpace());
2136
2137 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2138 for (MemoryAccess *MA : ReadOnlyPair.second)
2139 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2140
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002141 Valid =
2142 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002143
2144 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002145 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002146 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002147
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002148 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002149}
2150
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002151static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2152 Loop *L = LI.getLoopFor(R.getEntry());
2153 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2154}
2155
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002156static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2157 ScopDetection &SD) {
2158
2159 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2160
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002161 unsigned MinLD = INT_MAX, MaxLD = 0;
2162 for (BasicBlock *BB : R.blocks()) {
2163 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002164 if (!R.contains(L))
2165 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002166 if (BoxedLoops && BoxedLoops->count(L))
2167 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002168 unsigned LD = L->getLoopDepth();
2169 MinLD = std::min(MinLD, LD);
2170 MaxLD = std::max(MaxLD, LD);
2171 }
2172 }
2173
2174 // Handle the case that there is no loop in the SCoP first.
2175 if (MaxLD == 0)
2176 return 1;
2177
2178 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2179 assert(MaxLD >= MinLD &&
2180 "Maximal loop depth was smaller than mininaml loop depth?");
2181 return MaxLD - MinLD + 1;
2182}
2183
Michael Kruse9d080092015-09-11 21:41:48 +00002184Scop::Scop(Region &R, AccFuncMapType &AccFuncMap,
2185 ScalarEvolution &ScalarEvolution, DominatorTree &DT,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002186 isl_ctx *Context, unsigned MaxLoopDepth)
Michael Kruse9d080092015-09-11 21:41:48 +00002187 : DT(DT), SE(&ScalarEvolution), R(R), AccFuncMap(AccFuncMap),
2188 IsOptimized(false), HasSingleExitEdge(R.getExitingBlock()),
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002189 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Affinator(this),
2190 BoundaryContext(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002191
Michael Kruse9d080092015-09-11 21:41:48 +00002192void Scop::init(LoopInfo &LI, ScopDetection &SD, AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002193 buildContext();
Tobias Grosser75805372011-04-29 06:27:02 +00002194
Johannes Doerfert96425c22015-08-30 21:13:53 +00002195 buildDomains(&R, LI, SD, DT);
2196
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002197 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Tobias Grosser75805372011-04-29 06:27:02 +00002198
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002199 Loop *L = getLoopSurroundingRegion(R, LI);
2200 LoopSchedules[L];
Michael Kruse9d080092015-09-11 21:41:48 +00002201 buildSchedule(&R, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002202 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002203
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002204 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002205 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002206 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002207 buildBoundaryContext();
2208 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002209 buildAliasChecks(AA);
Tobias Grosser75805372011-04-29 06:27:02 +00002210}
2211
2212Scop::~Scop() {
2213 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002214 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002215 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002216 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002217
Johannes Doerfert96425c22015-08-30 21:13:53 +00002218 for (auto It : DomainMap)
2219 isl_set_free(It.second);
2220
Johannes Doerfertb164c792014-09-18 11:17:17 +00002221 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002222 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002223 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002224 isl_pw_multi_aff_free(MMA.first);
2225 isl_pw_multi_aff_free(MMA.second);
2226 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002227 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002228 isl_pw_multi_aff_free(MMA.first);
2229 isl_pw_multi_aff_free(MMA.second);
2230 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002231 }
Tobias Grosser75805372011-04-29 06:27:02 +00002232}
2233
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002234const ScopArrayInfo *
2235Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Michael Kruse28468772015-09-14 15:45:33 +00002236 ArrayRef<const SCEV *> Sizes, bool IsPHI) {
Tobias Grosser92245222015-07-28 14:53:44 +00002237 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)];
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002238 if (!SAI)
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002239 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, IsPHI,
2240 this));
Tobias Grosserab671442015-05-23 05:58:27 +00002241 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002242}
2243
Tobias Grosser92245222015-07-28 14:53:44 +00002244const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, bool IsPHI) {
2245 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, IsPHI)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002246 assert(SAI && "No ScopArrayInfo available for this base pointer");
2247 return SAI;
2248}
2249
Tobias Grosser74394f02013-01-14 22:40:23 +00002250std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002251std::string Scop::getAssumedContextStr() const {
2252 return stringFromIslObj(AssumedContext);
2253}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002254std::string Scop::getBoundaryContextStr() const {
2255 return stringFromIslObj(BoundaryContext);
2256}
Tobias Grosser75805372011-04-29 06:27:02 +00002257
2258std::string Scop::getNameStr() const {
2259 std::string ExitName, EntryName;
2260 raw_string_ostream ExitStr(ExitName);
2261 raw_string_ostream EntryStr(EntryName);
2262
Tobias Grosserf240b482014-01-09 10:42:15 +00002263 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002264 EntryStr.str();
2265
2266 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002267 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002268 ExitStr.str();
2269 } else
2270 ExitName = "FunctionExit";
2271
2272 return EntryName + "---" + ExitName;
2273}
2274
Tobias Grosser74394f02013-01-14 22:40:23 +00002275__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002276__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002277 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002278}
2279
Tobias Grossere86109f2013-10-29 21:05:49 +00002280__isl_give isl_set *Scop::getAssumedContext() const {
2281 return isl_set_copy(AssumedContext);
2282}
2283
Johannes Doerfert43788c52015-08-20 05:58:56 +00002284__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2285 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002286 RuntimeCheckContext =
2287 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2288 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002289 return RuntimeCheckContext;
2290}
2291
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002292bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002293 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002294 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002295 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2296 isl_set_free(RuntimeCheckContext);
2297 return IsFeasible;
2298}
2299
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002300void Scop::addAssumption(__isl_take isl_set *Set) {
2301 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002302 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002303}
2304
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002305__isl_give isl_set *Scop::getBoundaryContext() const {
2306 return isl_set_copy(BoundaryContext);
2307}
2308
Tobias Grosser75805372011-04-29 06:27:02 +00002309void Scop::printContext(raw_ostream &OS) const {
2310 OS << "Context:\n";
2311
2312 if (!Context) {
2313 OS.indent(4) << "n/a\n\n";
2314 return;
2315 }
2316
2317 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002318
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002319 OS.indent(4) << "Assumed Context:\n";
2320 if (!AssumedContext) {
2321 OS.indent(4) << "n/a\n\n";
2322 return;
2323 }
2324
2325 OS.indent(4) << getAssumedContextStr() << "\n";
2326
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002327 OS.indent(4) << "Boundary Context:\n";
2328 if (!BoundaryContext) {
2329 OS.indent(4) << "n/a\n\n";
2330 return;
2331 }
2332
2333 OS.indent(4) << getBoundaryContextStr() << "\n";
2334
Tobias Grosser083d3d32014-06-28 08:59:45 +00002335 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002336 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002337 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2338 }
Tobias Grosser75805372011-04-29 06:27:02 +00002339}
2340
Johannes Doerfertb164c792014-09-18 11:17:17 +00002341void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002342 int noOfGroups = 0;
2343 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002344 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002345 noOfGroups += 1;
2346 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002347 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002348 }
2349
Tobias Grosserbb853c22015-07-25 12:31:03 +00002350 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002351 if (MinMaxAliasGroups.empty()) {
2352 OS.indent(8) << "n/a\n";
2353 return;
2354 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002355
Tobias Grosserbb853c22015-07-25 12:31:03 +00002356 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002357
2358 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002359 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002360 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002361 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002362 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2363 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002364 }
2365 OS << " ]]\n";
2366 }
2367
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002368 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002369 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002370 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002371 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002372 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2373 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002374 }
2375 OS << " ]]\n";
2376 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002377 }
2378}
2379
Tobias Grosser75805372011-04-29 06:27:02 +00002380void Scop::printStatements(raw_ostream &OS) const {
2381 OS << "Statements {\n";
2382
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002383 for (const ScopStmt &Stmt : *this)
2384 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002385
2386 OS.indent(4) << "}\n";
2387}
2388
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002389void Scop::printArrayInfo(raw_ostream &OS) const {
2390 OS << "Arrays {\n";
2391
Tobias Grosserab671442015-05-23 05:58:27 +00002392 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002393 Array.second->print(OS);
2394
2395 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002396
2397 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2398
2399 for (auto &Array : arrays())
2400 Array.second->print(OS, /* SizeAsPwAff */ true);
2401
2402 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002403}
2404
Tobias Grosser75805372011-04-29 06:27:02 +00002405void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002406 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2407 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002408 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002409 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00002410 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002411 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00002412 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00002413 printStatements(OS.indent(4));
2414}
2415
2416void Scop::dump() const { print(dbgs()); }
2417
Tobias Grosser9a38ab82011-11-08 15:41:03 +00002418isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00002419
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002420__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
2421 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00002422}
2423
Tobias Grosser808cd692015-07-14 09:33:13 +00002424__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002425 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002426
Tobias Grosser808cd692015-07-14 09:33:13 +00002427 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002428 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00002429
2430 return Domain;
2431}
2432
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002433__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002434 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002435
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002436 for (ScopStmt &Stmt : *this) {
2437 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002438 if (!MA->isMustWrite())
2439 continue;
2440
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002441 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002442 isl_map *AccessDomain = MA->getAccessRelation();
2443 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2444 Write = isl_union_map_add_map(Write, AccessDomain);
2445 }
2446 }
2447 return isl_union_map_coalesce(Write);
2448}
2449
2450__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002451 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002452
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002453 for (ScopStmt &Stmt : *this) {
2454 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002455 if (!MA->isMayWrite())
2456 continue;
2457
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002458 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00002459 isl_map *AccessDomain = MA->getAccessRelation();
2460 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2461 Write = isl_union_map_add_map(Write, AccessDomain);
2462 }
2463 }
2464 return isl_union_map_coalesce(Write);
2465}
2466
Tobias Grosser37eb4222014-02-20 21:43:54 +00002467__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002468 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002469
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002470 for (ScopStmt &Stmt : *this) {
2471 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002472 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002473 continue;
2474
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002475 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002476 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002477 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2478 Write = isl_union_map_add_map(Write, AccessDomain);
2479 }
2480 }
2481 return isl_union_map_coalesce(Write);
2482}
2483
2484__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002485 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002486
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002487 for (ScopStmt &Stmt : *this) {
2488 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00002489 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00002490 continue;
2491
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002492 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00002493 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00002494
2495 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
2496 Read = isl_union_map_add_map(Read, AccessDomain);
2497 }
2498 }
2499 return isl_union_map_coalesce(Read);
2500}
2501
Tobias Grosser808cd692015-07-14 09:33:13 +00002502__isl_give isl_union_map *Scop::getSchedule() const {
2503 auto Tree = getScheduleTree();
2504 auto S = isl_schedule_get_map(Tree);
2505 isl_schedule_free(Tree);
2506 return S;
2507}
Tobias Grosser37eb4222014-02-20 21:43:54 +00002508
Tobias Grosser808cd692015-07-14 09:33:13 +00002509__isl_give isl_schedule *Scop::getScheduleTree() const {
2510 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
2511 getDomains());
2512}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00002513
Tobias Grosser808cd692015-07-14 09:33:13 +00002514void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
2515 auto *S = isl_schedule_from_domain(getDomains());
2516 S = isl_schedule_insert_partial_schedule(
2517 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
2518 isl_schedule_free(Schedule);
2519 Schedule = S;
2520}
2521
2522void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
2523 isl_schedule_free(Schedule);
2524 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00002525}
2526
2527bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
2528 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002529 for (ScopStmt &Stmt : *this) {
2530 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00002531 isl_union_set *NewStmtDomain = isl_union_set_intersect(
2532 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
2533
2534 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
2535 isl_union_set_free(StmtDomain);
2536 isl_union_set_free(NewStmtDomain);
2537 continue;
2538 }
2539
2540 Changed = true;
2541
2542 isl_union_set_free(StmtDomain);
2543 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
2544
2545 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002546 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002547 isl_union_set_free(NewStmtDomain);
2548 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002549 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00002550 }
2551 isl_union_set_free(Domain);
2552 return Changed;
2553}
2554
Tobias Grosser75805372011-04-29 06:27:02 +00002555ScalarEvolution *Scop::getSE() const { return SE; }
2556
Michael Kruse9d080092015-09-11 21:41:48 +00002557bool Scop::isTrivialBB(BasicBlock *BB) {
2558 if (getAccessFunctions(BB) && !isErrorBlock(*BB))
Tobias Grosser75805372011-04-29 06:27:02 +00002559 return false;
2560
2561 return true;
2562}
2563
Tobias Grosser808cd692015-07-14 09:33:13 +00002564struct MapToDimensionDataTy {
2565 int N;
2566 isl_union_pw_multi_aff *Res;
2567};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002568
Tobias Grosser808cd692015-07-14 09:33:13 +00002569// @brief Create a function that maps the elements of 'Set' to its N-th
2570// dimension.
2571//
2572// The result is added to 'User->Res'.
2573//
2574// @param Set The input set.
2575// @param N The dimension to map to.
2576//
2577// @returns Zero if no error occurred, non-zero otherwise.
2578static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
2579 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
2580 int Dim;
2581 isl_space *Space;
2582 isl_pw_multi_aff *PMA;
2583
2584 Dim = isl_set_dim(Set, isl_dim_set);
2585 Space = isl_set_get_space(Set);
2586 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
2587 Dim - Data->N);
2588 if (Data->N > 1)
2589 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
2590 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
2591
2592 isl_set_free(Set);
2593
2594 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002595}
2596
Tobias Grosser808cd692015-07-14 09:33:13 +00002597// @brief Create a function that maps the elements of Domain to their Nth
2598// dimension.
2599//
2600// @param Domain The set of elements to map.
2601// @param N The dimension to map to.
2602static __isl_give isl_multi_union_pw_aff *
2603mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002604 if (N <= 0 || isl_union_set_is_empty(Domain)) {
2605 isl_union_set_free(Domain);
2606 return nullptr;
2607 }
2608
Tobias Grosser808cd692015-07-14 09:33:13 +00002609 struct MapToDimensionDataTy Data;
2610 isl_space *Space;
2611
2612 Space = isl_union_set_get_space(Domain);
2613 Data.N = N;
2614 Data.Res = isl_union_pw_multi_aff_empty(Space);
2615 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
2616 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
2617
2618 isl_union_set_free(Domain);
2619 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
2620}
2621
Michael Kruse9d080092015-09-11 21:41:48 +00002622ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00002623 ScopStmt *Stmt;
2624 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00002625 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00002626 Stmt = &Stmts.back();
2627 StmtMap[BB] = Stmt;
2628 } else {
2629 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00002630 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00002631 Stmt = &Stmts.back();
2632 for (BasicBlock *BB : R->blocks())
2633 StmtMap[BB] = Stmt;
2634 }
2635 return Stmt;
2636}
2637
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002638void Scop::buildSchedule(
Michael Kruse9d080092015-09-11 21:41:48 +00002639 Region *R, LoopInfo &LI, ScopDetection &SD,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002640 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00002641
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002642 if (SD.isNonAffineSubRegion(R, &getRegion())) {
2643 auto *Stmt = addScopStmt(nullptr, R);
2644 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2645 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2646 auto &LSchedulePair = LoopSchedules[nullptr];
2647 LSchedulePair.first = StmtSchedule;
2648 return;
2649 }
2650
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002651 ReversePostOrderTraversal<Region *> RTraversal(R);
2652 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00002653
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002654 if (RN->isSubRegion()) {
2655 Region *SubRegion = RN->getNodeAs<Region>();
2656 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Michael Kruse9d080092015-09-11 21:41:48 +00002657 buildSchedule(SubRegion, LI, SD, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002658 continue;
2659 }
Tobias Grosser75805372011-04-29 06:27:02 +00002660 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002661
2662 Loop *L = getRegionNodeLoop(RN, LI);
2663 int LD = getRelativeLoopDepth(L);
2664 auto &LSchedulePair = LoopSchedules[L];
2665 LSchedulePair.second += getNumBlocksInRegionNode(RN);
2666
2667 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse9d080092015-09-11 21:41:48 +00002668 if (RN->isSubRegion() || !isTrivialBB(BB)) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002669
2670 ScopStmt *Stmt;
2671 if (RN->isSubRegion())
Michael Kruse9d080092015-09-11 21:41:48 +00002672 Stmt = addScopStmt(nullptr, RN->getNodeAs<Region>());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002673 else
Michael Kruse9d080092015-09-11 21:41:48 +00002674 Stmt = addScopStmt(BB, nullptr);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002675
2676 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
2677 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
2678 LSchedulePair.first =
2679 combineInSequence(LSchedulePair.first, StmtSchedule);
2680 }
2681
2682 unsigned NumVisited = LSchedulePair.second;
2683 while (L && NumVisited == L->getNumBlocks()) {
2684 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
2685 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
2686 LSchedulePair.first =
2687 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
2688
2689 auto *PL = L->getParentLoop();
2690 assert(LoopSchedules.count(PL));
2691 auto &PSchedulePair = LoopSchedules[PL];
2692 PSchedulePair.first =
2693 combineInSequence(PSchedulePair.first, LSchedulePair.first);
2694 PSchedulePair.second += NumVisited;
2695
2696 L = PL;
2697 NumVisited = PSchedulePair.second;
2698 }
Tobias Grosser808cd692015-07-14 09:33:13 +00002699 }
Tobias Grosser75805372011-04-29 06:27:02 +00002700}
2701
Johannes Doerfert7c494212014-10-31 23:13:39 +00002702ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00002703 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00002704 if (StmtMapIt == StmtMap.end())
2705 return nullptr;
2706 return StmtMapIt->second;
2707}
2708
Michael Kruse9d080092015-09-11 21:41:48 +00002709void Scop::printIRAccesses(raw_ostream &OS, ScalarEvolution *SE,
2710 LoopInfo *LI) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002711 OS << "Scop: " << R.getNameStr() << "\n";
2712
Michael Kruse9d080092015-09-11 21:41:48 +00002713 printIRAccessesDetail(OS, SE, LI, &R, 0);
Michael Kruse7bf39442015-09-10 12:46:52 +00002714}
2715
Michael Kruse9d080092015-09-11 21:41:48 +00002716void Scop::printIRAccessesDetail(raw_ostream &OS, ScalarEvolution *SE,
2717 LoopInfo *LI, const Region *CurR,
2718 unsigned ind) const {
Michael Kruse7bf39442015-09-10 12:46:52 +00002719 // FIXME: Print other details rather than memory accesses.
2720 for (const auto &CurBlock : CurR->blocks()) {
2721 AccFuncMapType::const_iterator AccSetIt = AccFuncMap.find(CurBlock);
2722
2723 // Ignore trivial blocks that do not contain any memory access.
2724 if (AccSetIt == AccFuncMap.end())
2725 continue;
2726
2727 OS.indent(ind) << "BB: " << CurBlock->getName() << '\n';
2728 typedef AccFuncSetType::const_iterator access_iterator;
2729 const AccFuncSetType &AccFuncs = AccSetIt->second;
2730
2731 for (access_iterator AI = AccFuncs.begin(), AE = AccFuncs.end(); AI != AE;
2732 ++AI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00002733 AI->printIR(OS.indent(ind + 2));
Michael Kruse7bf39442015-09-10 12:46:52 +00002734 }
2735}
2736
Johannes Doerfert96425c22015-08-30 21:13:53 +00002737int Scop::getRelativeLoopDepth(const Loop *L) const {
2738 Loop *OuterLoop =
2739 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
2740 if (!OuterLoop)
2741 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00002742 return L->getLoopDepth() - OuterLoop->getLoopDepth();
2743}
2744
Michael Krused868b5d2015-09-10 15:25:24 +00002745void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00002746 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002747
2748 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
2749 // true, are not modeled as ordinary PHI nodes as they are not part of the
2750 // region. However, we model the operands in the predecessor blocks that are
2751 // part of the region as regular scalar accesses.
2752
2753 // If we can synthesize a PHI we can skip it, however only if it is in
2754 // the region. If it is not it can only be in the exit block of the region.
2755 // In this case we model the operands but not the PHI itself.
2756 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
2757 return;
2758
2759 // PHI nodes are modeled as if they had been demoted prior to the SCoP
2760 // detection. Hence, the PHI is a load of a new memory location in which the
2761 // incoming value was written at the end of the incoming basic block.
2762 bool OnlyNonAffineSubRegionOperands = true;
2763 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
2764 Value *Op = PHI->getIncomingValue(u);
2765 BasicBlock *OpBB = PHI->getIncomingBlock(u);
2766
2767 // Do not build scalar dependences inside a non-affine subregion.
2768 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
2769 continue;
2770
2771 OnlyNonAffineSubRegionOperands = false;
2772
2773 if (!R.contains(OpBB))
2774 continue;
2775
2776 Instruction *OpI = dyn_cast<Instruction>(Op);
2777 if (OpI) {
2778 BasicBlock *OpIBB = OpI->getParent();
2779 // As we pretend there is a use (or more precise a write) of OpI in OpBB
2780 // we have to insert a scalar dependence from the definition of OpI to
2781 // OpBB if the definition is not in OpBB.
2782 if (OpIBB != OpBB) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002783 addMemoryAccess(OpBB, PHI, MemoryAccess::READ, OpI, ZeroOffset, 1, true,
2784 OpI);
2785 addMemoryAccess(OpIBB, OpI, MemoryAccess::MUST_WRITE, OpI, ZeroOffset,
2786 1, true, OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00002787 }
2788 }
2789
2790 // Always use the terminator of the incoming basic block as the access
2791 // instruction.
2792 OpI = OpBB->getTerminator();
2793
Michael Krusee2bccbb2015-09-18 19:59:43 +00002794 addMemoryAccess(OpBB, OpI, MemoryAccess::MUST_WRITE, PHI, ZeroOffset, 1,
2795 true, Op, /* IsPHI */ !IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002796 }
2797
2798 if (!OnlyNonAffineSubRegionOperands) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00002799 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, ZeroOffset,
2800 1, true, PHI,
2801 /* IsPHI */ !IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00002802 }
2803}
2804
Michael Krused868b5d2015-09-10 15:25:24 +00002805bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
2806 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002807 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
2808 if (isIgnoredIntrinsic(Inst))
2809 return false;
2810
2811 bool AnyCrossStmtUse = false;
2812 BasicBlock *ParentBB = Inst->getParent();
2813
2814 for (User *U : Inst->users()) {
2815 Instruction *UI = dyn_cast<Instruction>(U);
2816
2817 // Ignore the strange user
2818 if (UI == 0)
2819 continue;
2820
2821 BasicBlock *UseParent = UI->getParent();
2822
2823 // Ignore the users in the same BB (statement)
2824 if (UseParent == ParentBB)
2825 continue;
2826
2827 // Do not build scalar dependences inside a non-affine subregion.
2828 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
2829 continue;
2830
2831 // Check whether or not the use is in the SCoP.
2832 if (!R->contains(UseParent)) {
2833 AnyCrossStmtUse = true;
2834 continue;
2835 }
2836
2837 // If the instruction can be synthesized and the user is in the region
2838 // we do not need to add scalar dependences.
2839 if (canSynthesizeInst)
2840 continue;
2841
2842 // No need to translate these scalar dependences into polyhedral form,
2843 // because synthesizable scalars can be generated by the code generator.
2844 if (canSynthesize(UI, LI, SE, R))
2845 continue;
2846
2847 // Skip PHI nodes in the region as they handle their operands on their own.
2848 if (isa<PHINode>(UI))
2849 continue;
2850
2851 // Now U is used in another statement.
2852 AnyCrossStmtUse = true;
2853
2854 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00002855 // Use the def instruction as base address of the MemoryAccess, so that it
2856 // will become the name of the scalar access in the polyhedral form.
2857 addMemoryAccess(UseParent, UI, MemoryAccess::READ, Inst, ZeroOffset, 1,
2858 true, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00002859 }
2860
2861 if (ModelReadOnlyScalars) {
2862 for (Value *Op : Inst->operands()) {
2863 if (canSynthesize(Op, LI, SE, R))
2864 continue;
2865
2866 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
2867 if (R->contains(OpInst))
2868 continue;
2869
2870 if (isa<Constant>(Op))
2871 continue;
2872
Michael Krusee2bccbb2015-09-18 19:59:43 +00002873 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::READ, Op,
2874 ZeroOffset, 1, true, Op);
Michael Kruse7bf39442015-09-10 12:46:52 +00002875 }
2876 }
2877
2878 return AnyCrossStmtUse;
2879}
2880
2881extern MapInsnToMemAcc InsnToMemAcc;
2882
Michael Krusee2bccbb2015-09-18 19:59:43 +00002883void ScopInfo::buildMemoryAccess(
2884 Instruction *Inst, Loop *L, Region *R,
2885 const ScopDetection::BoxedLoopsSetTy *BoxedLoops) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002886 unsigned Size;
2887 Type *SizeType;
2888 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00002889 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00002890
2891 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
2892 SizeType = Load->getType();
2893 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002894 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00002895 Val = Load;
2896 } else {
2897 StoreInst *Store = cast<StoreInst>(Inst);
2898 SizeType = Store->getValueOperand()->getType();
2899 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002900 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002901 Val = Store->getValueOperand();
2902 }
2903
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002904 auto Address = getPointerOperand(*Inst);
2905
2906 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00002907 const SCEVUnknown *BasePointer =
2908 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
2909
2910 assert(BasePointer && "Could not find base pointer");
2911 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
2912
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002913 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
2914 auto NewAddress = Address;
2915 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
2916 auto Src = BitCast->getOperand(0);
2917 auto SrcTy = Src->getType();
2918 auto DstTy = BitCast->getType();
2919 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
2920 NewAddress = Src;
2921 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002922
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002923 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
2924 std::vector<const SCEV *> Subscripts;
2925 std::vector<int> Sizes;
2926 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
2927 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002928
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002929 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002930
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002931 bool AllAffineSubcripts = true;
2932 for (auto Subscript : Subscripts)
2933 if (!isAffineExpr(R, Subscript, *SE)) {
2934 AllAffineSubcripts = false;
2935 break;
2936 }
2937
2938 if (AllAffineSubcripts && Sizes.size() > 0) {
2939 for (auto V : Sizes)
2940 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
2941 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002942 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002943 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002944
Michael Krusee2bccbb2015-09-18 19:59:43 +00002945 addMemoryAccess(Inst->getParent(), Inst, Type, BasePointer->getValue(),
2946 AccessFunction, Size, true, Subscripts, SizesSCEV, Val);
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00002947 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00002948 }
2949 }
2950
Michael Kruse7bf39442015-09-10 12:46:52 +00002951 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002952 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
2953 addMemoryAccess(Inst->getParent(), Inst, Type, BasePointer->getValue(),
2954 AccessFunction, Size, true,
Michael Kruse7bf39442015-09-10 12:46:52 +00002955 AccItr->second.DelinearizedSubscripts,
2956 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00002957 return;
2958 }
Michael Kruse7bf39442015-09-10 12:46:52 +00002959
2960 // Check if the access depends on a loop contained in a non-affine subregion.
2961 bool isVariantInNonAffineLoop = false;
2962 if (BoxedLoops) {
2963 SetVector<const Loop *> Loops;
2964 findLoops(AccessFunction, Loops);
2965 for (const Loop *L : Loops)
2966 if (BoxedLoops->count(L))
2967 isVariantInNonAffineLoop = true;
2968 }
2969
2970 bool IsAffine = !isVariantInNonAffineLoop &&
2971 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue());
2972
2973 SmallVector<const SCEV *, 4> Subscripts, Sizes;
2974 Subscripts.push_back(AccessFunction);
2975 Sizes.push_back(SE->getConstant(ZeroOffset->getType(), Size));
2976
Michael Krusee2bccbb2015-09-18 19:59:43 +00002977 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
2978 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00002979
Michael Krusee2bccbb2015-09-18 19:59:43 +00002980 addMemoryAccess(Inst->getParent(), Inst, Type, BasePointer->getValue(),
2981 AccessFunction, Size, IsAffine, Subscripts, Sizes, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00002982}
2983
Michael Krused868b5d2015-09-10 15:25:24 +00002984void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00002985
2986 if (SD->isNonAffineSubRegion(&SR, &R)) {
2987 for (BasicBlock *BB : SR.blocks())
2988 buildAccessFunctions(R, *BB, &SR);
2989 return;
2990 }
2991
2992 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
2993 if (I->isSubRegion())
2994 buildAccessFunctions(R, *I->getNodeAs<Region>());
2995 else
2996 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
2997}
2998
Michael Krused868b5d2015-09-10 15:25:24 +00002999void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3000 Region *NonAffineSubRegion,
3001 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003002 Loop *L = LI->getLoopFor(&BB);
3003
3004 // The set of loops contained in non-affine subregions that are part of R.
3005 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3006
3007 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
3008 Instruction *Inst = I;
3009
3010 PHINode *PHI = dyn_cast<PHINode>(Inst);
3011 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003012 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003013
3014 // For the exit block we stop modeling after the last PHI node.
3015 if (!PHI && IsExitBlock)
3016 break;
3017
3018 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Michael Krusee2bccbb2015-09-18 19:59:43 +00003019 buildMemoryAccess(Inst, L, &R, BoxedLoops);
Michael Kruse7bf39442015-09-10 12:46:52 +00003020
3021 if (isIgnoredIntrinsic(Inst))
3022 continue;
3023
3024 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003025 if (!isa<StoreInst>(Inst))
3026 addMemoryAccess(&BB, Inst, MemoryAccess::MUST_WRITE, Inst, ZeroOffset,
3027 1, true, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003028 }
3029 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003030}
Michael Kruse7bf39442015-09-10 12:46:52 +00003031
Michael Krusee2bccbb2015-09-18 19:59:43 +00003032void ScopInfo::addMemoryAccess(
3033 BasicBlock *BB, Instruction *Inst, MemoryAccess::AccessType Type,
3034 Value *BaseAddress, const SCEV *Offset, unsigned ElemBytes, bool Affine,
3035 Value *AccessValue, ArrayRef<const SCEV *> Subscripts,
3036 ArrayRef<const SCEV *> Sizes, bool IsPHI = false) {
3037 AccFuncSetType &AccList = AccFuncMap[BB];
3038 size_t Identifier = AccList.size();
Michael Kruse7bf39442015-09-10 12:46:52 +00003039
Michael Krusee2bccbb2015-09-18 19:59:43 +00003040 Value *BaseAddr = BaseAddress;
3041 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3042
3043 std::string IdName = "__polly_array_ref_" + std::to_string(Identifier);
3044 isl_id *Id = isl_id_alloc(ctx, IdName.c_str(), nullptr);
3045
3046 AccList.emplace_back(Inst, Id, Type, BaseAddress, Offset, ElemBytes, Affine,
3047 Subscripts, Sizes, AccessValue, IsPHI, BaseName);
Michael Kruse7bf39442015-09-10 12:46:52 +00003048}
3049
Michael Kruse9d080092015-09-11 21:41:48 +00003050Scop *ScopInfo::buildScop(Region &R, DominatorTree &DT) {
3051 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
3052 Scop *S = new Scop(R, AccFuncMap, *SE, DT, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003053
3054 buildAccessFunctions(R, R);
3055
3056 // In case the region does not have an exiting block we will later (during
3057 // code generation) split the exit block. This will move potential PHI nodes
3058 // from the current exit block into the new region exiting block. Hence, PHI
3059 // nodes that are at this point not part of the region will be.
3060 // To handle these PHI nodes later we will now model their operands as scalar
3061 // accesses. Note that we do not model anything in the exit block if we have
3062 // an exiting block in the region, as there will not be any splitting later.
3063 if (!R.getExitingBlock())
3064 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3065
Michael Kruse9d080092015-09-11 21:41:48 +00003066 S->init(*LI, *SD, *AA);
3067 return S;
Michael Kruse7bf39442015-09-10 12:46:52 +00003068}
3069
Michael Krused868b5d2015-09-10 15:25:24 +00003070void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003071 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003072 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003073 return;
3074 }
3075
3076 scop->printIRAccesses(OS, SE, LI);
3077 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003078}
3079
Michael Krused868b5d2015-09-10 15:25:24 +00003080void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003081 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003082 if (scop) {
3083 delete scop;
3084 scop = 0;
3085 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003086}
3087
3088//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003089ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003090 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003091 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003092}
3093
3094ScopInfo::~ScopInfo() {
3095 clear();
3096 isl_ctx_free(ctx);
3097}
3098
Tobias Grosser75805372011-04-29 06:27:02 +00003099void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Michael Krused868b5d2015-09-10 15:25:24 +00003100 AU.addRequiredID(IndependentBlocksID);
Chandler Carruthf5579872015-01-17 14:16:56 +00003101 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003102 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003103 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003104 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3105 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003106 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003107 AU.setPreservesAll();
3108}
3109
3110bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003111 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003112
Michael Krused868b5d2015-09-10 15:25:24 +00003113 if (!SD->isMaxRegionInScop(*R))
3114 return false;
3115
3116 Function *F = R->getEntry()->getParent();
3117 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3118 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3119 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3120 TD = &F->getParent()->getDataLayout();
3121 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3122 ZeroOffset = SE->getConstant(TD->getIntPtrType(F->getContext()), 0);
3123
Michael Kruse9d080092015-09-11 21:41:48 +00003124 scop = buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003125
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003126 DEBUG(scop->print(dbgs()));
3127
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003128 if (!scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003129 delete scop;
3130 scop = nullptr;
3131 return false;
3132 }
3133
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003134 // Statistics.
3135 ++ScopFound;
3136 if (scop->getMaxLoopDepth() > 0)
3137 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003138 return false;
3139}
3140
3141char ScopInfo::ID = 0;
3142
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003143Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3144
Tobias Grosser73600b82011-10-08 00:30:40 +00003145INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3146 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003147 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003148INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003149INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003150INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003151INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003152INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003153INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003154INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3155 "Polly - Create polyhedral description of Scops", false,
3156 false)