blob: 790c7f554f4377e425b8af7fb9ff2f7cd143bc60 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000026#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000034#include "llvm/Analysis/AssumptionCache.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000036#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000037#include "llvm/Analysis/RegionIterator.h"
38#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000039#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000040#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000045#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000047#include "isl/schedule.h"
48#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "isl/set.h"
50#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000051#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000052#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include <sstream>
54#include <string>
55#include <vector>
56
57using namespace llvm;
58using namespace polly;
59
Chandler Carruth95fef942014-04-22 03:30:19 +000060#define DEBUG_TYPE "polly-scops"
61
Tobias Grosser74394f02013-01-14 22:40:23 +000062STATISTIC(ScopFound, "Number of valid Scops");
63STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000064
Michael Kruse7bf39442015-09-10 12:46:52 +000065static cl::opt<bool> ModelReadOnlyScalars(
66 "polly-analyze-read-only-scalars",
67 cl::desc("Model read-only scalar values in the scop description"),
68 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
69
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000070// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000071// operations can overflow easily. Additive reductions and bit operations
72// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000073static cl::opt<bool> DisableMultiplicativeReductions(
74 "polly-disable-multiplicative-reductions",
75 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
76 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000077
Johannes Doerfert9143d672014-09-27 11:02:39 +000078static cl::opt<unsigned> RunTimeChecksMaxParameters(
79 "polly-rtc-max-parameters",
80 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
81 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
82
Tobias Grosser71500722015-03-28 15:11:14 +000083static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
84 "polly-rtc-max-arrays-per-group",
85 cl::desc("The maximal number of arrays to compare in each alias group."),
86 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000087static cl::opt<std::string> UserContextStr(
88 "polly-context", cl::value_desc("isl parameter set"),
89 cl::desc("Provide additional constraints on the context parameters"),
90 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000091
Tobias Grosserd83b8a82015-08-20 19:08:11 +000092static cl::opt<bool> DetectReductions("polly-detect-reductions",
93 cl::desc("Detect and exploit reductions"),
94 cl::Hidden, cl::ZeroOrMore,
95 cl::init(true), cl::cat(PollyCategory));
96
Tobias Grosser20a4c0c2015-11-11 16:22:36 +000097static cl::opt<int> MaxDisjunctsAssumed(
98 "polly-max-disjuncts-assumed",
99 cl::desc("The maximal number of disjuncts we allow in the assumption "
100 "context (this bounds compile time)"),
101 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
102
Michael Kruse7bf39442015-09-10 12:46:52 +0000103//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000104
Michael Kruse046dde42015-08-10 13:01:57 +0000105// Create a sequence of two schedules. Either argument may be null and is
106// interpreted as the empty schedule. Can also return null if both schedules are
107// empty.
108static __isl_give isl_schedule *
109combineInSequence(__isl_take isl_schedule *Prev,
110 __isl_take isl_schedule *Succ) {
111 if (!Prev)
112 return Succ;
113 if (!Succ)
114 return Prev;
115
116 return isl_schedule_sequence(Prev, Succ);
117}
118
Johannes Doerferte7044942015-02-24 11:58:30 +0000119static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
120 const ConstantRange &Range,
121 int dim,
122 enum isl_dim_type type) {
123 isl_val *V;
124 isl_ctx *ctx = isl_set_get_ctx(S);
125
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000126 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
127 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000128 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000129 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
130
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000131 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000132 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000133 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000134 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000135 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
136
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000138 return isl_set_union(SLB, SUB);
139 else
140 return isl_set_intersect(SLB, SUB);
141}
142
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000143static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
144 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
145 if (!BasePtrLI)
146 return nullptr;
147
148 if (!S->getRegion().contains(BasePtrLI))
149 return nullptr;
150
151 ScalarEvolution &SE = *S->getSE();
152
153 auto *OriginBaseSCEV =
154 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
155 if (!OriginBaseSCEV)
156 return nullptr;
157
158 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
159 if (!OriginBaseSCEVUnknown)
160 return nullptr;
161
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000162 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
163 ScopArrayInfo::KIND_ARRAY);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000164}
165
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000166ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000167 ArrayRef<const SCEV *> Sizes, enum ARRAYKIND Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000168 const DataLayout &DL, Scop *S)
169 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000170 std::string BasePtrName =
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000171 getIslCompatibleName("MemRef_", BasePtr, Kind == KIND_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000172 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000173
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000174 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
176 if (BasePtrOriginSAI)
177 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000178}
179
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000180__isl_give isl_space *ScopArrayInfo::getSpace() const {
181 auto Space =
182 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
183 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
184 return Space;
185}
186
Tobias Grosser8286b832015-11-02 11:29:32 +0000187bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000188 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
189 int ExtraDimsNew = NewSizes.size() - SharedDims;
190 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000191 for (int i = 0; i < SharedDims; i++)
192 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
193 return false;
194
195 if (DimensionSizes.size() >= NewSizes.size())
196 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000197
198 DimensionSizes.clear();
199 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
200 NewSizes.end());
201 for (isl_pw_aff *Size : DimensionSizesPw)
202 isl_pw_aff_free(Size);
203 DimensionSizesPw.clear();
204 for (const SCEV *Expr : DimensionSizes) {
205 isl_pw_aff *Size = S.getPwAff(Expr);
206 DimensionSizesPw.push_back(Size);
207 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000208 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000209}
210
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000211ScopArrayInfo::~ScopArrayInfo() {
212 isl_id_free(Id);
213 for (isl_pw_aff *Size : DimensionSizesPw)
214 isl_pw_aff_free(Size);
215}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000216
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000217std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
218
219int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000220 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000221}
222
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000223isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
224
225void ScopArrayInfo::dump() const { print(errs()); }
226
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000227void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000228 OS.indent(8) << *getElementType() << " " << getName();
229 if (getNumberOfDimensions() > 0)
230 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000231 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000232 OS << "[";
233
Tobias Grosser26253842015-11-10 14:24:21 +0000234 if (SizeAsPwAff) {
235 auto Size = getDimensionSizePw(u);
236 OS << " " << Size << " ";
237 isl_pw_aff_free(Size);
238 } else {
239 OS << *getDimensionSize(u);
240 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000241
242 OS << "]";
243 }
244
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000245 OS << ";";
246
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000247 if (BasePtrOriginSAI)
248 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
249
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000250 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000251}
252
253const ScopArrayInfo *
254ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
255 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
256 assert(Id && "Output dimension didn't have an ID");
257 return getFromId(Id);
258}
259
260const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
261 void *User = isl_id_get_user(Id);
262 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
263 isl_id_free(Id);
264 return SAI;
265}
266
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000267void MemoryAccess::updateDimensionality() {
268 auto ArraySpace = getScopArrayInfo()->getSpace();
269 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
270
271 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
272 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
273 auto DimsMissing = DimsArray - DimsAccess;
274
275 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
276 isl_set_universe(ArraySpace));
277
278 for (unsigned i = 0; i < DimsMissing; i++)
279 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
280
281 for (unsigned i = DimsMissing; i < DimsArray; i++)
282 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
283
284 AccessRelation = isl_map_apply_range(AccessRelation, Map);
285}
286
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000287const std::string
288MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
289 switch (RT) {
290 case MemoryAccess::RT_NONE:
291 llvm_unreachable("Requested a reduction operator string for a memory "
292 "access which isn't a reduction");
293 case MemoryAccess::RT_ADD:
294 return "+";
295 case MemoryAccess::RT_MUL:
296 return "*";
297 case MemoryAccess::RT_BOR:
298 return "|";
299 case MemoryAccess::RT_BXOR:
300 return "^";
301 case MemoryAccess::RT_BAND:
302 return "&";
303 }
304 llvm_unreachable("Unknown reduction type");
305 return "";
306}
307
Johannes Doerfertf6183392014-07-01 20:52:51 +0000308/// @brief Return the reduction type for a given binary operator
309static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
310 const Instruction *Load) {
311 if (!BinOp)
312 return MemoryAccess::RT_NONE;
313 switch (BinOp->getOpcode()) {
314 case Instruction::FAdd:
315 if (!BinOp->hasUnsafeAlgebra())
316 return MemoryAccess::RT_NONE;
317 // Fall through
318 case Instruction::Add:
319 return MemoryAccess::RT_ADD;
320 case Instruction::Or:
321 return MemoryAccess::RT_BOR;
322 case Instruction::Xor:
323 return MemoryAccess::RT_BXOR;
324 case Instruction::And:
325 return MemoryAccess::RT_BAND;
326 case Instruction::FMul:
327 if (!BinOp->hasUnsafeAlgebra())
328 return MemoryAccess::RT_NONE;
329 // Fall through
330 case Instruction::Mul:
331 if (DisableMultiplicativeReductions)
332 return MemoryAccess::RT_NONE;
333 return MemoryAccess::RT_MUL;
334 default:
335 return MemoryAccess::RT_NONE;
336 }
337}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000338
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000339/// @brief Derive the individual index expressions from a GEP instruction
340///
341/// This function optimistically assumes the GEP references into a fixed size
342/// array. If this is actually true, this function returns a list of array
343/// subscript expressions as SCEV as well as a list of integers describing
344/// the size of the individual array dimensions. Both lists have either equal
345/// length of the size list is one element shorter in case there is no known
346/// size available for the outermost array dimension.
347///
348/// @param GEP The GetElementPtr instruction to analyze.
349///
350/// @return A tuple with the subscript expressions and the dimension sizes.
351static std::tuple<std::vector<const SCEV *>, std::vector<int>>
352getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
353 std::vector<const SCEV *> Subscripts;
354 std::vector<int> Sizes;
355
356 Type *Ty = GEP->getPointerOperandType();
357
358 bool DroppedFirstDim = false;
359
Michael Kruse26ed65e2015-09-24 17:32:49 +0000360 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000361
362 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
363
364 if (i == 1) {
365 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
366 Ty = PtrTy->getElementType();
367 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
368 Ty = ArrayTy->getElementType();
369 } else {
370 Subscripts.clear();
371 Sizes.clear();
372 break;
373 }
374 if (auto Const = dyn_cast<SCEVConstant>(Expr))
375 if (Const->getValue()->isZero()) {
376 DroppedFirstDim = true;
377 continue;
378 }
379 Subscripts.push_back(Expr);
380 continue;
381 }
382
383 auto ArrayTy = dyn_cast<ArrayType>(Ty);
384 if (!ArrayTy) {
385 Subscripts.clear();
386 Sizes.clear();
387 break;
388 }
389
390 Subscripts.push_back(Expr);
391 if (!(DroppedFirstDim && i == 2))
392 Sizes.push_back(ArrayTy->getNumElements());
393
394 Ty = ArrayTy->getElementType();
395 }
396
397 return std::make_tuple(Subscripts, Sizes);
398}
399
Tobias Grosser75805372011-04-29 06:27:02 +0000400MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000401 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000402 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000403 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000404}
405
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000406const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
407 isl_id *ArrayId = getArrayId();
408 void *User = isl_id_get_user(ArrayId);
409 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
410 isl_id_free(ArrayId);
411 return SAI;
412}
413
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000414__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000415 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
416}
417
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000418__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
419 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000420 isl_map *Schedule, *ScheduledAccRel;
421 isl_union_set *UDomain;
422
423 UDomain = isl_union_set_from_set(getStatement()->getDomain());
424 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
425 Schedule = isl_map_from_union_map(USchedule);
426 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
427 return isl_pw_multi_aff_from_map(ScheduledAccRel);
428}
429
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000430__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000431 return isl_map_copy(AccessRelation);
432}
433
Johannes Doerferta99130f2014-10-13 12:58:03 +0000434std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000435 return stringFromIslObj(AccessRelation);
436}
437
Johannes Doerferta99130f2014-10-13 12:58:03 +0000438__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000439 return isl_map_get_space(AccessRelation);
440}
441
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000442__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000443 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000444}
445
Tobias Grosser6f730082015-09-05 07:46:47 +0000446std::string MemoryAccess::getNewAccessRelationStr() const {
447 return stringFromIslObj(NewAccessRelation);
448}
449
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000450__isl_give isl_basic_map *
451MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000452 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000453 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000454
Tobias Grosser084d8f72012-05-29 09:29:44 +0000455 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000456 isl_basic_set_universe(Statement->getDomainSpace()),
457 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000458}
459
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000460// Formalize no out-of-bound access assumption
461//
462// When delinearizing array accesses we optimistically assume that the
463// delinearized accesses do not access out of bound locations (the subscript
464// expression of each array evaluates for each statement instance that is
465// executed to a value that is larger than zero and strictly smaller than the
466// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000467// dimension for which we do not need to assume any upper bound. At this point
468// we formalize this assumption to ensure that at code generation time the
469// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000470//
471// To find the set of constraints necessary to avoid out of bound accesses, we
472// first build the set of data locations that are not within array bounds. We
473// then apply the reverse access relation to obtain the set of iterations that
474// may contain invalid accesses and reduce this set of iterations to the ones
475// that are actually executed by intersecting them with the domain of the
476// statement. If we now project out all loop dimensions, we obtain a set of
477// parameters that may cause statement instances to be executed that may
478// possibly yield out of bound memory accesses. The complement of these
479// constraints is the set of constraints that needs to be assumed to ensure such
480// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000481void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000482 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000483 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000484 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000485 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
486 isl_pw_aff *Var =
487 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
488 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
489
490 isl_set *DimOutside;
491
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000492 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000493 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000494
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000495 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
496 Statement->getNumIterators());
497 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
498 isl_space_dim(Space, isl_dim_set));
499 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
500 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000501
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000502 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000503
504 Outside = isl_set_union(Outside, DimOutside);
505 }
506
507 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
508 Outside = isl_set_intersect(Outside, Statement->getDomain());
509 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000510
511 // Remove divs to avoid the construction of overly complicated assumptions.
512 // Doing so increases the set of parameter combinations that are assumed to
513 // not appear. This is always save, but may make the resulting run-time check
514 // bail out more often than strictly necessary.
515 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000516 Outside = isl_set_complement(Outside);
Johannes Doerfertd84493e2015-11-12 02:33:38 +0000517 Statement->getParent()->addAssumption(INBOUNDS, Outside,
518 getAccessInstruction()->getDebugLoc());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000519 isl_space_free(Space);
520}
521
Johannes Doerferte7044942015-02-24 11:58:30 +0000522void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
523 ScalarEvolution *SE = Statement->getParent()->getSE();
524
525 Value *Ptr = getPointerOperand(*getAccessInstruction());
526 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
527 return;
528
529 auto *PtrSCEV = SE->getSCEV(Ptr);
530 if (isa<SCEVCouldNotCompute>(PtrSCEV))
531 return;
532
533 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
534 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
535 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
536
537 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
538 if (Range.isFullSet())
539 return;
540
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000541 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000542 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000543 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
544 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
545
546 auto Min = LB.sdiv(APInt(BW, ElementSize));
547 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000548
549 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
550 AccessRange =
551 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
552 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
553}
554
Michael Krusee2bccbb2015-09-18 19:59:43 +0000555__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000556 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000557 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000558
559 for (int i = Size - 2; i >= 0; --i) {
560 isl_space *Space;
561 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000562 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000563
564 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
565 isl_pw_aff_free(DimSize);
566 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
567
568 Space = isl_map_get_space(AccessRelation);
569 Space = isl_space_map_from_set(isl_space_range(Space));
570 Space = isl_space_align_params(Space, SpaceSize);
571
572 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
573 isl_id_free(ParamId);
574
575 MapOne = isl_map_universe(isl_space_copy(Space));
576 for (int j = 0; j < Size; ++j)
577 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
578 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
579
580 MapTwo = isl_map_universe(isl_space_copy(Space));
581 for (int j = 0; j < Size; ++j)
582 if (j < i || j > i + 1)
583 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
584
585 isl_local_space *LS = isl_local_space_from_space(Space);
586 isl_constraint *C;
587 C = isl_equality_alloc(isl_local_space_copy(LS));
588 C = isl_constraint_set_constant_si(C, -1);
589 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
590 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
591 MapTwo = isl_map_add_constraint(MapTwo, C);
592 C = isl_equality_alloc(LS);
593 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
594 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
595 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
596 MapTwo = isl_map_add_constraint(MapTwo, C);
597 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
598
599 MapOne = isl_map_union(MapOne, MapTwo);
600 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
601 }
602 return AccessRelation;
603}
604
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000605/// @brief Check if @p Expr is divisible by @p Size.
606static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
607
608 // Only one factor needs to be divisible.
609 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
610 for (auto *FactorExpr : MulExpr->operands())
611 if (isDivisible(FactorExpr, Size, SE))
612 return true;
613 return false;
614 }
615
616 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
617 // to be divisble.
618 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
619 for (auto *OpExpr : NAryExpr->operands())
620 if (!isDivisible(OpExpr, Size, SE))
621 return false;
622 return true;
623 }
624
625 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
626 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
627 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
628 return MulSCEV == Expr;
629}
630
Michael Krusee2bccbb2015-09-18 19:59:43 +0000631void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
632 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000633
Michael Krusee2bccbb2015-09-18 19:59:43 +0000634 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000635 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000636
Michael Krusee2bccbb2015-09-18 19:59:43 +0000637 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000638 // We overapproximate non-affine accesses with a possible access to the
639 // whole array. For read accesses it does not make a difference, if an
640 // access must or may happen. However, for write accesses it is important to
641 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000642 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000643 AccessRelation =
644 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000645
Michael Krusee2bccbb2015-09-18 19:59:43 +0000646 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000647 return;
648 }
649
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000650 Scop &S = *getStatement()->getParent();
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000651 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000652 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000653
Michael Krusee2bccbb2015-09-18 19:59:43 +0000654 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
655 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000656
Sebastian Pop422e33f2014-06-03 18:16:31 +0000657 if (Size == 1) {
658 // For the non delinearized arrays, divide the access function of the last
659 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000660 //
661 // A stride one array access in C expressed as A[i] is expressed in
662 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
663 // two subsequent values of 'i' index two values that are stored next to
664 // each other in memory. By this division we make this characteristic
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000665 // obvious again. However, if the index is not divisible by the element
666 // size we will bail out.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000667 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000668 Affine = isl_pw_aff_scale_down_val(Affine, v);
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000669
670 if (!isDivisible(Subscripts[0], getElemSizeInBytes(), *S.getSE()))
671 S.addAssumption(ALIGNMENT, isl_set_empty(S.getParamSpace()),
672 AccessInstruction->getDebugLoc());
Sebastian Pop18016682014-04-08 21:20:44 +0000673 }
674
675 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
676
Tobias Grosser79baa212014-04-10 08:38:02 +0000677 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000678 }
679
Michael Krusee2bccbb2015-09-18 19:59:43 +0000680 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
681 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000682
Tobias Grosser79baa212014-04-10 08:38:02 +0000683 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000684 AccessRelation = isl_map_set_tuple_id(
685 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000686 AccessRelation =
687 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
688
Michael Krusee2bccbb2015-09-18 19:59:43 +0000689 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000690 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000691 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000692}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000693
Michael Krusecac948e2015-10-02 13:53:07 +0000694MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000695 AccessType Type, Value *BaseAddress,
696 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000697 ArrayRef<const SCEV *> Subscripts,
698 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000699 AccessOrigin Origin, StringRef BaseName)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000700 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000701 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
702 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
703 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000704 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000705 NewAccessRelation(nullptr) {
706
707 std::string IdName = "__polly_array_ref";
708 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
709}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000710
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000711void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000712 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000713 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000714}
715
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000716const std::string MemoryAccess::getReductionOperatorStr() const {
717 return MemoryAccess::getReductionOperatorStr(getReductionType());
718}
719
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000720__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
721
Johannes Doerfertf6183392014-07-01 20:52:51 +0000722raw_ostream &polly::operator<<(raw_ostream &OS,
723 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000724 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000725 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000726 else
727 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000728 return OS;
729}
730
Tobias Grosser75805372011-04-29 06:27:02 +0000731void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000732 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000733 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000734 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000735 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000736 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000737 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000738 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000739 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000740 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000741 break;
742 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000743 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000744 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000745 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000746 if (hasNewAccessRelation())
747 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000748}
749
Tobias Grosser74394f02013-01-14 22:40:23 +0000750void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000751
752// Create a map in the size of the provided set domain, that maps from the
753// one element of the provided set domain to another element of the provided
754// set domain.
755// The mapping is limited to all points that are equal in all but the last
756// dimension and for which the last dimension of the input is strict smaller
757// than the last dimension of the output.
758//
759// getEqualAndLarger(set[i0, i1, ..., iX]):
760//
761// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
762// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
763//
Tobias Grosserf5338802011-10-06 00:03:35 +0000764static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000765 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000766 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000767 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000768
769 // Set all but the last dimension to be equal for the input and output
770 //
771 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
772 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000773 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000774 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000775
776 // Set the last dimension of the input to be strict smaller than the
777 // last dimension of the output.
778 //
779 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000780 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
781 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000782 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000783}
784
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000785__isl_give isl_set *
786MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000787 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000788 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000789 isl_space *Space = isl_space_range(isl_map_get_space(S));
790 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000791
Sebastian Popa00a0292012-12-18 07:46:06 +0000792 S = isl_map_reverse(S);
793 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000794
Sebastian Popa00a0292012-12-18 07:46:06 +0000795 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
796 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
797 NextScatt = isl_map_apply_domain(NextScatt, S);
798 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000799
Sebastian Popa00a0292012-12-18 07:46:06 +0000800 isl_set *Deltas = isl_map_deltas(NextScatt);
801 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000802}
803
Sebastian Popa00a0292012-12-18 07:46:06 +0000804bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000805 int StrideWidth) const {
806 isl_set *Stride, *StrideX;
807 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000808
Sebastian Popa00a0292012-12-18 07:46:06 +0000809 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000810 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000811 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
812 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
813 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
814 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000815 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000816
Tobias Grosser28dd4862012-01-24 16:42:16 +0000817 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000818 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000819
Tobias Grosser28dd4862012-01-24 16:42:16 +0000820 return IsStrideX;
821}
822
Sebastian Popa00a0292012-12-18 07:46:06 +0000823bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
824 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000825}
826
Sebastian Popa00a0292012-12-18 07:46:06 +0000827bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
828 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000829}
830
Tobias Grosser166c4222015-09-05 07:46:40 +0000831void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
832 isl_map_free(NewAccessRelation);
833 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000834}
Tobias Grosser75805372011-04-29 06:27:02 +0000835
836//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000837
Tobias Grosser808cd692015-07-14 09:33:13 +0000838isl_map *ScopStmt::getSchedule() const {
839 isl_set *Domain = getDomain();
840 if (isl_set_is_empty(Domain)) {
841 isl_set_free(Domain);
842 return isl_map_from_aff(
843 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
844 }
845 auto *Schedule = getParent()->getSchedule();
846 Schedule = isl_union_map_intersect_domain(
847 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
848 if (isl_union_map_is_empty(Schedule)) {
849 isl_set_free(Domain);
850 isl_union_map_free(Schedule);
851 return isl_map_from_aff(
852 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
853 }
854 auto *M = isl_map_from_union_map(Schedule);
855 M = isl_map_coalesce(M);
856 M = isl_map_gist_domain(M, Domain);
857 M = isl_map_coalesce(M);
858 return M;
859}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000860
Johannes Doerfert574182d2015-08-12 10:19:50 +0000861__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000862 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
863 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000864}
865
Tobias Grosser37eb4222014-02-20 21:43:54 +0000866void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
867 assert(isl_set_is_subset(NewDomain, Domain) &&
868 "New domain is not a subset of old domain!");
869 isl_set_free(Domain);
870 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000871}
872
Michael Krusecac948e2015-10-02 13:53:07 +0000873void ScopStmt::buildAccessRelations() {
874 for (MemoryAccess *Access : MemAccs) {
875 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000876
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000877 ScopArrayInfo::ARRAYKIND Ty;
878 if (Access->isPHI())
879 Ty = ScopArrayInfo::KIND_PHI;
880 else if (Access->isImplicit())
881 Ty = ScopArrayInfo::KIND_SCALAR;
882 else
883 Ty = ScopArrayInfo::KIND_ARRAY;
884
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000885 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000886 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000887
Michael Krusecac948e2015-10-02 13:53:07 +0000888 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000889 }
890}
891
Michael Krusecac948e2015-10-02 13:53:07 +0000892void ScopStmt::addAccess(MemoryAccess *Access) {
893 Instruction *AccessInst = Access->getAccessInstruction();
894
895 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
896 if (!MAL)
897 MAL = new MemoryAccessList();
898 MAL->emplace_front(Access);
899 MemAccs.push_back(MAL->front());
900}
901
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000902void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000903 for (MemoryAccess *MA : *this)
904 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000905
906 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000907}
908
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000909/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
910static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
911 void *User) {
912 isl_set **BoundedParts = static_cast<isl_set **>(User);
913 if (isl_basic_set_is_bounded(BSet))
914 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
915 else
916 isl_basic_set_free(BSet);
917 return isl_stat_ok;
918}
919
920/// @brief Return the bounded parts of @p S.
921static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
922 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
923 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
924 isl_set_free(S);
925 return BoundedParts;
926}
927
928/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
929///
930/// @returns A separation of @p S into first an unbounded then a bounded subset,
931/// both with regards to the dimension @p Dim.
932static std::pair<__isl_give isl_set *, __isl_give isl_set *>
933partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
934
935 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000936 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000937
938 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000939 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000940
941 // Remove dimensions that are greater than Dim as they are not interesting.
942 assert(NumDimsS >= Dim + 1);
943 OnlyDimS =
944 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
945
946 // Create artificial parametric upper bounds for dimensions smaller than Dim
947 // as we are not interested in them.
948 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
949 for (unsigned u = 0; u < Dim; u++) {
950 isl_constraint *C = isl_inequality_alloc(
951 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
952 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
953 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
954 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
955 }
956
957 // Collect all bounded parts of OnlyDimS.
958 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
959
960 // Create the dimensions greater than Dim again.
961 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
962 NumDimsS - Dim - 1);
963
964 // Remove the artificial upper bound parameters again.
965 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
966
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000967 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000968 return std::make_pair(UnboundedParts, BoundedParts);
969}
970
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000971/// @brief Set the dimension Ids from @p From in @p To.
972static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
973 __isl_take isl_set *To) {
974 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
975 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
976 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
977 }
978 return To;
979}
980
981/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000982static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000983 __isl_take isl_pw_aff *L,
984 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000985 switch (Pred) {
986 case ICmpInst::ICMP_EQ:
987 return isl_pw_aff_eq_set(L, R);
988 case ICmpInst::ICMP_NE:
989 return isl_pw_aff_ne_set(L, R);
990 case ICmpInst::ICMP_SLT:
991 return isl_pw_aff_lt_set(L, R);
992 case ICmpInst::ICMP_SLE:
993 return isl_pw_aff_le_set(L, R);
994 case ICmpInst::ICMP_SGT:
995 return isl_pw_aff_gt_set(L, R);
996 case ICmpInst::ICMP_SGE:
997 return isl_pw_aff_ge_set(L, R);
998 case ICmpInst::ICMP_ULT:
999 return isl_pw_aff_lt_set(L, R);
1000 case ICmpInst::ICMP_UGT:
1001 return isl_pw_aff_gt_set(L, R);
1002 case ICmpInst::ICMP_ULE:
1003 return isl_pw_aff_le_set(L, R);
1004 case ICmpInst::ICMP_UGE:
1005 return isl_pw_aff_ge_set(L, R);
1006 default:
1007 llvm_unreachable("Non integer predicate not supported");
1008 }
1009}
1010
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001011/// @brief Create the conditions under which @p L @p Pred @p R is true.
1012///
1013/// Helper function that will make sure the dimensions of the result have the
1014/// same isl_id's as the @p Domain.
1015static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1016 __isl_take isl_pw_aff *L,
1017 __isl_take isl_pw_aff *R,
1018 __isl_keep isl_set *Domain) {
1019 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1020 return setDimensionIds(Domain, ConsequenceCondSet);
1021}
1022
1023/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001024///
1025/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001026/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1027/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001028static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001029buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001030 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1031
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001032 Value *Condition = getConditionFromTerminator(SI);
1033 assert(Condition && "No condition for switch");
1034
1035 ScalarEvolution &SE = *S.getSE();
1036 BasicBlock *BB = SI->getParent();
1037 isl_pw_aff *LHS, *RHS;
1038 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1039
1040 unsigned NumSuccessors = SI->getNumSuccessors();
1041 ConditionSets.resize(NumSuccessors);
1042 for (auto &Case : SI->cases()) {
1043 unsigned Idx = Case.getSuccessorIndex();
1044 ConstantInt *CaseValue = Case.getCaseValue();
1045
1046 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1047 isl_set *CaseConditionSet =
1048 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1049 ConditionSets[Idx] = isl_set_coalesce(
1050 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1051 }
1052
1053 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1054 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1055 for (unsigned u = 2; u < NumSuccessors; u++)
1056 ConditionSetUnion =
1057 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1058 ConditionSets[0] = setDimensionIds(
1059 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1060
1061 S.markAsOptimized();
1062 isl_pw_aff_free(LHS);
1063}
1064
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001065/// @brief Build the conditions sets for the branch condition @p Condition in
1066/// the @p Domain.
1067///
1068/// This will fill @p ConditionSets with the conditions under which control
1069/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001070/// have as many elements as @p TI has successors. If @p TI is nullptr the
1071/// context under which @p Condition is true/false will be returned as the
1072/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001073static void
1074buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1075 __isl_keep isl_set *Domain,
1076 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1077
1078 isl_set *ConsequenceCondSet = nullptr;
1079 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1080 if (CCond->isZero())
1081 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1082 else
1083 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1084 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1085 auto Opcode = BinOp->getOpcode();
1086 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1087
1088 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1089 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1090
1091 isl_set_free(ConditionSets.pop_back_val());
1092 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1093 isl_set_free(ConditionSets.pop_back_val());
1094 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1095
1096 if (Opcode == Instruction::And)
1097 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1098 else
1099 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1100 } else {
1101 auto *ICond = dyn_cast<ICmpInst>(Condition);
1102 assert(ICond &&
1103 "Condition of exiting branch was neither constant nor ICmp!");
1104
1105 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001106 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001107 isl_pw_aff *LHS, *RHS;
1108 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1109 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1110 ConsequenceCondSet =
1111 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1112 }
1113
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001114 // If no terminator was given we are only looking for parameter constraints
1115 // under which @p Condition is true/false.
1116 if (!TI)
1117 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1118
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001119 assert(ConsequenceCondSet);
1120 isl_set *AlternativeCondSet =
1121 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1122
1123 ConditionSets.push_back(isl_set_coalesce(
1124 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1125 ConditionSets.push_back(isl_set_coalesce(
1126 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1127}
1128
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001129/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1130///
1131/// This will fill @p ConditionSets with the conditions under which control
1132/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1133/// have as many elements as @p TI has successors.
1134static void
1135buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1136 __isl_keep isl_set *Domain,
1137 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1138
1139 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1140 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1141
1142 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1143
1144 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001145 ConditionSets.push_back(isl_set_copy(Domain));
1146 return;
1147 }
1148
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001149 Value *Condition = getConditionFromTerminator(TI);
1150 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001151
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001152 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001153}
1154
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001155void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001156 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001157
Tobias Grosser084d8f72012-05-29 09:29:44 +00001158 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1159
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001160 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001161 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001162}
1163
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001164void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001165 isl_ctx *Ctx = Parent.getIslCtx();
1166 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1167 Type *Ty = GEP->getPointerOperandType();
1168 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001169 ScopDetection &SD = Parent.getSD();
1170
1171 // The set of loads that are required to be invariant.
1172 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001173
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001174 std::vector<const SCEV *> Subscripts;
1175 std::vector<int> Sizes;
1176
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001177 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001178
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001179 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001180 Ty = PtrTy->getElementType();
1181 }
1182
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001183 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001184
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001185 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001186
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001187 for (size_t i = 0; i < Sizes.size(); i++) {
1188 auto Expr = Subscripts[i + IndexOffset];
1189 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001190
Johannes Doerfert09e36972015-10-07 20:17:36 +00001191 InvariantLoadsSetTy AccessILS;
1192 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1193 continue;
1194
1195 bool NonAffine = false;
1196 for (LoadInst *LInst : AccessILS)
1197 if (!ScopRIL.count(LInst))
1198 NonAffine = true;
1199
1200 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001201 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001202
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001203 isl_pw_aff *AccessOffset = getPwAff(Expr);
1204 AccessOffset =
1205 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001206
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001207 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1208 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001209
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001210 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1211 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1212 OutOfBound = isl_set_params(OutOfBound);
1213 isl_set *InBound = isl_set_complement(OutOfBound);
1214 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001215
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001216 // A => B == !A or B
1217 isl_set *InBoundIfExecuted =
1218 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001219
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001220 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001221 }
1222
1223 isl_local_space_free(LSpace);
1224}
1225
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001226void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1227 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001228 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1229 deriveAssumptionsFromGEP(GEP);
1230}
1231
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001232void ScopStmt::collectSurroundingLoops() {
1233 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1234 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1235 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1236 isl_id_free(DimId);
1237 }
1238}
1239
Michael Kruse9d080092015-09-11 21:41:48 +00001240ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001241 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001242
Tobias Grosser16c44032015-07-09 07:31:45 +00001243 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001244}
1245
Michael Kruse9d080092015-09-11 21:41:48 +00001246ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001247 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001248
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001249 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001250}
1251
1252void ScopStmt::init() {
1253 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001254
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001255 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001256 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001257 buildAccessRelations();
1258
1259 if (BB) {
1260 deriveAssumptions(BB);
1261 } else {
1262 for (BasicBlock *Block : R->blocks()) {
1263 deriveAssumptions(Block);
1264 }
1265 }
1266
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001267 if (DetectReductions)
1268 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001269}
1270
Johannes Doerferte58a0122014-06-27 20:31:28 +00001271/// @brief Collect loads which might form a reduction chain with @p StoreMA
1272///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001273/// Check if the stored value for @p StoreMA is a binary operator with one or
1274/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001275/// used only once (by @p StoreMA) and its load operands are also used only
1276/// once, we have found a possible reduction chain. It starts at an operand
1277/// load and includes the binary operator and @p StoreMA.
1278///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001279/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001280/// escape this block or into any other store except @p StoreMA.
1281void ScopStmt::collectCandiateReductionLoads(
1282 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1283 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1284 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001285 return;
1286
1287 // Skip if there is not one binary operator between the load and the store
1288 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001289 if (!BinOp)
1290 return;
1291
1292 // Skip if the binary operators has multiple uses
1293 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001294 return;
1295
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001296 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001297 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1298 return;
1299
Johannes Doerfert9890a052014-07-01 00:32:29 +00001300 // Skip if the binary operator is outside the current SCoP
1301 if (BinOp->getParent() != Store->getParent())
1302 return;
1303
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001304 // Skip if it is a multiplicative reduction and we disabled them
1305 if (DisableMultiplicativeReductions &&
1306 (BinOp->getOpcode() == Instruction::Mul ||
1307 BinOp->getOpcode() == Instruction::FMul))
1308 return;
1309
Johannes Doerferte58a0122014-06-27 20:31:28 +00001310 // Check the binary operator operands for a candidate load
1311 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1312 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1313 if (!PossibleLoad0 && !PossibleLoad1)
1314 return;
1315
1316 // A load is only a candidate if it cannot escape (thus has only this use)
1317 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001318 if (PossibleLoad0->getParent() == Store->getParent())
1319 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001320 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001321 if (PossibleLoad1->getParent() == Store->getParent())
1322 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001323}
1324
1325/// @brief Check for reductions in this ScopStmt
1326///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001327/// Iterate over all store memory accesses and check for valid binary reduction
1328/// like chains. For all candidates we check if they have the same base address
1329/// and there are no other accesses which overlap with them. The base address
1330/// check rules out impossible reductions candidates early. The overlap check,
1331/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001332/// guarantees that none of the intermediate results will escape during
1333/// execution of the loop nest. We basically check here that no other memory
1334/// access can access the same memory as the potential reduction.
1335void ScopStmt::checkForReductions() {
1336 SmallVector<MemoryAccess *, 2> Loads;
1337 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1338
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001339 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001340 // stores and collecting possible reduction loads.
1341 for (MemoryAccess *StoreMA : MemAccs) {
1342 if (StoreMA->isRead())
1343 continue;
1344
1345 Loads.clear();
1346 collectCandiateReductionLoads(StoreMA, Loads);
1347 for (MemoryAccess *LoadMA : Loads)
1348 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1349 }
1350
1351 // Then check each possible candidate pair.
1352 for (const auto &CandidatePair : Candidates) {
1353 bool Valid = true;
1354 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1355 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1356
1357 // Skip those with obviously unequal base addresses.
1358 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1359 isl_map_free(LoadAccs);
1360 isl_map_free(StoreAccs);
1361 continue;
1362 }
1363
1364 // And check if the remaining for overlap with other memory accesses.
1365 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1366 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1367 isl_set *AllAccs = isl_map_range(AllAccsRel);
1368
1369 for (MemoryAccess *MA : MemAccs) {
1370 if (MA == CandidatePair.first || MA == CandidatePair.second)
1371 continue;
1372
1373 isl_map *AccRel =
1374 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1375 isl_set *Accs = isl_map_range(AccRel);
1376
1377 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1378 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1379 Valid = Valid && isl_set_is_empty(OverlapAccs);
1380 isl_set_free(OverlapAccs);
1381 }
1382 }
1383
1384 isl_set_free(AllAccs);
1385 if (!Valid)
1386 continue;
1387
Johannes Doerfertf6183392014-07-01 20:52:51 +00001388 const LoadInst *Load =
1389 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1390 MemoryAccess::ReductionType RT =
1391 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1392
Johannes Doerferte58a0122014-06-27 20:31:28 +00001393 // If no overlapping access was found we mark the load and store as
1394 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001395 CandidatePair.first->markAsReductionLike(RT);
1396 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001397 }
Tobias Grosser75805372011-04-29 06:27:02 +00001398}
1399
Tobias Grosser74394f02013-01-14 22:40:23 +00001400std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001401
Tobias Grosser54839312015-04-21 11:37:25 +00001402std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001403 auto *S = getSchedule();
1404 auto Str = stringFromIslObj(S);
1405 isl_map_free(S);
1406 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001407}
1408
Tobias Grosser74394f02013-01-14 22:40:23 +00001409unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001410
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001411unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001412
Tobias Grosser75805372011-04-29 06:27:02 +00001413const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1414
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001415const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001416 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001417}
1418
Tobias Grosser74394f02013-01-14 22:40:23 +00001419isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001420
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001421__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001422
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001423__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001424 return isl_set_get_space(Domain);
1425}
1426
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001427__isl_give isl_id *ScopStmt::getDomainId() const {
1428 return isl_set_get_tuple_id(Domain);
1429}
Tobias Grossercd95b772012-08-30 11:49:38 +00001430
Tobias Grosser75805372011-04-29 06:27:02 +00001431ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001432 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001433 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001434}
1435
1436void ScopStmt::print(raw_ostream &OS) const {
1437 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001438 OS.indent(12) << "Domain :=\n";
1439
1440 if (Domain) {
1441 OS.indent(16) << getDomainStr() << ";\n";
1442 } else
1443 OS.indent(16) << "n/a\n";
1444
Tobias Grosser54839312015-04-21 11:37:25 +00001445 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001446
1447 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001448 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001449 } else
1450 OS.indent(16) << "n/a\n";
1451
Tobias Grosser083d3d32014-06-28 08:59:45 +00001452 for (MemoryAccess *Access : MemAccs)
1453 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001454}
1455
1456void ScopStmt::dump() const { print(dbgs()); }
1457
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001458void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001459
1460 // Remove all memory accesses in @p InvMAs from this statement together
1461 // with all scalar accesses that were caused by them. The tricky iteration
1462 // order uses is needed because the MemAccs is a vector and the order in
1463 // which the accesses of each memory access list (MAL) are stored in this
1464 // vector is reversed.
1465 for (MemoryAccess *MA : InvMAs) {
1466 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1467 MAL.reverse();
1468
1469 auto MALIt = MAL.begin();
1470 auto MALEnd = MAL.end();
1471 auto MemAccsIt = MemAccs.begin();
1472 while (MALIt != MALEnd) {
1473 while (*MemAccsIt != *MALIt)
1474 MemAccsIt++;
1475
1476 MALIt++;
1477 MemAccs.erase(MemAccsIt);
1478 }
1479
1480 InstructionToAccess.erase(MA->getAccessInstruction());
1481 delete &MAL;
1482 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001483}
1484
Tobias Grosser75805372011-04-29 06:27:02 +00001485//===----------------------------------------------------------------------===//
1486/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001487
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001488void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001489 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1490 isl_set_free(Context);
1491 Context = NewContext;
1492}
1493
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001494/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1495struct SCEVSensitiveParameterRewriter
1496 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1497 ValueToValueMap &VMap;
1498 ScalarEvolution &SE;
1499
1500public:
1501 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1502 : VMap(VMap), SE(SE) {}
1503
1504 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1505 ValueToValueMap &VMap) {
1506 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1507 return SSPR.visit(E);
1508 }
1509
1510 const SCEV *visit(const SCEV *E) {
1511 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1512 }
1513
1514 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1515
1516 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1517 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1518 }
1519
1520 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1521 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1522 }
1523
1524 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1525 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1526 }
1527
1528 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1529 SmallVector<const SCEV *, 4> Operands;
1530 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1531 Operands.push_back(visit(E->getOperand(i)));
1532 return SE.getAddExpr(Operands);
1533 }
1534
1535 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1536 SmallVector<const SCEV *, 4> Operands;
1537 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1538 Operands.push_back(visit(E->getOperand(i)));
1539 return SE.getMulExpr(Operands);
1540 }
1541
1542 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1543 SmallVector<const SCEV *, 4> Operands;
1544 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1545 Operands.push_back(visit(E->getOperand(i)));
1546 return SE.getSMaxExpr(Operands);
1547 }
1548
1549 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1550 SmallVector<const SCEV *, 4> Operands;
1551 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1552 Operands.push_back(visit(E->getOperand(i)));
1553 return SE.getUMaxExpr(Operands);
1554 }
1555
1556 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1557 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1558 }
1559
1560 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1561 auto *Start = visit(E->getStart());
1562 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1563 visit(E->getStepRecurrence(SE)),
1564 E->getLoop(), SCEV::FlagAnyWrap);
1565 return SE.getAddExpr(Start, AddRec);
1566 }
1567
1568 const SCEV *visitUnknown(const SCEVUnknown *E) {
1569 if (auto *NewValue = VMap.lookup(E->getValue()))
1570 return SE.getUnknown(NewValue);
1571 return E;
1572 }
1573};
1574
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001575const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001576 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001577}
1578
Tobias Grosserabfbe632013-02-05 12:09:06 +00001579void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001580 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001581 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001582
1583 // Normalize the SCEV to get the representing element for an invariant load.
1584 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1585
Tobias Grosser60b54f12011-11-08 15:41:28 +00001586 if (ParameterIds.find(Parameter) != ParameterIds.end())
1587 continue;
1588
1589 int dimension = Parameters.size();
1590
1591 Parameters.push_back(Parameter);
1592 ParameterIds[Parameter] = dimension;
1593 }
1594}
1595
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001596__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001597 // Normalize the SCEV to get the representing element for an invariant load.
1598 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1599
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001600 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001601
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001602 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001603 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001604
Tobias Grosser8f99c162011-11-15 11:38:55 +00001605 std::string ParameterName;
1606
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001607 ParameterName = "p_" + utostr_32(IdIter->second);
1608
Tobias Grosser8f99c162011-11-15 11:38:55 +00001609 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1610 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001611
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001612 // If this parameter references a specific Value and this value has a name
1613 // we use this name as it is likely to be unique and more useful than just
1614 // a number.
1615 if (Val->hasName())
1616 ParameterName = Val->getName();
1617 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1618 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1619 if (LoadOrigin->hasName()) {
1620 ParameterName += "_loaded_from_";
1621 ParameterName +=
1622 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1623 }
1624 }
1625 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001626
Tobias Grosser20532b82014-04-11 17:56:49 +00001627 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1628 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001629}
Tobias Grosser75805372011-04-29 06:27:02 +00001630
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001631isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1632 isl_set *DomainContext = isl_union_set_params(getDomains());
1633 return isl_set_intersect_params(C, DomainContext);
1634}
1635
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001636void Scop::buildBoundaryContext() {
1637 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001638
1639 // The isl_set_complement operation used to create the boundary context
1640 // can possibly become very expensive. We bound the compile time of
1641 // this operation by setting a compute out.
1642 //
1643 // TODO: We can probably get around using isl_set_complement and directly
1644 // AST generate BoundaryContext.
1645 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001646 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001647 isl_ctx_set_max_operations(getIslCtx(), 300000);
1648 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1649
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001650 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001651
Tobias Grossera52b4da2015-11-11 17:59:53 +00001652 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1653 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001654 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001655 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001656
1657 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1658 isl_ctx_reset_operations(getIslCtx());
1659 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001660 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001661 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001662}
1663
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001664void Scop::addUserAssumptions(AssumptionCache &AC) {
1665 auto *R = &getRegion();
1666 auto &F = *R->getEntry()->getParent();
1667 for (auto &Assumption : AC.assumptions()) {
1668 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1669 if (!CI || CI->getNumArgOperands() != 1)
1670 continue;
1671 if (!DT.dominates(CI->getParent(), R->getEntry()))
1672 continue;
1673
1674 auto *Val = CI->getArgOperand(0);
1675 std::vector<const SCEV *> Params;
1676 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1677 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1678 CI->getDebugLoc(),
1679 "Non-affine user assumption ignored.");
1680 continue;
1681 }
1682
1683 addParams(Params);
1684
1685 auto *L = LI.getLoopFor(CI->getParent());
1686 SmallVector<isl_set *, 2> ConditionSets;
1687 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1688 assert(ConditionSets.size() == 2);
1689 isl_set_free(ConditionSets[1]);
1690
1691 auto *AssumptionCtx = ConditionSets[0];
1692 emitOptimizationRemarkAnalysis(
1693 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1694 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1695 Context = isl_set_intersect(Context, AssumptionCtx);
1696 }
1697}
1698
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001699void Scop::addUserContext() {
1700 if (UserContextStr.empty())
1701 return;
1702
1703 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1704 isl_space *Space = getParamSpace();
1705 if (isl_space_dim(Space, isl_dim_param) !=
1706 isl_set_dim(UserContext, isl_dim_param)) {
1707 auto SpaceStr = isl_space_to_str(Space);
1708 errs() << "Error: the context provided in -polly-context has not the same "
1709 << "number of dimensions than the computed context. Due to this "
1710 << "mismatch, the -polly-context option is ignored. Please provide "
1711 << "the context in the parameter space: " << SpaceStr << ".\n";
1712 free(SpaceStr);
1713 isl_set_free(UserContext);
1714 isl_space_free(Space);
1715 return;
1716 }
1717
1718 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1719 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1720 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1721
1722 if (strcmp(NameContext, NameUserContext) != 0) {
1723 auto SpaceStr = isl_space_to_str(Space);
1724 errs() << "Error: the name of dimension " << i
1725 << " provided in -polly-context "
1726 << "is '" << NameUserContext << "', but the name in the computed "
1727 << "context is '" << NameContext
1728 << "'. Due to this name mismatch, "
1729 << "the -polly-context option is ignored. Please provide "
1730 << "the context in the parameter space: " << SpaceStr << ".\n";
1731 free(SpaceStr);
1732 isl_set_free(UserContext);
1733 isl_space_free(Space);
1734 return;
1735 }
1736
1737 UserContext =
1738 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1739 isl_space_get_dim_id(Space, isl_dim_param, i));
1740 }
1741
1742 Context = isl_set_intersect(Context, UserContext);
1743 isl_space_free(Space);
1744}
1745
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001746void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001747 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1748
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001749 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001750 for (LoadInst *LInst : RIL) {
1751 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1752
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001753 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001754 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001755 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001756 continue;
1757 }
1758
1759 ClassRep = LInst;
1760 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1761 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001762 }
1763}
1764
Tobias Grosser6be480c2011-11-08 15:41:13 +00001765void Scop::buildContext() {
1766 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001767 Context = isl_set_universe(isl_space_copy(Space));
1768 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001769}
1770
Tobias Grosser18daaca2012-05-22 10:47:27 +00001771void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001772 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001773 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001774
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001775 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001776
Johannes Doerferte7044942015-02-24 11:58:30 +00001777 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001778 }
1779}
1780
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001781void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001782 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001783 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001784
Tobias Grosser083d3d32014-06-28 08:59:45 +00001785 for (const auto &ParamID : ParameterIds) {
1786 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001787 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001788 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001789 }
1790
1791 // Align the parameters of all data structures to the model.
1792 Context = isl_set_align_params(Context, Space);
1793
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001794 for (ScopStmt &Stmt : *this)
1795 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001796}
1797
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001798static __isl_give isl_set *
1799simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1800 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001801 // If we modelt all blocks in the SCoP that have side effects we can simplify
1802 // the context with the constraints that are needed for anything to be
1803 // executed at all. However, if we have error blocks in the SCoP we already
1804 // assumed some parameter combinations cannot occure and removed them from the
1805 // domains, thus we cannot use the remaining domain to simplify the
1806 // assumptions.
1807 if (!S.hasErrorBlock()) {
1808 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1809 AssumptionContext =
1810 isl_set_gist_params(AssumptionContext, DomainParameters);
1811 }
1812
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001813 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1814 return AssumptionContext;
1815}
1816
1817void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001818 // The parameter constraints of the iteration domains give us a set of
1819 // constraints that need to hold for all cases where at least a single
1820 // statement iteration is executed in the whole scop. We now simplify the
1821 // assumed context under the assumption that such constraints hold and at
1822 // least a single statement iteration is executed. For cases where no
1823 // statement instances are executed, the assumptions we have taken about
1824 // the executed code do not matter and can be changed.
1825 //
1826 // WARNING: This only holds if the assumptions we have taken do not reduce
1827 // the set of statement instances that are executed. Otherwise we
1828 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001829 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001830 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001831 // performed. In such a case, modifying the run-time conditions and
1832 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001833 // to not be executed.
1834 //
1835 // Example:
1836 //
1837 // When delinearizing the following code:
1838 //
1839 // for (long i = 0; i < 100; i++)
1840 // for (long j = 0; j < m; j++)
1841 // A[i+p][j] = 1.0;
1842 //
1843 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001844 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001845 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001846 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1847 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001848}
1849
Johannes Doerfertb164c792014-09-18 11:17:17 +00001850/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001851static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001852 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1853 isl_pw_multi_aff *MinPMA, *MaxPMA;
1854 isl_pw_aff *LastDimAff;
1855 isl_aff *OneAff;
1856 unsigned Pos;
1857
Johannes Doerfert9143d672014-09-27 11:02:39 +00001858 // Restrict the number of parameters involved in the access as the lexmin/
1859 // lexmax computation will take too long if this number is high.
1860 //
1861 // Experiments with a simple test case using an i7 4800MQ:
1862 //
1863 // #Parameters involved | Time (in sec)
1864 // 6 | 0.01
1865 // 7 | 0.04
1866 // 8 | 0.12
1867 // 9 | 0.40
1868 // 10 | 1.54
1869 // 11 | 6.78
1870 // 12 | 30.38
1871 //
1872 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1873 unsigned InvolvedParams = 0;
1874 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1875 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1876 InvolvedParams++;
1877
1878 if (InvolvedParams > RunTimeChecksMaxParameters) {
1879 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001880 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001881 }
1882 }
1883
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001884 Set = isl_set_remove_divs(Set);
1885
Johannes Doerfertb164c792014-09-18 11:17:17 +00001886 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1887 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1888
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001889 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1890 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1891
Johannes Doerfertb164c792014-09-18 11:17:17 +00001892 // Adjust the last dimension of the maximal access by one as we want to
1893 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1894 // we test during code generation might now point after the end of the
1895 // allocated array but we will never dereference it anyway.
1896 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1897 "Assumed at least one output dimension");
1898 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1899 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1900 OneAff = isl_aff_zero_on_domain(
1901 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1902 OneAff = isl_aff_add_constant_si(OneAff, 1);
1903 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1904 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1905
1906 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1907
1908 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001909 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001910}
1911
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001912static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1913 isl_set *Domain = MA->getStatement()->getDomain();
1914 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1915 return isl_set_reset_tuple_id(Domain);
1916}
1917
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001918/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1919static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001920 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001921 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001922
1923 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1924 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001925 Locations = isl_union_set_coalesce(Locations);
1926 Locations = isl_union_set_detect_equalities(Locations);
1927 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001928 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001929 isl_union_set_free(Locations);
1930 return Valid;
1931}
1932
Johannes Doerfert96425c22015-08-30 21:13:53 +00001933/// @brief Helper to treat non-affine regions and basic blocks the same.
1934///
1935///{
1936
1937/// @brief Return the block that is the representing block for @p RN.
1938static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1939 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1940 : RN->getNodeAs<BasicBlock>();
1941}
1942
1943/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001944static inline BasicBlock *
1945getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001946 if (RN->isSubRegion()) {
1947 assert(idx == 0);
1948 return RN->getNodeAs<Region>()->getExit();
1949 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001950 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001951}
1952
1953/// @brief Return the smallest loop surrounding @p RN.
1954static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1955 if (!RN->isSubRegion())
1956 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1957
1958 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1959 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1960 while (L && NonAffineSubRegion->contains(L))
1961 L = L->getParentLoop();
1962 return L;
1963}
1964
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001965static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1966 if (!RN->isSubRegion())
1967 return 1;
1968
1969 unsigned NumBlocks = 0;
1970 Region *R = RN->getNodeAs<Region>();
1971 for (auto BB : R->blocks()) {
1972 (void)BB;
1973 NumBlocks++;
1974 }
1975 return NumBlocks;
1976}
1977
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001978static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1979 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001980 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001981 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001982 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001983 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001984 return true;
1985 return false;
1986}
1987
Johannes Doerfert96425c22015-08-30 21:13:53 +00001988///}
1989
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001990static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1991 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001992 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001993 isl_id *DimId =
1994 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1995 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1996}
1997
Johannes Doerfert96425c22015-08-30 21:13:53 +00001998isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1999 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2000 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002001 return getDomainConditions(BB);
2002}
2003
2004isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2005 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002006 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002007}
2008
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002009void Scop::removeErrorBlockDomains() {
2010 auto removeDomains = [this](BasicBlock *Start) {
2011 auto BBNode = DT.getNode(Start);
2012 for (auto ErrorChild : depth_first(BBNode)) {
2013 auto ErrorChildBlock = ErrorChild->getBlock();
2014 auto CurrentDomain = DomainMap[ErrorChildBlock];
2015 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2016 DomainMap[ErrorChildBlock] = Empty;
2017 isl_set_free(CurrentDomain);
2018 }
2019 };
2020
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002021 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002022
2023 while (!Todo.empty()) {
2024 auto SubRegion = Todo.back();
2025 Todo.pop_back();
2026
2027 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2028 for (auto &Child : *SubRegion)
2029 Todo.push_back(Child.get());
2030 continue;
2031 }
2032 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2033 removeDomains(SubRegion->getEntry());
2034 }
2035
2036 for (auto BB : R.blocks())
2037 if (isErrorBlock(*BB, R, LI, DT))
2038 removeDomains(BB);
2039}
2040
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002041void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002042
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002043 auto *EntryBB = R->getEntry();
2044 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
2045 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002046
2047 Loop *L = LI.getLoopFor(EntryBB);
2048 while (LD-- >= 0) {
2049 S = addDomainDimId(S, LD + 1, L);
2050 L = L->getParentLoop();
2051 }
2052
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002053 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002054
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002055 if (SD.isNonAffineSubRegion(R, R))
2056 return;
2057
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002058 buildDomainsWithBranchConstraints(R);
2059 propagateDomainConstraints(R);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002060
2061 // Error blocks and blocks dominated by them have been assumed to never be
2062 // executed. Representing them in the Scop does not add any value. In fact,
2063 // it is likely to cause issues during construction of the ScopStmts. The
2064 // contents of error blocks have not been verfied to be expressible and
2065 // will cause problems when building up a ScopStmt for them.
2066 // Furthermore, basic blocks dominated by error blocks may reference
2067 // instructions in the error block which, if the error block is not modeled,
2068 // can themselves not be constructed properly.
2069 removeErrorBlockDomains();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002070}
2071
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002072void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002073 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002074
2075 // To create the domain for each block in R we iterate over all blocks and
2076 // subregions in R and propagate the conditions under which the current region
2077 // element is executed. To this end we iterate in reverse post order over R as
2078 // it ensures that we first visit all predecessors of a region node (either a
2079 // basic block or a subregion) before we visit the region node itself.
2080 // Initially, only the domain for the SCoP region entry block is set and from
2081 // there we propagate the current domain to all successors, however we add the
2082 // condition that the successor is actually executed next.
2083 // As we are only interested in non-loop carried constraints here we can
2084 // simply skip loop back edges.
2085
2086 ReversePostOrderTraversal<Region *> RTraversal(R);
2087 for (auto *RN : RTraversal) {
2088
2089 // Recurse for affine subregions but go on for basic blocks and non-affine
2090 // subregions.
2091 if (RN->isSubRegion()) {
2092 Region *SubRegion = RN->getNodeAs<Region>();
2093 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002094 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002095 continue;
2096 }
2097 }
2098
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002099 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002100 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002101
Johannes Doerfert96425c22015-08-30 21:13:53 +00002102 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002103 TerminatorInst *TI = BB->getTerminator();
2104
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002105 if (isa<UnreachableInst>(TI))
2106 continue;
2107
Johannes Doerfertf5673802015-10-01 23:48:18 +00002108 isl_set *Domain = DomainMap.lookup(BB);
2109 if (!Domain) {
2110 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2111 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002112 continue;
2113 }
2114
Johannes Doerfert96425c22015-08-30 21:13:53 +00002115 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002116
2117 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2118 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2119
2120 // Build the condition sets for the successor nodes of the current region
2121 // node. If it is a non-affine subregion we will always execute the single
2122 // exit node, hence the single entry node domain is the condition set. For
2123 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002124 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002125 if (RN->isSubRegion())
2126 ConditionSets.push_back(isl_set_copy(Domain));
2127 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002128 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002129
2130 // Now iterate over the successors and set their initial domain based on
2131 // their condition set. We skip back edges here and have to be careful when
2132 // we leave a loop not to keep constraints over a dimension that doesn't
2133 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002134 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002135 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002136 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002137 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002138
2139 // Skip back edges.
2140 if (DT.dominates(SuccBB, BB)) {
2141 isl_set_free(CondSet);
2142 continue;
2143 }
2144
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002145 // Do not adjust the number of dimensions if we enter a boxed loop or are
2146 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002147 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002148 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002149 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2150 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2151 SuccBBLoop = SuccBBLoop->getParentLoop();
2152
2153 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002154
2155 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2156 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2157 // and enter a new one we need to drop the old constraints.
2158 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002159 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002160 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002161 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2162 isl_set_n_dim(CondSet) - LoopDepthDiff,
2163 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002164 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002165 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002166 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002167 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002168 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002169 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002170 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2171 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002172 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002173 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002174 }
2175
2176 // Set the domain for the successor or merge it with an existing domain in
2177 // case there are multiple paths (without loop back edges) to the
2178 // successor block.
2179 isl_set *&SuccDomain = DomainMap[SuccBB];
2180 if (!SuccDomain)
2181 SuccDomain = CondSet;
2182 else
2183 SuccDomain = isl_set_union(SuccDomain, CondSet);
2184
2185 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002186 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2187 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002188 }
2189 }
2190}
2191
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002192/// @brief Return the domain for @p BB wrt @p DomainMap.
2193///
2194/// This helper function will lookup @p BB in @p DomainMap but also handle the
2195/// case where @p BB is contained in a non-affine subregion using the region
2196/// tree obtained by @p RI.
2197static __isl_give isl_set *
2198getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2199 RegionInfo &RI) {
2200 auto DIt = DomainMap.find(BB);
2201 if (DIt != DomainMap.end())
2202 return isl_set_copy(DIt->getSecond());
2203
2204 Region *R = RI.getRegionFor(BB);
2205 while (R->getEntry() == BB)
2206 R = R->getParent();
2207 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2208}
2209
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002210void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002211 // Iterate over the region R and propagate the domain constrains from the
2212 // predecessors to the current node. In contrast to the
2213 // buildDomainsWithBranchConstraints function, this one will pull the domain
2214 // information from the predecessors instead of pushing it to the successors.
2215 // Additionally, we assume the domains to be already present in the domain
2216 // map here. However, we iterate again in reverse post order so we know all
2217 // predecessors have been visited before a block or non-affine subregion is
2218 // visited.
2219
2220 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2221 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2222
2223 ReversePostOrderTraversal<Region *> RTraversal(R);
2224 for (auto *RN : RTraversal) {
2225
2226 // Recurse for affine subregions but go on for basic blocks and non-affine
2227 // subregions.
2228 if (RN->isSubRegion()) {
2229 Region *SubRegion = RN->getNodeAs<Region>();
2230 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002231 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002232 continue;
2233 }
2234 }
2235
Johannes Doerfertf5673802015-10-01 23:48:18 +00002236 // Get the domain for the current block and check if it was initialized or
2237 // not. The only way it was not is if this block is only reachable via error
2238 // blocks, thus will not be executed under the assumptions we make. Such
2239 // blocks have to be skipped as their predecessors might not have domains
2240 // either. It would not benefit us to compute the domain anyway, only the
2241 // domains of the error blocks that are reachable from non-error blocks
2242 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002243 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002244 isl_set *&Domain = DomainMap[BB];
2245 if (!Domain) {
2246 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2247 << ", it is only reachable from error blocks.\n");
2248 DomainMap.erase(BB);
2249 continue;
2250 }
2251 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2252
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002253 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2254 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2255
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002256 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2257 for (auto *PredBB : predecessors(BB)) {
2258
2259 // Skip backedges
2260 if (DT.dominates(BB, PredBB))
2261 continue;
2262
2263 isl_set *PredBBDom = nullptr;
2264
2265 // Handle the SCoP entry block with its outside predecessors.
2266 if (!getRegion().contains(PredBB))
2267 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2268
2269 if (!PredBBDom) {
2270 // Determine the loop depth of the predecessor and adjust its domain to
2271 // the domain of the current block. This can mean we have to:
2272 // o) Drop a dimension if this block is the exit of a loop, not the
2273 // header of a new loop and the predecessor was part of the loop.
2274 // o) Add an unconstrainted new dimension if this block is the header
2275 // of a loop and the predecessor is not part of it.
2276 // o) Drop the information about the innermost loop dimension when the
2277 // predecessor and the current block are surrounded by different
2278 // loops in the same depth.
2279 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2280 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2281 while (BoxedLoops.count(PredBBLoop))
2282 PredBBLoop = PredBBLoop->getParentLoop();
2283
2284 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002285 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002286 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002287 PredBBDom = isl_set_project_out(
2288 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2289 LoopDepthDiff);
2290 else if (PredBBLoopDepth < BBLoopDepth) {
2291 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002292 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002293 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2294 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002295 PredBBDom = isl_set_drop_constraints_involving_dims(
2296 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002297 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002298 }
2299
2300 PredDom = isl_set_union(PredDom, PredBBDom);
2301 }
2302
2303 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002304 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002305
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002306 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002307 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002308
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002309 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002310 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002311 IsOptimized = true;
2312 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002313 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2314 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002315 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002316 }
2317}
2318
2319/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2320/// is incremented by one and all other dimensions are equal, e.g.,
2321/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2322/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2323static __isl_give isl_map *
2324createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2325 auto *MapSpace = isl_space_map_from_set(SetSpace);
2326 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2327 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2328 if (u != Dim)
2329 NextIterationMap =
2330 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2331 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2332 C = isl_constraint_set_constant_si(C, 1);
2333 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2334 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2335 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2336 return NextIterationMap;
2337}
2338
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002339void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002340 int LoopDepth = getRelativeLoopDepth(L);
2341 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002342
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002343 BasicBlock *HeaderBB = L->getHeader();
2344 assert(DomainMap.count(HeaderBB));
2345 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002346
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002347 isl_map *NextIterationMap =
2348 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002349
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002350 isl_set *UnionBackedgeCondition =
2351 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002352
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002353 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2354 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002355
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002356 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002357
2358 // If the latch is only reachable via error statements we skip it.
2359 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2360 if (!LatchBBDom)
2361 continue;
2362
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002363 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002364
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002365 TerminatorInst *TI = LatchBB->getTerminator();
2366 BranchInst *BI = dyn_cast<BranchInst>(TI);
2367 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002368 BackedgeCondition = isl_set_copy(LatchBBDom);
2369 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002370 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002371 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002372 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002373
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002374 // Free the non back edge condition set as we do not need it.
2375 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002376
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002377 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002378 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002379
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002380 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2381 assert(LatchLoopDepth >= LoopDepth);
2382 BackedgeCondition =
2383 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2384 LatchLoopDepth - LoopDepth);
2385 UnionBackedgeCondition =
2386 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002387 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002388
2389 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2390 for (int i = 0; i < LoopDepth; i++)
2391 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2392
2393 isl_set *UnionBackedgeConditionComplement =
2394 isl_set_complement(UnionBackedgeCondition);
2395 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2396 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2397 UnionBackedgeConditionComplement =
2398 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2399 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2400 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2401
2402 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2403 HeaderBBDom = Parts.second;
2404
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002405 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2406 // the bounded assumptions to the context as they are already implied by the
2407 // <nsw> tag.
2408 if (Affinator.hasNSWAddRecForLoop(L)) {
2409 isl_set_free(Parts.first);
2410 return;
2411 }
2412
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002413 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2414 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002415 addAssumption(INFINITELOOP, BoundedCtx,
2416 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002417}
2418
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002419void Scop::buildAliasChecks(AliasAnalysis &AA) {
2420 if (!PollyUseRuntimeAliasChecks)
2421 return;
2422
2423 if (buildAliasGroups(AA))
2424 return;
2425
2426 // If a problem occurs while building the alias groups we need to delete
2427 // this SCoP and pretend it wasn't valid in the first place. To this end
2428 // we make the assumed context infeasible.
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002429 addAssumption(ALIASING, isl_set_empty(getParamSpace()), DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002430
2431 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2432 << " could not be created as the number of parameters involved "
2433 "is too high. The SCoP will be "
2434 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2435 "the maximal number of parameters but be advised that the "
2436 "compile time might increase exponentially.\n\n");
2437}
2438
Johannes Doerfert9143d672014-09-27 11:02:39 +00002439bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002440 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002441 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002442 // for all memory accesses inside the SCoP.
2443 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002444 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002445 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002446 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002447 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002448 // if their access domains intersect, otherwise they are in different
2449 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002450 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002451 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002452 // and maximal accesses to each array of a group in read only and non
2453 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002454 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2455
2456 AliasSetTracker AST(AA);
2457
2458 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002459 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002460 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002461
2462 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002463 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002464 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2465 isl_set_free(StmtDomain);
2466 if (StmtDomainEmpty)
2467 continue;
2468
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002469 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002470 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002471 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002472 if (!MA->isRead())
2473 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002474 Instruction *Acc = MA->getAccessInstruction();
2475 PtrToAcc[getPointerOperand(*Acc)] = MA;
2476 AST.add(Acc);
2477 }
2478 }
2479
2480 SmallVector<AliasGroupTy, 4> AliasGroups;
2481 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002482 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002483 continue;
2484 AliasGroupTy AG;
2485 for (auto PR : AS)
2486 AG.push_back(PtrToAcc[PR.getValue()]);
2487 assert(AG.size() > 1 &&
2488 "Alias groups should contain at least two accesses");
2489 AliasGroups.push_back(std::move(AG));
2490 }
2491
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002492 // Split the alias groups based on their domain.
2493 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2494 AliasGroupTy NewAG;
2495 AliasGroupTy &AG = AliasGroups[u];
2496 AliasGroupTy::iterator AGI = AG.begin();
2497 isl_set *AGDomain = getAccessDomain(*AGI);
2498 while (AGI != AG.end()) {
2499 MemoryAccess *MA = *AGI;
2500 isl_set *MADomain = getAccessDomain(MA);
2501 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2502 NewAG.push_back(MA);
2503 AGI = AG.erase(AGI);
2504 isl_set_free(MADomain);
2505 } else {
2506 AGDomain = isl_set_union(AGDomain, MADomain);
2507 AGI++;
2508 }
2509 }
2510 if (NewAG.size() > 1)
2511 AliasGroups.push_back(std::move(NewAG));
2512 isl_set_free(AGDomain);
2513 }
2514
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002515 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002516 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002517 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2518 for (AliasGroupTy &AG : AliasGroups) {
2519 NonReadOnlyBaseValues.clear();
2520 ReadOnlyPairs.clear();
2521
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002522 if (AG.size() < 2) {
2523 AG.clear();
2524 continue;
2525 }
2526
Johannes Doerfert13771732014-10-01 12:40:46 +00002527 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002528 emitOptimizationRemarkAnalysis(
2529 F.getContext(), DEBUG_TYPE, F,
2530 (*II)->getAccessInstruction()->getDebugLoc(),
2531 "Possibly aliasing pointer, use restrict keyword.");
2532
Johannes Doerfert13771732014-10-01 12:40:46 +00002533 Value *BaseAddr = (*II)->getBaseAddr();
2534 if (HasWriteAccess.count(BaseAddr)) {
2535 NonReadOnlyBaseValues.insert(BaseAddr);
2536 II++;
2537 } else {
2538 ReadOnlyPairs[BaseAddr].insert(*II);
2539 II = AG.erase(II);
2540 }
2541 }
2542
2543 // If we don't have read only pointers check if there are at least two
2544 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002545 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002546 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002547 continue;
2548 }
2549
2550 // If we don't have non read only pointers clear the alias group.
2551 if (NonReadOnlyBaseValues.empty()) {
2552 AG.clear();
2553 continue;
2554 }
2555
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002556 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002557 MinMaxAliasGroups.emplace_back();
2558 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2559 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2560 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2561 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002562
2563 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002564
2565 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002566 for (MemoryAccess *MA : AG)
2567 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002568
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002569 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2570 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002571
2572 // Bail out if the number of values we need to compare is too large.
2573 // This is important as the number of comparisions grows quadratically with
2574 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002575 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2576 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002577 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002578
2579 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002580 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002581 Accesses = isl_union_map_empty(getParamSpace());
2582
2583 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2584 for (MemoryAccess *MA : ReadOnlyPair.second)
2585 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2586
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002587 Valid =
2588 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002589
2590 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002591 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002592 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002593
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002594 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002595}
2596
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002597/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002598static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002599 // Start with the smallest loop containing the entry and expand that
2600 // loop until it contains all blocks in the region. If there is a loop
2601 // containing all blocks in the region check if it is itself contained
2602 // and if so take the parent loop as it will be the smallest containing
2603 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002604 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002605 while (L) {
2606 bool AllContained = true;
2607 for (auto *BB : R.blocks())
2608 AllContained &= L->contains(BB);
2609 if (AllContained)
2610 break;
2611 L = L->getParentLoop();
2612 }
2613
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002614 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2615}
2616
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002617static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2618 ScopDetection &SD) {
2619
2620 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2621
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002622 unsigned MinLD = INT_MAX, MaxLD = 0;
2623 for (BasicBlock *BB : R.blocks()) {
2624 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002625 if (!R.contains(L))
2626 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002627 if (BoxedLoops && BoxedLoops->count(L))
2628 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002629 unsigned LD = L->getLoopDepth();
2630 MinLD = std::min(MinLD, LD);
2631 MaxLD = std::max(MaxLD, LD);
2632 }
2633 }
2634
2635 // Handle the case that there is no loop in the SCoP first.
2636 if (MaxLD == 0)
2637 return 1;
2638
2639 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2640 assert(MaxLD >= MinLD &&
2641 "Maximal loop depth was smaller than mininaml loop depth?");
2642 return MaxLD - MinLD + 1;
2643}
2644
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002645Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002646 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002647 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002648 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2649 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002650 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2651 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2652 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2653 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002654
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002655void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002656 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002657 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002658 buildInvariantEquivalenceClasses();
2659
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002660 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002661
Michael Krusecac948e2015-10-02 13:53:07 +00002662 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002663 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002664 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002665 if (Stmts.empty())
2666 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002667
Michael Krusecac948e2015-10-02 13:53:07 +00002668 // The ScopStmts now have enough information to initialize themselves.
2669 for (ScopStmt &Stmt : Stmts)
2670 Stmt.init();
2671
2672 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002673 Loop *L = getLoopSurroundingRegion(R, LI);
2674 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002675 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002676 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002677
Tobias Grosser8286b832015-11-02 11:29:32 +00002678 if (isl_set_is_empty(AssumedContext))
2679 return;
2680
2681 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002682 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002683 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002684 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002685 buildBoundaryContext();
2686 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002687 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002688
2689 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002690 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002691}
2692
2693Scop::~Scop() {
2694 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002695 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002696 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002697 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002698
Johannes Doerfert96425c22015-08-30 21:13:53 +00002699 for (auto It : DomainMap)
2700 isl_set_free(It.second);
2701
Johannes Doerfertb164c792014-09-18 11:17:17 +00002702 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002703 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002704 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002705 isl_pw_multi_aff_free(MMA.first);
2706 isl_pw_multi_aff_free(MMA.second);
2707 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002708 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002709 isl_pw_multi_aff_free(MMA.first);
2710 isl_pw_multi_aff_free(MMA.second);
2711 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002712 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002713
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002714 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002715 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002716}
2717
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002718void Scop::updateAccessDimensionality() {
2719 for (auto &Stmt : *this)
2720 for (auto &Access : Stmt)
2721 Access->updateDimensionality();
2722}
2723
Michael Krusecac948e2015-10-02 13:53:07 +00002724void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002725 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2726 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002727 RegionNode *RN = Stmt.isRegionStmt()
2728 ? Stmt.getRegion()->getNode()
2729 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002730
Johannes Doerferteca9e892015-11-03 16:54:49 +00002731 bool RemoveStmt = StmtIt->isEmpty();
2732 if (!RemoveStmt)
2733 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2734 if (!RemoveStmt)
2735 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002736
Johannes Doerferteca9e892015-11-03 16:54:49 +00002737 // Remove read only statements only after invariant loop hoisting.
2738 if (!RemoveStmt && !RemoveIgnoredStmts) {
2739 bool OnlyRead = true;
2740 for (MemoryAccess *MA : Stmt) {
2741 if (MA->isRead())
2742 continue;
2743
2744 OnlyRead = false;
2745 break;
2746 }
2747
2748 RemoveStmt = OnlyRead;
2749 }
2750
2751 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002752 // Remove the statement because it is unnecessary.
2753 if (Stmt.isRegionStmt())
2754 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2755 StmtMap.erase(BB);
2756 else
2757 StmtMap.erase(Stmt.getBasicBlock());
2758
2759 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002760 continue;
2761 }
2762
Michael Krusecac948e2015-10-02 13:53:07 +00002763 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002764 }
2765}
2766
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002767const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2768 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2769 if (!LInst)
2770 return nullptr;
2771
2772 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2773 LInst = cast<LoadInst>(Rep);
2774
2775 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2776 for (auto &IAClass : InvariantEquivClasses)
2777 if (PointerSCEV == std::get<0>(IAClass))
2778 return &IAClass;
2779
2780 return nullptr;
2781}
2782
2783void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2784
2785 // Get the context under which the statement is executed.
2786 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2787 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2788 DomainCtx = isl_set_detect_equalities(DomainCtx);
2789 DomainCtx = isl_set_coalesce(DomainCtx);
2790
2791 // Project out all parameters that relate to loads in the statement. Otherwise
2792 // we could have cyclic dependences on the constraints under which the
2793 // hoisted loads are executed and we could not determine an order in which to
2794 // pre-load them. This happens because not only lower bounds are part of the
2795 // domain but also upper bounds.
2796 for (MemoryAccess *MA : InvMAs) {
2797 Instruction *AccInst = MA->getAccessInstruction();
2798 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002799 SetVector<Value *> Values;
2800 for (const SCEV *Parameter : Parameters) {
2801 Values.clear();
2802 findValues(Parameter, Values);
2803 if (!Values.count(AccInst))
2804 continue;
2805
2806 if (isl_id *ParamId = getIdForParam(Parameter)) {
2807 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2808 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2809 isl_id_free(ParamId);
2810 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002811 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002812 }
2813 }
2814
2815 for (MemoryAccess *MA : InvMAs) {
2816 // Check for another invariant access that accesses the same location as
2817 // MA and if found consolidate them. Otherwise create a new equivalence
2818 // class at the end of InvariantEquivClasses.
2819 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2820 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2821
2822 bool Consolidated = false;
2823 for (auto &IAClass : InvariantEquivClasses) {
2824 if (PointerSCEV != std::get<0>(IAClass))
2825 continue;
2826
2827 Consolidated = true;
2828
2829 // Add MA to the list of accesses that are in this class.
2830 auto &MAs = std::get<1>(IAClass);
2831 MAs.push_front(MA);
2832
2833 // Unify the execution context of the class and this statement.
2834 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002835 if (IAClassDomainCtx)
2836 IAClassDomainCtx = isl_set_coalesce(
2837 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2838 else
2839 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002840 break;
2841 }
2842
2843 if (Consolidated)
2844 continue;
2845
2846 // If we did not consolidate MA, thus did not find an equivalence class
2847 // for it, we create a new one.
2848 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2849 isl_set_copy(DomainCtx));
2850 }
2851
2852 isl_set_free(DomainCtx);
2853}
2854
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002855void Scop::hoistInvariantLoads() {
2856 isl_union_map *Writes = getWrites();
2857 for (ScopStmt &Stmt : *this) {
2858
2859 // TODO: Loads that are not loop carried, hence are in a statement with
2860 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002861 // currently "hoist" them anyway. This is necessary because we allow
2862 // them to be treated as parameters (e.g., in conditions) and our code
2863 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002864
Johannes Doerfert8930f482015-10-02 14:51:00 +00002865 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2866 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002867 isl_set *Domain = Stmt.getDomain();
2868 MemoryAccessList InvMAs;
2869
2870 for (MemoryAccess *MA : Stmt) {
2871 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2872 continue;
2873
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002874 // Skip accesses that have an invariant base pointer which is defined but
2875 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2876 // returns a pointer that is used as a base address. However, as we want
2877 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002878 // the region if it is also a memory access. Each ScopArrayInfo object
2879 // that has a base pointer origin has a base pointer that is loaded and
2880 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002881 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002882 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002883 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002884 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2885 SAI = BasePtrOriginSAI;
2886
2887 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2888 if (R.contains(BasePtrInst))
2889 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002890
Johannes Doerfert8930f482015-10-02 14:51:00 +00002891 // Skip accesses in non-affine subregions as they might not be executed
2892 // under the same condition as the entry of the non-affine subregion.
2893 if (BB != MA->getAccessInstruction()->getParent())
2894 continue;
2895
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002896 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002897
2898 // Skip accesses that have an empty access relation. These can be caused
2899 // by multiple offsets with a type cast in-between that cause the overall
2900 // byte offset to be not divisible by the new types sizes.
2901 if (isl_map_is_empty(AccessRelation)) {
2902 isl_map_free(AccessRelation);
2903 continue;
2904 }
2905
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002906 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2907 Stmt.getNumIterators())) {
2908 isl_map_free(AccessRelation);
2909 continue;
2910 }
2911
2912 AccessRelation =
2913 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2914 isl_set *AccessRange = isl_map_range(AccessRelation);
2915
2916 isl_union_map *Written = isl_union_map_intersect_range(
2917 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2918 bool IsWritten = !isl_union_map_is_empty(Written);
2919 isl_union_map_free(Written);
2920
2921 if (IsWritten)
2922 continue;
2923
2924 InvMAs.push_front(MA);
2925 }
2926
2927 // We inserted invariant accesses always in the front but need them to be
2928 // sorted in a "natural order". The statements are already sorted in reverse
2929 // post order and that suffices for the accesses too. The reason we require
2930 // an order in the first place is the dependences between invariant loads
2931 // that can be caused by indirect loads.
2932 InvMAs.reverse();
2933
2934 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002935 Stmt.removeMemoryAccesses(InvMAs);
2936 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002937
2938 isl_set_free(Domain);
2939 }
2940 isl_union_map_free(Writes);
2941
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002942 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002943 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002944 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002945 assert(LI && getRegion().contains(LI));
2946 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2947 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2948 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2949 << ") is required to be invariant but was not marked as "
2950 "such. SCoP for "
2951 << getRegion() << " will be dropped\n\n");
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002952 addAssumption(INVARIANTLOAD, isl_set_empty(getParamSpace()),
2953 LI->getDebugLoc());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002954 return;
2955 }
2956 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002957}
2958
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002959const ScopArrayInfo *
2960Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002961 ArrayRef<const SCEV *> Sizes,
2962 ScopArrayInfo::ARRAYKIND Kind) {
2963 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002964 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002965 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2966 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2967 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002968 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002969 // In case of mismatching array sizes, we bail out by setting the run-time
2970 // context to false.
2971 if (!SAI->updateSizes(Sizes))
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002972 addAssumption(DELINEARIZATION, isl_set_empty(getParamSpace()),
2973 DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002974 }
Tobias Grosserab671442015-05-23 05:58:27 +00002975 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002976}
2977
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002978const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2979 ScopArrayInfo::ARRAYKIND Kind) {
2980 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002981 assert(SAI && "No ScopArrayInfo available for this base pointer");
2982 return SAI;
2983}
2984
Tobias Grosser74394f02013-01-14 22:40:23 +00002985std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002986std::string Scop::getAssumedContextStr() const {
2987 return stringFromIslObj(AssumedContext);
2988}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002989std::string Scop::getBoundaryContextStr() const {
2990 return stringFromIslObj(BoundaryContext);
2991}
Tobias Grosser75805372011-04-29 06:27:02 +00002992
2993std::string Scop::getNameStr() const {
2994 std::string ExitName, EntryName;
2995 raw_string_ostream ExitStr(ExitName);
2996 raw_string_ostream EntryStr(EntryName);
2997
Tobias Grosserf240b482014-01-09 10:42:15 +00002998 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002999 EntryStr.str();
3000
3001 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003002 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003003 ExitStr.str();
3004 } else
3005 ExitName = "FunctionExit";
3006
3007 return EntryName + "---" + ExitName;
3008}
3009
Tobias Grosser74394f02013-01-14 22:40:23 +00003010__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003011__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003012 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003013}
3014
Tobias Grossere86109f2013-10-29 21:05:49 +00003015__isl_give isl_set *Scop::getAssumedContext() const {
3016 return isl_set_copy(AssumedContext);
3017}
3018
Johannes Doerfert43788c52015-08-20 05:58:56 +00003019__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3020 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003021 RuntimeCheckContext =
3022 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3023 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003024 return RuntimeCheckContext;
3025}
3026
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003027bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003028 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003029 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003030 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3031 isl_set_free(RuntimeCheckContext);
3032 return IsFeasible;
3033}
3034
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003035static std::string toString(AssumptionKind Kind) {
3036 switch (Kind) {
3037 case ALIASING:
3038 return "No-aliasing";
3039 case INBOUNDS:
3040 return "Inbounds";
3041 case WRAPPING:
3042 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003043 case ALIGNMENT:
3044 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003045 case ERRORBLOCK:
3046 return "No-error";
3047 case INFINITELOOP:
3048 return "Finite loop";
3049 case INVARIANTLOAD:
3050 return "Invariant load";
3051 case DELINEARIZATION:
3052 return "Delinearization";
3053 }
3054 llvm_unreachable("Unknown AssumptionKind!");
3055}
3056
3057void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3058 DebugLoc Loc) {
3059 if (isl_set_is_subset(Context, Set))
3060 return;
3061
3062 if (isl_set_is_subset(AssumedContext, Set))
3063 return;
3064
3065 auto &F = *getRegion().getEntry()->getParent();
3066 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3067 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3068}
3069
3070void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3071 DebugLoc Loc) {
3072 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003073 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003074
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003075 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003076 if (NSets >= MaxDisjunctsAssumed) {
3077 isl_space *Space = isl_set_get_space(AssumedContext);
3078 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003079 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003080 }
3081
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003082 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003083}
3084
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003085__isl_give isl_set *Scop::getBoundaryContext() const {
3086 return isl_set_copy(BoundaryContext);
3087}
3088
Tobias Grosser75805372011-04-29 06:27:02 +00003089void Scop::printContext(raw_ostream &OS) const {
3090 OS << "Context:\n";
3091
3092 if (!Context) {
3093 OS.indent(4) << "n/a\n\n";
3094 return;
3095 }
3096
3097 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003098
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003099 OS.indent(4) << "Assumed Context:\n";
3100 if (!AssumedContext) {
3101 OS.indent(4) << "n/a\n\n";
3102 return;
3103 }
3104
3105 OS.indent(4) << getAssumedContextStr() << "\n";
3106
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003107 OS.indent(4) << "Boundary Context:\n";
3108 if (!BoundaryContext) {
3109 OS.indent(4) << "n/a\n\n";
3110 return;
3111 }
3112
3113 OS.indent(4) << getBoundaryContextStr() << "\n";
3114
Tobias Grosser083d3d32014-06-28 08:59:45 +00003115 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003116 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003117 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3118 }
Tobias Grosser75805372011-04-29 06:27:02 +00003119}
3120
Johannes Doerfertb164c792014-09-18 11:17:17 +00003121void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003122 int noOfGroups = 0;
3123 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003124 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003125 noOfGroups += 1;
3126 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003127 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003128 }
3129
Tobias Grosserbb853c22015-07-25 12:31:03 +00003130 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003131 if (MinMaxAliasGroups.empty()) {
3132 OS.indent(8) << "n/a\n";
3133 return;
3134 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003135
Tobias Grosserbb853c22015-07-25 12:31:03 +00003136 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003137
3138 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003139 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003140 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003141 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003142 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3143 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003144 }
3145 OS << " ]]\n";
3146 }
3147
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003148 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003149 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003150 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003151 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003152 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3153 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003154 }
3155 OS << " ]]\n";
3156 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003157 }
3158}
3159
Tobias Grosser75805372011-04-29 06:27:02 +00003160void Scop::printStatements(raw_ostream &OS) const {
3161 OS << "Statements {\n";
3162
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003163 for (const ScopStmt &Stmt : *this)
3164 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003165
3166 OS.indent(4) << "}\n";
3167}
3168
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003169void Scop::printArrayInfo(raw_ostream &OS) const {
3170 OS << "Arrays {\n";
3171
Tobias Grosserab671442015-05-23 05:58:27 +00003172 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003173 Array.second->print(OS);
3174
3175 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003176
3177 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3178
3179 for (auto &Array : arrays())
3180 Array.second->print(OS, /* SizeAsPwAff */ true);
3181
3182 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003183}
3184
Tobias Grosser75805372011-04-29 06:27:02 +00003185void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003186 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3187 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003188 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003189 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003190 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003191 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003192 const auto &MAs = std::get<1>(IAClass);
3193 if (MAs.empty()) {
3194 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003195 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003196 MAs.front()->print(OS);
3197 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003198 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003199 }
3200 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003201 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003202 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003203 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003204 printStatements(OS.indent(4));
3205}
3206
3207void Scop::dump() const { print(dbgs()); }
3208
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003209isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003210
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003211__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3212 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003213}
3214
Tobias Grosser808cd692015-07-14 09:33:13 +00003215__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003216 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003217
Tobias Grosser808cd692015-07-14 09:33:13 +00003218 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003219 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003220
3221 return Domain;
3222}
3223
Tobias Grossere5a35142015-11-12 14:07:09 +00003224__isl_give isl_union_map *
3225Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3226 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003227
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003228 for (ScopStmt &Stmt : *this) {
3229 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003230 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003231 continue;
3232
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003233 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003234 isl_map *AccessDomain = MA->getAccessRelation();
3235 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003236 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003237 }
3238 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003239 return isl_union_map_coalesce(Accesses);
3240}
3241
3242__isl_give isl_union_map *Scop::getMustWrites() {
3243 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003244}
3245
3246__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003247 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003248}
3249
Tobias Grosser37eb4222014-02-20 21:43:54 +00003250__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003251 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003252}
3253
3254__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003255 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003256}
3257
Tobias Grosser2ac23382015-11-12 14:07:13 +00003258__isl_give isl_union_map *Scop::getAccesses() {
3259 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3260}
3261
Tobias Grosser808cd692015-07-14 09:33:13 +00003262__isl_give isl_union_map *Scop::getSchedule() const {
3263 auto Tree = getScheduleTree();
3264 auto S = isl_schedule_get_map(Tree);
3265 isl_schedule_free(Tree);
3266 return S;
3267}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003268
Tobias Grosser808cd692015-07-14 09:33:13 +00003269__isl_give isl_schedule *Scop::getScheduleTree() const {
3270 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3271 getDomains());
3272}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003273
Tobias Grosser808cd692015-07-14 09:33:13 +00003274void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3275 auto *S = isl_schedule_from_domain(getDomains());
3276 S = isl_schedule_insert_partial_schedule(
3277 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3278 isl_schedule_free(Schedule);
3279 Schedule = S;
3280}
3281
3282void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3283 isl_schedule_free(Schedule);
3284 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003285}
3286
3287bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3288 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003289 for (ScopStmt &Stmt : *this) {
3290 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003291 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3292 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3293
3294 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3295 isl_union_set_free(StmtDomain);
3296 isl_union_set_free(NewStmtDomain);
3297 continue;
3298 }
3299
3300 Changed = true;
3301
3302 isl_union_set_free(StmtDomain);
3303 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3304
3305 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003306 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003307 isl_union_set_free(NewStmtDomain);
3308 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003309 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003310 }
3311 isl_union_set_free(Domain);
3312 return Changed;
3313}
3314
Tobias Grosser75805372011-04-29 06:27:02 +00003315ScalarEvolution *Scop::getSE() const { return SE; }
3316
Johannes Doerfertf5673802015-10-01 23:48:18 +00003317bool Scop::isIgnored(RegionNode *RN) {
3318 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003319
Johannes Doerfertf5673802015-10-01 23:48:18 +00003320 // Check if there are accesses contained.
3321 bool ContainsAccesses = false;
3322 if (!RN->isSubRegion())
3323 ContainsAccesses = getAccessFunctions(BB);
3324 else
3325 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3326 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3327 if (!ContainsAccesses)
3328 return true;
3329
3330 // Check for reachability via non-error blocks.
3331 if (!DomainMap.count(BB))
3332 return true;
3333
3334 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003335 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003336 return true;
3337
3338 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003339}
3340
Tobias Grosser808cd692015-07-14 09:33:13 +00003341struct MapToDimensionDataTy {
3342 int N;
3343 isl_union_pw_multi_aff *Res;
3344};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003345
Tobias Grosser808cd692015-07-14 09:33:13 +00003346// @brief Create a function that maps the elements of 'Set' to its N-th
3347// dimension.
3348//
3349// The result is added to 'User->Res'.
3350//
3351// @param Set The input set.
3352// @param N The dimension to map to.
3353//
3354// @returns Zero if no error occurred, non-zero otherwise.
3355static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3356 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3357 int Dim;
3358 isl_space *Space;
3359 isl_pw_multi_aff *PMA;
3360
3361 Dim = isl_set_dim(Set, isl_dim_set);
3362 Space = isl_set_get_space(Set);
3363 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3364 Dim - Data->N);
3365 if (Data->N > 1)
3366 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3367 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3368
3369 isl_set_free(Set);
3370
3371 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003372}
3373
Tobias Grosser808cd692015-07-14 09:33:13 +00003374// @brief Create a function that maps the elements of Domain to their Nth
3375// dimension.
3376//
3377// @param Domain The set of elements to map.
3378// @param N The dimension to map to.
3379static __isl_give isl_multi_union_pw_aff *
3380mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003381 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3382 isl_union_set_free(Domain);
3383 return nullptr;
3384 }
3385
Tobias Grosser808cd692015-07-14 09:33:13 +00003386 struct MapToDimensionDataTy Data;
3387 isl_space *Space;
3388
3389 Space = isl_union_set_get_space(Domain);
3390 Data.N = N;
3391 Data.Res = isl_union_pw_multi_aff_empty(Space);
3392 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3393 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3394
3395 isl_union_set_free(Domain);
3396 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3397}
3398
Tobias Grosser316b5b22015-11-11 19:28:14 +00003399void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003400 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003401 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003402 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003403 StmtMap[BB] = Stmt;
3404 } else {
3405 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003406 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003407 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003408 for (BasicBlock *BB : R->blocks())
3409 StmtMap[BB] = Stmt;
3410 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003411}
3412
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003413void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003414 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003415 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003416
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003417 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003418 Loop *L = getLoopSurroundingRegion(*R, LI);
3419 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003420 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003421 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003422 auto *UDomain = isl_union_set_from_set(Domain);
3423 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003424 LSchedulePair.first = StmtSchedule;
3425 return;
3426 }
3427
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003428 ReversePostOrderTraversal<Region *> RTraversal(R);
3429 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003430
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003431 if (RN->isSubRegion()) {
3432 Region *SubRegion = RN->getNodeAs<Region>();
3433 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003434 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003435 continue;
3436 }
Tobias Grosser75805372011-04-29 06:27:02 +00003437 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003438
3439 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003440 if (!getRegion().contains(L))
3441 L = getLoopSurroundingRegion(getRegion(), LI);
3442
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003443 int LD = getRelativeLoopDepth(L);
3444 auto &LSchedulePair = LoopSchedules[L];
3445 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3446
Michael Krusecac948e2015-10-02 13:53:07 +00003447 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3448 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3449 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003450 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3451 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3452 LSchedulePair.first =
3453 combineInSequence(LSchedulePair.first, StmtSchedule);
3454 }
3455
3456 unsigned NumVisited = LSchedulePair.second;
3457 while (L && NumVisited == L->getNumBlocks()) {
3458 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3459 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3460 LSchedulePair.first =
3461 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3462
3463 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003464
3465 // Either we have a proper loop and we also build a schedule for the
3466 // parent loop or we have a infinite loop that does not have a proper
3467 // parent loop. In the former case this conditional will be skipped, in
3468 // the latter case however we will break here as we do not build a domain
3469 // nor a schedule for a infinite loop.
3470 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3471 if (!LoopSchedules.count(PL))
3472 break;
3473
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003474 auto &PSchedulePair = LoopSchedules[PL];
3475 PSchedulePair.first =
3476 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3477 PSchedulePair.second += NumVisited;
3478
3479 L = PL;
3480 NumVisited = PSchedulePair.second;
3481 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003482 }
Tobias Grosser75805372011-04-29 06:27:02 +00003483}
3484
Johannes Doerfert7c494212014-10-31 23:13:39 +00003485ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003486 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003487 if (StmtMapIt == StmtMap.end())
3488 return nullptr;
3489 return StmtMapIt->second;
3490}
3491
Johannes Doerfert96425c22015-08-30 21:13:53 +00003492int Scop::getRelativeLoopDepth(const Loop *L) const {
3493 Loop *OuterLoop =
3494 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3495 if (!OuterLoop)
3496 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003497 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3498}
3499
Michael Krused868b5d2015-09-10 15:25:24 +00003500void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003501 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003502
3503 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3504 // true, are not modeled as ordinary PHI nodes as they are not part of the
3505 // region. However, we model the operands in the predecessor blocks that are
3506 // part of the region as regular scalar accesses.
3507
3508 // If we can synthesize a PHI we can skip it, however only if it is in
3509 // the region. If it is not it can only be in the exit block of the region.
3510 // In this case we model the operands but not the PHI itself.
3511 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3512 return;
3513
3514 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3515 // detection. Hence, the PHI is a load of a new memory location in which the
3516 // incoming value was written at the end of the incoming basic block.
3517 bool OnlyNonAffineSubRegionOperands = true;
3518 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3519 Value *Op = PHI->getIncomingValue(u);
3520 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3521
3522 // Do not build scalar dependences inside a non-affine subregion.
3523 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3524 continue;
3525
3526 OnlyNonAffineSubRegionOperands = false;
3527
3528 if (!R.contains(OpBB))
3529 continue;
3530
3531 Instruction *OpI = dyn_cast<Instruction>(Op);
3532 if (OpI) {
3533 BasicBlock *OpIBB = OpI->getParent();
3534 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3535 // we have to insert a scalar dependence from the definition of OpI to
3536 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003537 if (scop->getStmtForBasicBlock(OpIBB) !=
3538 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003539 addScalarReadAccess(OpI, PHI, OpBB);
3540 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003541 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003542 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003543 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003544 }
3545
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003546 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003547 }
3548
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003549 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3550 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003551 }
3552}
3553
Michael Krused868b5d2015-09-10 15:25:24 +00003554bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3555 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003556 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3557 if (isIgnoredIntrinsic(Inst))
3558 return false;
3559
3560 bool AnyCrossStmtUse = false;
3561 BasicBlock *ParentBB = Inst->getParent();
3562
3563 for (User *U : Inst->users()) {
3564 Instruction *UI = dyn_cast<Instruction>(U);
3565
3566 // Ignore the strange user
3567 if (UI == 0)
3568 continue;
3569
3570 BasicBlock *UseParent = UI->getParent();
3571
Tobias Grosserbaffa092015-10-24 20:55:27 +00003572 // Ignore basic block local uses. A value that is defined in a scop, but
3573 // used in a PHI node in the same basic block does not count as basic block
3574 // local, as for such cases a control flow edge is passed between definition
3575 // and use.
3576 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003577 continue;
3578
Michael Krusef714d472015-11-05 13:18:43 +00003579 // Uses by PHI nodes in the entry node count as external uses in case the
3580 // use is through an incoming block that is itself not contained in the
3581 // region.
3582 if (R->getEntry() == UseParent) {
3583 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3584 bool ExternalUse = false;
3585 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3586 if (PHI->getIncomingValue(i) == Inst &&
3587 !R->contains(PHI->getIncomingBlock(i))) {
3588 ExternalUse = true;
3589 break;
3590 }
3591 }
3592
3593 if (ExternalUse) {
3594 AnyCrossStmtUse = true;
3595 continue;
3596 }
3597 }
3598 }
3599
Michael Kruse7bf39442015-09-10 12:46:52 +00003600 // Do not build scalar dependences inside a non-affine subregion.
3601 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3602 continue;
3603
Michael Kruse01cb3792015-10-17 21:07:08 +00003604 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003605 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003606 //
3607 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003608 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3609 // the control flow a different value will be assigned to the PHI node. In
3610 // case this is the case, there is no need to create an additional normal
3611 // scalar dependence. Hence, bail out before we register an "out-of-region"
3612 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003613 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3614 !R->getExitingBlock())
3615 continue;
3616
Michael Kruse7bf39442015-09-10 12:46:52 +00003617 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003618 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003619 AnyCrossStmtUse = true;
3620 continue;
3621 }
3622
3623 // If the instruction can be synthesized and the user is in the region
3624 // we do not need to add scalar dependences.
3625 if (canSynthesizeInst)
3626 continue;
3627
3628 // No need to translate these scalar dependences into polyhedral form,
3629 // because synthesizable scalars can be generated by the code generator.
3630 if (canSynthesize(UI, LI, SE, R))
3631 continue;
3632
3633 // Skip PHI nodes in the region as they handle their operands on their own.
3634 if (isa<PHINode>(UI))
3635 continue;
3636
3637 // Now U is used in another statement.
3638 AnyCrossStmtUse = true;
3639
3640 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003641 // Use the def instruction as base address of the MemoryAccess, so that it
3642 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003643 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003644 }
3645
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003646 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003647 for (Value *Op : Inst->operands()) {
3648 if (canSynthesize(Op, LI, SE, R))
3649 continue;
3650
3651 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3652 if (R->contains(OpInst))
3653 continue;
3654
3655 if (isa<Constant>(Op))
3656 continue;
3657
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003658 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003659 }
3660 }
3661
3662 return AnyCrossStmtUse;
3663}
3664
3665extern MapInsnToMemAcc InsnToMemAcc;
3666
Michael Krusee2bccbb2015-09-18 19:59:43 +00003667void ScopInfo::buildMemoryAccess(
3668 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003669 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3670 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003671 unsigned Size;
3672 Type *SizeType;
3673 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003674 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003675
3676 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3677 SizeType = Load->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003678 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003679 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003680 Val = Load;
3681 } else {
3682 StoreInst *Store = cast<StoreInst>(Inst);
3683 SizeType = Store->getValueOperand()->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003684 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003685 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003686 Val = Store->getValueOperand();
3687 }
3688
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003689 auto Address = getPointerOperand(*Inst);
3690
3691 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003692 const SCEVUnknown *BasePointer =
3693 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3694
3695 assert(BasePointer && "Could not find base pointer");
3696 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3697
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003698 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3699 auto NewAddress = Address;
3700 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3701 auto Src = BitCast->getOperand(0);
3702 auto SrcTy = Src->getType();
3703 auto DstTy = BitCast->getType();
3704 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3705 NewAddress = Src;
3706 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003707
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003708 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3709 std::vector<const SCEV *> Subscripts;
3710 std::vector<int> Sizes;
3711 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3712 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003713
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003714 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003715
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003716 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003717 for (auto Subscript : Subscripts) {
3718 InvariantLoadsSetTy AccessILS;
3719 AllAffineSubcripts =
3720 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3721
3722 for (LoadInst *LInst : AccessILS)
3723 if (!ScopRIL.count(LInst))
3724 AllAffineSubcripts = false;
3725
3726 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003727 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003728 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003729
3730 if (AllAffineSubcripts && Sizes.size() > 0) {
3731 for (auto V : Sizes)
3732 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3733 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003734 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003735 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003736
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003737 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3738 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003739 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003740 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003741 }
3742 }
3743
Michael Kruse7bf39442015-09-10 12:46:52 +00003744 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003745 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003746 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3747 AccItr->second.DelinearizedSubscripts,
3748 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003749 return;
3750 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003751
3752 // Check if the access depends on a loop contained in a non-affine subregion.
3753 bool isVariantInNonAffineLoop = false;
3754 if (BoxedLoops) {
3755 SetVector<const Loop *> Loops;
3756 findLoops(AccessFunction, Loops);
3757 for (const Loop *L : Loops)
3758 if (BoxedLoops->count(L))
3759 isVariantInNonAffineLoop = true;
3760 }
3761
Johannes Doerfert09e36972015-10-07 20:17:36 +00003762 InvariantLoadsSetTy AccessILS;
3763 bool IsAffine =
3764 !isVariantInNonAffineLoop &&
3765 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3766
3767 for (LoadInst *LInst : AccessILS)
3768 if (!ScopRIL.count(LInst))
3769 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003770
Michael Krusecaac2b62015-09-26 15:51:44 +00003771 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003772 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003773 const SCEV *SizeSCEV =
3774 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003775
Michael Krusee2bccbb2015-09-18 19:59:43 +00003776 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3777 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003778
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003779 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3780 ArrayRef<const SCEV *>(AccessFunction),
3781 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003782}
3783
Michael Krused868b5d2015-09-10 15:25:24 +00003784void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003785
3786 if (SD->isNonAffineSubRegion(&SR, &R)) {
3787 for (BasicBlock *BB : SR.blocks())
3788 buildAccessFunctions(R, *BB, &SR);
3789 return;
3790 }
3791
3792 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3793 if (I->isSubRegion())
3794 buildAccessFunctions(R, *I->getNodeAs<Region>());
3795 else
3796 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3797}
3798
Michael Krusecac948e2015-10-02 13:53:07 +00003799void ScopInfo::buildStmts(Region &SR) {
3800 Region *R = getRegion();
3801
3802 if (SD->isNonAffineSubRegion(&SR, R)) {
3803 scop->addScopStmt(nullptr, &SR);
3804 return;
3805 }
3806
3807 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3808 if (I->isSubRegion())
3809 buildStmts(*I->getNodeAs<Region>());
3810 else
3811 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3812}
3813
Michael Krused868b5d2015-09-10 15:25:24 +00003814void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3815 Region *NonAffineSubRegion,
3816 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003817 // We do not build access functions for error blocks, as they may contain
3818 // instructions we can not model.
3819 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3820 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3821 return;
3822
Michael Kruse7bf39442015-09-10 12:46:52 +00003823 Loop *L = LI->getLoopFor(&BB);
3824
3825 // The set of loops contained in non-affine subregions that are part of R.
3826 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3827
Johannes Doerfert09e36972015-10-07 20:17:36 +00003828 // The set of loads that are required to be invariant.
3829 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3830
Michael Kruse7bf39442015-09-10 12:46:52 +00003831 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003832 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003833
3834 PHINode *PHI = dyn_cast<PHINode>(Inst);
3835 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003836 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003837
3838 // For the exit block we stop modeling after the last PHI node.
3839 if (!PHI && IsExitBlock)
3840 break;
3841
Johannes Doerfert09e36972015-10-07 20:17:36 +00003842 // TODO: At this point we only know that elements of ScopRIL have to be
3843 // invariant and will be hoisted for the SCoP to be processed. Though,
3844 // there might be other invariant accesses that will be hoisted and
3845 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003846 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003847 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003848
3849 if (isIgnoredIntrinsic(Inst))
3850 continue;
3851
Johannes Doerfert09e36972015-10-07 20:17:36 +00003852 // Do not build scalar dependences for required invariant loads as we will
3853 // hoist them later on anyway or drop the SCoP if we cannot.
3854 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3855 continue;
3856
Michael Kruse7bf39442015-09-10 12:46:52 +00003857 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003858 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003859 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003860 }
3861 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003862}
Michael Kruse7bf39442015-09-10 12:46:52 +00003863
Michael Kruse2d0ece92015-09-24 11:41:21 +00003864void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3865 MemoryAccess::AccessType Type,
3866 Value *BaseAddress, unsigned ElemBytes,
3867 bool Affine, Value *AccessValue,
3868 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003869 ArrayRef<const SCEV *> Sizes,
3870 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003871 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3872
3873 // Do not create a memory access for anything not in the SCoP. It would be
3874 // ignored anyway.
3875 if (!Stmt)
3876 return;
3877
Michael Krusee2bccbb2015-09-18 19:59:43 +00003878 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003879 Value *BaseAddr = BaseAddress;
3880 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3881
Michael Krusecac948e2015-10-02 13:53:07 +00003882 bool isApproximated =
3883 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3884 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3885 Type = MemoryAccess::MAY_WRITE;
3886
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003887 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003888 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003889 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003890}
3891
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003892void ScopInfo::addExplicitAccess(
3893 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3894 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3895 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3896 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3897 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3898 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003899 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3900 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003901}
3902void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3903 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3904 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003905 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003906}
3907void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3908 assert(!isa<PHINode>(User));
3909 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3910 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003911 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003912}
3913void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3914 BasicBlock *UserBB) {
3915 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003916 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3917 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003918}
3919void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3920 Value *IncomingValue, bool IsExitBlock) {
3921 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3922 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3923 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003924 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003925}
3926void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3927 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003928 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3929 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003930}
3931
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003932void ScopInfo::buildScop(Region &R, DominatorTree &DT, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003933 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003934 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003935
Michael Krusecac948e2015-10-02 13:53:07 +00003936 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003937 buildAccessFunctions(R, R);
3938
3939 // In case the region does not have an exiting block we will later (during
3940 // code generation) split the exit block. This will move potential PHI nodes
3941 // from the current exit block into the new region exiting block. Hence, PHI
3942 // nodes that are at this point not part of the region will be.
3943 // To handle these PHI nodes later we will now model their operands as scalar
3944 // accesses. Note that we do not model anything in the exit block if we have
3945 // an exiting block in the region, as there will not be any splitting later.
3946 if (!R.getExitingBlock())
3947 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3948
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003949 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003950}
3951
Michael Krused868b5d2015-09-10 15:25:24 +00003952void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003953 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003954 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003955 return;
3956 }
3957
Michael Kruse9d080092015-09-11 21:41:48 +00003958 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003959}
3960
Michael Krused868b5d2015-09-10 15:25:24 +00003961void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003962 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003963 if (scop) {
3964 delete scop;
3965 scop = 0;
3966 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003967}
3968
3969//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003970ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003971 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003972 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003973}
3974
3975ScopInfo::~ScopInfo() {
3976 clear();
3977 isl_ctx_free(ctx);
3978}
3979
Tobias Grosser75805372011-04-29 06:27:02 +00003980void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003981 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003982 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003983 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003984 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3985 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003986 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003987 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00003988 AU.setPreservesAll();
3989}
3990
3991bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003992 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003993
Michael Krused868b5d2015-09-10 15:25:24 +00003994 if (!SD->isMaxRegionInScop(*R))
3995 return false;
3996
3997 Function *F = R->getEntry()->getParent();
3998 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3999 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4000 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4001 TD = &F->getParent()->getDataLayout();
4002 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004003 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004004
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004005 DebugLoc Beg, End;
4006 getDebugLocations(R, Beg, End);
4007 std::string Msg = "SCoP begins here.";
4008 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4009
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004010 buildScop(*R, DT, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004011
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004012 DEBUG(scop->print(dbgs()));
4013
Michael Kruseafe06702015-10-02 16:33:27 +00004014 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004015 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00004016 delete scop;
4017 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004018 } else {
4019 Msg = "SCoP ends here.";
4020 ++ScopFound;
4021 if (scop->getMaxLoopDepth() > 0)
4022 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004023 }
4024
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004025 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4026
Tobias Grosser75805372011-04-29 06:27:02 +00004027 return false;
4028}
4029
4030char ScopInfo::ID = 0;
4031
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004032Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4033
Tobias Grosser73600b82011-10-08 00:30:40 +00004034INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4035 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004036 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004037INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004038INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004039INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004040INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004041INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004042INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004043INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004044INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4045 "Polly - Create polyhedral description of Scops", false,
4046 false)