blob: 4be92227c97e01624dd7f9806854395944562261 [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 Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.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
Tobias Grosser75dc40c2015-12-20 13:31:48 +000065// The maximal number of basic sets we allow during domain construction to
66// be created. More complex scops will result in very high compile time and
67// are also unlikely to result in good code
68static int const MaxConjunctsInDomain = 20;
69
Michael Kruse7bf39442015-09-10 12:46:52 +000070static cl::opt<bool> ModelReadOnlyScalars(
71 "polly-analyze-read-only-scalars",
72 cl::desc("Model read-only scalar values in the scop description"),
73 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
74
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000075// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000076// operations can overflow easily. Additive reductions and bit operations
77// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000078static cl::opt<bool> DisableMultiplicativeReductions(
79 "polly-disable-multiplicative-reductions",
80 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
81 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000082
Johannes Doerfert9143d672014-09-27 11:02:39 +000083static cl::opt<unsigned> RunTimeChecksMaxParameters(
84 "polly-rtc-max-parameters",
85 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
86 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
87
Tobias Grosser71500722015-03-28 15:11:14 +000088static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
89 "polly-rtc-max-arrays-per-group",
90 cl::desc("The maximal number of arrays to compare in each alias group."),
91 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser20a4c0c2015-11-11 16:22:36 +0000102static cl::opt<int> MaxDisjunctsAssumed(
103 "polly-max-disjuncts-assumed",
104 cl::desc("The maximal number of disjuncts we allow in the assumption "
105 "context (this bounds compile time)"),
106 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
107
Tobias Grosser4927c8e2015-11-24 12:50:02 +0000108static cl::opt<bool> IgnoreIntegerWrapping(
109 "polly-ignore-integer-wrapping",
110 cl::desc("Do not build run-time checks to proof absence of integer "
111 "wrapping"),
112 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
113
Michael Kruse7bf39442015-09-10 12:46:52 +0000114//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000115
Michael Kruse046dde42015-08-10 13:01:57 +0000116// Create a sequence of two schedules. Either argument may be null and is
117// interpreted as the empty schedule. Can also return null if both schedules are
118// empty.
119static __isl_give isl_schedule *
120combineInSequence(__isl_take isl_schedule *Prev,
121 __isl_take isl_schedule *Succ) {
122 if (!Prev)
123 return Succ;
124 if (!Succ)
125 return Prev;
126
127 return isl_schedule_sequence(Prev, Succ);
128}
129
Johannes Doerferte7044942015-02-24 11:58:30 +0000130static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
131 const ConstantRange &Range,
132 int dim,
133 enum isl_dim_type type) {
134 isl_val *V;
135 isl_ctx *ctx = isl_set_get_ctx(S);
136
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
138 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000143 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000144 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000145 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000146 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
147
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000148 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000149 return isl_set_union(SLB, SUB);
150 else
151 return isl_set_intersect(SLB, SUB);
152}
153
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000154static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
155 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
156 if (!BasePtrLI)
157 return nullptr;
158
159 if (!S->getRegion().contains(BasePtrLI))
160 return nullptr;
161
162 ScalarEvolution &SE = *S->getSE();
163
164 auto *OriginBaseSCEV =
165 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
166 if (!OriginBaseSCEV)
167 return nullptr;
168
169 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
170 if (!OriginBaseSCEVUnknown)
171 return nullptr;
172
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000173 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000174 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175}
176
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000177ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000178 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000179 const DataLayout &DL, Scop *S)
180 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000181 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000182 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000184
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000185 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000186 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
187 if (BasePtrOriginSAI)
188 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000189}
190
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000191__isl_give isl_space *ScopArrayInfo::getSpace() const {
192 auto Space =
193 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
194 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
195 return Space;
196}
197
Tobias Grosser8286b832015-11-02 11:29:32 +0000198bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000199 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
200 int ExtraDimsNew = NewSizes.size() - SharedDims;
201 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000202 for (int i = 0; i < SharedDims; i++)
203 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
204 return false;
205
206 if (DimensionSizes.size() >= NewSizes.size())
207 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000208
209 DimensionSizes.clear();
210 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
211 NewSizes.end());
212 for (isl_pw_aff *Size : DimensionSizesPw)
213 isl_pw_aff_free(Size);
214 DimensionSizesPw.clear();
215 for (const SCEV *Expr : DimensionSizes) {
216 isl_pw_aff *Size = S.getPwAff(Expr);
217 DimensionSizesPw.push_back(Size);
218 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000219 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000220}
221
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000222ScopArrayInfo::~ScopArrayInfo() {
223 isl_id_free(Id);
224 for (isl_pw_aff *Size : DimensionSizesPw)
225 isl_pw_aff_free(Size);
226}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000227
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000228std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
229
230int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000231 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000232}
233
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000234isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
235
236void ScopArrayInfo::dump() const { print(errs()); }
237
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000238void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000239 OS.indent(8) << *getElementType() << " " << getName();
240 if (getNumberOfDimensions() > 0)
241 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000242 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000243 OS << "[";
244
Tobias Grosser26253842015-11-10 14:24:21 +0000245 if (SizeAsPwAff) {
246 auto Size = getDimensionSizePw(u);
247 OS << " " << Size << " ";
248 isl_pw_aff_free(Size);
249 } else {
250 OS << *getDimensionSize(u);
251 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000252
253 OS << "]";
254 }
255
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000256 OS << ";";
257
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000258 if (BasePtrOriginSAI)
259 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
260
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000261 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000262}
263
264const ScopArrayInfo *
265ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
266 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
267 assert(Id && "Output dimension didn't have an ID");
268 return getFromId(Id);
269}
270
271const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
272 void *User = isl_id_get_user(Id);
273 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
274 isl_id_free(Id);
275 return SAI;
276}
277
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000278void MemoryAccess::updateDimensionality() {
279 auto ArraySpace = getScopArrayInfo()->getSpace();
280 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
281
282 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
283 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
284 auto DimsMissing = DimsArray - DimsAccess;
285
286 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
287 isl_set_universe(ArraySpace));
288
289 for (unsigned i = 0; i < DimsMissing; i++)
290 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
291
292 for (unsigned i = DimsMissing; i < DimsArray; i++)
293 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
294
295 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000296
297 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000298}
299
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000300const std::string
301MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
302 switch (RT) {
303 case MemoryAccess::RT_NONE:
304 llvm_unreachable("Requested a reduction operator string for a memory "
305 "access which isn't a reduction");
306 case MemoryAccess::RT_ADD:
307 return "+";
308 case MemoryAccess::RT_MUL:
309 return "*";
310 case MemoryAccess::RT_BOR:
311 return "|";
312 case MemoryAccess::RT_BXOR:
313 return "^";
314 case MemoryAccess::RT_BAND:
315 return "&";
316 }
317 llvm_unreachable("Unknown reduction type");
318 return "";
319}
320
Johannes Doerfertf6183392014-07-01 20:52:51 +0000321/// @brief Return the reduction type for a given binary operator
322static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
323 const Instruction *Load) {
324 if (!BinOp)
325 return MemoryAccess::RT_NONE;
326 switch (BinOp->getOpcode()) {
327 case Instruction::FAdd:
328 if (!BinOp->hasUnsafeAlgebra())
329 return MemoryAccess::RT_NONE;
330 // Fall through
331 case Instruction::Add:
332 return MemoryAccess::RT_ADD;
333 case Instruction::Or:
334 return MemoryAccess::RT_BOR;
335 case Instruction::Xor:
336 return MemoryAccess::RT_BXOR;
337 case Instruction::And:
338 return MemoryAccess::RT_BAND;
339 case Instruction::FMul:
340 if (!BinOp->hasUnsafeAlgebra())
341 return MemoryAccess::RT_NONE;
342 // Fall through
343 case Instruction::Mul:
344 if (DisableMultiplicativeReductions)
345 return MemoryAccess::RT_NONE;
346 return MemoryAccess::RT_MUL;
347 default:
348 return MemoryAccess::RT_NONE;
349 }
350}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000351
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000352/// @brief Derive the individual index expressions from a GEP instruction
353///
354/// This function optimistically assumes the GEP references into a fixed size
355/// array. If this is actually true, this function returns a list of array
356/// subscript expressions as SCEV as well as a list of integers describing
357/// the size of the individual array dimensions. Both lists have either equal
358/// length of the size list is one element shorter in case there is no known
359/// size available for the outermost array dimension.
360///
361/// @param GEP The GetElementPtr instruction to analyze.
362///
363/// @return A tuple with the subscript expressions and the dimension sizes.
364static std::tuple<std::vector<const SCEV *>, std::vector<int>>
365getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
366 std::vector<const SCEV *> Subscripts;
367 std::vector<int> Sizes;
368
369 Type *Ty = GEP->getPointerOperandType();
370
371 bool DroppedFirstDim = false;
372
Michael Kruse26ed65e2015-09-24 17:32:49 +0000373 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000374
375 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
376
377 if (i == 1) {
378 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
379 Ty = PtrTy->getElementType();
380 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
381 Ty = ArrayTy->getElementType();
382 } else {
383 Subscripts.clear();
384 Sizes.clear();
385 break;
386 }
387 if (auto Const = dyn_cast<SCEVConstant>(Expr))
388 if (Const->getValue()->isZero()) {
389 DroppedFirstDim = true;
390 continue;
391 }
392 Subscripts.push_back(Expr);
393 continue;
394 }
395
396 auto ArrayTy = dyn_cast<ArrayType>(Ty);
397 if (!ArrayTy) {
398 Subscripts.clear();
399 Sizes.clear();
400 break;
401 }
402
403 Subscripts.push_back(Expr);
404 if (!(DroppedFirstDim && i == 2))
405 Sizes.push_back(ArrayTy->getNumElements());
406
407 Ty = ArrayTy->getElementType();
408 }
409
410 return std::make_tuple(Subscripts, Sizes);
411}
412
Tobias Grosser75805372011-04-29 06:27:02 +0000413MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000414 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000415 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000416 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000417}
418
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000419const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
420 isl_id *ArrayId = getArrayId();
421 void *User = isl_id_get_user(ArrayId);
422 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
423 isl_id_free(ArrayId);
424 return SAI;
425}
426
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000427__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000428 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
429}
430
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000431__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
432 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000433 isl_map *Schedule, *ScheduledAccRel;
434 isl_union_set *UDomain;
435
436 UDomain = isl_union_set_from_set(getStatement()->getDomain());
437 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
438 Schedule = isl_map_from_union_map(USchedule);
439 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
440 return isl_pw_multi_aff_from_map(ScheduledAccRel);
441}
442
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000443__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000444 return isl_map_copy(AccessRelation);
445}
446
Johannes Doerferta99130f2014-10-13 12:58:03 +0000447std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000448 return stringFromIslObj(AccessRelation);
449}
450
Johannes Doerferta99130f2014-10-13 12:58:03 +0000451__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000452 return isl_map_get_space(AccessRelation);
453}
454
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000455__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000456 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000457}
458
Tobias Grosser6f730082015-09-05 07:46:47 +0000459std::string MemoryAccess::getNewAccessRelationStr() const {
460 return stringFromIslObj(NewAccessRelation);
461}
462
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000463__isl_give isl_basic_map *
464MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000465 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000466 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000467
Tobias Grosser084d8f72012-05-29 09:29:44 +0000468 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000469 isl_basic_set_universe(Statement->getDomainSpace()),
470 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000471}
472
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000473// Formalize no out-of-bound access assumption
474//
475// When delinearizing array accesses we optimistically assume that the
476// delinearized accesses do not access out of bound locations (the subscript
477// expression of each array evaluates for each statement instance that is
478// executed to a value that is larger than zero and strictly smaller than the
479// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000480// dimension for which we do not need to assume any upper bound. At this point
481// we formalize this assumption to ensure that at code generation time the
482// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000483//
484// To find the set of constraints necessary to avoid out of bound accesses, we
485// first build the set of data locations that are not within array bounds. We
486// then apply the reverse access relation to obtain the set of iterations that
487// may contain invalid accesses and reduce this set of iterations to the ones
488// that are actually executed by intersecting them with the domain of the
489// statement. If we now project out all loop dimensions, we obtain a set of
490// parameters that may cause statement instances to be executed that may
491// possibly yield out of bound memory accesses. The complement of these
492// constraints is the set of constraints that needs to be assumed to ensure such
493// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000494void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000495 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000496 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000497 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000498 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
499 isl_pw_aff *Var =
500 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
501 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
502
503 isl_set *DimOutside;
504
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000505 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Roman Gareev10595a12016-01-08 14:01:59 +0000506 isl_pw_aff *SizeE = getScopArrayInfo()->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000507 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
508 isl_space_dim(Space, isl_dim_set));
509 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
510 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000511
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000512 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000513
514 Outside = isl_set_union(Outside, DimOutside);
515 }
516
517 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
518 Outside = isl_set_intersect(Outside, Statement->getDomain());
519 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000520
521 // Remove divs to avoid the construction of overly complicated assumptions.
522 // Doing so increases the set of parameter combinations that are assumed to
523 // not appear. This is always save, but may make the resulting run-time check
524 // bail out more often than strictly necessary.
525 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000526 Outside = isl_set_complement(Outside);
Johannes Doerfertd84493e2015-11-12 02:33:38 +0000527 Statement->getParent()->addAssumption(INBOUNDS, Outside,
528 getAccessInstruction()->getDebugLoc());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000529 isl_space_free(Space);
530}
531
Johannes Doerferte7044942015-02-24 11:58:30 +0000532void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
533 ScalarEvolution *SE = Statement->getParent()->getSE();
534
535 Value *Ptr = getPointerOperand(*getAccessInstruction());
536 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
537 return;
538
539 auto *PtrSCEV = SE->getSCEV(Ptr);
540 if (isa<SCEVCouldNotCompute>(PtrSCEV))
541 return;
542
543 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
544 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
545 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
546
547 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
548 if (Range.isFullSet())
549 return;
550
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000551 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000552 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000553 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
554 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
555
556 auto Min = LB.sdiv(APInt(BW, ElementSize));
557 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000558
559 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
560 AccessRange =
561 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
562 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
563}
564
Michael Krusee2bccbb2015-09-18 19:59:43 +0000565__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000566 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000567 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000568
569 for (int i = Size - 2; i >= 0; --i) {
570 isl_space *Space;
571 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000572 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000573
574 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
575 isl_pw_aff_free(DimSize);
576 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
577
578 Space = isl_map_get_space(AccessRelation);
579 Space = isl_space_map_from_set(isl_space_range(Space));
580 Space = isl_space_align_params(Space, SpaceSize);
581
582 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
583 isl_id_free(ParamId);
584
585 MapOne = isl_map_universe(isl_space_copy(Space));
586 for (int j = 0; j < Size; ++j)
587 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
588 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
589
590 MapTwo = isl_map_universe(isl_space_copy(Space));
591 for (int j = 0; j < Size; ++j)
592 if (j < i || j > i + 1)
593 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
594
595 isl_local_space *LS = isl_local_space_from_space(Space);
596 isl_constraint *C;
597 C = isl_equality_alloc(isl_local_space_copy(LS));
598 C = isl_constraint_set_constant_si(C, -1);
599 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
600 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
601 MapTwo = isl_map_add_constraint(MapTwo, C);
602 C = isl_equality_alloc(LS);
603 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
604 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
605 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
606 MapTwo = isl_map_add_constraint(MapTwo, C);
607 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
608
609 MapOne = isl_map_union(MapOne, MapTwo);
610 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
611 }
612 return AccessRelation;
613}
614
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000615/// @brief Check if @p Expr is divisible by @p Size.
616static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
617
618 // Only one factor needs to be divisible.
619 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
620 for (auto *FactorExpr : MulExpr->operands())
621 if (isDivisible(FactorExpr, Size, SE))
622 return true;
623 return false;
624 }
625
626 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
627 // to be divisble.
628 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
629 for (auto *OpExpr : NAryExpr->operands())
630 if (!isDivisible(OpExpr, Size, SE))
631 return false;
632 return true;
633 }
634
635 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
636 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
637 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
638 return MulSCEV == Expr;
639}
640
Michael Krusee2bccbb2015-09-18 19:59:43 +0000641void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
642 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000643
Michael Krusee2bccbb2015-09-18 19:59:43 +0000644 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000645 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000646
Michael Krusee2bccbb2015-09-18 19:59:43 +0000647 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000648 // We overapproximate non-affine accesses with a possible access to the
649 // whole array. For read accesses it does not make a difference, if an
650 // access must or may happen. However, for write accesses it is important to
651 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000652 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000653 AccessRelation =
654 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000655
Michael Krusee2bccbb2015-09-18 19:59:43 +0000656 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000657 return;
658 }
659
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000660 Scop &S = *getStatement()->getParent();
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000661 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000662 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000663
Michael Krusee2bccbb2015-09-18 19:59:43 +0000664 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
665 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000666
Sebastian Pop422e33f2014-06-03 18:16:31 +0000667 if (Size == 1) {
668 // For the non delinearized arrays, divide the access function of the last
669 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000670 //
671 // A stride one array access in C expressed as A[i] is expressed in
672 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
673 // two subsequent values of 'i' index two values that are stored next to
674 // each other in memory. By this division we make this characteristic
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000675 // obvious again. However, if the index is not divisible by the element
676 // size we will bail out.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000677 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000678 Affine = isl_pw_aff_scale_down_val(Affine, v);
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000679
680 if (!isDivisible(Subscripts[0], getElemSizeInBytes(), *S.getSE()))
Tobias Grosser8d4f6262015-12-12 09:52:26 +0000681 S.invalidate(ALIGNMENT, AccessInstruction->getDebugLoc());
Sebastian Pop18016682014-04-08 21:20:44 +0000682 }
683
684 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
685
Tobias Grosser79baa212014-04-10 08:38:02 +0000686 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000687 }
688
Michael Krusee2bccbb2015-09-18 19:59:43 +0000689 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
690 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000691
Tobias Grosser79baa212014-04-10 08:38:02 +0000692 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000693 AccessRelation = isl_map_set_tuple_id(
694 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000695 AccessRelation =
696 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
697
Tobias Grosseraa660a92015-03-30 00:07:50 +0000698 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000699 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000700}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000701
Michael Krusecac948e2015-10-02 13:53:07 +0000702MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000703 AccessType Type, Value *BaseAddress,
704 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000705 ArrayRef<const SCEV *> Subscripts,
706 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000707 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
708 : Kind(Kind), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000709 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
710 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
711 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000712 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000713 NewAccessRelation(nullptr) {
714
715 std::string IdName = "__polly_array_ref";
716 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
717}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000718
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000719void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000720 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000721 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000722}
723
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000724const std::string MemoryAccess::getReductionOperatorStr() const {
725 return MemoryAccess::getReductionOperatorStr(getReductionType());
726}
727
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000728__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
729
Johannes Doerfertf6183392014-07-01 20:52:51 +0000730raw_ostream &polly::operator<<(raw_ostream &OS,
731 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000732 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000733 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000734 else
735 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000736 return OS;
737}
738
Tobias Grosser75805372011-04-29 06:27:02 +0000739void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000740 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000741 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000742 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000743 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000744 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000745 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000746 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000747 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000748 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000749 break;
750 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000751 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000752 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000753 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000754 if (hasNewAccessRelation())
755 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000756}
757
Tobias Grosser74394f02013-01-14 22:40:23 +0000758void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000759
760// Create a map in the size of the provided set domain, that maps from the
761// one element of the provided set domain to another element of the provided
762// set domain.
763// The mapping is limited to all points that are equal in all but the last
764// dimension and for which the last dimension of the input is strict smaller
765// than the last dimension of the output.
766//
767// getEqualAndLarger(set[i0, i1, ..., iX]):
768//
769// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
770// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
771//
Tobias Grosserf5338802011-10-06 00:03:35 +0000772static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000773 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000774 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000775 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000776
777 // Set all but the last dimension to be equal for the input and output
778 //
779 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
780 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000781 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000782 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000783
784 // Set the last dimension of the input to be strict smaller than the
785 // last dimension of the output.
786 //
787 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000788 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
789 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000790 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000791}
792
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000793__isl_give isl_set *
794MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000795 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000796 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000797 isl_space *Space = isl_space_range(isl_map_get_space(S));
798 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000799
Sebastian Popa00a0292012-12-18 07:46:06 +0000800 S = isl_map_reverse(S);
801 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000802
Sebastian Popa00a0292012-12-18 07:46:06 +0000803 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
804 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
805 NextScatt = isl_map_apply_domain(NextScatt, S);
806 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000807
Sebastian Popa00a0292012-12-18 07:46:06 +0000808 isl_set *Deltas = isl_map_deltas(NextScatt);
809 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000810}
811
Sebastian Popa00a0292012-12-18 07:46:06 +0000812bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000813 int StrideWidth) const {
814 isl_set *Stride, *StrideX;
815 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000816
Sebastian Popa00a0292012-12-18 07:46:06 +0000817 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000818 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000819 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
820 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
821 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
822 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000823 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000824
Tobias Grosser28dd4862012-01-24 16:42:16 +0000825 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000826 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000827
Tobias Grosser28dd4862012-01-24 16:42:16 +0000828 return IsStrideX;
829}
830
Sebastian Popa00a0292012-12-18 07:46:06 +0000831bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
832 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000833}
834
Sebastian Popa00a0292012-12-18 07:46:06 +0000835bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
836 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000837}
838
Tobias Grosser166c4222015-09-05 07:46:40 +0000839void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
840 isl_map_free(NewAccessRelation);
841 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000842}
Tobias Grosser75805372011-04-29 06:27:02 +0000843
844//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000845
Tobias Grosser808cd692015-07-14 09:33:13 +0000846isl_map *ScopStmt::getSchedule() const {
847 isl_set *Domain = getDomain();
848 if (isl_set_is_empty(Domain)) {
849 isl_set_free(Domain);
850 return isl_map_from_aff(
851 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
852 }
853 auto *Schedule = getParent()->getSchedule();
854 Schedule = isl_union_map_intersect_domain(
855 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
856 if (isl_union_map_is_empty(Schedule)) {
857 isl_set_free(Domain);
858 isl_union_map_free(Schedule);
859 return isl_map_from_aff(
860 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
861 }
862 auto *M = isl_map_from_union_map(Schedule);
863 M = isl_map_coalesce(M);
864 M = isl_map_gist_domain(M, Domain);
865 M = isl_map_coalesce(M);
866 return M;
867}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000868
Johannes Doerfert574182d2015-08-12 10:19:50 +0000869__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000870 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
871 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000872}
873
Tobias Grosser37eb4222014-02-20 21:43:54 +0000874void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
875 assert(isl_set_is_subset(NewDomain, Domain) &&
876 "New domain is not a subset of old domain!");
877 isl_set_free(Domain);
878 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000879}
880
Michael Krusecac948e2015-10-02 13:53:07 +0000881void ScopStmt::buildAccessRelations() {
882 for (MemoryAccess *Access : MemAccs) {
883 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000884
Tobias Grossera535dff2015-12-13 19:59:01 +0000885 ScopArrayInfo::MemoryKind Ty;
886 if (Access->isPHIKind())
887 Ty = ScopArrayInfo::MK_PHI;
888 else if (Access->isExitPHIKind())
889 Ty = ScopArrayInfo::MK_ExitPHI;
890 else if (Access->isValueKind())
891 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000892 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000893 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000894
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000895 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000896 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000897
Michael Krusecac948e2015-10-02 13:53:07 +0000898 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000899 }
900}
901
Michael Krusecac948e2015-10-02 13:53:07 +0000902void ScopStmt::addAccess(MemoryAccess *Access) {
903 Instruction *AccessInst = Access->getAccessInstruction();
904
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000905 if (Access->isArrayKind()) {
906 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
907 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +0000908 } else if (Access->isValueKind() && Access->isWrite()) {
909 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
910 assert(Parent.getStmtForBasicBlock(AccessVal->getParent()) == this);
911 assert(!ValueWrites.lookup(AccessVal));
912
913 ValueWrites[AccessVal] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +0000914 }
915
916 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +0000917}
918
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000919void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000920 for (MemoryAccess *MA : *this)
921 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000922
923 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000924}
925
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000926/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
927static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
928 void *User) {
929 isl_set **BoundedParts = static_cast<isl_set **>(User);
930 if (isl_basic_set_is_bounded(BSet))
931 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
932 else
933 isl_basic_set_free(BSet);
934 return isl_stat_ok;
935}
936
937/// @brief Return the bounded parts of @p S.
938static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
939 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
940 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
941 isl_set_free(S);
942 return BoundedParts;
943}
944
945/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
946///
947/// @returns A separation of @p S into first an unbounded then a bounded subset,
948/// both with regards to the dimension @p Dim.
949static std::pair<__isl_give isl_set *, __isl_give isl_set *>
950partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
951
952 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000953 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000954
955 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000956 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000957
958 // Remove dimensions that are greater than Dim as they are not interesting.
959 assert(NumDimsS >= Dim + 1);
960 OnlyDimS =
961 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
962
963 // Create artificial parametric upper bounds for dimensions smaller than Dim
964 // as we are not interested in them.
965 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
966 for (unsigned u = 0; u < Dim; u++) {
967 isl_constraint *C = isl_inequality_alloc(
968 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
969 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
970 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
971 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
972 }
973
974 // Collect all bounded parts of OnlyDimS.
975 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
976
977 // Create the dimensions greater than Dim again.
978 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
979 NumDimsS - Dim - 1);
980
981 // Remove the artificial upper bound parameters again.
982 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
983
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000984 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000985 return std::make_pair(UnboundedParts, BoundedParts);
986}
987
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000988/// @brief Set the dimension Ids from @p From in @p To.
989static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
990 __isl_take isl_set *To) {
991 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
992 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
993 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
994 }
995 return To;
996}
997
998/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000999static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001000 __isl_take isl_pw_aff *L,
1001 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001002 switch (Pred) {
1003 case ICmpInst::ICMP_EQ:
1004 return isl_pw_aff_eq_set(L, R);
1005 case ICmpInst::ICMP_NE:
1006 return isl_pw_aff_ne_set(L, R);
1007 case ICmpInst::ICMP_SLT:
1008 return isl_pw_aff_lt_set(L, R);
1009 case ICmpInst::ICMP_SLE:
1010 return isl_pw_aff_le_set(L, R);
1011 case ICmpInst::ICMP_SGT:
1012 return isl_pw_aff_gt_set(L, R);
1013 case ICmpInst::ICMP_SGE:
1014 return isl_pw_aff_ge_set(L, R);
1015 case ICmpInst::ICMP_ULT:
1016 return isl_pw_aff_lt_set(L, R);
1017 case ICmpInst::ICMP_UGT:
1018 return isl_pw_aff_gt_set(L, R);
1019 case ICmpInst::ICMP_ULE:
1020 return isl_pw_aff_le_set(L, R);
1021 case ICmpInst::ICMP_UGE:
1022 return isl_pw_aff_ge_set(L, R);
1023 default:
1024 llvm_unreachable("Non integer predicate not supported");
1025 }
1026}
1027
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001028/// @brief Create the conditions under which @p L @p Pred @p R is true.
1029///
1030/// Helper function that will make sure the dimensions of the result have the
1031/// same isl_id's as the @p Domain.
1032static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1033 __isl_take isl_pw_aff *L,
1034 __isl_take isl_pw_aff *R,
1035 __isl_keep isl_set *Domain) {
1036 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1037 return setDimensionIds(Domain, ConsequenceCondSet);
1038}
1039
1040/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001041///
1042/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001043/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1044/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001045static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001046buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001047 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1048
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001049 Value *Condition = getConditionFromTerminator(SI);
1050 assert(Condition && "No condition for switch");
1051
1052 ScalarEvolution &SE = *S.getSE();
1053 BasicBlock *BB = SI->getParent();
1054 isl_pw_aff *LHS, *RHS;
1055 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1056
1057 unsigned NumSuccessors = SI->getNumSuccessors();
1058 ConditionSets.resize(NumSuccessors);
1059 for (auto &Case : SI->cases()) {
1060 unsigned Idx = Case.getSuccessorIndex();
1061 ConstantInt *CaseValue = Case.getCaseValue();
1062
1063 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1064 isl_set *CaseConditionSet =
1065 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1066 ConditionSets[Idx] = isl_set_coalesce(
1067 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1068 }
1069
1070 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1071 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1072 for (unsigned u = 2; u < NumSuccessors; u++)
1073 ConditionSetUnion =
1074 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1075 ConditionSets[0] = setDimensionIds(
1076 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1077
1078 S.markAsOptimized();
1079 isl_pw_aff_free(LHS);
1080}
1081
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001082/// @brief Build the conditions sets for the branch condition @p Condition in
1083/// the @p Domain.
1084///
1085/// This will fill @p ConditionSets with the conditions under which control
1086/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001087/// have as many elements as @p TI has successors. If @p TI is nullptr the
1088/// context under which @p Condition is true/false will be returned as the
1089/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001090static void
1091buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1092 __isl_keep isl_set *Domain,
1093 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1094
1095 isl_set *ConsequenceCondSet = nullptr;
1096 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1097 if (CCond->isZero())
1098 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1099 else
1100 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1101 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1102 auto Opcode = BinOp->getOpcode();
1103 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1104
1105 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1106 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1107
1108 isl_set_free(ConditionSets.pop_back_val());
1109 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1110 isl_set_free(ConditionSets.pop_back_val());
1111 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1112
1113 if (Opcode == Instruction::And)
1114 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1115 else
1116 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1117 } else {
1118 auto *ICond = dyn_cast<ICmpInst>(Condition);
1119 assert(ICond &&
1120 "Condition of exiting branch was neither constant nor ICmp!");
1121
1122 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001123 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001124 isl_pw_aff *LHS, *RHS;
1125 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1126 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1127 ConsequenceCondSet =
1128 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1129 }
1130
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001131 // If no terminator was given we are only looking for parameter constraints
1132 // under which @p Condition is true/false.
1133 if (!TI)
1134 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1135
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001136 assert(ConsequenceCondSet);
1137 isl_set *AlternativeCondSet =
1138 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1139
1140 ConditionSets.push_back(isl_set_coalesce(
1141 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1142 ConditionSets.push_back(isl_set_coalesce(
1143 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1144}
1145
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001146/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1147///
1148/// This will fill @p ConditionSets with the conditions under which control
1149/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1150/// have as many elements as @p TI has successors.
1151static void
1152buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1153 __isl_keep isl_set *Domain,
1154 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1155
1156 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1157 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1158
1159 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1160
1161 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001162 ConditionSets.push_back(isl_set_copy(Domain));
1163 return;
1164 }
1165
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001166 Value *Condition = getConditionFromTerminator(TI);
1167 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001168
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001169 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001170}
1171
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001172void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001173 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001174
Tobias Grosser084d8f72012-05-29 09:29:44 +00001175 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1176
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001177 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001178 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001179}
1180
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001181void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001182 isl_ctx *Ctx = Parent.getIslCtx();
1183 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1184 Type *Ty = GEP->getPointerOperandType();
1185 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001186 ScopDetection &SD = Parent.getSD();
1187
1188 // The set of loads that are required to be invariant.
1189 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001190
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001191 std::vector<const SCEV *> Subscripts;
1192 std::vector<int> Sizes;
1193
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001194 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001195
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001196 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001197 Ty = PtrTy->getElementType();
1198 }
1199
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001200 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001201
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001202 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001203
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001204 for (size_t i = 0; i < Sizes.size(); i++) {
1205 auto Expr = Subscripts[i + IndexOffset];
1206 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001207
Johannes Doerfert09e36972015-10-07 20:17:36 +00001208 InvariantLoadsSetTy AccessILS;
1209 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1210 continue;
1211
1212 bool NonAffine = false;
1213 for (LoadInst *LInst : AccessILS)
1214 if (!ScopRIL.count(LInst))
1215 NonAffine = true;
1216
1217 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001218 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001219
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001220 isl_pw_aff *AccessOffset = getPwAff(Expr);
1221 AccessOffset =
1222 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001223
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001224 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1225 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001226
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001227 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1228 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1229 OutOfBound = isl_set_params(OutOfBound);
1230 isl_set *InBound = isl_set_complement(OutOfBound);
1231 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001232
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001233 // A => B == !A or B
1234 isl_set *InBoundIfExecuted =
1235 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001236
Roman Gareev10595a12016-01-08 14:01:59 +00001237 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001238 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001239 }
1240
1241 isl_local_space_free(LSpace);
1242}
1243
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001244void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1245 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001246 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1247 deriveAssumptionsFromGEP(GEP);
1248}
1249
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001250void ScopStmt::collectSurroundingLoops() {
1251 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1252 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1253 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1254 isl_id_free(DimId);
1255 }
1256}
1257
Michael Kruse9d080092015-09-11 21:41:48 +00001258ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001259 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001260
Tobias Grosser16c44032015-07-09 07:31:45 +00001261 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001262}
1263
Michael Kruse9d080092015-09-11 21:41:48 +00001264ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001265 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001266
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001267 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001268}
1269
1270void ScopStmt::init() {
1271 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001272
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001273 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001274 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001275 buildAccessRelations();
1276
1277 if (BB) {
1278 deriveAssumptions(BB);
1279 } else {
1280 for (BasicBlock *Block : R->blocks()) {
1281 deriveAssumptions(Block);
1282 }
1283 }
1284
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001285 if (DetectReductions)
1286 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001287}
1288
Johannes Doerferte58a0122014-06-27 20:31:28 +00001289/// @brief Collect loads which might form a reduction chain with @p StoreMA
1290///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001291/// Check if the stored value for @p StoreMA is a binary operator with one or
1292/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001293/// used only once (by @p StoreMA) and its load operands are also used only
1294/// once, we have found a possible reduction chain. It starts at an operand
1295/// load and includes the binary operator and @p StoreMA.
1296///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001297/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001298/// escape this block or into any other store except @p StoreMA.
1299void ScopStmt::collectCandiateReductionLoads(
1300 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1301 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1302 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001303 return;
1304
1305 // Skip if there is not one binary operator between the load and the store
1306 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001307 if (!BinOp)
1308 return;
1309
1310 // Skip if the binary operators has multiple uses
1311 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001312 return;
1313
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001314 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001315 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1316 return;
1317
Johannes Doerfert9890a052014-07-01 00:32:29 +00001318 // Skip if the binary operator is outside the current SCoP
1319 if (BinOp->getParent() != Store->getParent())
1320 return;
1321
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001322 // Skip if it is a multiplicative reduction and we disabled them
1323 if (DisableMultiplicativeReductions &&
1324 (BinOp->getOpcode() == Instruction::Mul ||
1325 BinOp->getOpcode() == Instruction::FMul))
1326 return;
1327
Johannes Doerferte58a0122014-06-27 20:31:28 +00001328 // Check the binary operator operands for a candidate load
1329 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1330 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1331 if (!PossibleLoad0 && !PossibleLoad1)
1332 return;
1333
1334 // A load is only a candidate if it cannot escape (thus has only this use)
1335 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001336 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001337 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001338 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001339 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001340 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001341}
1342
1343/// @brief Check for reductions in this ScopStmt
1344///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001345/// Iterate over all store memory accesses and check for valid binary reduction
1346/// like chains. For all candidates we check if they have the same base address
1347/// and there are no other accesses which overlap with them. The base address
1348/// check rules out impossible reductions candidates early. The overlap check,
1349/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001350/// guarantees that none of the intermediate results will escape during
1351/// execution of the loop nest. We basically check here that no other memory
1352/// access can access the same memory as the potential reduction.
1353void ScopStmt::checkForReductions() {
1354 SmallVector<MemoryAccess *, 2> Loads;
1355 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1356
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001357 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001358 // stores and collecting possible reduction loads.
1359 for (MemoryAccess *StoreMA : MemAccs) {
1360 if (StoreMA->isRead())
1361 continue;
1362
1363 Loads.clear();
1364 collectCandiateReductionLoads(StoreMA, Loads);
1365 for (MemoryAccess *LoadMA : Loads)
1366 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1367 }
1368
1369 // Then check each possible candidate pair.
1370 for (const auto &CandidatePair : Candidates) {
1371 bool Valid = true;
1372 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1373 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1374
1375 // Skip those with obviously unequal base addresses.
1376 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1377 isl_map_free(LoadAccs);
1378 isl_map_free(StoreAccs);
1379 continue;
1380 }
1381
1382 // And check if the remaining for overlap with other memory accesses.
1383 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1384 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1385 isl_set *AllAccs = isl_map_range(AllAccsRel);
1386
1387 for (MemoryAccess *MA : MemAccs) {
1388 if (MA == CandidatePair.first || MA == CandidatePair.second)
1389 continue;
1390
1391 isl_map *AccRel =
1392 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1393 isl_set *Accs = isl_map_range(AccRel);
1394
1395 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1396 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1397 Valid = Valid && isl_set_is_empty(OverlapAccs);
1398 isl_set_free(OverlapAccs);
1399 }
1400 }
1401
1402 isl_set_free(AllAccs);
1403 if (!Valid)
1404 continue;
1405
Johannes Doerfertf6183392014-07-01 20:52:51 +00001406 const LoadInst *Load =
1407 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1408 MemoryAccess::ReductionType RT =
1409 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1410
Johannes Doerferte58a0122014-06-27 20:31:28 +00001411 // If no overlapping access was found we mark the load and store as
1412 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001413 CandidatePair.first->markAsReductionLike(RT);
1414 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001415 }
Tobias Grosser75805372011-04-29 06:27:02 +00001416}
1417
Tobias Grosser74394f02013-01-14 22:40:23 +00001418std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001419
Tobias Grosser54839312015-04-21 11:37:25 +00001420std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001421 auto *S = getSchedule();
1422 auto Str = stringFromIslObj(S);
1423 isl_map_free(S);
1424 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001425}
1426
Tobias Grosser74394f02013-01-14 22:40:23 +00001427unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001428
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001429unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001430
Tobias Grosser75805372011-04-29 06:27:02 +00001431const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1432
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001433const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001434 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001435}
1436
Tobias Grosser74394f02013-01-14 22:40:23 +00001437isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001438
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001439__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001440
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001441__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001442 return isl_set_get_space(Domain);
1443}
1444
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001445__isl_give isl_id *ScopStmt::getDomainId() const {
1446 return isl_set_get_tuple_id(Domain);
1447}
Tobias Grossercd95b772012-08-30 11:49:38 +00001448
Tobias Grosser10120182015-12-16 16:14:03 +00001449ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001450
1451void ScopStmt::print(raw_ostream &OS) const {
1452 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001453 OS.indent(12) << "Domain :=\n";
1454
1455 if (Domain) {
1456 OS.indent(16) << getDomainStr() << ";\n";
1457 } else
1458 OS.indent(16) << "n/a\n";
1459
Tobias Grosser54839312015-04-21 11:37:25 +00001460 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001461
1462 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001463 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001464 } else
1465 OS.indent(16) << "n/a\n";
1466
Tobias Grosser083d3d32014-06-28 08:59:45 +00001467 for (MemoryAccess *Access : MemAccs)
1468 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001469}
1470
1471void ScopStmt::dump() const { print(dbgs()); }
1472
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001473void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001474 // Remove all memory accesses in @p InvMAs from this statement
1475 // together with all scalar accesses that were caused by them.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001476 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001477 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001478 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001479 };
1480 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1481 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001482 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001483 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001484}
1485
Tobias Grosser75805372011-04-29 06:27:02 +00001486//===----------------------------------------------------------------------===//
1487/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001488
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001489void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001490 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1491 isl_set_free(Context);
1492 Context = NewContext;
1493}
1494
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001495/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1496struct SCEVSensitiveParameterRewriter
1497 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1498 ValueToValueMap &VMap;
1499 ScalarEvolution &SE;
1500
1501public:
1502 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1503 : VMap(VMap), SE(SE) {}
1504
1505 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1506 ValueToValueMap &VMap) {
1507 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1508 return SSPR.visit(E);
1509 }
1510
1511 const SCEV *visit(const SCEV *E) {
1512 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1513 }
1514
1515 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1516
1517 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1518 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1519 }
1520
1521 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1522 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1523 }
1524
1525 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1526 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1527 }
1528
1529 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1530 SmallVector<const SCEV *, 4> Operands;
1531 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1532 Operands.push_back(visit(E->getOperand(i)));
1533 return SE.getAddExpr(Operands);
1534 }
1535
1536 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1537 SmallVector<const SCEV *, 4> Operands;
1538 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1539 Operands.push_back(visit(E->getOperand(i)));
1540 return SE.getMulExpr(Operands);
1541 }
1542
1543 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1544 SmallVector<const SCEV *, 4> Operands;
1545 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1546 Operands.push_back(visit(E->getOperand(i)));
1547 return SE.getSMaxExpr(Operands);
1548 }
1549
1550 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1551 SmallVector<const SCEV *, 4> Operands;
1552 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1553 Operands.push_back(visit(E->getOperand(i)));
1554 return SE.getUMaxExpr(Operands);
1555 }
1556
1557 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1558 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1559 }
1560
1561 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1562 auto *Start = visit(E->getStart());
1563 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1564 visit(E->getStepRecurrence(SE)),
1565 E->getLoop(), SCEV::FlagAnyWrap);
1566 return SE.getAddExpr(Start, AddRec);
1567 }
1568
1569 const SCEV *visitUnknown(const SCEVUnknown *E) {
1570 if (auto *NewValue = VMap.lookup(E->getValue()))
1571 return SE.getUnknown(NewValue);
1572 return E;
1573 }
1574};
1575
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001576const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001577 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001578}
1579
Tobias Grosserabfbe632013-02-05 12:09:06 +00001580void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001581 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001582 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001583
1584 // Normalize the SCEV to get the representing element for an invariant load.
1585 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1586
Tobias Grosser60b54f12011-11-08 15:41:28 +00001587 if (ParameterIds.find(Parameter) != ParameterIds.end())
1588 continue;
1589
1590 int dimension = Parameters.size();
1591
1592 Parameters.push_back(Parameter);
1593 ParameterIds[Parameter] = dimension;
1594 }
1595}
1596
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001597__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001598 // Normalize the SCEV to get the representing element for an invariant load.
1599 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1600
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001601 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001602
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001603 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001604 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001605
Tobias Grosser8f99c162011-11-15 11:38:55 +00001606 std::string ParameterName;
1607
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001608 ParameterName = "p_" + utostr_32(IdIter->second);
1609
Tobias Grosser8f99c162011-11-15 11:38:55 +00001610 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1611 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001612
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001613 // If this parameter references a specific Value and this value has a name
1614 // we use this name as it is likely to be unique and more useful than just
1615 // a number.
1616 if (Val->hasName())
1617 ParameterName = Val->getName();
1618 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1619 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1620 if (LoadOrigin->hasName()) {
1621 ParameterName += "_loaded_from_";
1622 ParameterName +=
1623 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1624 }
1625 }
1626 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001627
Tobias Grosser20532b82014-04-11 17:56:49 +00001628 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1629 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001630}
Tobias Grosser75805372011-04-29 06:27:02 +00001631
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001632isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1633 isl_set *DomainContext = isl_union_set_params(getDomains());
1634 return isl_set_intersect_params(C, DomainContext);
1635}
1636
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001637void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001638 if (IgnoreIntegerWrapping) {
1639 BoundaryContext = isl_set_universe(getParamSpace());
1640 return;
1641 }
1642
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001643 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001644
1645 // The isl_set_complement operation used to create the boundary context
1646 // can possibly become very expensive. We bound the compile time of
1647 // this operation by setting a compute out.
1648 //
1649 // TODO: We can probably get around using isl_set_complement and directly
1650 // AST generate BoundaryContext.
1651 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001652 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001653 isl_ctx_set_max_operations(getIslCtx(), 300000);
1654 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1655
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001656 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001657
Tobias Grossera52b4da2015-11-11 17:59:53 +00001658 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1659 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001660 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001661 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001662
1663 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1664 isl_ctx_reset_operations(getIslCtx());
1665 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001666 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001667 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001668}
1669
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001670void Scop::addUserAssumptions(AssumptionCache &AC) {
1671 auto *R = &getRegion();
1672 auto &F = *R->getEntry()->getParent();
1673 for (auto &Assumption : AC.assumptions()) {
1674 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1675 if (!CI || CI->getNumArgOperands() != 1)
1676 continue;
1677 if (!DT.dominates(CI->getParent(), R->getEntry()))
1678 continue;
1679
1680 auto *Val = CI->getArgOperand(0);
1681 std::vector<const SCEV *> Params;
1682 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1683 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1684 CI->getDebugLoc(),
1685 "Non-affine user assumption ignored.");
1686 continue;
1687 }
1688
1689 addParams(Params);
1690
1691 auto *L = LI.getLoopFor(CI->getParent());
1692 SmallVector<isl_set *, 2> ConditionSets;
1693 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1694 assert(ConditionSets.size() == 2);
1695 isl_set_free(ConditionSets[1]);
1696
1697 auto *AssumptionCtx = ConditionSets[0];
1698 emitOptimizationRemarkAnalysis(
1699 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1700 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1701 Context = isl_set_intersect(Context, AssumptionCtx);
1702 }
1703}
1704
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001705void Scop::addUserContext() {
1706 if (UserContextStr.empty())
1707 return;
1708
1709 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1710 isl_space *Space = getParamSpace();
1711 if (isl_space_dim(Space, isl_dim_param) !=
1712 isl_set_dim(UserContext, isl_dim_param)) {
1713 auto SpaceStr = isl_space_to_str(Space);
1714 errs() << "Error: the context provided in -polly-context has not the same "
1715 << "number of dimensions than the computed context. Due to this "
1716 << "mismatch, the -polly-context option is ignored. Please provide "
1717 << "the context in the parameter space: " << SpaceStr << ".\n";
1718 free(SpaceStr);
1719 isl_set_free(UserContext);
1720 isl_space_free(Space);
1721 return;
1722 }
1723
1724 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1725 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1726 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1727
1728 if (strcmp(NameContext, NameUserContext) != 0) {
1729 auto SpaceStr = isl_space_to_str(Space);
1730 errs() << "Error: the name of dimension " << i
1731 << " provided in -polly-context "
1732 << "is '" << NameUserContext << "', but the name in the computed "
1733 << "context is '" << NameContext
1734 << "'. Due to this name mismatch, "
1735 << "the -polly-context option is ignored. Please provide "
1736 << "the context in the parameter space: " << SpaceStr << ".\n";
1737 free(SpaceStr);
1738 isl_set_free(UserContext);
1739 isl_space_free(Space);
1740 return;
1741 }
1742
1743 UserContext =
1744 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1745 isl_space_get_dim_id(Space, isl_dim_param, i));
1746 }
1747
1748 Context = isl_set_intersect(Context, UserContext);
1749 isl_space_free(Space);
1750}
1751
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001752void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001753 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1754
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001755 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001756 for (LoadInst *LInst : RIL) {
1757 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1758
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001759 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001760 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001761 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001762 continue;
1763 }
1764
1765 ClassRep = LInst;
1766 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1767 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001768 }
1769}
1770
Tobias Grosser6be480c2011-11-08 15:41:13 +00001771void Scop::buildContext() {
1772 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001773 Context = isl_set_universe(isl_space_copy(Space));
1774 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001775}
1776
Tobias Grosser18daaca2012-05-22 10:47:27 +00001777void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001778 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001779 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001780
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001781 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001782
Johannes Doerferte7044942015-02-24 11:58:30 +00001783 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001784 }
1785}
1786
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001787void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001788 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001789 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001790
Tobias Grosser083d3d32014-06-28 08:59:45 +00001791 for (const auto &ParamID : ParameterIds) {
1792 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001793 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001794 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001795 }
1796
1797 // Align the parameters of all data structures to the model.
1798 Context = isl_set_align_params(Context, Space);
1799
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001800 for (ScopStmt &Stmt : *this)
1801 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001802}
1803
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001804static __isl_give isl_set *
1805simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1806 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001807 // If we modelt all blocks in the SCoP that have side effects we can simplify
1808 // the context with the constraints that are needed for anything to be
1809 // executed at all. However, if we have error blocks in the SCoP we already
1810 // assumed some parameter combinations cannot occure and removed them from the
1811 // domains, thus we cannot use the remaining domain to simplify the
1812 // assumptions.
1813 if (!S.hasErrorBlock()) {
1814 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1815 AssumptionContext =
1816 isl_set_gist_params(AssumptionContext, DomainParameters);
1817 }
1818
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001819 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1820 return AssumptionContext;
1821}
1822
1823void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001824 // The parameter constraints of the iteration domains give us a set of
1825 // constraints that need to hold for all cases where at least a single
1826 // statement iteration is executed in the whole scop. We now simplify the
1827 // assumed context under the assumption that such constraints hold and at
1828 // least a single statement iteration is executed. For cases where no
1829 // statement instances are executed, the assumptions we have taken about
1830 // the executed code do not matter and can be changed.
1831 //
1832 // WARNING: This only holds if the assumptions we have taken do not reduce
1833 // the set of statement instances that are executed. Otherwise we
1834 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001835 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001836 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001837 // performed. In such a case, modifying the run-time conditions and
1838 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001839 // to not be executed.
1840 //
1841 // Example:
1842 //
1843 // When delinearizing the following code:
1844 //
1845 // for (long i = 0; i < 100; i++)
1846 // for (long j = 0; j < m; j++)
1847 // A[i+p][j] = 1.0;
1848 //
1849 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001850 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001851 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001852 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1853 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001854}
1855
Johannes Doerfertb164c792014-09-18 11:17:17 +00001856/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001857static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001858 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1859 isl_pw_multi_aff *MinPMA, *MaxPMA;
1860 isl_pw_aff *LastDimAff;
1861 isl_aff *OneAff;
1862 unsigned Pos;
1863
Johannes Doerfert9143d672014-09-27 11:02:39 +00001864 // Restrict the number of parameters involved in the access as the lexmin/
1865 // lexmax computation will take too long if this number is high.
1866 //
1867 // Experiments with a simple test case using an i7 4800MQ:
1868 //
1869 // #Parameters involved | Time (in sec)
1870 // 6 | 0.01
1871 // 7 | 0.04
1872 // 8 | 0.12
1873 // 9 | 0.40
1874 // 10 | 1.54
1875 // 11 | 6.78
1876 // 12 | 30.38
1877 //
1878 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1879 unsigned InvolvedParams = 0;
1880 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1881 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1882 InvolvedParams++;
1883
1884 if (InvolvedParams > RunTimeChecksMaxParameters) {
1885 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001886 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001887 }
1888 }
1889
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001890 Set = isl_set_remove_divs(Set);
1891
Johannes Doerfertb164c792014-09-18 11:17:17 +00001892 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1893 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1894
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001895 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1896 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1897
Johannes Doerfertb164c792014-09-18 11:17:17 +00001898 // Adjust the last dimension of the maximal access by one as we want to
1899 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1900 // we test during code generation might now point after the end of the
1901 // allocated array but we will never dereference it anyway.
1902 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1903 "Assumed at least one output dimension");
1904 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1905 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1906 OneAff = isl_aff_zero_on_domain(
1907 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1908 OneAff = isl_aff_add_constant_si(OneAff, 1);
1909 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1910 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1911
1912 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1913
1914 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001915 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001916}
1917
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001918static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1919 isl_set *Domain = MA->getStatement()->getDomain();
1920 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1921 return isl_set_reset_tuple_id(Domain);
1922}
1923
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001924/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1925static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001926 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001927 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001928
1929 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1930 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001931 Locations = isl_union_set_coalesce(Locations);
1932 Locations = isl_union_set_detect_equalities(Locations);
1933 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001934 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001935 isl_union_set_free(Locations);
1936 return Valid;
1937}
1938
Johannes Doerfert96425c22015-08-30 21:13:53 +00001939/// @brief Helper to treat non-affine regions and basic blocks the same.
1940///
1941///{
1942
1943/// @brief Return the block that is the representing block for @p RN.
1944static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1945 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1946 : RN->getNodeAs<BasicBlock>();
1947}
1948
1949/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001950static inline BasicBlock *
1951getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001952 if (RN->isSubRegion()) {
1953 assert(idx == 0);
1954 return RN->getNodeAs<Region>()->getExit();
1955 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001956 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001957}
1958
1959/// @brief Return the smallest loop surrounding @p RN.
1960static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1961 if (!RN->isSubRegion())
1962 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1963
1964 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1965 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1966 while (L && NonAffineSubRegion->contains(L))
1967 L = L->getParentLoop();
1968 return L;
1969}
1970
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001971static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1972 if (!RN->isSubRegion())
1973 return 1;
1974
1975 unsigned NumBlocks = 0;
1976 Region *R = RN->getNodeAs<Region>();
1977 for (auto BB : R->blocks()) {
1978 (void)BB;
1979 NumBlocks++;
1980 }
1981 return NumBlocks;
1982}
1983
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001984static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1985 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001986 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001987 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001988 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001989 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001990 return true;
1991 return false;
1992}
1993
Johannes Doerfert96425c22015-08-30 21:13:53 +00001994///}
1995
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001996static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1997 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001998 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001999 isl_id *DimId =
2000 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2001 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2002}
2003
Johannes Doerfert96425c22015-08-30 21:13:53 +00002004isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
2005 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
2006 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002007 return getDomainConditions(BB);
2008}
2009
2010isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2011 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002012 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002013}
2014
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002015void Scop::removeErrorBlockDomains() {
2016 auto removeDomains = [this](BasicBlock *Start) {
2017 auto BBNode = DT.getNode(Start);
2018 for (auto ErrorChild : depth_first(BBNode)) {
2019 auto ErrorChildBlock = ErrorChild->getBlock();
2020 auto CurrentDomain = DomainMap[ErrorChildBlock];
2021 auto Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
2022 DomainMap[ErrorChildBlock] = Empty;
2023 isl_set_free(CurrentDomain);
2024 }
2025 };
2026
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002027 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002028
2029 while (!Todo.empty()) {
2030 auto SubRegion = Todo.back();
2031 Todo.pop_back();
2032
2033 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2034 for (auto &Child : *SubRegion)
2035 Todo.push_back(Child.get());
2036 continue;
2037 }
2038 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2039 removeDomains(SubRegion->getEntry());
2040 }
2041
2042 for (auto BB : R.blocks())
2043 if (isErrorBlock(*BB, R, LI, DT))
2044 removeDomains(BB);
2045}
2046
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002047void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002048
Johannes Doerfert432658d2016-01-26 11:01:41 +00002049 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002050 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002051 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2052 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002053 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002054
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002055 while (LD-- >= 0) {
2056 S = addDomainDimId(S, LD + 1, L);
2057 L = L->getParentLoop();
2058 }
2059
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002060 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002061
Johannes Doerfert432658d2016-01-26 11:01:41 +00002062 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002063 return;
2064
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002065 buildDomainsWithBranchConstraints(R);
2066 propagateDomainConstraints(R);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002067
2068 // Error blocks and blocks dominated by them have been assumed to never be
2069 // executed. Representing them in the Scop does not add any value. In fact,
2070 // it is likely to cause issues during construction of the ScopStmts. The
2071 // contents of error blocks have not been verfied to be expressible and
2072 // will cause problems when building up a ScopStmt for them.
2073 // Furthermore, basic blocks dominated by error blocks may reference
2074 // instructions in the error block which, if the error block is not modeled,
2075 // can themselves not be constructed properly.
2076 removeErrorBlockDomains();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002077}
2078
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002079void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002080 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002081
2082 // To create the domain for each block in R we iterate over all blocks and
2083 // subregions in R and propagate the conditions under which the current region
2084 // element is executed. To this end we iterate in reverse post order over R as
2085 // it ensures that we first visit all predecessors of a region node (either a
2086 // basic block or a subregion) before we visit the region node itself.
2087 // Initially, only the domain for the SCoP region entry block is set and from
2088 // there we propagate the current domain to all successors, however we add the
2089 // condition that the successor is actually executed next.
2090 // As we are only interested in non-loop carried constraints here we can
2091 // simply skip loop back edges.
2092
2093 ReversePostOrderTraversal<Region *> RTraversal(R);
2094 for (auto *RN : RTraversal) {
2095
2096 // Recurse for affine subregions but go on for basic blocks and non-affine
2097 // subregions.
2098 if (RN->isSubRegion()) {
2099 Region *SubRegion = RN->getNodeAs<Region>();
2100 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002101 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002102 continue;
2103 }
2104 }
2105
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002106 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002107 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002108
Johannes Doerfert96425c22015-08-30 21:13:53 +00002109 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002110 TerminatorInst *TI = BB->getTerminator();
2111
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002112 if (isa<UnreachableInst>(TI))
2113 continue;
2114
Johannes Doerfertf5673802015-10-01 23:48:18 +00002115 isl_set *Domain = DomainMap.lookup(BB);
2116 if (!Domain) {
2117 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2118 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002119 continue;
2120 }
2121
Johannes Doerfert96425c22015-08-30 21:13:53 +00002122 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002123
2124 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2125 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2126
2127 // Build the condition sets for the successor nodes of the current region
2128 // node. If it is a non-affine subregion we will always execute the single
2129 // exit node, hence the single entry node domain is the condition set. For
2130 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002131 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002132 if (RN->isSubRegion())
2133 ConditionSets.push_back(isl_set_copy(Domain));
2134 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002135 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002136
2137 // Now iterate over the successors and set their initial domain based on
2138 // their condition set. We skip back edges here and have to be careful when
2139 // we leave a loop not to keep constraints over a dimension that doesn't
2140 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002141 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002142 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002143 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002144 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002145
2146 // Skip back edges.
2147 if (DT.dominates(SuccBB, BB)) {
2148 isl_set_free(CondSet);
2149 continue;
2150 }
2151
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002152 // Do not adjust the number of dimensions if we enter a boxed loop or are
2153 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002154 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002155 while (BoxedLoops.count(SuccBBLoop))
2156 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002157
2158 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002159
2160 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2161 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2162 // and enter a new one we need to drop the old constraints.
2163 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002164 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002165 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002166 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2167 isl_set_n_dim(CondSet) - LoopDepthDiff,
2168 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002169 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002170 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002171 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 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002174 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002175 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2176 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002177 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002178 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002179 }
2180
2181 // Set the domain for the successor or merge it with an existing domain in
2182 // case there are multiple paths (without loop back edges) to the
2183 // successor block.
2184 isl_set *&SuccDomain = DomainMap[SuccBB];
2185 if (!SuccDomain)
2186 SuccDomain = CondSet;
2187 else
2188 SuccDomain = isl_set_union(SuccDomain, CondSet);
2189
2190 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002191 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2192 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2193 isl_set_free(SuccDomain);
2194 SuccDomain = Empty;
2195 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2196 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002197 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2198 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002199 }
2200 }
2201}
2202
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002203/// @brief Return the domain for @p BB wrt @p DomainMap.
2204///
2205/// This helper function will lookup @p BB in @p DomainMap but also handle the
2206/// case where @p BB is contained in a non-affine subregion using the region
2207/// tree obtained by @p RI.
2208static __isl_give isl_set *
2209getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2210 RegionInfo &RI) {
2211 auto DIt = DomainMap.find(BB);
2212 if (DIt != DomainMap.end())
2213 return isl_set_copy(DIt->getSecond());
2214
2215 Region *R = RI.getRegionFor(BB);
2216 while (R->getEntry() == BB)
2217 R = R->getParent();
2218 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2219}
2220
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002221void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002222 // Iterate over the region R and propagate the domain constrains from the
2223 // predecessors to the current node. In contrast to the
2224 // buildDomainsWithBranchConstraints function, this one will pull the domain
2225 // information from the predecessors instead of pushing it to the successors.
2226 // Additionally, we assume the domains to be already present in the domain
2227 // map here. However, we iterate again in reverse post order so we know all
2228 // predecessors have been visited before a block or non-affine subregion is
2229 // visited.
2230
2231 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2232 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2233
2234 ReversePostOrderTraversal<Region *> RTraversal(R);
2235 for (auto *RN : RTraversal) {
2236
2237 // Recurse for affine subregions but go on for basic blocks and non-affine
2238 // subregions.
2239 if (RN->isSubRegion()) {
2240 Region *SubRegion = RN->getNodeAs<Region>();
2241 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002242 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002243 continue;
2244 }
2245 }
2246
Johannes Doerfertf5673802015-10-01 23:48:18 +00002247 // Get the domain for the current block and check if it was initialized or
2248 // not. The only way it was not is if this block is only reachable via error
2249 // blocks, thus will not be executed under the assumptions we make. Such
2250 // blocks have to be skipped as their predecessors might not have domains
2251 // either. It would not benefit us to compute the domain anyway, only the
2252 // domains of the error blocks that are reachable from non-error blocks
2253 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002254 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002255 isl_set *&Domain = DomainMap[BB];
2256 if (!Domain) {
2257 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2258 << ", it is only reachable from error blocks.\n");
2259 DomainMap.erase(BB);
2260 continue;
2261 }
2262 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2263
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002264 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2265 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2266
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002267 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2268 for (auto *PredBB : predecessors(BB)) {
2269
2270 // Skip backedges
2271 if (DT.dominates(BB, PredBB))
2272 continue;
2273
2274 isl_set *PredBBDom = nullptr;
2275
2276 // Handle the SCoP entry block with its outside predecessors.
2277 if (!getRegion().contains(PredBB))
2278 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2279
2280 if (!PredBBDom) {
2281 // Determine the loop depth of the predecessor and adjust its domain to
2282 // the domain of the current block. This can mean we have to:
2283 // o) Drop a dimension if this block is the exit of a loop, not the
2284 // header of a new loop and the predecessor was part of the loop.
2285 // o) Add an unconstrainted new dimension if this block is the header
2286 // of a loop and the predecessor is not part of it.
2287 // o) Drop the information about the innermost loop dimension when the
2288 // predecessor and the current block are surrounded by different
2289 // loops in the same depth.
2290 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2291 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2292 while (BoxedLoops.count(PredBBLoop))
2293 PredBBLoop = PredBBLoop->getParentLoop();
2294
2295 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002296 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002297 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002298 PredBBDom = isl_set_project_out(
2299 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2300 LoopDepthDiff);
2301 else if (PredBBLoopDepth < BBLoopDepth) {
2302 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002303 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002304 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2305 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002306 PredBBDom = isl_set_drop_constraints_involving_dims(
2307 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002308 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002309 }
2310
2311 PredDom = isl_set_union(PredDom, PredBBDom);
2312 }
2313
2314 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002315 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002316
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002317 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002318 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002319
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002320 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002321 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002322 IsOptimized = true;
2323 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002324 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2325 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002326 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002327 }
2328}
2329
2330/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2331/// is incremented by one and all other dimensions are equal, e.g.,
2332/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2333/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2334static __isl_give isl_map *
2335createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2336 auto *MapSpace = isl_space_map_from_set(SetSpace);
2337 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2338 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2339 if (u != Dim)
2340 NextIterationMap =
2341 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2342 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2343 C = isl_constraint_set_constant_si(C, 1);
2344 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2345 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2346 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2347 return NextIterationMap;
2348}
2349
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002350void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002351 int LoopDepth = getRelativeLoopDepth(L);
2352 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002353
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002354 BasicBlock *HeaderBB = L->getHeader();
2355 assert(DomainMap.count(HeaderBB));
2356 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002357
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002358 isl_map *NextIterationMap =
2359 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002360
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002361 isl_set *UnionBackedgeCondition =
2362 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002363
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002364 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2365 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002366
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002367 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002368
2369 // If the latch is only reachable via error statements we skip it.
2370 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2371 if (!LatchBBDom)
2372 continue;
2373
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002374 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002375
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002376 TerminatorInst *TI = LatchBB->getTerminator();
2377 BranchInst *BI = dyn_cast<BranchInst>(TI);
2378 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002379 BackedgeCondition = isl_set_copy(LatchBBDom);
2380 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002381 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002382 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002383 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002384
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002385 // Free the non back edge condition set as we do not need it.
2386 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002387
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002388 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002389 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002390
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002391 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2392 assert(LatchLoopDepth >= LoopDepth);
2393 BackedgeCondition =
2394 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2395 LatchLoopDepth - LoopDepth);
2396 UnionBackedgeCondition =
2397 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002398 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002399
2400 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2401 for (int i = 0; i < LoopDepth; i++)
2402 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2403
2404 isl_set *UnionBackedgeConditionComplement =
2405 isl_set_complement(UnionBackedgeCondition);
2406 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2407 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2408 UnionBackedgeConditionComplement =
2409 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2410 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2411 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2412
2413 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2414 HeaderBBDom = Parts.second;
2415
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002416 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2417 // the bounded assumptions to the context as they are already implied by the
2418 // <nsw> tag.
2419 if (Affinator.hasNSWAddRecForLoop(L)) {
2420 isl_set_free(Parts.first);
2421 return;
2422 }
2423
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002424 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2425 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002426 addAssumption(INFINITELOOP, BoundedCtx,
2427 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002428}
2429
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002430void Scop::buildAliasChecks(AliasAnalysis &AA) {
2431 if (!PollyUseRuntimeAliasChecks)
2432 return;
2433
2434 if (buildAliasGroups(AA))
2435 return;
2436
2437 // If a problem occurs while building the alias groups we need to delete
2438 // this SCoP and pretend it wasn't valid in the first place. To this end
2439 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002440 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002441
2442 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2443 << " could not be created as the number of parameters involved "
2444 "is too high. The SCoP will be "
2445 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2446 "the maximal number of parameters but be advised that the "
2447 "compile time might increase exponentially.\n\n");
2448}
2449
Johannes Doerfert9143d672014-09-27 11:02:39 +00002450bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002451 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002452 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002453 // for all memory accesses inside the SCoP.
2454 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002455 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002456 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002457 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002458 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002459 // if their access domains intersect, otherwise they are in different
2460 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002461 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002462 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002463 // and maximal accesses to each array of a group in read only and non
2464 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002465 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2466
2467 AliasSetTracker AST(AA);
2468
2469 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002470 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002471 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002472
2473 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002474 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002475 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2476 isl_set_free(StmtDomain);
2477 if (StmtDomainEmpty)
2478 continue;
2479
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002480 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002481 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002482 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002483 if (!MA->isRead())
2484 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002485 Instruction *Acc = MA->getAccessInstruction();
2486 PtrToAcc[getPointerOperand(*Acc)] = MA;
2487 AST.add(Acc);
2488 }
2489 }
2490
2491 SmallVector<AliasGroupTy, 4> AliasGroups;
2492 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002493 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002494 continue;
2495 AliasGroupTy AG;
2496 for (auto PR : AS)
2497 AG.push_back(PtrToAcc[PR.getValue()]);
2498 assert(AG.size() > 1 &&
2499 "Alias groups should contain at least two accesses");
2500 AliasGroups.push_back(std::move(AG));
2501 }
2502
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002503 // Split the alias groups based on their domain.
2504 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2505 AliasGroupTy NewAG;
2506 AliasGroupTy &AG = AliasGroups[u];
2507 AliasGroupTy::iterator AGI = AG.begin();
2508 isl_set *AGDomain = getAccessDomain(*AGI);
2509 while (AGI != AG.end()) {
2510 MemoryAccess *MA = *AGI;
2511 isl_set *MADomain = getAccessDomain(MA);
2512 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2513 NewAG.push_back(MA);
2514 AGI = AG.erase(AGI);
2515 isl_set_free(MADomain);
2516 } else {
2517 AGDomain = isl_set_union(AGDomain, MADomain);
2518 AGI++;
2519 }
2520 }
2521 if (NewAG.size() > 1)
2522 AliasGroups.push_back(std::move(NewAG));
2523 isl_set_free(AGDomain);
2524 }
2525
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002526 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002527 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002528 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2529 for (AliasGroupTy &AG : AliasGroups) {
2530 NonReadOnlyBaseValues.clear();
2531 ReadOnlyPairs.clear();
2532
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002533 if (AG.size() < 2) {
2534 AG.clear();
2535 continue;
2536 }
2537
Johannes Doerfert13771732014-10-01 12:40:46 +00002538 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002539 emitOptimizationRemarkAnalysis(
2540 F.getContext(), DEBUG_TYPE, F,
2541 (*II)->getAccessInstruction()->getDebugLoc(),
2542 "Possibly aliasing pointer, use restrict keyword.");
2543
Johannes Doerfert13771732014-10-01 12:40:46 +00002544 Value *BaseAddr = (*II)->getBaseAddr();
2545 if (HasWriteAccess.count(BaseAddr)) {
2546 NonReadOnlyBaseValues.insert(BaseAddr);
2547 II++;
2548 } else {
2549 ReadOnlyPairs[BaseAddr].insert(*II);
2550 II = AG.erase(II);
2551 }
2552 }
2553
2554 // If we don't have read only pointers check if there are at least two
2555 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002556 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002557 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002558 continue;
2559 }
2560
2561 // If we don't have non read only pointers clear the alias group.
2562 if (NonReadOnlyBaseValues.empty()) {
2563 AG.clear();
2564 continue;
2565 }
2566
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002567 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002568 MinMaxAliasGroups.emplace_back();
2569 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2570 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2571 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2572 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002573
2574 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002575
2576 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002577 for (MemoryAccess *MA : AG)
2578 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002579
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002580 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2581 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002582
2583 // Bail out if the number of values we need to compare is too large.
2584 // This is important as the number of comparisions grows quadratically with
2585 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002586 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2587 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002588 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002589
2590 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002591 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002592 Accesses = isl_union_map_empty(getParamSpace());
2593
2594 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2595 for (MemoryAccess *MA : ReadOnlyPair.second)
2596 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2597
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002598 Valid =
2599 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002600
2601 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002602 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002603 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002604
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002605 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002606}
2607
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002608/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002609static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002610 // Start with the smallest loop containing the entry and expand that
2611 // loop until it contains all blocks in the region. If there is a loop
2612 // containing all blocks in the region check if it is itself contained
2613 // and if so take the parent loop as it will be the smallest containing
2614 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002615 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002616 while (L) {
2617 bool AllContained = true;
2618 for (auto *BB : R.blocks())
2619 AllContained &= L->contains(BB);
2620 if (AllContained)
2621 break;
2622 L = L->getParentLoop();
2623 }
2624
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002625 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2626}
2627
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002628static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2629 ScopDetection &SD) {
2630
2631 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2632
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002633 unsigned MinLD = INT_MAX, MaxLD = 0;
2634 for (BasicBlock *BB : R.blocks()) {
2635 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002636 if (!R.contains(L))
2637 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002638 if (BoxedLoops && BoxedLoops->count(L))
2639 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002640 unsigned LD = L->getLoopDepth();
2641 MinLD = std::min(MinLD, LD);
2642 MaxLD = std::max(MaxLD, LD);
2643 }
2644 }
2645
2646 // Handle the case that there is no loop in the SCoP first.
2647 if (MaxLD == 0)
2648 return 1;
2649
2650 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2651 assert(MaxLD >= MinLD &&
2652 "Maximal loop depth was smaller than mininaml loop depth?");
2653 return MaxLD - MinLD + 1;
2654}
2655
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002656Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002657 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002658 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002659 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2660 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002661 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2662 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2663 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2664 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002665
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002666void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002667 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002668 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002669 buildInvariantEquivalenceClasses();
2670
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002671 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002672
Michael Krusecac948e2015-10-02 13:53:07 +00002673 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002674 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002675 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002676 if (Stmts.empty())
2677 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002678
Michael Krusecac948e2015-10-02 13:53:07 +00002679 // The ScopStmts now have enough information to initialize themselves.
2680 for (ScopStmt &Stmt : Stmts)
2681 Stmt.init();
2682
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00002683 buildSchedule();
Tobias Grosser75805372011-04-29 06:27:02 +00002684
Tobias Grosser8286b832015-11-02 11:29:32 +00002685 if (isl_set_is_empty(AssumedContext))
2686 return;
2687
2688 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002689 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002690 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002691 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002692 buildBoundaryContext();
2693 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002694 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002695
2696 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002697 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002698}
2699
2700Scop::~Scop() {
2701 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002702 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002703 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002704 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002705
Johannes Doerfert96425c22015-08-30 21:13:53 +00002706 for (auto It : DomainMap)
2707 isl_set_free(It.second);
2708
Johannes Doerfertb164c792014-09-18 11:17:17 +00002709 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002710 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002711 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002712 isl_pw_multi_aff_free(MMA.first);
2713 isl_pw_multi_aff_free(MMA.second);
2714 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002715 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002716 isl_pw_multi_aff_free(MMA.first);
2717 isl_pw_multi_aff_free(MMA.second);
2718 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002719 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002720
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002721 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002722 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002723}
2724
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002725void Scop::updateAccessDimensionality() {
2726 for (auto &Stmt : *this)
2727 for (auto &Access : Stmt)
2728 Access->updateDimensionality();
2729}
2730
Michael Krusecac948e2015-10-02 13:53:07 +00002731void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002732 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2733 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002734 RegionNode *RN = Stmt.isRegionStmt()
2735 ? Stmt.getRegion()->getNode()
2736 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002737
Johannes Doerferteca9e892015-11-03 16:54:49 +00002738 bool RemoveStmt = StmtIt->isEmpty();
2739 if (!RemoveStmt)
2740 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2741 if (!RemoveStmt)
2742 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002743
Johannes Doerferteca9e892015-11-03 16:54:49 +00002744 // Remove read only statements only after invariant loop hoisting.
2745 if (!RemoveStmt && !RemoveIgnoredStmts) {
2746 bool OnlyRead = true;
2747 for (MemoryAccess *MA : Stmt) {
2748 if (MA->isRead())
2749 continue;
2750
2751 OnlyRead = false;
2752 break;
2753 }
2754
2755 RemoveStmt = OnlyRead;
2756 }
2757
2758 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002759 // Remove the statement because it is unnecessary.
2760 if (Stmt.isRegionStmt())
2761 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2762 StmtMap.erase(BB);
2763 else
2764 StmtMap.erase(Stmt.getBasicBlock());
2765
2766 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002767 continue;
2768 }
2769
Michael Krusecac948e2015-10-02 13:53:07 +00002770 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002771 }
2772}
2773
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002774const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2775 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2776 if (!LInst)
2777 return nullptr;
2778
2779 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2780 LInst = cast<LoadInst>(Rep);
2781
2782 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2783 for (auto &IAClass : InvariantEquivClasses)
2784 if (PointerSCEV == std::get<0>(IAClass))
2785 return &IAClass;
2786
2787 return nullptr;
2788}
2789
2790void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2791
2792 // Get the context under which the statement is executed.
2793 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2794 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2795 DomainCtx = isl_set_detect_equalities(DomainCtx);
2796 DomainCtx = isl_set_coalesce(DomainCtx);
2797
2798 // Project out all parameters that relate to loads in the statement. Otherwise
2799 // we could have cyclic dependences on the constraints under which the
2800 // hoisted loads are executed and we could not determine an order in which to
2801 // pre-load them. This happens because not only lower bounds are part of the
2802 // domain but also upper bounds.
2803 for (MemoryAccess *MA : InvMAs) {
2804 Instruction *AccInst = MA->getAccessInstruction();
2805 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002806 SetVector<Value *> Values;
2807 for (const SCEV *Parameter : Parameters) {
2808 Values.clear();
2809 findValues(Parameter, Values);
2810 if (!Values.count(AccInst))
2811 continue;
2812
2813 if (isl_id *ParamId = getIdForParam(Parameter)) {
2814 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2815 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2816 isl_id_free(ParamId);
2817 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002818 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002819 }
2820 }
2821
2822 for (MemoryAccess *MA : InvMAs) {
2823 // Check for another invariant access that accesses the same location as
2824 // MA and if found consolidate them. Otherwise create a new equivalence
2825 // class at the end of InvariantEquivClasses.
2826 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2827 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2828
2829 bool Consolidated = false;
2830 for (auto &IAClass : InvariantEquivClasses) {
2831 if (PointerSCEV != std::get<0>(IAClass))
2832 continue;
2833
2834 Consolidated = true;
2835
2836 // Add MA to the list of accesses that are in this class.
2837 auto &MAs = std::get<1>(IAClass);
2838 MAs.push_front(MA);
2839
2840 // Unify the execution context of the class and this statement.
2841 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002842 if (IAClassDomainCtx)
2843 IAClassDomainCtx = isl_set_coalesce(
2844 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2845 else
2846 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002847 break;
2848 }
2849
2850 if (Consolidated)
2851 continue;
2852
2853 // If we did not consolidate MA, thus did not find an equivalence class
2854 // for it, we create a new one.
2855 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2856 isl_set_copy(DomainCtx));
2857 }
2858
2859 isl_set_free(DomainCtx);
2860}
2861
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002862bool Scop::isHoistableAccess(MemoryAccess *Access,
2863 __isl_keep isl_union_map *Writes) {
2864 // TODO: Loads that are not loop carried, hence are in a statement with
2865 // zero iterators, are by construction invariant, though we
2866 // currently "hoist" them anyway. This is necessary because we allow
2867 // them to be treated as parameters (e.g., in conditions) and our code
2868 // generation would otherwise use the old value.
2869
2870 auto &Stmt = *Access->getStatement();
2871 BasicBlock *BB =
2872 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
2873
2874 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
2875 return false;
2876
2877 // Skip accesses that have an invariant base pointer which is defined but
2878 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2879 // returns a pointer that is used as a base address. However, as we want
2880 // to hoist indirect pointers, we allow the base pointer to be defined in
2881 // the region if it is also a memory access. Each ScopArrayInfo object
2882 // that has a base pointer origin has a base pointer that is loaded and
2883 // that it is invariant, thus it will be hoisted too. However, if there is
2884 // no base pointer origin we check that the base pointer is defined
2885 // outside the region.
2886 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
2887 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2888 SAI = BasePtrOriginSAI;
2889
2890 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2891 if (R.contains(BasePtrInst))
2892 return false;
2893
2894 // Skip accesses in non-affine subregions as they might not be executed
2895 // under the same condition as the entry of the non-affine subregion.
2896 if (BB != Access->getAccessInstruction()->getParent())
2897 return false;
2898
2899 isl_map *AccessRelation = Access->getAccessRelation();
2900
2901 // Skip accesses that have an empty access relation. These can be caused
2902 // by multiple offsets with a type cast in-between that cause the overall
2903 // byte offset to be not divisible by the new types sizes.
2904 if (isl_map_is_empty(AccessRelation)) {
2905 isl_map_free(AccessRelation);
2906 return false;
2907 }
2908
2909 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2910 Stmt.getNumIterators())) {
2911 isl_map_free(AccessRelation);
2912 return false;
2913 }
2914
2915 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
2916 isl_set *AccessRange = isl_map_range(AccessRelation);
2917
2918 isl_union_map *Written = isl_union_map_intersect_range(
2919 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2920 bool IsWritten = !isl_union_map_is_empty(Written);
2921 isl_union_map_free(Written);
2922
2923 if (IsWritten)
2924 return false;
2925
2926 return true;
2927}
2928
2929void Scop::verifyInvariantLoads() {
2930 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
2931 for (LoadInst *LI : RIL) {
2932 assert(LI && getRegion().contains(LI));
2933 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
Tobias Grosser949e8c62015-12-21 07:10:39 +00002934 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002935 invalidate(INVARIANTLOAD, LI->getDebugLoc());
2936 return;
2937 }
2938 }
2939}
2940
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002941void Scop::hoistInvariantLoads() {
2942 isl_union_map *Writes = getWrites();
2943 for (ScopStmt &Stmt : *this) {
2944
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002945 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002946
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002947 for (MemoryAccess *Access : Stmt)
2948 if (isHoistableAccess(Access, Writes))
2949 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002950
2951 // We inserted invariant accesses always in the front but need them to be
2952 // sorted in a "natural order". The statements are already sorted in reverse
2953 // post order and that suffices for the accesses too. The reason we require
2954 // an order in the first place is the dependences between invariant loads
2955 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002956 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002957
2958 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002959 Stmt.removeMemoryAccesses(InvariantAccesses);
2960 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002961 }
2962 isl_union_map_free(Writes);
2963
Tobias Grosser29f38ab2015-12-13 21:00:40 +00002964 verifyInvariantLoads();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002965}
2966
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002967const ScopArrayInfo *
2968Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002969 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00002970 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002971 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002972 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002973 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2974 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2975 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002976 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002977 // In case of mismatching array sizes, we bail out by setting the run-time
2978 // context to false.
2979 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002980 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002981 }
Tobias Grosserab671442015-05-23 05:58:27 +00002982 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002983}
2984
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002985const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00002986 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002987 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002988 assert(SAI && "No ScopArrayInfo available for this base pointer");
2989 return SAI;
2990}
2991
Tobias Grosser74394f02013-01-14 22:40:23 +00002992std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002993std::string Scop::getAssumedContextStr() const {
2994 return stringFromIslObj(AssumedContext);
2995}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002996std::string Scop::getBoundaryContextStr() const {
2997 return stringFromIslObj(BoundaryContext);
2998}
Tobias Grosser75805372011-04-29 06:27:02 +00002999
3000std::string Scop::getNameStr() const {
3001 std::string ExitName, EntryName;
3002 raw_string_ostream ExitStr(ExitName);
3003 raw_string_ostream EntryStr(EntryName);
3004
Tobias Grosserf240b482014-01-09 10:42:15 +00003005 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003006 EntryStr.str();
3007
3008 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003009 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003010 ExitStr.str();
3011 } else
3012 ExitName = "FunctionExit";
3013
3014 return EntryName + "---" + ExitName;
3015}
3016
Tobias Grosser74394f02013-01-14 22:40:23 +00003017__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003018__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003019 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003020}
3021
Tobias Grossere86109f2013-10-29 21:05:49 +00003022__isl_give isl_set *Scop::getAssumedContext() const {
3023 return isl_set_copy(AssumedContext);
3024}
3025
Johannes Doerfert43788c52015-08-20 05:58:56 +00003026__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3027 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003028 RuntimeCheckContext =
3029 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3030 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003031 return RuntimeCheckContext;
3032}
3033
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003034bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003035 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003036 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003037 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3038 isl_set_free(RuntimeCheckContext);
3039 return IsFeasible;
3040}
3041
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003042static std::string toString(AssumptionKind Kind) {
3043 switch (Kind) {
3044 case ALIASING:
3045 return "No-aliasing";
3046 case INBOUNDS:
3047 return "Inbounds";
3048 case WRAPPING:
3049 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003050 case ALIGNMENT:
3051 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003052 case ERRORBLOCK:
3053 return "No-error";
3054 case INFINITELOOP:
3055 return "Finite loop";
3056 case INVARIANTLOAD:
3057 return "Invariant load";
3058 case DELINEARIZATION:
3059 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003060 case ERROR_DOMAINCONJUNCTS:
3061 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003062 }
3063 llvm_unreachable("Unknown AssumptionKind!");
3064}
3065
3066void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3067 DebugLoc Loc) {
3068 if (isl_set_is_subset(Context, Set))
3069 return;
3070
3071 if (isl_set_is_subset(AssumedContext, Set))
3072 return;
3073
3074 auto &F = *getRegion().getEntry()->getParent();
3075 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3076 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3077}
3078
3079void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3080 DebugLoc Loc) {
3081 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003082 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003083
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003084 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003085 if (NSets >= MaxDisjunctsAssumed) {
3086 isl_space *Space = isl_set_get_space(AssumedContext);
3087 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003088 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003089 }
3090
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003091 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003092}
3093
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003094void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3095 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3096}
3097
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003098__isl_give isl_set *Scop::getBoundaryContext() const {
3099 return isl_set_copy(BoundaryContext);
3100}
3101
Tobias Grosser75805372011-04-29 06:27:02 +00003102void Scop::printContext(raw_ostream &OS) const {
3103 OS << "Context:\n";
3104
3105 if (!Context) {
3106 OS.indent(4) << "n/a\n\n";
3107 return;
3108 }
3109
3110 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003111
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003112 OS.indent(4) << "Assumed Context:\n";
3113 if (!AssumedContext) {
3114 OS.indent(4) << "n/a\n\n";
3115 return;
3116 }
3117
3118 OS.indent(4) << getAssumedContextStr() << "\n";
3119
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003120 OS.indent(4) << "Boundary Context:\n";
3121 if (!BoundaryContext) {
3122 OS.indent(4) << "n/a\n\n";
3123 return;
3124 }
3125
3126 OS.indent(4) << getBoundaryContextStr() << "\n";
3127
Tobias Grosser083d3d32014-06-28 08:59:45 +00003128 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003129 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003130 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3131 }
Tobias Grosser75805372011-04-29 06:27:02 +00003132}
3133
Johannes Doerfertb164c792014-09-18 11:17:17 +00003134void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003135 int noOfGroups = 0;
3136 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003137 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003138 noOfGroups += 1;
3139 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003140 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003141 }
3142
Tobias Grosserbb853c22015-07-25 12:31:03 +00003143 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003144 if (MinMaxAliasGroups.empty()) {
3145 OS.indent(8) << "n/a\n";
3146 return;
3147 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003148
Tobias Grosserbb853c22015-07-25 12:31:03 +00003149 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003150
3151 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003152 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003153 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003154 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003155 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3156 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003157 }
3158 OS << " ]]\n";
3159 }
3160
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003161 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003162 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003163 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003164 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003165 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3166 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003167 }
3168 OS << " ]]\n";
3169 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003170 }
3171}
3172
Tobias Grosser75805372011-04-29 06:27:02 +00003173void Scop::printStatements(raw_ostream &OS) const {
3174 OS << "Statements {\n";
3175
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003176 for (const ScopStmt &Stmt : *this)
3177 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003178
3179 OS.indent(4) << "}\n";
3180}
3181
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003182void Scop::printArrayInfo(raw_ostream &OS) const {
3183 OS << "Arrays {\n";
3184
Tobias Grosserab671442015-05-23 05:58:27 +00003185 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003186 Array.second->print(OS);
3187
3188 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003189
3190 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3191
3192 for (auto &Array : arrays())
3193 Array.second->print(OS, /* SizeAsPwAff */ true);
3194
3195 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003196}
3197
Tobias Grosser75805372011-04-29 06:27:02 +00003198void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003199 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3200 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003201 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003202 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003203 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003204 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003205 const auto &MAs = std::get<1>(IAClass);
3206 if (MAs.empty()) {
3207 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003208 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003209 MAs.front()->print(OS);
3210 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003211 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003212 }
3213 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003214 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003215 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003216 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003217 printStatements(OS.indent(4));
3218}
3219
3220void Scop::dump() const { print(dbgs()); }
3221
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003222isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003223
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003224__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3225 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003226}
3227
Tobias Grosser808cd692015-07-14 09:33:13 +00003228__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003229 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003230
Tobias Grosser808cd692015-07-14 09:33:13 +00003231 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003232 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003233
3234 return Domain;
3235}
3236
Tobias Grossere5a35142015-11-12 14:07:09 +00003237__isl_give isl_union_map *
3238Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3239 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003240
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003241 for (ScopStmt &Stmt : *this) {
3242 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003243 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003244 continue;
3245
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003246 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003247 isl_map *AccessDomain = MA->getAccessRelation();
3248 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003249 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003250 }
3251 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003252 return isl_union_map_coalesce(Accesses);
3253}
3254
3255__isl_give isl_union_map *Scop::getMustWrites() {
3256 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003257}
3258
3259__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003260 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003261}
3262
Tobias Grosser37eb4222014-02-20 21:43:54 +00003263__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003264 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003265}
3266
3267__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003268 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003269}
3270
Tobias Grosser2ac23382015-11-12 14:07:13 +00003271__isl_give isl_union_map *Scop::getAccesses() {
3272 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3273}
3274
Tobias Grosser808cd692015-07-14 09:33:13 +00003275__isl_give isl_union_map *Scop::getSchedule() const {
3276 auto Tree = getScheduleTree();
3277 auto S = isl_schedule_get_map(Tree);
3278 isl_schedule_free(Tree);
3279 return S;
3280}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003281
Tobias Grosser808cd692015-07-14 09:33:13 +00003282__isl_give isl_schedule *Scop::getScheduleTree() const {
3283 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3284 getDomains());
3285}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003286
Tobias Grosser808cd692015-07-14 09:33:13 +00003287void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3288 auto *S = isl_schedule_from_domain(getDomains());
3289 S = isl_schedule_insert_partial_schedule(
3290 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3291 isl_schedule_free(Schedule);
3292 Schedule = S;
3293}
3294
3295void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3296 isl_schedule_free(Schedule);
3297 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003298}
3299
3300bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3301 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003302 for (ScopStmt &Stmt : *this) {
3303 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003304 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3305 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3306
3307 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3308 isl_union_set_free(StmtDomain);
3309 isl_union_set_free(NewStmtDomain);
3310 continue;
3311 }
3312
3313 Changed = true;
3314
3315 isl_union_set_free(StmtDomain);
3316 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3317
3318 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003319 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003320 isl_union_set_free(NewStmtDomain);
3321 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003322 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003323 }
3324 isl_union_set_free(Domain);
3325 return Changed;
3326}
3327
Tobias Grosser75805372011-04-29 06:27:02 +00003328ScalarEvolution *Scop::getSE() const { return SE; }
3329
Johannes Doerfertf5673802015-10-01 23:48:18 +00003330bool Scop::isIgnored(RegionNode *RN) {
3331 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003332 ScopStmt *Stmt = getStmtForRegionNode(RN);
3333
3334 // If there is no stmt, then it already has been removed.
3335 if (!Stmt)
3336 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003337
Johannes Doerfertf5673802015-10-01 23:48:18 +00003338 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003339 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003340 return true;
3341
3342 // Check for reachability via non-error blocks.
3343 if (!DomainMap.count(BB))
3344 return true;
3345
3346 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003347 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003348 return true;
3349
3350 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003351}
3352
Tobias Grosser808cd692015-07-14 09:33:13 +00003353struct MapToDimensionDataTy {
3354 int N;
3355 isl_union_pw_multi_aff *Res;
3356};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003357
Tobias Grosser808cd692015-07-14 09:33:13 +00003358// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003359// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003360//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003361// @param Set The input set.
3362// @param User->N The dimension to map to.
3363// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003364//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003365// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003366static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3367 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3368 int Dim;
3369 isl_space *Space;
3370 isl_pw_multi_aff *PMA;
3371
3372 Dim = isl_set_dim(Set, isl_dim_set);
3373 Space = isl_set_get_space(Set);
3374 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3375 Dim - Data->N);
3376 if (Data->N > 1)
3377 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3378 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3379
3380 isl_set_free(Set);
3381
3382 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003383}
3384
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003385// @brief Create an isl_multi_union_aff that defines an identity mapping
3386// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003387//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003388// # Example:
3389//
3390// Domain: { A[i,j]; B[i,j,k] }
3391// N: 1
3392//
3393// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3394//
3395// @param USet A union set describing the elements for which to generate a
3396// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003397// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003398// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003399static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003400mapToDimension(__isl_take isl_union_set *USet, int N) {
3401 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003402 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003403 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003404
Tobias Grosser808cd692015-07-14 09:33:13 +00003405 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003406
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003407 auto *Space = isl_union_set_get_space(USet);
3408 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003409
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003410 Data = {N, PwAff};
3411
3412 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
3413
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003414 (void)Res;
3415
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003416 assert(Res == isl_stat_ok);
3417
3418 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003419 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3420}
3421
Tobias Grosser316b5b22015-11-11 19:28:14 +00003422void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003423 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003424 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003425 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003426 StmtMap[BB] = Stmt;
3427 } else {
3428 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003429 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003430 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003431 for (BasicBlock *BB : R->blocks())
3432 StmtMap[BB] = Stmt;
3433 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003434}
3435
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003436void Scop::buildSchedule() {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003437 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
3438 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
3439 LoopSchedules[L];
Tobias Grosser8362c262016-01-06 15:30:06 +00003440 buildSchedule(getRegion().getNode(), LoopSchedules);
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003441 Schedule = LoopSchedules[L].first;
3442}
3443
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003444void Scop::buildSchedule(
Tobias Grosser8362c262016-01-06 15:30:06 +00003445 RegionNode *RN,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003446 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003447
Tobias Grosser8362c262016-01-06 15:30:06 +00003448 if (RN->isSubRegion()) {
3449 auto *LocalRegion = RN->getNodeAs<Region>();
3450 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
3451 ReversePostOrderTraversal<Region *> RTraversal(LocalRegion);
3452 for (auto *Child : RTraversal)
3453 buildSchedule(Child, LoopSchedules);
3454 return;
3455 }
3456 }
Michael Kruse046dde42015-08-10 13:01:57 +00003457
Tobias Grosser8362c262016-01-06 15:30:06 +00003458 Loop *L = getRegionNodeLoop(RN, LI);
3459 if (!getRegion().contains(L))
3460 L = getLoopSurroundingRegion(getRegion(), LI);
3461
3462 int LD = getRelativeLoopDepth(L);
3463 auto &LSchedulePair = LoopSchedules[L];
3464 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3465
Tobias Grosserc9abde82016-01-23 20:23:06 +00003466 if (auto *Stmt = getStmtForRegionNode(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003467 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3468 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3469 LSchedulePair.first = combineInSequence(LSchedulePair.first, StmtSchedule);
3470 }
3471
3472 isl_schedule *LSchedule = LSchedulePair.first;
3473 unsigned NumVisited = LSchedulePair.second;
3474 while (L && NumVisited == L->getNumBlocks()) {
3475 auto *PL = L->getParentLoop();
3476
3477 // Either we have a proper loop and we also build a schedule for the
3478 // parent loop or we have a infinite loop that does not have a proper
3479 // parent loop. In the former case this conditional will be skipped, in
3480 // the latter case however we will break here as we do not build a domain
3481 // nor a schedule for a infinite loop.
3482 assert(LoopSchedules.count(PL) || LSchedule == nullptr);
3483 if (!LoopSchedules.count(PL))
3484 break;
3485
3486 auto &PSchedulePair = LoopSchedules[PL];
3487
3488 if (LSchedule) {
3489 auto *LDomain = isl_schedule_get_domain(LSchedule);
3490 auto *MUPA = mapToDimension(LDomain, LD + 1);
3491 LSchedule = isl_schedule_insert_partial_schedule(LSchedule, MUPA);
3492 PSchedulePair.first = combineInSequence(PSchedulePair.first, LSchedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003493 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003494
Tobias Grosser8362c262016-01-06 15:30:06 +00003495 PSchedulePair.second += NumVisited;
Johannes Doerfert30c22652015-10-18 21:17:11 +00003496
Tobias Grosser8362c262016-01-06 15:30:06 +00003497 L = PL;
3498 LD--;
3499 NumVisited = PSchedulePair.second;
3500 LSchedule = PSchedulePair.first;
Tobias Grosser808cd692015-07-14 09:33:13 +00003501 }
Tobias Grosser75805372011-04-29 06:27:02 +00003502}
3503
Johannes Doerfert7c494212014-10-31 23:13:39 +00003504ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003505 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003506 if (StmtMapIt == StmtMap.end())
3507 return nullptr;
3508 return StmtMapIt->second;
3509}
3510
Michael Krusea902ba62015-12-13 19:21:45 +00003511ScopStmt *Scop::getStmtForRegionNode(RegionNode *RN) const {
3512 return getStmtForBasicBlock(getRegionNodeBasicBlock(RN));
3513}
3514
Johannes Doerfert96425c22015-08-30 21:13:53 +00003515int Scop::getRelativeLoopDepth(const Loop *L) const {
3516 Loop *OuterLoop =
3517 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3518 if (!OuterLoop)
3519 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003520 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3521}
3522
Michael Krused868b5d2015-09-10 15:25:24 +00003523void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003524 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003525
3526 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3527 // true, are not modeled as ordinary PHI nodes as they are not part of the
3528 // region. However, we model the operands in the predecessor blocks that are
3529 // part of the region as regular scalar accesses.
3530
3531 // If we can synthesize a PHI we can skip it, however only if it is in
3532 // the region. If it is not it can only be in the exit block of the region.
3533 // In this case we model the operands but not the PHI itself.
3534 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3535 return;
3536
3537 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3538 // detection. Hence, the PHI is a load of a new memory location in which the
3539 // incoming value was written at the end of the incoming basic block.
3540 bool OnlyNonAffineSubRegionOperands = true;
3541 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3542 Value *Op = PHI->getIncomingValue(u);
3543 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3544
3545 // Do not build scalar dependences inside a non-affine subregion.
3546 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3547 continue;
3548
3549 OnlyNonAffineSubRegionOperands = false;
3550
3551 if (!R.contains(OpBB))
3552 continue;
3553
3554 Instruction *OpI = dyn_cast<Instruction>(Op);
3555 if (OpI) {
3556 BasicBlock *OpIBB = OpI->getParent();
3557 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3558 // we have to insert a scalar dependence from the definition of OpI to
3559 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003560 if (scop->getStmtForBasicBlock(OpIBB) !=
3561 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse34e11222015-12-13 22:47:43 +00003562 addValueReadAccess(OpI, PHI, OpBB);
Michael Kruse436db622016-01-26 13:33:10 +00003563 ensureValueWrite(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003564 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003565 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse34e11222015-12-13 22:47:43 +00003566 addValueReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003567 }
3568
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003569 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003570 }
3571
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003572 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3573 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003574 }
3575}
3576
Michael Krused868b5d2015-09-10 15:25:24 +00003577bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3578 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003579 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3580 if (isIgnoredIntrinsic(Inst))
3581 return false;
3582
3583 bool AnyCrossStmtUse = false;
3584 BasicBlock *ParentBB = Inst->getParent();
3585
3586 for (User *U : Inst->users()) {
3587 Instruction *UI = dyn_cast<Instruction>(U);
3588
3589 // Ignore the strange user
3590 if (UI == 0)
3591 continue;
3592
3593 BasicBlock *UseParent = UI->getParent();
3594
Tobias Grosserbaffa092015-10-24 20:55:27 +00003595 // Ignore basic block local uses. A value that is defined in a scop, but
3596 // used in a PHI node in the same basic block does not count as basic block
3597 // local, as for such cases a control flow edge is passed between definition
3598 // and use.
3599 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003600 continue;
3601
Michael Krusef714d472015-11-05 13:18:43 +00003602 // Uses by PHI nodes in the entry node count as external uses in case the
3603 // use is through an incoming block that is itself not contained in the
3604 // region.
3605 if (R->getEntry() == UseParent) {
3606 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3607 bool ExternalUse = false;
3608 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3609 if (PHI->getIncomingValue(i) == Inst &&
3610 !R->contains(PHI->getIncomingBlock(i))) {
3611 ExternalUse = true;
3612 break;
3613 }
3614 }
3615
3616 if (ExternalUse) {
3617 AnyCrossStmtUse = true;
3618 continue;
3619 }
3620 }
3621 }
3622
Michael Kruse7bf39442015-09-10 12:46:52 +00003623 // Do not build scalar dependences inside a non-affine subregion.
3624 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3625 continue;
3626
Michael Kruse01cb3792015-10-17 21:07:08 +00003627 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003628 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003629 //
3630 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003631 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3632 // the control flow a different value will be assigned to the PHI node. In
3633 // case this is the case, there is no need to create an additional normal
3634 // scalar dependence. Hence, bail out before we register an "out-of-region"
3635 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003636 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3637 !R->getExitingBlock())
3638 continue;
3639
Michael Kruse7bf39442015-09-10 12:46:52 +00003640 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003641 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003642 AnyCrossStmtUse = true;
3643 continue;
3644 }
3645
3646 // If the instruction can be synthesized and the user is in the region
3647 // we do not need to add scalar dependences.
3648 if (canSynthesizeInst)
3649 continue;
3650
3651 // No need to translate these scalar dependences into polyhedral form,
3652 // because synthesizable scalars can be generated by the code generator.
3653 if (canSynthesize(UI, LI, SE, R))
3654 continue;
3655
3656 // Skip PHI nodes in the region as they handle their operands on their own.
3657 if (isa<PHINode>(UI))
3658 continue;
3659
3660 // Now U is used in another statement.
3661 AnyCrossStmtUse = true;
3662
3663 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003664 // Use the def instruction as base address of the MemoryAccess, so that it
3665 // will become the name of the scalar access in the polyhedral form.
Michael Kruse34e11222015-12-13 22:47:43 +00003666 addValueReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003667 }
3668
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003669 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003670 for (Value *Op : Inst->operands()) {
3671 if (canSynthesize(Op, LI, SE, R))
3672 continue;
3673
3674 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3675 if (R->contains(OpInst))
3676 continue;
3677
3678 if (isa<Constant>(Op))
3679 continue;
3680
Michael Kruse34e11222015-12-13 22:47:43 +00003681 addValueReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003682 }
3683 }
3684
3685 return AnyCrossStmtUse;
3686}
3687
3688extern MapInsnToMemAcc InsnToMemAcc;
3689
Michael Krusee2bccbb2015-09-18 19:59:43 +00003690void ScopInfo::buildMemoryAccess(
3691 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003692 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3693 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003694 unsigned Size;
3695 Type *SizeType;
3696 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003697 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003698
3699 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3700 SizeType = Load->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003701 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003702 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003703 Val = Load;
3704 } else {
3705 StoreInst *Store = cast<StoreInst>(Inst);
3706 SizeType = Store->getValueOperand()->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003707 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003708 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003709 Val = Store->getValueOperand();
3710 }
3711
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003712 auto Address = getPointerOperand(*Inst);
3713
3714 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003715 const SCEVUnknown *BasePointer =
3716 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3717
3718 assert(BasePointer && "Could not find base pointer");
3719 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3720
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003721 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3722 auto NewAddress = Address;
3723 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3724 auto Src = BitCast->getOperand(0);
3725 auto SrcTy = Src->getType();
3726 auto DstTy = BitCast->getType();
3727 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3728 NewAddress = Src;
3729 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003730
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003731 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3732 std::vector<const SCEV *> Subscripts;
3733 std::vector<int> Sizes;
3734 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3735 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003736
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003737 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003738
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003739 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003740 for (auto Subscript : Subscripts) {
3741 InvariantLoadsSetTy AccessILS;
3742 AllAffineSubcripts =
3743 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3744
3745 for (LoadInst *LInst : AccessILS)
3746 if (!ScopRIL.count(LInst))
3747 AllAffineSubcripts = false;
3748
3749 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003750 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003751 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003752
3753 if (AllAffineSubcripts && Sizes.size() > 0) {
3754 for (auto V : Sizes)
3755 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3756 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003757 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003758 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003759
Tobias Grossera535dff2015-12-13 19:59:01 +00003760 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3761 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003762 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003763 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003764 }
3765 }
3766
Michael Kruse7bf39442015-09-10 12:46:52 +00003767 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003768 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grossera535dff2015-12-13 19:59:01 +00003769 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, true,
3770 AccItr->second.DelinearizedSubscripts,
3771 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003772 return;
3773 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003774
3775 // Check if the access depends on a loop contained in a non-affine subregion.
3776 bool isVariantInNonAffineLoop = false;
3777 if (BoxedLoops) {
3778 SetVector<const Loop *> Loops;
3779 findLoops(AccessFunction, Loops);
3780 for (const Loop *L : Loops)
3781 if (BoxedLoops->count(L))
3782 isVariantInNonAffineLoop = true;
3783 }
3784
Johannes Doerfert09e36972015-10-07 20:17:36 +00003785 InvariantLoadsSetTy AccessILS;
3786 bool IsAffine =
3787 !isVariantInNonAffineLoop &&
3788 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3789
3790 for (LoadInst *LInst : AccessILS)
3791 if (!ScopRIL.count(LInst))
3792 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003793
Michael Krusecaac2b62015-09-26 15:51:44 +00003794 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003795 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003796 const SCEV *SizeSCEV =
3797 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003798
Michael Krusee2bccbb2015-09-18 19:59:43 +00003799 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3800 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003801
Tobias Grossera535dff2015-12-13 19:59:01 +00003802 addArrayAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3803 ArrayRef<const SCEV *>(AccessFunction),
3804 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003805}
3806
Michael Krused868b5d2015-09-10 15:25:24 +00003807void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003808
3809 if (SD->isNonAffineSubRegion(&SR, &R)) {
3810 for (BasicBlock *BB : SR.blocks())
3811 buildAccessFunctions(R, *BB, &SR);
3812 return;
3813 }
3814
3815 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3816 if (I->isSubRegion())
3817 buildAccessFunctions(R, *I->getNodeAs<Region>());
3818 else
3819 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3820}
3821
Michael Krusecac948e2015-10-02 13:53:07 +00003822void ScopInfo::buildStmts(Region &SR) {
3823 Region *R = getRegion();
3824
3825 if (SD->isNonAffineSubRegion(&SR, R)) {
3826 scop->addScopStmt(nullptr, &SR);
3827 return;
3828 }
3829
3830 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3831 if (I->isSubRegion())
3832 buildStmts(*I->getNodeAs<Region>());
3833 else
3834 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3835}
3836
Michael Krused868b5d2015-09-10 15:25:24 +00003837void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3838 Region *NonAffineSubRegion,
3839 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003840 // We do not build access functions for error blocks, as they may contain
3841 // instructions we can not model.
3842 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3843 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3844 return;
3845
Michael Kruse7bf39442015-09-10 12:46:52 +00003846 Loop *L = LI->getLoopFor(&BB);
3847
3848 // The set of loops contained in non-affine subregions that are part of R.
3849 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3850
Johannes Doerfert09e36972015-10-07 20:17:36 +00003851 // The set of loads that are required to be invariant.
3852 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3853
Michael Kruse7bf39442015-09-10 12:46:52 +00003854 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003855 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003856
3857 PHINode *PHI = dyn_cast<PHINode>(Inst);
3858 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003859 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003860
3861 // For the exit block we stop modeling after the last PHI node.
3862 if (!PHI && IsExitBlock)
3863 break;
3864
Johannes Doerfert09e36972015-10-07 20:17:36 +00003865 // TODO: At this point we only know that elements of ScopRIL have to be
3866 // invariant and will be hoisted for the SCoP to be processed. Though,
3867 // there might be other invariant accesses that will be hoisted and
3868 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003869 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003870 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003871
3872 if (isIgnoredIntrinsic(Inst))
3873 continue;
3874
Johannes Doerfert09e36972015-10-07 20:17:36 +00003875 // Do not build scalar dependences for required invariant loads as we will
3876 // hoist them later on anyway or drop the SCoP if we cannot.
3877 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3878 continue;
3879
Michael Kruse7bf39442015-09-10 12:46:52 +00003880 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003881 if (!isa<StoreInst>(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00003882 ensureValueWrite(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003883 }
3884 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003885}
Michael Kruse7bf39442015-09-10 12:46:52 +00003886
Michael Kruse2d0ece92015-09-24 11:41:21 +00003887void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3888 MemoryAccess::AccessType Type,
3889 Value *BaseAddress, unsigned ElemBytes,
3890 bool Affine, Value *AccessValue,
3891 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003892 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003893 ScopArrayInfo::MemoryKind Kind) {
Michael Krusecac948e2015-10-02 13:53:07 +00003894 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3895
3896 // Do not create a memory access for anything not in the SCoP. It would be
3897 // ignored anyway.
3898 if (!Stmt)
3899 return;
3900
Michael Krusee2bccbb2015-09-18 19:59:43 +00003901 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003902 Value *BaseAddr = BaseAddress;
3903 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3904
Tobias Grosserf4f68702015-12-14 15:05:37 +00003905 bool isKnownMustAccess = false;
3906
3907 // Accesses in single-basic block statements are always excuted.
3908 if (Stmt->isBlockStmt())
3909 isKnownMustAccess = true;
3910
3911 if (Stmt->isRegionStmt()) {
3912 // Accesses that dominate the exit block of a non-affine region are always
3913 // executed. In non-affine regions there may exist MK_Values that do not
3914 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
3915 // only if there is at most one PHI_WRITE in the non-affine region.
3916 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
3917 isKnownMustAccess = true;
3918 }
3919
3920 if (!isKnownMustAccess && Type == MemoryAccess::MUST_WRITE)
Michael Krusecac948e2015-10-02 13:53:07 +00003921 Type = MemoryAccess::MAY_WRITE;
3922
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003923 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00003924 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003925 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003926}
3927
Tobias Grossera535dff2015-12-13 19:59:01 +00003928void ScopInfo::addArrayAccess(Instruction *MemAccInst,
3929 MemoryAccess::AccessType Type, Value *BaseAddress,
3930 unsigned ElemBytes, bool IsAffine,
3931 ArrayRef<const SCEV *> Subscripts,
3932 ArrayRef<const SCEV *> Sizes,
3933 Value *AccessValue) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003934 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3935 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3936 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003937 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003938 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003939}
Michael Kruse436db622016-01-26 13:33:10 +00003940void ScopInfo::ensureValueWrite(Instruction *Value) {
3941 ScopStmt *Stmt = scop->getStmtForBasicBlock(Value->getParent());
3942
3943 // Value not defined within this SCoP.
3944 if (!Stmt)
3945 return;
3946
3947 // Do not process further if the value is already written.
3948 if (Stmt->lookupValueWriteOf(Value))
3949 return;
3950
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003951 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3952 true, Value, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003953 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003954}
Michael Kruse34e11222015-12-13 22:47:43 +00003955void ScopInfo::addValueReadAccess(Value *Value, Instruction *User) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003956 assert(!isa<PHINode>(User));
3957 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3958 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003959 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003960}
Michael Kruse34e11222015-12-13 22:47:43 +00003961void ScopInfo::addValueReadAccess(Value *Value, PHINode *User,
3962 BasicBlock *UserBB) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003963 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003964 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003965 ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003966}
3967void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3968 Value *IncomingValue, bool IsExitBlock) {
3969 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3970 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3971 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003972 IsExitBlock ? ScopArrayInfo::MK_ExitPHI
3973 : ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003974}
3975void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3976 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003977 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00003978 ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003979}
3980
Michael Krusedaf66942015-12-13 22:10:37 +00003981void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003982 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Krusedaf66942015-12-13 22:10:37 +00003983 scop = new Scop(R, AccFuncMap, *SD, *SE, *DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003984
Michael Krusecac948e2015-10-02 13:53:07 +00003985 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003986 buildAccessFunctions(R, R);
3987
3988 // In case the region does not have an exiting block we will later (during
3989 // code generation) split the exit block. This will move potential PHI nodes
3990 // from the current exit block into the new region exiting block. Hence, PHI
3991 // nodes that are at this point not part of the region will be.
3992 // To handle these PHI nodes later we will now model their operands as scalar
3993 // accesses. Note that we do not model anything in the exit block if we have
3994 // an exiting block in the region, as there will not be any splitting later.
3995 if (!R.getExitingBlock())
3996 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3997
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003998 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003999}
4000
Michael Krused868b5d2015-09-10 15:25:24 +00004001void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004002 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004003 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004004 return;
4005 }
4006
Michael Kruse9d080092015-09-11 21:41:48 +00004007 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004008}
4009
Michael Krused868b5d2015-09-10 15:25:24 +00004010void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00004011 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00004012 if (scop) {
4013 delete scop;
4014 scop = 0;
4015 }
Michael Kruse7bf39442015-09-10 12:46:52 +00004016}
4017
4018//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00004019ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00004020 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00004021 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00004022}
4023
4024ScopInfo::~ScopInfo() {
4025 clear();
4026 isl_ctx_free(ctx);
4027}
4028
Tobias Grosser75805372011-04-29 06:27:02 +00004029void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004030 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004031 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004032 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004033 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4034 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004035 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004036 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004037 AU.setPreservesAll();
4038}
4039
4040bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004041 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004042
Michael Krused868b5d2015-09-10 15:25:24 +00004043 if (!SD->isMaxRegionInScop(*R))
4044 return false;
4045
4046 Function *F = R->getEntry()->getParent();
4047 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4048 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4049 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4050 TD = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004051 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004052 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004053
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004054 DebugLoc Beg, End;
4055 getDebugLocations(R, Beg, End);
4056 std::string Msg = "SCoP begins here.";
4057 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4058
Michael Krusedaf66942015-12-13 22:10:37 +00004059 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004060
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004061 DEBUG(scop->print(dbgs()));
4062
Michael Kruseafe06702015-10-02 16:33:27 +00004063 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004064 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00004065 delete scop;
4066 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004067 } else {
4068 Msg = "SCoP ends here.";
4069 ++ScopFound;
4070 if (scop->getMaxLoopDepth() > 0)
4071 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004072 }
4073
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004074 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4075
Tobias Grosser75805372011-04-29 06:27:02 +00004076 return false;
4077}
4078
4079char ScopInfo::ID = 0;
4080
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004081Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4082
Tobias Grosser73600b82011-10-08 00:30:40 +00004083INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4084 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004085 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004086INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004087INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004088INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004089INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004090INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004091INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004092INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004093INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4094 "Polly - Create polyhedral description of Scops", false,
4095 false)