blob: b16bfa647886b9c822d87488fa3f76c02f3c0b38 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser75805372011-04-29 06:27:02 +000020#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000021#include "polly/Options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000022#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000026#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000027#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000029#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000030#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000031#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000032#include "llvm/Analysis/AliasAnalysis.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000033#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000034#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000035#include "llvm/Analysis/RegionIterator.h"
36#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Tobias Grosser75805372011-04-29 06:27:02 +000037#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000038#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000039#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000040#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000042#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000044#include "isl/schedule.h"
45#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/set.h"
47#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000048#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000049#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000050#include <sstream>
51#include <string>
52#include <vector>
53
54using namespace llvm;
55using namespace polly;
56
Chandler Carruth95fef942014-04-22 03:30:19 +000057#define DEBUG_TYPE "polly-scops"
58
Tobias Grosser74394f02013-01-14 22:40:23 +000059STATISTIC(ScopFound, "Number of valid Scops");
60STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000061
Michael Kruse7bf39442015-09-10 12:46:52 +000062static cl::opt<bool> ModelReadOnlyScalars(
63 "polly-analyze-read-only-scalars",
64 cl::desc("Model read-only scalar values in the scop description"),
65 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
66
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000067// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000068// operations can overflow easily. Additive reductions and bit operations
69// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000070static cl::opt<bool> DisableMultiplicativeReductions(
71 "polly-disable-multiplicative-reductions",
72 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
73 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000074
Johannes Doerfert9143d672014-09-27 11:02:39 +000075static cl::opt<unsigned> RunTimeChecksMaxParameters(
76 "polly-rtc-max-parameters",
77 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
78 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
79
Tobias Grosser71500722015-03-28 15:11:14 +000080static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
81 "polly-rtc-max-arrays-per-group",
82 cl::desc("The maximal number of arrays to compare in each alias group."),
83 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000084static cl::opt<std::string> UserContextStr(
85 "polly-context", cl::value_desc("isl parameter set"),
86 cl::desc("Provide additional constraints on the context parameters"),
87 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000088
Tobias Grosserd83b8a82015-08-20 19:08:11 +000089static cl::opt<bool> DetectReductions("polly-detect-reductions",
90 cl::desc("Detect and exploit reductions"),
91 cl::Hidden, cl::ZeroOrMore,
92 cl::init(true), cl::cat(PollyCategory));
93
Tobias Grosser20a4c0c2015-11-11 16:22:36 +000094static cl::opt<int> MaxDisjunctsAssumed(
95 "polly-max-disjuncts-assumed",
96 cl::desc("The maximal number of disjuncts we allow in the assumption "
97 "context (this bounds compile time)"),
98 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
99
Michael Kruse7bf39442015-09-10 12:46:52 +0000100//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000101
Michael Kruse046dde42015-08-10 13:01:57 +0000102// Create a sequence of two schedules. Either argument may be null and is
103// interpreted as the empty schedule. Can also return null if both schedules are
104// empty.
105static __isl_give isl_schedule *
106combineInSequence(__isl_take isl_schedule *Prev,
107 __isl_take isl_schedule *Succ) {
108 if (!Prev)
109 return Succ;
110 if (!Succ)
111 return Prev;
112
113 return isl_schedule_sequence(Prev, Succ);
114}
115
Johannes Doerferte7044942015-02-24 11:58:30 +0000116static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
117 const ConstantRange &Range,
118 int dim,
119 enum isl_dim_type type) {
120 isl_val *V;
121 isl_ctx *ctx = isl_set_get_ctx(S);
122
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000123 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
124 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000125 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000126 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
127
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000128 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000129 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000132 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
133
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000134 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000135 return isl_set_union(SLB, SUB);
136 else
137 return isl_set_intersect(SLB, SUB);
138}
139
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000140static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
141 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
142 if (!BasePtrLI)
143 return nullptr;
144
145 if (!S->getRegion().contains(BasePtrLI))
146 return nullptr;
147
148 ScalarEvolution &SE = *S->getSE();
149
150 auto *OriginBaseSCEV =
151 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
152 if (!OriginBaseSCEV)
153 return nullptr;
154
155 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
156 if (!OriginBaseSCEVUnknown)
157 return nullptr;
158
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000159 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
160 ScopArrayInfo::KIND_ARRAY);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000161}
162
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000163ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000164 ArrayRef<const SCEV *> Sizes, enum ARRAYKIND Kind,
165 Scop *S)
166 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000167 std::string BasePtrName =
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000168 getIslCompatibleName("MemRef_", BasePtr, Kind == KIND_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000169 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000170
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000171 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000172 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
173 if (BasePtrOriginSAI)
174 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000175}
176
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000177__isl_give isl_space *ScopArrayInfo::getSpace() const {
178 auto Space =
179 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
180 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
181 return Space;
182}
183
Tobias Grosser8286b832015-11-02 11:29:32 +0000184bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000185 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
186 int ExtraDimsNew = NewSizes.size() - SharedDims;
187 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000188 for (int i = 0; i < SharedDims; i++)
189 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
190 return false;
191
192 if (DimensionSizes.size() >= NewSizes.size())
193 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000194
195 DimensionSizes.clear();
196 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
197 NewSizes.end());
198 for (isl_pw_aff *Size : DimensionSizesPw)
199 isl_pw_aff_free(Size);
200 DimensionSizesPw.clear();
201 for (const SCEV *Expr : DimensionSizes) {
202 isl_pw_aff *Size = S.getPwAff(Expr);
203 DimensionSizesPw.push_back(Size);
204 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000205 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000206}
207
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000208ScopArrayInfo::~ScopArrayInfo() {
209 isl_id_free(Id);
210 for (isl_pw_aff *Size : DimensionSizesPw)
211 isl_pw_aff_free(Size);
212}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000213
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000214std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
215
216int ScopArrayInfo::getElemSizeInBytes() const {
217 return ElementType->getPrimitiveSizeInBits() / 8;
218}
219
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000220isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
221
222void ScopArrayInfo::dump() const { print(errs()); }
223
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000224void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000225 OS.indent(8) << *getElementType() << " " << getName();
226 if (getNumberOfDimensions() > 0)
227 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000228 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000229 OS << "[";
230
Tobias Grosser26253842015-11-10 14:24:21 +0000231 if (SizeAsPwAff) {
232 auto Size = getDimensionSizePw(u);
233 OS << " " << Size << " ";
234 isl_pw_aff_free(Size);
235 } else {
236 OS << *getDimensionSize(u);
237 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000238
239 OS << "]";
240 }
241
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000242 OS << ";";
243
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000244 if (BasePtrOriginSAI)
245 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
246
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000247 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000248}
249
250const ScopArrayInfo *
251ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
252 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
253 assert(Id && "Output dimension didn't have an ID");
254 return getFromId(Id);
255}
256
257const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
258 void *User = isl_id_get_user(Id);
259 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
260 isl_id_free(Id);
261 return SAI;
262}
263
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000264void MemoryAccess::updateDimensionality() {
265 auto ArraySpace = getScopArrayInfo()->getSpace();
266 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
267
268 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
269 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
270 auto DimsMissing = DimsArray - DimsAccess;
271
272 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
273 isl_set_universe(ArraySpace));
274
275 for (unsigned i = 0; i < DimsMissing; i++)
276 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
277
278 for (unsigned i = DimsMissing; i < DimsArray; i++)
279 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
280
281 AccessRelation = isl_map_apply_range(AccessRelation, Map);
282}
283
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000284const std::string
285MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
286 switch (RT) {
287 case MemoryAccess::RT_NONE:
288 llvm_unreachable("Requested a reduction operator string for a memory "
289 "access which isn't a reduction");
290 case MemoryAccess::RT_ADD:
291 return "+";
292 case MemoryAccess::RT_MUL:
293 return "*";
294 case MemoryAccess::RT_BOR:
295 return "|";
296 case MemoryAccess::RT_BXOR:
297 return "^";
298 case MemoryAccess::RT_BAND:
299 return "&";
300 }
301 llvm_unreachable("Unknown reduction type");
302 return "";
303}
304
Johannes Doerfertf6183392014-07-01 20:52:51 +0000305/// @brief Return the reduction type for a given binary operator
306static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
307 const Instruction *Load) {
308 if (!BinOp)
309 return MemoryAccess::RT_NONE;
310 switch (BinOp->getOpcode()) {
311 case Instruction::FAdd:
312 if (!BinOp->hasUnsafeAlgebra())
313 return MemoryAccess::RT_NONE;
314 // Fall through
315 case Instruction::Add:
316 return MemoryAccess::RT_ADD;
317 case Instruction::Or:
318 return MemoryAccess::RT_BOR;
319 case Instruction::Xor:
320 return MemoryAccess::RT_BXOR;
321 case Instruction::And:
322 return MemoryAccess::RT_BAND;
323 case Instruction::FMul:
324 if (!BinOp->hasUnsafeAlgebra())
325 return MemoryAccess::RT_NONE;
326 // Fall through
327 case Instruction::Mul:
328 if (DisableMultiplicativeReductions)
329 return MemoryAccess::RT_NONE;
330 return MemoryAccess::RT_MUL;
331 default:
332 return MemoryAccess::RT_NONE;
333 }
334}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000335
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000336/// @brief Derive the individual index expressions from a GEP instruction
337///
338/// This function optimistically assumes the GEP references into a fixed size
339/// array. If this is actually true, this function returns a list of array
340/// subscript expressions as SCEV as well as a list of integers describing
341/// the size of the individual array dimensions. Both lists have either equal
342/// length of the size list is one element shorter in case there is no known
343/// size available for the outermost array dimension.
344///
345/// @param GEP The GetElementPtr instruction to analyze.
346///
347/// @return A tuple with the subscript expressions and the dimension sizes.
348static std::tuple<std::vector<const SCEV *>, std::vector<int>>
349getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
350 std::vector<const SCEV *> Subscripts;
351 std::vector<int> Sizes;
352
353 Type *Ty = GEP->getPointerOperandType();
354
355 bool DroppedFirstDim = false;
356
Michael Kruse26ed65e2015-09-24 17:32:49 +0000357 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000358
359 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
360
361 if (i == 1) {
362 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
363 Ty = PtrTy->getElementType();
364 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
365 Ty = ArrayTy->getElementType();
366 } else {
367 Subscripts.clear();
368 Sizes.clear();
369 break;
370 }
371 if (auto Const = dyn_cast<SCEVConstant>(Expr))
372 if (Const->getValue()->isZero()) {
373 DroppedFirstDim = true;
374 continue;
375 }
376 Subscripts.push_back(Expr);
377 continue;
378 }
379
380 auto ArrayTy = dyn_cast<ArrayType>(Ty);
381 if (!ArrayTy) {
382 Subscripts.clear();
383 Sizes.clear();
384 break;
385 }
386
387 Subscripts.push_back(Expr);
388 if (!(DroppedFirstDim && i == 2))
389 Sizes.push_back(ArrayTy->getNumElements());
390
391 Ty = ArrayTy->getElementType();
392 }
393
394 return std::make_tuple(Subscripts, Sizes);
395}
396
Tobias Grosser75805372011-04-29 06:27:02 +0000397MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000398 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000399 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000400 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000401}
402
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000403const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
404 isl_id *ArrayId = getArrayId();
405 void *User = isl_id_get_user(ArrayId);
406 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
407 isl_id_free(ArrayId);
408 return SAI;
409}
410
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000411__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000412 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
413}
414
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000415__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
416 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000417 isl_map *Schedule, *ScheduledAccRel;
418 isl_union_set *UDomain;
419
420 UDomain = isl_union_set_from_set(getStatement()->getDomain());
421 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
422 Schedule = isl_map_from_union_map(USchedule);
423 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
424 return isl_pw_multi_aff_from_map(ScheduledAccRel);
425}
426
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000427__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000428 return isl_map_copy(AccessRelation);
429}
430
Johannes Doerferta99130f2014-10-13 12:58:03 +0000431std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000432 return stringFromIslObj(AccessRelation);
433}
434
Johannes Doerferta99130f2014-10-13 12:58:03 +0000435__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000436 return isl_map_get_space(AccessRelation);
437}
438
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000439__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000440 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000441}
442
Tobias Grosser6f730082015-09-05 07:46:47 +0000443std::string MemoryAccess::getNewAccessRelationStr() const {
444 return stringFromIslObj(NewAccessRelation);
445}
446
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000447__isl_give isl_basic_map *
448MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000449 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000450 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000451
Tobias Grosser084d8f72012-05-29 09:29:44 +0000452 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000453 isl_basic_set_universe(Statement->getDomainSpace()),
454 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000455}
456
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000457// Formalize no out-of-bound access assumption
458//
459// When delinearizing array accesses we optimistically assume that the
460// delinearized accesses do not access out of bound locations (the subscript
461// expression of each array evaluates for each statement instance that is
462// executed to a value that is larger than zero and strictly smaller than the
463// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000464// dimension for which we do not need to assume any upper bound. At this point
465// we formalize this assumption to ensure that at code generation time the
466// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000467//
468// To find the set of constraints necessary to avoid out of bound accesses, we
469// first build the set of data locations that are not within array bounds. We
470// then apply the reverse access relation to obtain the set of iterations that
471// may contain invalid accesses and reduce this set of iterations to the ones
472// that are actually executed by intersecting them with the domain of the
473// statement. If we now project out all loop dimensions, we obtain a set of
474// parameters that may cause statement instances to be executed that may
475// possibly yield out of bound memory accesses. The complement of these
476// constraints is the set of constraints that needs to be assumed to ensure such
477// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000478void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000479 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000480 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000481 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000482 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
483 isl_pw_aff *Var =
484 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
485 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
486
487 isl_set *DimOutside;
488
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000489 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000490 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000491
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000492 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
493 Statement->getNumIterators());
494 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
495 isl_space_dim(Space, isl_dim_set));
496 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
497 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000498
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000499 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000500
501 Outside = isl_set_union(Outside, DimOutside);
502 }
503
504 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
505 Outside = isl_set_intersect(Outside, Statement->getDomain());
506 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000507
508 // Remove divs to avoid the construction of overly complicated assumptions.
509 // Doing so increases the set of parameter combinations that are assumed to
510 // not appear. This is always save, but may make the resulting run-time check
511 // bail out more often than strictly necessary.
512 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000513 Outside = isl_set_complement(Outside);
514 Statement->getParent()->addAssumption(Outside);
515 isl_space_free(Space);
516}
517
Johannes Doerferte7044942015-02-24 11:58:30 +0000518void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
519 ScalarEvolution *SE = Statement->getParent()->getSE();
520
521 Value *Ptr = getPointerOperand(*getAccessInstruction());
522 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
523 return;
524
525 auto *PtrSCEV = SE->getSCEV(Ptr);
526 if (isa<SCEVCouldNotCompute>(PtrSCEV))
527 return;
528
529 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
530 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
531 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
532
533 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
534 if (Range.isFullSet())
535 return;
536
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000537 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000538 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000539 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
540 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
541
542 auto Min = LB.sdiv(APInt(BW, ElementSize));
543 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000544
545 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
546 AccessRange =
547 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
548 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
549}
550
Michael Krusee2bccbb2015-09-18 19:59:43 +0000551__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000552 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000553 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000554
555 for (int i = Size - 2; i >= 0; --i) {
556 isl_space *Space;
557 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000558 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000559
560 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
561 isl_pw_aff_free(DimSize);
562 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
563
564 Space = isl_map_get_space(AccessRelation);
565 Space = isl_space_map_from_set(isl_space_range(Space));
566 Space = isl_space_align_params(Space, SpaceSize);
567
568 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
569 isl_id_free(ParamId);
570
571 MapOne = isl_map_universe(isl_space_copy(Space));
572 for (int j = 0; j < Size; ++j)
573 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
574 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
575
576 MapTwo = isl_map_universe(isl_space_copy(Space));
577 for (int j = 0; j < Size; ++j)
578 if (j < i || j > i + 1)
579 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
580
581 isl_local_space *LS = isl_local_space_from_space(Space);
582 isl_constraint *C;
583 C = isl_equality_alloc(isl_local_space_copy(LS));
584 C = isl_constraint_set_constant_si(C, -1);
585 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
586 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
587 MapTwo = isl_map_add_constraint(MapTwo, C);
588 C = isl_equality_alloc(LS);
589 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
590 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
591 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
592 MapTwo = isl_map_add_constraint(MapTwo, C);
593 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
594
595 MapOne = isl_map_union(MapOne, MapTwo);
596 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
597 }
598 return AccessRelation;
599}
600
Michael Krusee2bccbb2015-09-18 19:59:43 +0000601void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
602 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000603
Michael Krusee2bccbb2015-09-18 19:59:43 +0000604 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000605 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000606
Michael Krusee2bccbb2015-09-18 19:59:43 +0000607 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000608 // We overapproximate non-affine accesses with a possible access to the
609 // whole array. For read accesses it does not make a difference, if an
610 // access must or may happen. However, for write accesses it is important to
611 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000612 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000613 AccessRelation =
614 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000615
Michael Krusee2bccbb2015-09-18 19:59:43 +0000616 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000617 return;
618 }
619
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000620 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000621 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000622
Michael Krusee2bccbb2015-09-18 19:59:43 +0000623 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
624 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000625
Sebastian Pop422e33f2014-06-03 18:16:31 +0000626 if (Size == 1) {
627 // For the non delinearized arrays, divide the access function of the last
628 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000629 //
630 // A stride one array access in C expressed as A[i] is expressed in
631 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
632 // two subsequent values of 'i' index two values that are stored next to
633 // each other in memory. By this division we make this characteristic
634 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000635 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000636 Affine = isl_pw_aff_scale_down_val(Affine, v);
637 }
638
639 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
640
Tobias Grosser79baa212014-04-10 08:38:02 +0000641 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000642 }
643
Michael Krusee2bccbb2015-09-18 19:59:43 +0000644 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
645 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000646
Tobias Grosser79baa212014-04-10 08:38:02 +0000647 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000648 AccessRelation = isl_map_set_tuple_id(
649 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000650 AccessRelation =
651 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
652
Michael Krusee2bccbb2015-09-18 19:59:43 +0000653 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000654 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000655 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000656}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000657
Michael Krusecac948e2015-10-02 13:53:07 +0000658MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000659 AccessType Type, Value *BaseAddress,
660 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000661 ArrayRef<const SCEV *> Subscripts,
662 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000663 AccessOrigin Origin, StringRef BaseName)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000664 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000665 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
666 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
667 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000668 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000669 NewAccessRelation(nullptr) {
670
671 std::string IdName = "__polly_array_ref";
672 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
673}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000674
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000675void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000676 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000677 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000678}
679
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000680const std::string MemoryAccess::getReductionOperatorStr() const {
681 return MemoryAccess::getReductionOperatorStr(getReductionType());
682}
683
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000684__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
685
Johannes Doerfertf6183392014-07-01 20:52:51 +0000686raw_ostream &polly::operator<<(raw_ostream &OS,
687 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000688 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000689 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000690 else
691 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000692 return OS;
693}
694
Tobias Grosser75805372011-04-29 06:27:02 +0000695void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000696 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000697 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000698 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000699 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000700 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000701 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000702 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000703 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000704 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000705 break;
706 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000707 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000708 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000709 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000710 if (hasNewAccessRelation())
711 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000712}
713
Tobias Grosser74394f02013-01-14 22:40:23 +0000714void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000715
716// Create a map in the size of the provided set domain, that maps from the
717// one element of the provided set domain to another element of the provided
718// set domain.
719// The mapping is limited to all points that are equal in all but the last
720// dimension and for which the last dimension of the input is strict smaller
721// than the last dimension of the output.
722//
723// getEqualAndLarger(set[i0, i1, ..., iX]):
724//
725// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
726// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
727//
Tobias Grosserf5338802011-10-06 00:03:35 +0000728static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000729 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000730 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000731 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000732
733 // Set all but the last dimension to be equal for the input and output
734 //
735 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
736 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000737 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000738 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000739
740 // Set the last dimension of the input to be strict smaller than the
741 // last dimension of the output.
742 //
743 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000744 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
745 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000746 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000747}
748
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000749__isl_give isl_set *
750MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000751 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000752 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000753 isl_space *Space = isl_space_range(isl_map_get_space(S));
754 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000755
Sebastian Popa00a0292012-12-18 07:46:06 +0000756 S = isl_map_reverse(S);
757 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000758
Sebastian Popa00a0292012-12-18 07:46:06 +0000759 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
760 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
761 NextScatt = isl_map_apply_domain(NextScatt, S);
762 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000763
Sebastian Popa00a0292012-12-18 07:46:06 +0000764 isl_set *Deltas = isl_map_deltas(NextScatt);
765 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000766}
767
Sebastian Popa00a0292012-12-18 07:46:06 +0000768bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000769 int StrideWidth) const {
770 isl_set *Stride, *StrideX;
771 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000772
Sebastian Popa00a0292012-12-18 07:46:06 +0000773 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000774 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000775 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
776 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
777 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
778 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000779 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000780
Tobias Grosser28dd4862012-01-24 16:42:16 +0000781 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000782 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000783
Tobias Grosser28dd4862012-01-24 16:42:16 +0000784 return IsStrideX;
785}
786
Sebastian Popa00a0292012-12-18 07:46:06 +0000787bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
788 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000789}
790
Sebastian Popa00a0292012-12-18 07:46:06 +0000791bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
792 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000793}
794
Tobias Grosser166c4222015-09-05 07:46:40 +0000795void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
796 isl_map_free(NewAccessRelation);
797 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000798}
Tobias Grosser75805372011-04-29 06:27:02 +0000799
800//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000801
Tobias Grosser808cd692015-07-14 09:33:13 +0000802isl_map *ScopStmt::getSchedule() const {
803 isl_set *Domain = getDomain();
804 if (isl_set_is_empty(Domain)) {
805 isl_set_free(Domain);
806 return isl_map_from_aff(
807 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
808 }
809 auto *Schedule = getParent()->getSchedule();
810 Schedule = isl_union_map_intersect_domain(
811 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
812 if (isl_union_map_is_empty(Schedule)) {
813 isl_set_free(Domain);
814 isl_union_map_free(Schedule);
815 return isl_map_from_aff(
816 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
817 }
818 auto *M = isl_map_from_union_map(Schedule);
819 M = isl_map_coalesce(M);
820 M = isl_map_gist_domain(M, Domain);
821 M = isl_map_coalesce(M);
822 return M;
823}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000824
Johannes Doerfert574182d2015-08-12 10:19:50 +0000825__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000826 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
827 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000828}
829
Tobias Grosser37eb4222014-02-20 21:43:54 +0000830void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
831 assert(isl_set_is_subset(NewDomain, Domain) &&
832 "New domain is not a subset of old domain!");
833 isl_set_free(Domain);
834 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000835}
836
Michael Krusecac948e2015-10-02 13:53:07 +0000837void ScopStmt::buildAccessRelations() {
838 for (MemoryAccess *Access : MemAccs) {
839 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000840
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000841 ScopArrayInfo::ARRAYKIND Ty;
842 if (Access->isPHI())
843 Ty = ScopArrayInfo::KIND_PHI;
844 else if (Access->isImplicit())
845 Ty = ScopArrayInfo::KIND_SCALAR;
846 else
847 Ty = ScopArrayInfo::KIND_ARRAY;
848
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000849 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000850 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000851
Michael Krusecac948e2015-10-02 13:53:07 +0000852 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000853 }
854}
855
Michael Krusecac948e2015-10-02 13:53:07 +0000856void ScopStmt::addAccess(MemoryAccess *Access) {
857 Instruction *AccessInst = Access->getAccessInstruction();
858
859 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
860 if (!MAL)
861 MAL = new MemoryAccessList();
862 MAL->emplace_front(Access);
863 MemAccs.push_back(MAL->front());
864}
865
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000866void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000867 for (MemoryAccess *MA : *this)
868 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000869
870 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000871}
872
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000873/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
874static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
875 void *User) {
876 isl_set **BoundedParts = static_cast<isl_set **>(User);
877 if (isl_basic_set_is_bounded(BSet))
878 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
879 else
880 isl_basic_set_free(BSet);
881 return isl_stat_ok;
882}
883
884/// @brief Return the bounded parts of @p S.
885static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
886 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
887 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
888 isl_set_free(S);
889 return BoundedParts;
890}
891
892/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
893///
894/// @returns A separation of @p S into first an unbounded then a bounded subset,
895/// both with regards to the dimension @p Dim.
896static std::pair<__isl_give isl_set *, __isl_give isl_set *>
897partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
898
899 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000900 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000901
902 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000903 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000904
905 // Remove dimensions that are greater than Dim as they are not interesting.
906 assert(NumDimsS >= Dim + 1);
907 OnlyDimS =
908 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
909
910 // Create artificial parametric upper bounds for dimensions smaller than Dim
911 // as we are not interested in them.
912 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
913 for (unsigned u = 0; u < Dim; u++) {
914 isl_constraint *C = isl_inequality_alloc(
915 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
916 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
917 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
918 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
919 }
920
921 // Collect all bounded parts of OnlyDimS.
922 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
923
924 // Create the dimensions greater than Dim again.
925 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
926 NumDimsS - Dim - 1);
927
928 // Remove the artificial upper bound parameters again.
929 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
930
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000931 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000932 return std::make_pair(UnboundedParts, BoundedParts);
933}
934
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000935/// @brief Set the dimension Ids from @p From in @p To.
936static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
937 __isl_take isl_set *To) {
938 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
939 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
940 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
941 }
942 return To;
943}
944
945/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000946static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000947 __isl_take isl_pw_aff *L,
948 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000949 switch (Pred) {
950 case ICmpInst::ICMP_EQ:
951 return isl_pw_aff_eq_set(L, R);
952 case ICmpInst::ICMP_NE:
953 return isl_pw_aff_ne_set(L, R);
954 case ICmpInst::ICMP_SLT:
955 return isl_pw_aff_lt_set(L, R);
956 case ICmpInst::ICMP_SLE:
957 return isl_pw_aff_le_set(L, R);
958 case ICmpInst::ICMP_SGT:
959 return isl_pw_aff_gt_set(L, R);
960 case ICmpInst::ICMP_SGE:
961 return isl_pw_aff_ge_set(L, R);
962 case ICmpInst::ICMP_ULT:
963 return isl_pw_aff_lt_set(L, R);
964 case ICmpInst::ICMP_UGT:
965 return isl_pw_aff_gt_set(L, R);
966 case ICmpInst::ICMP_ULE:
967 return isl_pw_aff_le_set(L, R);
968 case ICmpInst::ICMP_UGE:
969 return isl_pw_aff_ge_set(L, R);
970 default:
971 llvm_unreachable("Non integer predicate not supported");
972 }
973}
974
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000975/// @brief Create the conditions under which @p L @p Pred @p R is true.
976///
977/// Helper function that will make sure the dimensions of the result have the
978/// same isl_id's as the @p Domain.
979static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
980 __isl_take isl_pw_aff *L,
981 __isl_take isl_pw_aff *R,
982 __isl_keep isl_set *Domain) {
983 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
984 return setDimensionIds(Domain, ConsequenceCondSet);
985}
986
987/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000988///
989/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000990/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
991/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000992static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000993buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000994 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
995
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000996 Value *Condition = getConditionFromTerminator(SI);
997 assert(Condition && "No condition for switch");
998
999 ScalarEvolution &SE = *S.getSE();
1000 BasicBlock *BB = SI->getParent();
1001 isl_pw_aff *LHS, *RHS;
1002 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1003
1004 unsigned NumSuccessors = SI->getNumSuccessors();
1005 ConditionSets.resize(NumSuccessors);
1006 for (auto &Case : SI->cases()) {
1007 unsigned Idx = Case.getSuccessorIndex();
1008 ConstantInt *CaseValue = Case.getCaseValue();
1009
1010 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1011 isl_set *CaseConditionSet =
1012 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1013 ConditionSets[Idx] = isl_set_coalesce(
1014 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1015 }
1016
1017 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1018 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1019 for (unsigned u = 2; u < NumSuccessors; u++)
1020 ConditionSetUnion =
1021 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1022 ConditionSets[0] = setDimensionIds(
1023 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1024
1025 S.markAsOptimized();
1026 isl_pw_aff_free(LHS);
1027}
1028
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001029/// @brief Build the conditions sets for the branch condition @p Condition in
1030/// the @p Domain.
1031///
1032/// This will fill @p ConditionSets with the conditions under which control
1033/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1034/// have as many elements as @p TI has successors.
1035static void
1036buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1037 __isl_keep isl_set *Domain,
1038 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1039
1040 isl_set *ConsequenceCondSet = nullptr;
1041 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1042 if (CCond->isZero())
1043 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1044 else
1045 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1046 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1047 auto Opcode = BinOp->getOpcode();
1048 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1049
1050 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1051 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1052
1053 isl_set_free(ConditionSets.pop_back_val());
1054 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1055 isl_set_free(ConditionSets.pop_back_val());
1056 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1057
1058 if (Opcode == Instruction::And)
1059 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1060 else
1061 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1062 } else {
1063 auto *ICond = dyn_cast<ICmpInst>(Condition);
1064 assert(ICond &&
1065 "Condition of exiting branch was neither constant nor ICmp!");
1066
1067 ScalarEvolution &SE = *S.getSE();
1068 BasicBlock *BB = TI->getParent();
1069 isl_pw_aff *LHS, *RHS;
1070 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1071 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1072 ConsequenceCondSet =
1073 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1074 }
1075
1076 assert(ConsequenceCondSet);
1077 isl_set *AlternativeCondSet =
1078 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1079
1080 ConditionSets.push_back(isl_set_coalesce(
1081 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1082 ConditionSets.push_back(isl_set_coalesce(
1083 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1084}
1085
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001086/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1087///
1088/// This will fill @p ConditionSets with the conditions under which control
1089/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1090/// have as many elements as @p TI has successors.
1091static void
1092buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1093 __isl_keep isl_set *Domain,
1094 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1095
1096 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1097 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1098
1099 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1100
1101 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001102 ConditionSets.push_back(isl_set_copy(Domain));
1103 return;
1104 }
1105
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001106 Value *Condition = getConditionFromTerminator(TI);
1107 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001108
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001109 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001110}
1111
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001112void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001113 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001114
Tobias Grosser084d8f72012-05-29 09:29:44 +00001115 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1116
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001117 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001118 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001119}
1120
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001121void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001122 isl_ctx *Ctx = Parent.getIslCtx();
1123 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1124 Type *Ty = GEP->getPointerOperandType();
1125 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001126 ScopDetection &SD = Parent.getSD();
1127
1128 // The set of loads that are required to be invariant.
1129 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001130
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001131 std::vector<const SCEV *> Subscripts;
1132 std::vector<int> Sizes;
1133
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001134 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001135
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001136 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001137 Ty = PtrTy->getElementType();
1138 }
1139
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001140 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001141
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001142 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001143
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001144 for (size_t i = 0; i < Sizes.size(); i++) {
1145 auto Expr = Subscripts[i + IndexOffset];
1146 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001147
Johannes Doerfert09e36972015-10-07 20:17:36 +00001148 InvariantLoadsSetTy AccessILS;
1149 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1150 continue;
1151
1152 bool NonAffine = false;
1153 for (LoadInst *LInst : AccessILS)
1154 if (!ScopRIL.count(LInst))
1155 NonAffine = true;
1156
1157 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001158 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001159
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001160 isl_pw_aff *AccessOffset = getPwAff(Expr);
1161 AccessOffset =
1162 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001163
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001164 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1165 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001166
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001167 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1168 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1169 OutOfBound = isl_set_params(OutOfBound);
1170 isl_set *InBound = isl_set_complement(OutOfBound);
1171 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001172
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001173 // A => B == !A or B
1174 isl_set *InBoundIfExecuted =
1175 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001176
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001177 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001178 }
1179
1180 isl_local_space_free(LSpace);
1181}
1182
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001183void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1184 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001185 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1186 deriveAssumptionsFromGEP(GEP);
1187}
1188
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001189void ScopStmt::collectSurroundingLoops() {
1190 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1191 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1192 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1193 isl_id_free(DimId);
1194 }
1195}
1196
Michael Kruse9d080092015-09-11 21:41:48 +00001197ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001198 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001199
Tobias Grosser16c44032015-07-09 07:31:45 +00001200 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001201}
1202
Michael Kruse9d080092015-09-11 21:41:48 +00001203ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001204 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001205
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001206 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001207}
1208
1209void ScopStmt::init() {
1210 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001211
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001212 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001213 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001214 buildAccessRelations();
1215
1216 if (BB) {
1217 deriveAssumptions(BB);
1218 } else {
1219 for (BasicBlock *Block : R->blocks()) {
1220 deriveAssumptions(Block);
1221 }
1222 }
1223
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001224 if (DetectReductions)
1225 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001226}
1227
Johannes Doerferte58a0122014-06-27 20:31:28 +00001228/// @brief Collect loads which might form a reduction chain with @p StoreMA
1229///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001230/// Check if the stored value for @p StoreMA is a binary operator with one or
1231/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001232/// used only once (by @p StoreMA) and its load operands are also used only
1233/// once, we have found a possible reduction chain. It starts at an operand
1234/// load and includes the binary operator and @p StoreMA.
1235///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001236/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001237/// escape this block or into any other store except @p StoreMA.
1238void ScopStmt::collectCandiateReductionLoads(
1239 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1240 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1241 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001242 return;
1243
1244 // Skip if there is not one binary operator between the load and the store
1245 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001246 if (!BinOp)
1247 return;
1248
1249 // Skip if the binary operators has multiple uses
1250 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001251 return;
1252
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001253 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001254 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1255 return;
1256
Johannes Doerfert9890a052014-07-01 00:32:29 +00001257 // Skip if the binary operator is outside the current SCoP
1258 if (BinOp->getParent() != Store->getParent())
1259 return;
1260
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001261 // Skip if it is a multiplicative reduction and we disabled them
1262 if (DisableMultiplicativeReductions &&
1263 (BinOp->getOpcode() == Instruction::Mul ||
1264 BinOp->getOpcode() == Instruction::FMul))
1265 return;
1266
Johannes Doerferte58a0122014-06-27 20:31:28 +00001267 // Check the binary operator operands for a candidate load
1268 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1269 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1270 if (!PossibleLoad0 && !PossibleLoad1)
1271 return;
1272
1273 // A load is only a candidate if it cannot escape (thus has only this use)
1274 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001275 if (PossibleLoad0->getParent() == Store->getParent())
1276 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001277 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001278 if (PossibleLoad1->getParent() == Store->getParent())
1279 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001280}
1281
1282/// @brief Check for reductions in this ScopStmt
1283///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001284/// Iterate over all store memory accesses and check for valid binary reduction
1285/// like chains. For all candidates we check if they have the same base address
1286/// and there are no other accesses which overlap with them. The base address
1287/// check rules out impossible reductions candidates early. The overlap check,
1288/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001289/// guarantees that none of the intermediate results will escape during
1290/// execution of the loop nest. We basically check here that no other memory
1291/// access can access the same memory as the potential reduction.
1292void ScopStmt::checkForReductions() {
1293 SmallVector<MemoryAccess *, 2> Loads;
1294 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1295
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001296 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001297 // stores and collecting possible reduction loads.
1298 for (MemoryAccess *StoreMA : MemAccs) {
1299 if (StoreMA->isRead())
1300 continue;
1301
1302 Loads.clear();
1303 collectCandiateReductionLoads(StoreMA, Loads);
1304 for (MemoryAccess *LoadMA : Loads)
1305 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1306 }
1307
1308 // Then check each possible candidate pair.
1309 for (const auto &CandidatePair : Candidates) {
1310 bool Valid = true;
1311 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1312 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1313
1314 // Skip those with obviously unequal base addresses.
1315 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1316 isl_map_free(LoadAccs);
1317 isl_map_free(StoreAccs);
1318 continue;
1319 }
1320
1321 // And check if the remaining for overlap with other memory accesses.
1322 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1323 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1324 isl_set *AllAccs = isl_map_range(AllAccsRel);
1325
1326 for (MemoryAccess *MA : MemAccs) {
1327 if (MA == CandidatePair.first || MA == CandidatePair.second)
1328 continue;
1329
1330 isl_map *AccRel =
1331 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1332 isl_set *Accs = isl_map_range(AccRel);
1333
1334 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1335 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1336 Valid = Valid && isl_set_is_empty(OverlapAccs);
1337 isl_set_free(OverlapAccs);
1338 }
1339 }
1340
1341 isl_set_free(AllAccs);
1342 if (!Valid)
1343 continue;
1344
Johannes Doerfertf6183392014-07-01 20:52:51 +00001345 const LoadInst *Load =
1346 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1347 MemoryAccess::ReductionType RT =
1348 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1349
Johannes Doerferte58a0122014-06-27 20:31:28 +00001350 // If no overlapping access was found we mark the load and store as
1351 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001352 CandidatePair.first->markAsReductionLike(RT);
1353 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001354 }
Tobias Grosser75805372011-04-29 06:27:02 +00001355}
1356
Tobias Grosser74394f02013-01-14 22:40:23 +00001357std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001358
Tobias Grosser54839312015-04-21 11:37:25 +00001359std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001360 auto *S = getSchedule();
1361 auto Str = stringFromIslObj(S);
1362 isl_map_free(S);
1363 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001364}
1365
Tobias Grosser74394f02013-01-14 22:40:23 +00001366unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001367
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001368unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001369
Tobias Grosser75805372011-04-29 06:27:02 +00001370const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1371
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001372const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001373 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001374}
1375
Tobias Grosser74394f02013-01-14 22:40:23 +00001376isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001377
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001378__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001379
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001380__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001381 return isl_set_get_space(Domain);
1382}
1383
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001384__isl_give isl_id *ScopStmt::getDomainId() const {
1385 return isl_set_get_tuple_id(Domain);
1386}
Tobias Grossercd95b772012-08-30 11:49:38 +00001387
Tobias Grosser75805372011-04-29 06:27:02 +00001388ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001389 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001390 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001391}
1392
1393void ScopStmt::print(raw_ostream &OS) const {
1394 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001395 OS.indent(12) << "Domain :=\n";
1396
1397 if (Domain) {
1398 OS.indent(16) << getDomainStr() << ";\n";
1399 } else
1400 OS.indent(16) << "n/a\n";
1401
Tobias Grosser54839312015-04-21 11:37:25 +00001402 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001403
1404 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001405 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001406 } else
1407 OS.indent(16) << "n/a\n";
1408
Tobias Grosser083d3d32014-06-28 08:59:45 +00001409 for (MemoryAccess *Access : MemAccs)
1410 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001411}
1412
1413void ScopStmt::dump() const { print(dbgs()); }
1414
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001415void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001416
1417 // Remove all memory accesses in @p InvMAs from this statement together
1418 // with all scalar accesses that were caused by them. The tricky iteration
1419 // order uses is needed because the MemAccs is a vector and the order in
1420 // which the accesses of each memory access list (MAL) are stored in this
1421 // vector is reversed.
1422 for (MemoryAccess *MA : InvMAs) {
1423 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1424 MAL.reverse();
1425
1426 auto MALIt = MAL.begin();
1427 auto MALEnd = MAL.end();
1428 auto MemAccsIt = MemAccs.begin();
1429 while (MALIt != MALEnd) {
1430 while (*MemAccsIt != *MALIt)
1431 MemAccsIt++;
1432
1433 MALIt++;
1434 MemAccs.erase(MemAccsIt);
1435 }
1436
1437 InstructionToAccess.erase(MA->getAccessInstruction());
1438 delete &MAL;
1439 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001440}
1441
Tobias Grosser75805372011-04-29 06:27:02 +00001442//===----------------------------------------------------------------------===//
1443/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001444
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001445void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001446 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1447 isl_set_free(Context);
1448 Context = NewContext;
1449}
1450
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001451/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1452struct SCEVSensitiveParameterRewriter
1453 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1454 ValueToValueMap &VMap;
1455 ScalarEvolution &SE;
1456
1457public:
1458 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1459 : VMap(VMap), SE(SE) {}
1460
1461 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1462 ValueToValueMap &VMap) {
1463 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1464 return SSPR.visit(E);
1465 }
1466
1467 const SCEV *visit(const SCEV *E) {
1468 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1469 }
1470
1471 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1472
1473 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1474 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1475 }
1476
1477 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1478 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1479 }
1480
1481 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1482 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1483 }
1484
1485 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1486 SmallVector<const SCEV *, 4> Operands;
1487 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1488 Operands.push_back(visit(E->getOperand(i)));
1489 return SE.getAddExpr(Operands);
1490 }
1491
1492 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1493 SmallVector<const SCEV *, 4> Operands;
1494 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1495 Operands.push_back(visit(E->getOperand(i)));
1496 return SE.getMulExpr(Operands);
1497 }
1498
1499 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1500 SmallVector<const SCEV *, 4> Operands;
1501 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1502 Operands.push_back(visit(E->getOperand(i)));
1503 return SE.getSMaxExpr(Operands);
1504 }
1505
1506 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1507 SmallVector<const SCEV *, 4> Operands;
1508 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1509 Operands.push_back(visit(E->getOperand(i)));
1510 return SE.getUMaxExpr(Operands);
1511 }
1512
1513 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1514 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1515 }
1516
1517 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1518 auto *Start = visit(E->getStart());
1519 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1520 visit(E->getStepRecurrence(SE)),
1521 E->getLoop(), SCEV::FlagAnyWrap);
1522 return SE.getAddExpr(Start, AddRec);
1523 }
1524
1525 const SCEV *visitUnknown(const SCEVUnknown *E) {
1526 if (auto *NewValue = VMap.lookup(E->getValue()))
1527 return SE.getUnknown(NewValue);
1528 return E;
1529 }
1530};
1531
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001532const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001533 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001534}
1535
Tobias Grosserabfbe632013-02-05 12:09:06 +00001536void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001537 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001538 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001539
1540 // Normalize the SCEV to get the representing element for an invariant load.
1541 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1542
Tobias Grosser60b54f12011-11-08 15:41:28 +00001543 if (ParameterIds.find(Parameter) != ParameterIds.end())
1544 continue;
1545
1546 int dimension = Parameters.size();
1547
1548 Parameters.push_back(Parameter);
1549 ParameterIds[Parameter] = dimension;
1550 }
1551}
1552
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001553__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001554 // Normalize the SCEV to get the representing element for an invariant load.
1555 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1556
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001557 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001558
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001559 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001560 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001561
Tobias Grosser8f99c162011-11-15 11:38:55 +00001562 std::string ParameterName;
1563
1564 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1565 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001566 ParameterName = Val->getName();
Johannes Doerferte071f6d2015-11-03 16:49:59 +00001567 if (!Val->hasName())
1568 if (LoadInst *LI = dyn_cast<LoadInst>(Val))
1569 ParameterName =
1570 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001571 }
1572
1573 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001574 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001575
Tobias Grosser20532b82014-04-11 17:56:49 +00001576 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1577 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001578}
Tobias Grosser75805372011-04-29 06:27:02 +00001579
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001580isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1581 isl_set *DomainContext = isl_union_set_params(getDomains());
1582 return isl_set_intersect_params(C, DomainContext);
1583}
1584
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001585void Scop::buildBoundaryContext() {
1586 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001587
1588 // The isl_set_complement operation used to create the boundary context
1589 // can possibly become very expensive. We bound the compile time of
1590 // this operation by setting a compute out.
1591 //
1592 // TODO: We can probably get around using isl_set_complement and directly
1593 // AST generate BoundaryContext.
1594 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
1595 isl_ctx_set_max_operations(getIslCtx(), 300000);
1596 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1597
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001598 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001599
Tobias Grossera52b4da2015-11-11 17:59:53 +00001600 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1601 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001602 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001603 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001604
1605 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1606 isl_ctx_reset_operations(getIslCtx());
1607 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001608 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1609}
1610
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001611void Scop::addUserContext() {
1612 if (UserContextStr.empty())
1613 return;
1614
1615 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1616 isl_space *Space = getParamSpace();
1617 if (isl_space_dim(Space, isl_dim_param) !=
1618 isl_set_dim(UserContext, isl_dim_param)) {
1619 auto SpaceStr = isl_space_to_str(Space);
1620 errs() << "Error: the context provided in -polly-context has not the same "
1621 << "number of dimensions than the computed context. Due to this "
1622 << "mismatch, the -polly-context option is ignored. Please provide "
1623 << "the context in the parameter space: " << SpaceStr << ".\n";
1624 free(SpaceStr);
1625 isl_set_free(UserContext);
1626 isl_space_free(Space);
1627 return;
1628 }
1629
1630 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1631 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1632 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1633
1634 if (strcmp(NameContext, NameUserContext) != 0) {
1635 auto SpaceStr = isl_space_to_str(Space);
1636 errs() << "Error: the name of dimension " << i
1637 << " provided in -polly-context "
1638 << "is '" << NameUserContext << "', but the name in the computed "
1639 << "context is '" << NameContext
1640 << "'. Due to this name mismatch, "
1641 << "the -polly-context option is ignored. Please provide "
1642 << "the context in the parameter space: " << SpaceStr << ".\n";
1643 free(SpaceStr);
1644 isl_set_free(UserContext);
1645 isl_space_free(Space);
1646 return;
1647 }
1648
1649 UserContext =
1650 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1651 isl_space_get_dim_id(Space, isl_dim_param, i));
1652 }
1653
1654 Context = isl_set_intersect(Context, UserContext);
1655 isl_space_free(Space);
1656}
1657
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001658void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001659 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1660
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001661 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001662 for (LoadInst *LInst : RIL) {
1663 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1664
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001665 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001666 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001667 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001668 continue;
1669 }
1670
1671 ClassRep = LInst;
1672 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1673 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001674 }
1675}
1676
Tobias Grosser6be480c2011-11-08 15:41:13 +00001677void Scop::buildContext() {
1678 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001679 Context = isl_set_universe(isl_space_copy(Space));
1680 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001681}
1682
Tobias Grosser18daaca2012-05-22 10:47:27 +00001683void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001684 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001685 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001686
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001687 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001688
Johannes Doerferte7044942015-02-24 11:58:30 +00001689 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001690 }
1691}
1692
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001693void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001694 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001695 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001696
Tobias Grosser083d3d32014-06-28 08:59:45 +00001697 for (const auto &ParamID : ParameterIds) {
1698 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001699 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001700 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001701 }
1702
1703 // Align the parameters of all data structures to the model.
1704 Context = isl_set_align_params(Context, Space);
1705
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001706 for (ScopStmt &Stmt : *this)
1707 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001708}
1709
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001710static __isl_give isl_set *
1711simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1712 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001713 // If we modelt all blocks in the SCoP that have side effects we can simplify
1714 // the context with the constraints that are needed for anything to be
1715 // executed at all. However, if we have error blocks in the SCoP we already
1716 // assumed some parameter combinations cannot occure and removed them from the
1717 // domains, thus we cannot use the remaining domain to simplify the
1718 // assumptions.
1719 if (!S.hasErrorBlock()) {
1720 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1721 AssumptionContext =
1722 isl_set_gist_params(AssumptionContext, DomainParameters);
1723 }
1724
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001725 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1726 return AssumptionContext;
1727}
1728
1729void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001730 // The parameter constraints of the iteration domains give us a set of
1731 // constraints that need to hold for all cases where at least a single
1732 // statement iteration is executed in the whole scop. We now simplify the
1733 // assumed context under the assumption that such constraints hold and at
1734 // least a single statement iteration is executed. For cases where no
1735 // statement instances are executed, the assumptions we have taken about
1736 // the executed code do not matter and can be changed.
1737 //
1738 // WARNING: This only holds if the assumptions we have taken do not reduce
1739 // the set of statement instances that are executed. Otherwise we
1740 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001741 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001742 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001743 // performed. In such a case, modifying the run-time conditions and
1744 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001745 // to not be executed.
1746 //
1747 // Example:
1748 //
1749 // When delinearizing the following code:
1750 //
1751 // for (long i = 0; i < 100; i++)
1752 // for (long j = 0; j < m; j++)
1753 // A[i+p][j] = 1.0;
1754 //
1755 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001756 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001757 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001758 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1759 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001760}
1761
Johannes Doerfertb164c792014-09-18 11:17:17 +00001762/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001763static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001764 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1765 isl_pw_multi_aff *MinPMA, *MaxPMA;
1766 isl_pw_aff *LastDimAff;
1767 isl_aff *OneAff;
1768 unsigned Pos;
1769
Johannes Doerfert9143d672014-09-27 11:02:39 +00001770 // Restrict the number of parameters involved in the access as the lexmin/
1771 // lexmax computation will take too long if this number is high.
1772 //
1773 // Experiments with a simple test case using an i7 4800MQ:
1774 //
1775 // #Parameters involved | Time (in sec)
1776 // 6 | 0.01
1777 // 7 | 0.04
1778 // 8 | 0.12
1779 // 9 | 0.40
1780 // 10 | 1.54
1781 // 11 | 6.78
1782 // 12 | 30.38
1783 //
1784 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1785 unsigned InvolvedParams = 0;
1786 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1787 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1788 InvolvedParams++;
1789
1790 if (InvolvedParams > RunTimeChecksMaxParameters) {
1791 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001792 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001793 }
1794 }
1795
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001796 Set = isl_set_remove_divs(Set);
1797
Johannes Doerfertb164c792014-09-18 11:17:17 +00001798 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1799 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1800
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001801 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1802 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1803
Johannes Doerfertb164c792014-09-18 11:17:17 +00001804 // Adjust the last dimension of the maximal access by one as we want to
1805 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1806 // we test during code generation might now point after the end of the
1807 // allocated array but we will never dereference it anyway.
1808 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1809 "Assumed at least one output dimension");
1810 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1811 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1812 OneAff = isl_aff_zero_on_domain(
1813 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1814 OneAff = isl_aff_add_constant_si(OneAff, 1);
1815 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1816 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1817
1818 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1819
1820 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001821 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001822}
1823
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001824static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1825 isl_set *Domain = MA->getStatement()->getDomain();
1826 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1827 return isl_set_reset_tuple_id(Domain);
1828}
1829
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001830/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1831static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001832 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001833 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001834
1835 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1836 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001837 Locations = isl_union_set_coalesce(Locations);
1838 Locations = isl_union_set_detect_equalities(Locations);
1839 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001840 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001841 isl_union_set_free(Locations);
1842 return Valid;
1843}
1844
Johannes Doerfert96425c22015-08-30 21:13:53 +00001845/// @brief Helper to treat non-affine regions and basic blocks the same.
1846///
1847///{
1848
1849/// @brief Return the block that is the representing block for @p RN.
1850static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1851 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1852 : RN->getNodeAs<BasicBlock>();
1853}
1854
1855/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001856static inline BasicBlock *
1857getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001858 if (RN->isSubRegion()) {
1859 assert(idx == 0);
1860 return RN->getNodeAs<Region>()->getExit();
1861 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001862 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001863}
1864
1865/// @brief Return the smallest loop surrounding @p RN.
1866static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1867 if (!RN->isSubRegion())
1868 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1869
1870 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1871 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1872 while (L && NonAffineSubRegion->contains(L))
1873 L = L->getParentLoop();
1874 return L;
1875}
1876
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001877static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1878 if (!RN->isSubRegion())
1879 return 1;
1880
1881 unsigned NumBlocks = 0;
1882 Region *R = RN->getNodeAs<Region>();
1883 for (auto BB : R->blocks()) {
1884 (void)BB;
1885 NumBlocks++;
1886 }
1887 return NumBlocks;
1888}
1889
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001890static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1891 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001892 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001893 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001894 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001895 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001896 return true;
1897 return false;
1898}
1899
Johannes Doerfert96425c22015-08-30 21:13:53 +00001900///}
1901
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001902static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1903 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001904 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001905 isl_id *DimId =
1906 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1907 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1908}
1909
Johannes Doerfert96425c22015-08-30 21:13:53 +00001910isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1911 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1912 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001913 return getDomainConditions(BB);
1914}
1915
1916isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1917 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001918 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001919}
1920
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001921void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001922
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001923 auto *EntryBB = R->getEntry();
1924 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1925 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001926
1927 Loop *L = LI.getLoopFor(EntryBB);
1928 while (LD-- >= 0) {
1929 S = addDomainDimId(S, LD + 1, L);
1930 L = L->getParentLoop();
1931 }
1932
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001933 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001934
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001935 if (SD.isNonAffineSubRegion(R, R))
1936 return;
1937
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001938 buildDomainsWithBranchConstraints(R);
1939 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001940}
1941
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001942void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001943 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001944
1945 // To create the domain for each block in R we iterate over all blocks and
1946 // subregions in R and propagate the conditions under which the current region
1947 // element is executed. To this end we iterate in reverse post order over R as
1948 // it ensures that we first visit all predecessors of a region node (either a
1949 // basic block or a subregion) before we visit the region node itself.
1950 // Initially, only the domain for the SCoP region entry block is set and from
1951 // there we propagate the current domain to all successors, however we add the
1952 // condition that the successor is actually executed next.
1953 // As we are only interested in non-loop carried constraints here we can
1954 // simply skip loop back edges.
1955
1956 ReversePostOrderTraversal<Region *> RTraversal(R);
1957 for (auto *RN : RTraversal) {
1958
1959 // Recurse for affine subregions but go on for basic blocks and non-affine
1960 // subregions.
1961 if (RN->isSubRegion()) {
1962 Region *SubRegion = RN->getNodeAs<Region>();
1963 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001964 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001965 continue;
1966 }
1967 }
1968
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001969 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001970 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00001971
Johannes Doerfert96425c22015-08-30 21:13:53 +00001972 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001973 TerminatorInst *TI = BB->getTerminator();
1974
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001975 if (isa<UnreachableInst>(TI))
1976 continue;
1977
Johannes Doerfertf5673802015-10-01 23:48:18 +00001978 isl_set *Domain = DomainMap.lookup(BB);
1979 if (!Domain) {
1980 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1981 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001982 continue;
1983 }
1984
Johannes Doerfert96425c22015-08-30 21:13:53 +00001985 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001986
1987 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1988 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1989
1990 // Build the condition sets for the successor nodes of the current region
1991 // node. If it is a non-affine subregion we will always execute the single
1992 // exit node, hence the single entry node domain is the condition set. For
1993 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001994 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001995 if (RN->isSubRegion())
1996 ConditionSets.push_back(isl_set_copy(Domain));
1997 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001998 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001999
2000 // Now iterate over the successors and set their initial domain based on
2001 // their condition set. We skip back edges here and have to be careful when
2002 // we leave a loop not to keep constraints over a dimension that doesn't
2003 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002004 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002005 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002006 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002007 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002008
2009 // Skip back edges.
2010 if (DT.dominates(SuccBB, BB)) {
2011 isl_set_free(CondSet);
2012 continue;
2013 }
2014
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002015 // Do not adjust the number of dimensions if we enter a boxed loop or are
2016 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002017 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002018 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002019 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2020 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2021 SuccBBLoop = SuccBBLoop->getParentLoop();
2022
2023 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002024
2025 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2026 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2027 // and enter a new one we need to drop the old constraints.
2028 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002029 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002030 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002031 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2032 isl_set_n_dim(CondSet) - LoopDepthDiff,
2033 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002034 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002035 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002036 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002037 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002038 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002039 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002040 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2041 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002042 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002043 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002044 }
2045
2046 // Set the domain for the successor or merge it with an existing domain in
2047 // case there are multiple paths (without loop back edges) to the
2048 // successor block.
2049 isl_set *&SuccDomain = DomainMap[SuccBB];
2050 if (!SuccDomain)
2051 SuccDomain = CondSet;
2052 else
2053 SuccDomain = isl_set_union(SuccDomain, CondSet);
2054
2055 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002056 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2057 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002058 }
2059 }
2060}
2061
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002062/// @brief Return the domain for @p BB wrt @p DomainMap.
2063///
2064/// This helper function will lookup @p BB in @p DomainMap but also handle the
2065/// case where @p BB is contained in a non-affine subregion using the region
2066/// tree obtained by @p RI.
2067static __isl_give isl_set *
2068getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2069 RegionInfo &RI) {
2070 auto DIt = DomainMap.find(BB);
2071 if (DIt != DomainMap.end())
2072 return isl_set_copy(DIt->getSecond());
2073
2074 Region *R = RI.getRegionFor(BB);
2075 while (R->getEntry() == BB)
2076 R = R->getParent();
2077 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2078}
2079
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002080void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002081 // Iterate over the region R and propagate the domain constrains from the
2082 // predecessors to the current node. In contrast to the
2083 // buildDomainsWithBranchConstraints function, this one will pull the domain
2084 // information from the predecessors instead of pushing it to the successors.
2085 // Additionally, we assume the domains to be already present in the domain
2086 // map here. However, we iterate again in reverse post order so we know all
2087 // predecessors have been visited before a block or non-affine subregion is
2088 // visited.
2089
2090 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2091 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
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 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002102 continue;
2103 }
2104 }
2105
Johannes Doerfertf5673802015-10-01 23:48:18 +00002106 // Get the domain for the current block and check if it was initialized or
2107 // not. The only way it was not is if this block is only reachable via error
2108 // blocks, thus will not be executed under the assumptions we make. Such
2109 // blocks have to be skipped as their predecessors might not have domains
2110 // either. It would not benefit us to compute the domain anyway, only the
2111 // domains of the error blocks that are reachable from non-error blocks
2112 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002113 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002114 isl_set *&Domain = DomainMap[BB];
2115 if (!Domain) {
2116 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2117 << ", it is only reachable from error blocks.\n");
2118 DomainMap.erase(BB);
2119 continue;
2120 }
2121 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2122
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002123 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2124 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2125
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002126 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2127 for (auto *PredBB : predecessors(BB)) {
2128
2129 // Skip backedges
2130 if (DT.dominates(BB, PredBB))
2131 continue;
2132
2133 isl_set *PredBBDom = nullptr;
2134
2135 // Handle the SCoP entry block with its outside predecessors.
2136 if (!getRegion().contains(PredBB))
2137 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2138
2139 if (!PredBBDom) {
2140 // Determine the loop depth of the predecessor and adjust its domain to
2141 // the domain of the current block. This can mean we have to:
2142 // o) Drop a dimension if this block is the exit of a loop, not the
2143 // header of a new loop and the predecessor was part of the loop.
2144 // o) Add an unconstrainted new dimension if this block is the header
2145 // of a loop and the predecessor is not part of it.
2146 // o) Drop the information about the innermost loop dimension when the
2147 // predecessor and the current block are surrounded by different
2148 // loops in the same depth.
2149 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2150 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2151 while (BoxedLoops.count(PredBBLoop))
2152 PredBBLoop = PredBBLoop->getParentLoop();
2153
2154 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002155 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002156 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002157 PredBBDom = isl_set_project_out(
2158 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2159 LoopDepthDiff);
2160 else if (PredBBLoopDepth < BBLoopDepth) {
2161 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002162 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002163 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2164 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002165 PredBBDom = isl_set_drop_constraints_involving_dims(
2166 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002167 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002168 }
2169
2170 PredDom = isl_set_union(PredDom, PredBBDom);
2171 }
2172
2173 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002174 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002175
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002176 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002177 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002178
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002179 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002180 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002181 IsOptimized = true;
2182 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2183 addAssumption(isl_set_complement(DomPar));
2184 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002185 }
2186}
2187
2188/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2189/// is incremented by one and all other dimensions are equal, e.g.,
2190/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2191/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2192static __isl_give isl_map *
2193createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2194 auto *MapSpace = isl_space_map_from_set(SetSpace);
2195 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2196 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2197 if (u != Dim)
2198 NextIterationMap =
2199 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2200 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2201 C = isl_constraint_set_constant_si(C, 1);
2202 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2203 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2204 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2205 return NextIterationMap;
2206}
2207
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002208void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002209 int LoopDepth = getRelativeLoopDepth(L);
2210 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002211
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002212 BasicBlock *HeaderBB = L->getHeader();
2213 assert(DomainMap.count(HeaderBB));
2214 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002215
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002216 isl_map *NextIterationMap =
2217 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002218
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002219 isl_set *UnionBackedgeCondition =
2220 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002221
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002222 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2223 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002224
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002225 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002226
2227 // If the latch is only reachable via error statements we skip it.
2228 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2229 if (!LatchBBDom)
2230 continue;
2231
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002232 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002233
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002234 TerminatorInst *TI = LatchBB->getTerminator();
2235 BranchInst *BI = dyn_cast<BranchInst>(TI);
2236 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002237 BackedgeCondition = isl_set_copy(LatchBBDom);
2238 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002239 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002240 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002241 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002242
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002243 // Free the non back edge condition set as we do not need it.
2244 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002245
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002246 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002247 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002248
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002249 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2250 assert(LatchLoopDepth >= LoopDepth);
2251 BackedgeCondition =
2252 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2253 LatchLoopDepth - LoopDepth);
2254 UnionBackedgeCondition =
2255 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002256 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002257
2258 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2259 for (int i = 0; i < LoopDepth; i++)
2260 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2261
2262 isl_set *UnionBackedgeConditionComplement =
2263 isl_set_complement(UnionBackedgeCondition);
2264 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2265 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2266 UnionBackedgeConditionComplement =
2267 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2268 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2269 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2270
2271 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2272 HeaderBBDom = Parts.second;
2273
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002274 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2275 // the bounded assumptions to the context as they are already implied by the
2276 // <nsw> tag.
2277 if (Affinator.hasNSWAddRecForLoop(L)) {
2278 isl_set_free(Parts.first);
2279 return;
2280 }
2281
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002282 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2283 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002284 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002285}
2286
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002287void Scop::buildAliasChecks(AliasAnalysis &AA) {
2288 if (!PollyUseRuntimeAliasChecks)
2289 return;
2290
2291 if (buildAliasGroups(AA))
2292 return;
2293
2294 // If a problem occurs while building the alias groups we need to delete
2295 // this SCoP and pretend it wasn't valid in the first place. To this end
2296 // we make the assumed context infeasible.
2297 addAssumption(isl_set_empty(getParamSpace()));
2298
2299 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2300 << " could not be created as the number of parameters involved "
2301 "is too high. The SCoP will be "
2302 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2303 "the maximal number of parameters but be advised that the "
2304 "compile time might increase exponentially.\n\n");
2305}
2306
Johannes Doerfert9143d672014-09-27 11:02:39 +00002307bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002308 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002309 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002310 // for all memory accesses inside the SCoP.
2311 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002312 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002313 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002314 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002315 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002316 // if their access domains intersect, otherwise they are in different
2317 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002318 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002319 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002320 // and maximal accesses to each array of a group in read only and non
2321 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002322 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2323
2324 AliasSetTracker AST(AA);
2325
2326 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002327 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002328 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002329
2330 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002331 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002332 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2333 isl_set_free(StmtDomain);
2334 if (StmtDomainEmpty)
2335 continue;
2336
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002337 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002338 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002339 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002340 if (!MA->isRead())
2341 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002342 Instruction *Acc = MA->getAccessInstruction();
2343 PtrToAcc[getPointerOperand(*Acc)] = MA;
2344 AST.add(Acc);
2345 }
2346 }
2347
2348 SmallVector<AliasGroupTy, 4> AliasGroups;
2349 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002350 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002351 continue;
2352 AliasGroupTy AG;
2353 for (auto PR : AS)
2354 AG.push_back(PtrToAcc[PR.getValue()]);
2355 assert(AG.size() > 1 &&
2356 "Alias groups should contain at least two accesses");
2357 AliasGroups.push_back(std::move(AG));
2358 }
2359
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002360 // Split the alias groups based on their domain.
2361 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2362 AliasGroupTy NewAG;
2363 AliasGroupTy &AG = AliasGroups[u];
2364 AliasGroupTy::iterator AGI = AG.begin();
2365 isl_set *AGDomain = getAccessDomain(*AGI);
2366 while (AGI != AG.end()) {
2367 MemoryAccess *MA = *AGI;
2368 isl_set *MADomain = getAccessDomain(MA);
2369 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2370 NewAG.push_back(MA);
2371 AGI = AG.erase(AGI);
2372 isl_set_free(MADomain);
2373 } else {
2374 AGDomain = isl_set_union(AGDomain, MADomain);
2375 AGI++;
2376 }
2377 }
2378 if (NewAG.size() > 1)
2379 AliasGroups.push_back(std::move(NewAG));
2380 isl_set_free(AGDomain);
2381 }
2382
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002383 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002384 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2385 for (AliasGroupTy &AG : AliasGroups) {
2386 NonReadOnlyBaseValues.clear();
2387 ReadOnlyPairs.clear();
2388
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002389 if (AG.size() < 2) {
2390 AG.clear();
2391 continue;
2392 }
2393
Johannes Doerfert13771732014-10-01 12:40:46 +00002394 for (auto II = AG.begin(); II != AG.end();) {
2395 Value *BaseAddr = (*II)->getBaseAddr();
2396 if (HasWriteAccess.count(BaseAddr)) {
2397 NonReadOnlyBaseValues.insert(BaseAddr);
2398 II++;
2399 } else {
2400 ReadOnlyPairs[BaseAddr].insert(*II);
2401 II = AG.erase(II);
2402 }
2403 }
2404
2405 // If we don't have read only pointers check if there are at least two
2406 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002407 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002408 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002409 continue;
2410 }
2411
2412 // If we don't have non read only pointers clear the alias group.
2413 if (NonReadOnlyBaseValues.empty()) {
2414 AG.clear();
2415 continue;
2416 }
2417
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002418 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002419 MinMaxAliasGroups.emplace_back();
2420 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2421 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2422 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2423 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002424
2425 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002426
2427 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002428 for (MemoryAccess *MA : AG)
2429 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002430
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002431 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2432 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002433
2434 // Bail out if the number of values we need to compare is too large.
2435 // This is important as the number of comparisions grows quadratically with
2436 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002437 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2438 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002439 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002440
2441 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002442 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002443 Accesses = isl_union_map_empty(getParamSpace());
2444
2445 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2446 for (MemoryAccess *MA : ReadOnlyPair.second)
2447 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2448
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002449 Valid =
2450 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002451
2452 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002453 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002454 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002455
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002456 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002457}
2458
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002459static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2460 Loop *L = LI.getLoopFor(R.getEntry());
2461 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2462}
2463
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002464static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2465 ScopDetection &SD) {
2466
2467 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2468
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002469 unsigned MinLD = INT_MAX, MaxLD = 0;
2470 for (BasicBlock *BB : R.blocks()) {
2471 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002472 if (!R.contains(L))
2473 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002474 if (BoxedLoops && BoxedLoops->count(L))
2475 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002476 unsigned LD = L->getLoopDepth();
2477 MinLD = std::min(MinLD, LD);
2478 MaxLD = std::max(MaxLD, LD);
2479 }
2480 }
2481
2482 // Handle the case that there is no loop in the SCoP first.
2483 if (MaxLD == 0)
2484 return 1;
2485
2486 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2487 assert(MaxLD >= MinLD &&
2488 "Maximal loop depth was smaller than mininaml loop depth?");
2489 return MaxLD - MinLD + 1;
2490}
2491
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002492Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002493 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002494 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002495 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2496 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002497 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2498 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2499 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2500 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002501
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002502void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002503 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002504 buildInvariantEquivalenceClasses();
2505
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002506 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002507
Michael Krusecac948e2015-10-02 13:53:07 +00002508 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002509 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002510 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002511 if (Stmts.empty())
2512 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002513
Michael Krusecac948e2015-10-02 13:53:07 +00002514 // The ScopStmts now have enough information to initialize themselves.
2515 for (ScopStmt &Stmt : Stmts)
2516 Stmt.init();
2517
2518 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002519 Loop *L = getLoopSurroundingRegion(R, LI);
2520 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002521 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002522 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002523
Tobias Grosser8286b832015-11-02 11:29:32 +00002524 if (isl_set_is_empty(AssumedContext))
2525 return;
2526
2527 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002528 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002529 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002530 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002531 buildBoundaryContext();
2532 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002533 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002534
2535 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002536 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002537}
2538
2539Scop::~Scop() {
2540 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002541 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002542 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002543 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002544
Johannes Doerfert96425c22015-08-30 21:13:53 +00002545 for (auto It : DomainMap)
2546 isl_set_free(It.second);
2547
Johannes Doerfertb164c792014-09-18 11:17:17 +00002548 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002549 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002550 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002551 isl_pw_multi_aff_free(MMA.first);
2552 isl_pw_multi_aff_free(MMA.second);
2553 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002554 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002555 isl_pw_multi_aff_free(MMA.first);
2556 isl_pw_multi_aff_free(MMA.second);
2557 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002558 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002559
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002560 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002561 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002562}
2563
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002564void Scop::updateAccessDimensionality() {
2565 for (auto &Stmt : *this)
2566 for (auto &Access : Stmt)
2567 Access->updateDimensionality();
2568}
2569
Michael Krusecac948e2015-10-02 13:53:07 +00002570void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002571 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2572 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002573 RegionNode *RN = Stmt.isRegionStmt()
2574 ? Stmt.getRegion()->getNode()
2575 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002576
Johannes Doerferteca9e892015-11-03 16:54:49 +00002577 bool RemoveStmt = StmtIt->isEmpty();
2578 if (!RemoveStmt)
2579 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2580 if (!RemoveStmt)
2581 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002582
Johannes Doerferteca9e892015-11-03 16:54:49 +00002583 // Remove read only statements only after invariant loop hoisting.
2584 if (!RemoveStmt && !RemoveIgnoredStmts) {
2585 bool OnlyRead = true;
2586 for (MemoryAccess *MA : Stmt) {
2587 if (MA->isRead())
2588 continue;
2589
2590 OnlyRead = false;
2591 break;
2592 }
2593
2594 RemoveStmt = OnlyRead;
2595 }
2596
2597 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002598 // Remove the statement because it is unnecessary.
2599 if (Stmt.isRegionStmt())
2600 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2601 StmtMap.erase(BB);
2602 else
2603 StmtMap.erase(Stmt.getBasicBlock());
2604
2605 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002606 continue;
2607 }
2608
Michael Krusecac948e2015-10-02 13:53:07 +00002609 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002610 }
2611}
2612
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002613const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2614 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2615 if (!LInst)
2616 return nullptr;
2617
2618 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2619 LInst = cast<LoadInst>(Rep);
2620
2621 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2622 for (auto &IAClass : InvariantEquivClasses)
2623 if (PointerSCEV == std::get<0>(IAClass))
2624 return &IAClass;
2625
2626 return nullptr;
2627}
2628
2629void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2630
2631 // Get the context under which the statement is executed.
2632 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2633 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2634 DomainCtx = isl_set_detect_equalities(DomainCtx);
2635 DomainCtx = isl_set_coalesce(DomainCtx);
2636
2637 // Project out all parameters that relate to loads in the statement. Otherwise
2638 // we could have cyclic dependences on the constraints under which the
2639 // hoisted loads are executed and we could not determine an order in which to
2640 // pre-load them. This happens because not only lower bounds are part of the
2641 // domain but also upper bounds.
2642 for (MemoryAccess *MA : InvMAs) {
2643 Instruction *AccInst = MA->getAccessInstruction();
2644 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002645 SetVector<Value *> Values;
2646 for (const SCEV *Parameter : Parameters) {
2647 Values.clear();
2648 findValues(Parameter, Values);
2649 if (!Values.count(AccInst))
2650 continue;
2651
2652 if (isl_id *ParamId = getIdForParam(Parameter)) {
2653 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2654 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2655 isl_id_free(ParamId);
2656 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002657 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002658 }
2659 }
2660
2661 for (MemoryAccess *MA : InvMAs) {
2662 // Check for another invariant access that accesses the same location as
2663 // MA and if found consolidate them. Otherwise create a new equivalence
2664 // class at the end of InvariantEquivClasses.
2665 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2666 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2667
2668 bool Consolidated = false;
2669 for (auto &IAClass : InvariantEquivClasses) {
2670 if (PointerSCEV != std::get<0>(IAClass))
2671 continue;
2672
2673 Consolidated = true;
2674
2675 // Add MA to the list of accesses that are in this class.
2676 auto &MAs = std::get<1>(IAClass);
2677 MAs.push_front(MA);
2678
2679 // Unify the execution context of the class and this statement.
2680 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002681 if (IAClassDomainCtx)
2682 IAClassDomainCtx = isl_set_coalesce(
2683 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2684 else
2685 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002686 break;
2687 }
2688
2689 if (Consolidated)
2690 continue;
2691
2692 // If we did not consolidate MA, thus did not find an equivalence class
2693 // for it, we create a new one.
2694 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2695 isl_set_copy(DomainCtx));
2696 }
2697
2698 isl_set_free(DomainCtx);
2699}
2700
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002701void Scop::hoistInvariantLoads() {
2702 isl_union_map *Writes = getWrites();
2703 for (ScopStmt &Stmt : *this) {
2704
2705 // TODO: Loads that are not loop carried, hence are in a statement with
2706 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002707 // currently "hoist" them anyway. This is necessary because we allow
2708 // them to be treated as parameters (e.g., in conditions) and our code
2709 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002710
Johannes Doerfert8930f482015-10-02 14:51:00 +00002711 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2712 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002713 isl_set *Domain = Stmt.getDomain();
2714 MemoryAccessList InvMAs;
2715
2716 for (MemoryAccess *MA : Stmt) {
2717 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2718 continue;
2719
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002720 // Skip accesses that have an invariant base pointer which is defined but
2721 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2722 // returns a pointer that is used as a base address. However, as we want
2723 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002724 // the region if it is also a memory access. Each ScopArrayInfo object
2725 // that has a base pointer origin has a base pointer that is loaded and
2726 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002727 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002728 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002729 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002730 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2731 SAI = BasePtrOriginSAI;
2732
2733 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2734 if (R.contains(BasePtrInst))
2735 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002736
Johannes Doerfert8930f482015-10-02 14:51:00 +00002737 // Skip accesses in non-affine subregions as they might not be executed
2738 // under the same condition as the entry of the non-affine subregion.
2739 if (BB != MA->getAccessInstruction()->getParent())
2740 continue;
2741
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002742 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002743
2744 // Skip accesses that have an empty access relation. These can be caused
2745 // by multiple offsets with a type cast in-between that cause the overall
2746 // byte offset to be not divisible by the new types sizes.
2747 if (isl_map_is_empty(AccessRelation)) {
2748 isl_map_free(AccessRelation);
2749 continue;
2750 }
2751
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002752 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2753 Stmt.getNumIterators())) {
2754 isl_map_free(AccessRelation);
2755 continue;
2756 }
2757
2758 AccessRelation =
2759 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2760 isl_set *AccessRange = isl_map_range(AccessRelation);
2761
2762 isl_union_map *Written = isl_union_map_intersect_range(
2763 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2764 bool IsWritten = !isl_union_map_is_empty(Written);
2765 isl_union_map_free(Written);
2766
2767 if (IsWritten)
2768 continue;
2769
2770 InvMAs.push_front(MA);
2771 }
2772
2773 // We inserted invariant accesses always in the front but need them to be
2774 // sorted in a "natural order". The statements are already sorted in reverse
2775 // post order and that suffices for the accesses too. The reason we require
2776 // an order in the first place is the dependences between invariant loads
2777 // that can be caused by indirect loads.
2778 InvMAs.reverse();
2779
2780 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002781 Stmt.removeMemoryAccesses(InvMAs);
2782 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002783
2784 isl_set_free(Domain);
2785 }
2786 isl_union_map_free(Writes);
2787
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002788 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002789 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002790 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002791 assert(LI && getRegion().contains(LI));
2792 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2793 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2794 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2795 << ") is required to be invariant but was not marked as "
2796 "such. SCoP for "
2797 << getRegion() << " will be dropped\n\n");
2798 addAssumption(isl_set_empty(getParamSpace()));
2799 return;
2800 }
2801 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002802}
2803
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002804const ScopArrayInfo *
2805Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002806 ArrayRef<const SCEV *> Sizes,
2807 ScopArrayInfo::ARRAYKIND Kind) {
2808 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002809 if (!SAI) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002810 SAI.reset(
2811 new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002812 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002813 // In case of mismatching array sizes, we bail out by setting the run-time
2814 // context to false.
2815 if (!SAI->updateSizes(Sizes))
2816 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002817 }
Tobias Grosserab671442015-05-23 05:58:27 +00002818 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002819}
2820
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002821const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2822 ScopArrayInfo::ARRAYKIND Kind) {
2823 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002824 assert(SAI && "No ScopArrayInfo available for this base pointer");
2825 return SAI;
2826}
2827
Tobias Grosser74394f02013-01-14 22:40:23 +00002828std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002829std::string Scop::getAssumedContextStr() const {
2830 return stringFromIslObj(AssumedContext);
2831}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002832std::string Scop::getBoundaryContextStr() const {
2833 return stringFromIslObj(BoundaryContext);
2834}
Tobias Grosser75805372011-04-29 06:27:02 +00002835
2836std::string Scop::getNameStr() const {
2837 std::string ExitName, EntryName;
2838 raw_string_ostream ExitStr(ExitName);
2839 raw_string_ostream EntryStr(EntryName);
2840
Tobias Grosserf240b482014-01-09 10:42:15 +00002841 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002842 EntryStr.str();
2843
2844 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002845 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002846 ExitStr.str();
2847 } else
2848 ExitName = "FunctionExit";
2849
2850 return EntryName + "---" + ExitName;
2851}
2852
Tobias Grosser74394f02013-01-14 22:40:23 +00002853__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002854__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002855 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002856}
2857
Tobias Grossere86109f2013-10-29 21:05:49 +00002858__isl_give isl_set *Scop::getAssumedContext() const {
2859 return isl_set_copy(AssumedContext);
2860}
2861
Johannes Doerfert43788c52015-08-20 05:58:56 +00002862__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2863 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002864 RuntimeCheckContext =
2865 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2866 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002867 return RuntimeCheckContext;
2868}
2869
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002870bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002871 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002872 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002873 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2874 isl_set_free(RuntimeCheckContext);
2875 return IsFeasible;
2876}
2877
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002878void Scop::addAssumption(__isl_take isl_set *Set) {
2879 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002880 isl_basic_set_list *List = isl_set_get_basic_set_list(AssumedContext);
2881 int NSets = isl_basic_set_list_n_basic_set(List);
2882 isl_basic_set_list_free(List);
2883
2884 if (NSets >= MaxDisjunctsAssumed) {
2885 isl_space *Space = isl_set_get_space(AssumedContext);
2886 isl_set_free(AssumedContext);
2887 AssumedContext = isl_set_universe(Space);
2888 }
2889
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002890 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002891}
2892
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002893__isl_give isl_set *Scop::getBoundaryContext() const {
2894 return isl_set_copy(BoundaryContext);
2895}
2896
Tobias Grosser75805372011-04-29 06:27:02 +00002897void Scop::printContext(raw_ostream &OS) const {
2898 OS << "Context:\n";
2899
2900 if (!Context) {
2901 OS.indent(4) << "n/a\n\n";
2902 return;
2903 }
2904
2905 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002906
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002907 OS.indent(4) << "Assumed Context:\n";
2908 if (!AssumedContext) {
2909 OS.indent(4) << "n/a\n\n";
2910 return;
2911 }
2912
2913 OS.indent(4) << getAssumedContextStr() << "\n";
2914
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002915 OS.indent(4) << "Boundary Context:\n";
2916 if (!BoundaryContext) {
2917 OS.indent(4) << "n/a\n\n";
2918 return;
2919 }
2920
2921 OS.indent(4) << getBoundaryContextStr() << "\n";
2922
Tobias Grosser083d3d32014-06-28 08:59:45 +00002923 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002924 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002925 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2926 }
Tobias Grosser75805372011-04-29 06:27:02 +00002927}
2928
Johannes Doerfertb164c792014-09-18 11:17:17 +00002929void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002930 int noOfGroups = 0;
2931 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002932 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002933 noOfGroups += 1;
2934 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002935 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002936 }
2937
Tobias Grosserbb853c22015-07-25 12:31:03 +00002938 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002939 if (MinMaxAliasGroups.empty()) {
2940 OS.indent(8) << "n/a\n";
2941 return;
2942 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002943
Tobias Grosserbb853c22015-07-25 12:31:03 +00002944 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002945
2946 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002947 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002948 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002949 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002950 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2951 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002952 }
2953 OS << " ]]\n";
2954 }
2955
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002956 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002957 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002958 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002959 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002960 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2961 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002962 }
2963 OS << " ]]\n";
2964 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002965 }
2966}
2967
Tobias Grosser75805372011-04-29 06:27:02 +00002968void Scop::printStatements(raw_ostream &OS) const {
2969 OS << "Statements {\n";
2970
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002971 for (const ScopStmt &Stmt : *this)
2972 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002973
2974 OS.indent(4) << "}\n";
2975}
2976
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002977void Scop::printArrayInfo(raw_ostream &OS) const {
2978 OS << "Arrays {\n";
2979
Tobias Grosserab671442015-05-23 05:58:27 +00002980 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002981 Array.second->print(OS);
2982
2983 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002984
2985 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2986
2987 for (auto &Array : arrays())
2988 Array.second->print(OS, /* SizeAsPwAff */ true);
2989
2990 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002991}
2992
Tobias Grosser75805372011-04-29 06:27:02 +00002993void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002994 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2995 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002996 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002997 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002998 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002999 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003000 const auto &MAs = std::get<1>(IAClass);
3001 if (MAs.empty()) {
3002 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003003 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003004 MAs.front()->print(OS);
3005 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003006 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003007 }
3008 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003009 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003010 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003011 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003012 printStatements(OS.indent(4));
3013}
3014
3015void Scop::dump() const { print(dbgs()); }
3016
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003017isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003018
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003019__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3020 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003021}
3022
Tobias Grosser808cd692015-07-14 09:33:13 +00003023__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003024 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003025
Tobias Grosser808cd692015-07-14 09:33:13 +00003026 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003027 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003028
3029 return Domain;
3030}
3031
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003032__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003033 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003034
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003035 for (ScopStmt &Stmt : *this) {
3036 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003037 if (!MA->isMustWrite())
3038 continue;
3039
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003040 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003041 isl_map *AccessDomain = MA->getAccessRelation();
3042 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3043 Write = isl_union_map_add_map(Write, AccessDomain);
3044 }
3045 }
3046 return isl_union_map_coalesce(Write);
3047}
3048
3049__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003050 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003051
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003052 for (ScopStmt &Stmt : *this) {
3053 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003054 if (!MA->isMayWrite())
3055 continue;
3056
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003057 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003058 isl_map *AccessDomain = MA->getAccessRelation();
3059 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3060 Write = isl_union_map_add_map(Write, AccessDomain);
3061 }
3062 }
3063 return isl_union_map_coalesce(Write);
3064}
3065
Tobias Grosser37eb4222014-02-20 21:43:54 +00003066__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003067 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003068
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003069 for (ScopStmt &Stmt : *this) {
3070 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003071 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003072 continue;
3073
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003074 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003075 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003076 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3077 Write = isl_union_map_add_map(Write, AccessDomain);
3078 }
3079 }
3080 return isl_union_map_coalesce(Write);
3081}
3082
3083__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003084 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003085
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003086 for (ScopStmt &Stmt : *this) {
3087 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003088 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003089 continue;
3090
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003091 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003092 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003093
3094 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3095 Read = isl_union_map_add_map(Read, AccessDomain);
3096 }
3097 }
3098 return isl_union_map_coalesce(Read);
3099}
3100
Tobias Grosser808cd692015-07-14 09:33:13 +00003101__isl_give isl_union_map *Scop::getSchedule() const {
3102 auto Tree = getScheduleTree();
3103 auto S = isl_schedule_get_map(Tree);
3104 isl_schedule_free(Tree);
3105 return S;
3106}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003107
Tobias Grosser808cd692015-07-14 09:33:13 +00003108__isl_give isl_schedule *Scop::getScheduleTree() const {
3109 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3110 getDomains());
3111}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003112
Tobias Grosser808cd692015-07-14 09:33:13 +00003113void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3114 auto *S = isl_schedule_from_domain(getDomains());
3115 S = isl_schedule_insert_partial_schedule(
3116 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3117 isl_schedule_free(Schedule);
3118 Schedule = S;
3119}
3120
3121void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3122 isl_schedule_free(Schedule);
3123 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003124}
3125
3126bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3127 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003128 for (ScopStmt &Stmt : *this) {
3129 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003130 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3131 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3132
3133 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3134 isl_union_set_free(StmtDomain);
3135 isl_union_set_free(NewStmtDomain);
3136 continue;
3137 }
3138
3139 Changed = true;
3140
3141 isl_union_set_free(StmtDomain);
3142 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3143
3144 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003145 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003146 isl_union_set_free(NewStmtDomain);
3147 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003148 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003149 }
3150 isl_union_set_free(Domain);
3151 return Changed;
3152}
3153
Tobias Grosser75805372011-04-29 06:27:02 +00003154ScalarEvolution *Scop::getSE() const { return SE; }
3155
Johannes Doerfertf5673802015-10-01 23:48:18 +00003156bool Scop::isIgnored(RegionNode *RN) {
3157 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003158
Johannes Doerfertf5673802015-10-01 23:48:18 +00003159 // Check if there are accesses contained.
3160 bool ContainsAccesses = false;
3161 if (!RN->isSubRegion())
3162 ContainsAccesses = getAccessFunctions(BB);
3163 else
3164 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3165 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3166 if (!ContainsAccesses)
3167 return true;
3168
3169 // Check for reachability via non-error blocks.
3170 if (!DomainMap.count(BB))
3171 return true;
3172
3173 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003174 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003175 return true;
3176
3177 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003178}
3179
Tobias Grosser808cd692015-07-14 09:33:13 +00003180struct MapToDimensionDataTy {
3181 int N;
3182 isl_union_pw_multi_aff *Res;
3183};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003184
Tobias Grosser808cd692015-07-14 09:33:13 +00003185// @brief Create a function that maps the elements of 'Set' to its N-th
3186// dimension.
3187//
3188// The result is added to 'User->Res'.
3189//
3190// @param Set The input set.
3191// @param N The dimension to map to.
3192//
3193// @returns Zero if no error occurred, non-zero otherwise.
3194static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3195 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3196 int Dim;
3197 isl_space *Space;
3198 isl_pw_multi_aff *PMA;
3199
3200 Dim = isl_set_dim(Set, isl_dim_set);
3201 Space = isl_set_get_space(Set);
3202 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3203 Dim - Data->N);
3204 if (Data->N > 1)
3205 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3206 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3207
3208 isl_set_free(Set);
3209
3210 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003211}
3212
Tobias Grosser808cd692015-07-14 09:33:13 +00003213// @brief Create a function that maps the elements of Domain to their Nth
3214// dimension.
3215//
3216// @param Domain The set of elements to map.
3217// @param N The dimension to map to.
3218static __isl_give isl_multi_union_pw_aff *
3219mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003220 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3221 isl_union_set_free(Domain);
3222 return nullptr;
3223 }
3224
Tobias Grosser808cd692015-07-14 09:33:13 +00003225 struct MapToDimensionDataTy Data;
3226 isl_space *Space;
3227
3228 Space = isl_union_set_get_space(Domain);
3229 Data.N = N;
3230 Data.Res = isl_union_pw_multi_aff_empty(Space);
3231 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3232 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3233
3234 isl_union_set_free(Domain);
3235 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3236}
3237
Michael Kruse9d080092015-09-11 21:41:48 +00003238ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003239 ScopStmt *Stmt;
3240 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003241 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003242 Stmt = &Stmts.back();
3243 StmtMap[BB] = Stmt;
3244 } else {
3245 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003246 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003247 Stmt = &Stmts.back();
3248 for (BasicBlock *BB : R->blocks())
3249 StmtMap[BB] = Stmt;
3250 }
3251 return Stmt;
3252}
3253
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003254void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003255 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003256 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003257
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003258 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003259 Loop *L = getLoopSurroundingRegion(*R, LI);
3260 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003261 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003262 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003263 auto *UDomain = isl_union_set_from_set(Domain);
3264 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003265 LSchedulePair.first = StmtSchedule;
3266 return;
3267 }
3268
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003269 ReversePostOrderTraversal<Region *> RTraversal(R);
3270 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003271
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003272 if (RN->isSubRegion()) {
3273 Region *SubRegion = RN->getNodeAs<Region>();
3274 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003275 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003276 continue;
3277 }
Tobias Grosser75805372011-04-29 06:27:02 +00003278 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003279
3280 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003281 if (!getRegion().contains(L))
3282 L = getLoopSurroundingRegion(getRegion(), LI);
3283
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003284 int LD = getRelativeLoopDepth(L);
3285 auto &LSchedulePair = LoopSchedules[L];
3286 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3287
Michael Krusecac948e2015-10-02 13:53:07 +00003288 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3289 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3290 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003291 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3292 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3293 LSchedulePair.first =
3294 combineInSequence(LSchedulePair.first, StmtSchedule);
3295 }
3296
3297 unsigned NumVisited = LSchedulePair.second;
3298 while (L && NumVisited == L->getNumBlocks()) {
3299 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3300 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3301 LSchedulePair.first =
3302 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3303
3304 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003305
3306 // Either we have a proper loop and we also build a schedule for the
3307 // parent loop or we have a infinite loop that does not have a proper
3308 // parent loop. In the former case this conditional will be skipped, in
3309 // the latter case however we will break here as we do not build a domain
3310 // nor a schedule for a infinite loop.
3311 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3312 if (!LoopSchedules.count(PL))
3313 break;
3314
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003315 auto &PSchedulePair = LoopSchedules[PL];
3316 PSchedulePair.first =
3317 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3318 PSchedulePair.second += NumVisited;
3319
3320 L = PL;
3321 NumVisited = PSchedulePair.second;
3322 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003323 }
Tobias Grosser75805372011-04-29 06:27:02 +00003324}
3325
Johannes Doerfert7c494212014-10-31 23:13:39 +00003326ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003327 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003328 if (StmtMapIt == StmtMap.end())
3329 return nullptr;
3330 return StmtMapIt->second;
3331}
3332
Johannes Doerfert96425c22015-08-30 21:13:53 +00003333int Scop::getRelativeLoopDepth(const Loop *L) const {
3334 Loop *OuterLoop =
3335 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3336 if (!OuterLoop)
3337 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003338 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3339}
3340
Michael Krused868b5d2015-09-10 15:25:24 +00003341void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003342 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003343
3344 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3345 // true, are not modeled as ordinary PHI nodes as they are not part of the
3346 // region. However, we model the operands in the predecessor blocks that are
3347 // part of the region as regular scalar accesses.
3348
3349 // If we can synthesize a PHI we can skip it, however only if it is in
3350 // the region. If it is not it can only be in the exit block of the region.
3351 // In this case we model the operands but not the PHI itself.
3352 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3353 return;
3354
3355 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3356 // detection. Hence, the PHI is a load of a new memory location in which the
3357 // incoming value was written at the end of the incoming basic block.
3358 bool OnlyNonAffineSubRegionOperands = true;
3359 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3360 Value *Op = PHI->getIncomingValue(u);
3361 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3362
3363 // Do not build scalar dependences inside a non-affine subregion.
3364 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3365 continue;
3366
3367 OnlyNonAffineSubRegionOperands = false;
3368
3369 if (!R.contains(OpBB))
3370 continue;
3371
3372 Instruction *OpI = dyn_cast<Instruction>(Op);
3373 if (OpI) {
3374 BasicBlock *OpIBB = OpI->getParent();
3375 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3376 // we have to insert a scalar dependence from the definition of OpI to
3377 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003378 if (scop->getStmtForBasicBlock(OpIBB) !=
3379 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003380 addScalarReadAccess(OpI, PHI, OpBB);
3381 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003382 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003383 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003384 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003385 }
3386
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003387 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003388 }
3389
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003390 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3391 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003392 }
3393}
3394
Michael Krused868b5d2015-09-10 15:25:24 +00003395bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3396 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003397 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3398 if (isIgnoredIntrinsic(Inst))
3399 return false;
3400
3401 bool AnyCrossStmtUse = false;
3402 BasicBlock *ParentBB = Inst->getParent();
3403
3404 for (User *U : Inst->users()) {
3405 Instruction *UI = dyn_cast<Instruction>(U);
3406
3407 // Ignore the strange user
3408 if (UI == 0)
3409 continue;
3410
3411 BasicBlock *UseParent = UI->getParent();
3412
Tobias Grosserbaffa092015-10-24 20:55:27 +00003413 // Ignore basic block local uses. A value that is defined in a scop, but
3414 // used in a PHI node in the same basic block does not count as basic block
3415 // local, as for such cases a control flow edge is passed between definition
3416 // and use.
3417 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003418 continue;
3419
Michael Krusef714d472015-11-05 13:18:43 +00003420 // Uses by PHI nodes in the entry node count as external uses in case the
3421 // use is through an incoming block that is itself not contained in the
3422 // region.
3423 if (R->getEntry() == UseParent) {
3424 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3425 bool ExternalUse = false;
3426 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3427 if (PHI->getIncomingValue(i) == Inst &&
3428 !R->contains(PHI->getIncomingBlock(i))) {
3429 ExternalUse = true;
3430 break;
3431 }
3432 }
3433
3434 if (ExternalUse) {
3435 AnyCrossStmtUse = true;
3436 continue;
3437 }
3438 }
3439 }
3440
Michael Kruse7bf39442015-09-10 12:46:52 +00003441 // Do not build scalar dependences inside a non-affine subregion.
3442 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3443 continue;
3444
Michael Kruse01cb3792015-10-17 21:07:08 +00003445 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003446 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003447 //
3448 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003449 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3450 // the control flow a different value will be assigned to the PHI node. In
3451 // case this is the case, there is no need to create an additional normal
3452 // scalar dependence. Hence, bail out before we register an "out-of-region"
3453 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003454 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3455 !R->getExitingBlock())
3456 continue;
3457
Michael Kruse7bf39442015-09-10 12:46:52 +00003458 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003459 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003460 AnyCrossStmtUse = true;
3461 continue;
3462 }
3463
3464 // If the instruction can be synthesized and the user is in the region
3465 // we do not need to add scalar dependences.
3466 if (canSynthesizeInst)
3467 continue;
3468
3469 // No need to translate these scalar dependences into polyhedral form,
3470 // because synthesizable scalars can be generated by the code generator.
3471 if (canSynthesize(UI, LI, SE, R))
3472 continue;
3473
3474 // Skip PHI nodes in the region as they handle their operands on their own.
3475 if (isa<PHINode>(UI))
3476 continue;
3477
3478 // Now U is used in another statement.
3479 AnyCrossStmtUse = true;
3480
3481 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003482 // Use the def instruction as base address of the MemoryAccess, so that it
3483 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003484 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003485 }
3486
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003487 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003488 for (Value *Op : Inst->operands()) {
3489 if (canSynthesize(Op, LI, SE, R))
3490 continue;
3491
3492 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3493 if (R->contains(OpInst))
3494 continue;
3495
3496 if (isa<Constant>(Op))
3497 continue;
3498
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003499 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003500 }
3501 }
3502
3503 return AnyCrossStmtUse;
3504}
3505
3506extern MapInsnToMemAcc InsnToMemAcc;
3507
Michael Krusee2bccbb2015-09-18 19:59:43 +00003508void ScopInfo::buildMemoryAccess(
3509 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003510 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3511 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003512 unsigned Size;
3513 Type *SizeType;
3514 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003515 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003516
3517 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3518 SizeType = Load->getType();
3519 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003520 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003521 Val = Load;
3522 } else {
3523 StoreInst *Store = cast<StoreInst>(Inst);
3524 SizeType = Store->getValueOperand()->getType();
3525 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003526 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003527 Val = Store->getValueOperand();
3528 }
3529
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003530 auto Address = getPointerOperand(*Inst);
3531
3532 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003533 const SCEVUnknown *BasePointer =
3534 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3535
3536 assert(BasePointer && "Could not find base pointer");
3537 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3538
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003539 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3540 auto NewAddress = Address;
3541 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3542 auto Src = BitCast->getOperand(0);
3543 auto SrcTy = Src->getType();
3544 auto DstTy = BitCast->getType();
3545 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3546 NewAddress = Src;
3547 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003548
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003549 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3550 std::vector<const SCEV *> Subscripts;
3551 std::vector<int> Sizes;
3552 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3553 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003554
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003555 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003556
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003557 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003558 for (auto Subscript : Subscripts) {
3559 InvariantLoadsSetTy AccessILS;
3560 AllAffineSubcripts =
3561 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3562
3563 for (LoadInst *LInst : AccessILS)
3564 if (!ScopRIL.count(LInst))
3565 AllAffineSubcripts = false;
3566
3567 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003568 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003569 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003570
3571 if (AllAffineSubcripts && Sizes.size() > 0) {
3572 for (auto V : Sizes)
3573 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3574 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003575 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003576 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003577
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003578 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3579 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003580 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003581 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003582 }
3583 }
3584
Michael Kruse7bf39442015-09-10 12:46:52 +00003585 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003586 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003587 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3588 AccItr->second.DelinearizedSubscripts,
3589 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003590 return;
3591 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003592
3593 // Check if the access depends on a loop contained in a non-affine subregion.
3594 bool isVariantInNonAffineLoop = false;
3595 if (BoxedLoops) {
3596 SetVector<const Loop *> Loops;
3597 findLoops(AccessFunction, Loops);
3598 for (const Loop *L : Loops)
3599 if (BoxedLoops->count(L))
3600 isVariantInNonAffineLoop = true;
3601 }
3602
Johannes Doerfert09e36972015-10-07 20:17:36 +00003603 InvariantLoadsSetTy AccessILS;
3604 bool IsAffine =
3605 !isVariantInNonAffineLoop &&
3606 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3607
3608 for (LoadInst *LInst : AccessILS)
3609 if (!ScopRIL.count(LInst))
3610 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003611
Michael Krusecaac2b62015-09-26 15:51:44 +00003612 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003613 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003614 const SCEV *SizeSCEV =
3615 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003616
Michael Krusee2bccbb2015-09-18 19:59:43 +00003617 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3618 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003619
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003620 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3621 ArrayRef<const SCEV *>(AccessFunction),
3622 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003623}
3624
Michael Krused868b5d2015-09-10 15:25:24 +00003625void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003626
3627 if (SD->isNonAffineSubRegion(&SR, &R)) {
3628 for (BasicBlock *BB : SR.blocks())
3629 buildAccessFunctions(R, *BB, &SR);
3630 return;
3631 }
3632
3633 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3634 if (I->isSubRegion())
3635 buildAccessFunctions(R, *I->getNodeAs<Region>());
3636 else
3637 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3638}
3639
Michael Krusecac948e2015-10-02 13:53:07 +00003640void ScopInfo::buildStmts(Region &SR) {
3641 Region *R = getRegion();
3642
3643 if (SD->isNonAffineSubRegion(&SR, R)) {
3644 scop->addScopStmt(nullptr, &SR);
3645 return;
3646 }
3647
3648 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3649 if (I->isSubRegion())
3650 buildStmts(*I->getNodeAs<Region>());
3651 else
3652 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3653}
3654
Michael Krused868b5d2015-09-10 15:25:24 +00003655void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3656 Region *NonAffineSubRegion,
3657 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003658 Loop *L = LI->getLoopFor(&BB);
3659
3660 // The set of loops contained in non-affine subregions that are part of R.
3661 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3662
Johannes Doerfert09e36972015-10-07 20:17:36 +00003663 // The set of loads that are required to be invariant.
3664 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3665
Michael Kruse7bf39442015-09-10 12:46:52 +00003666 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003667 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003668
3669 PHINode *PHI = dyn_cast<PHINode>(Inst);
3670 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003671 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003672
3673 // For the exit block we stop modeling after the last PHI node.
3674 if (!PHI && IsExitBlock)
3675 break;
3676
Johannes Doerfert09e36972015-10-07 20:17:36 +00003677 // TODO: At this point we only know that elements of ScopRIL have to be
3678 // invariant and will be hoisted for the SCoP to be processed. Though,
3679 // there might be other invariant accesses that will be hoisted and
3680 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003681 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003682 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003683
3684 if (isIgnoredIntrinsic(Inst))
3685 continue;
3686
Johannes Doerfert09e36972015-10-07 20:17:36 +00003687 // Do not build scalar dependences for required invariant loads as we will
3688 // hoist them later on anyway or drop the SCoP if we cannot.
3689 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3690 continue;
3691
Michael Kruse7bf39442015-09-10 12:46:52 +00003692 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003693 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003694 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003695 }
3696 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003697}
Michael Kruse7bf39442015-09-10 12:46:52 +00003698
Michael Kruse2d0ece92015-09-24 11:41:21 +00003699void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3700 MemoryAccess::AccessType Type,
3701 Value *BaseAddress, unsigned ElemBytes,
3702 bool Affine, Value *AccessValue,
3703 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003704 ArrayRef<const SCEV *> Sizes,
3705 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003706 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3707
3708 // Do not create a memory access for anything not in the SCoP. It would be
3709 // ignored anyway.
3710 if (!Stmt)
3711 return;
3712
Michael Krusee2bccbb2015-09-18 19:59:43 +00003713 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003714 Value *BaseAddr = BaseAddress;
3715 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3716
Michael Krusecac948e2015-10-02 13:53:07 +00003717 bool isApproximated =
3718 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3719 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3720 Type = MemoryAccess::MAY_WRITE;
3721
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003722 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003723 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003724 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003725}
3726
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003727void ScopInfo::addExplicitAccess(
3728 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3729 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3730 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3731 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3732 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3733 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003734 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3735 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003736}
3737void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3738 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3739 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003740 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003741}
3742void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3743 assert(!isa<PHINode>(User));
3744 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3745 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003746 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003747}
3748void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3749 BasicBlock *UserBB) {
3750 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003751 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3752 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003753}
3754void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3755 Value *IncomingValue, bool IsExitBlock) {
3756 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3757 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3758 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003759 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003760}
3761void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3762 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003763 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3764 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003765}
3766
Michael Kruse76e924d2015-09-30 09:16:07 +00003767void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003768 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003769 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003770
Michael Krusecac948e2015-10-02 13:53:07 +00003771 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003772 buildAccessFunctions(R, R);
3773
3774 // In case the region does not have an exiting block we will later (during
3775 // code generation) split the exit block. This will move potential PHI nodes
3776 // from the current exit block into the new region exiting block. Hence, PHI
3777 // nodes that are at this point not part of the region will be.
3778 // To handle these PHI nodes later we will now model their operands as scalar
3779 // accesses. Note that we do not model anything in the exit block if we have
3780 // an exiting block in the region, as there will not be any splitting later.
3781 if (!R.getExitingBlock())
3782 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3783
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003784 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003785}
3786
Michael Krused868b5d2015-09-10 15:25:24 +00003787void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003788 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003789 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003790 return;
3791 }
3792
Michael Kruse9d080092015-09-11 21:41:48 +00003793 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003794}
3795
Michael Krused868b5d2015-09-10 15:25:24 +00003796void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003797 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003798 if (scop) {
3799 delete scop;
3800 scop = 0;
3801 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003802}
3803
3804//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003805ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003806 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003807 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003808}
3809
3810ScopInfo::~ScopInfo() {
3811 clear();
3812 isl_ctx_free(ctx);
3813}
3814
Tobias Grosser75805372011-04-29 06:27:02 +00003815void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003816 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003817 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003818 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003819 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3820 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003821 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003822 AU.setPreservesAll();
3823}
3824
3825bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003826 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003827
Michael Krused868b5d2015-09-10 15:25:24 +00003828 if (!SD->isMaxRegionInScop(*R))
3829 return false;
3830
3831 Function *F = R->getEntry()->getParent();
3832 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3833 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3834 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3835 TD = &F->getParent()->getDataLayout();
3836 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003837
Michael Kruse76e924d2015-09-30 09:16:07 +00003838 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003839
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003840 DEBUG(scop->print(dbgs()));
3841
Michael Kruseafe06702015-10-02 16:33:27 +00003842 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003843 delete scop;
3844 scop = nullptr;
3845 return false;
3846 }
3847
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003848 // Statistics.
3849 ++ScopFound;
3850 if (scop->getMaxLoopDepth() > 0)
3851 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003852 return false;
3853}
3854
3855char ScopInfo::ID = 0;
3856
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003857Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3858
Tobias Grosser73600b82011-10-08 00:30:40 +00003859INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3860 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003861 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003862INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003863INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003864INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003865INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003866INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003867INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003868INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3869 "Polly - Create polyhedral description of Scops", false,
3870 false)