blob: baa9bc1d6a687ecf88988f1b4b779c9281a4d9a3 [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
1600 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota)
1601 BoundaryContext = isl_set_empty(getParamSpace());
1602
1603 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1604 isl_ctx_reset_operations(getIslCtx());
1605 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001606 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1607}
1608
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001609void Scop::addUserContext() {
1610 if (UserContextStr.empty())
1611 return;
1612
1613 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1614 isl_space *Space = getParamSpace();
1615 if (isl_space_dim(Space, isl_dim_param) !=
1616 isl_set_dim(UserContext, isl_dim_param)) {
1617 auto SpaceStr = isl_space_to_str(Space);
1618 errs() << "Error: the context provided in -polly-context has not the same "
1619 << "number of dimensions than the computed context. Due to this "
1620 << "mismatch, the -polly-context option is ignored. Please provide "
1621 << "the context in the parameter space: " << SpaceStr << ".\n";
1622 free(SpaceStr);
1623 isl_set_free(UserContext);
1624 isl_space_free(Space);
1625 return;
1626 }
1627
1628 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1629 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1630 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1631
1632 if (strcmp(NameContext, NameUserContext) != 0) {
1633 auto SpaceStr = isl_space_to_str(Space);
1634 errs() << "Error: the name of dimension " << i
1635 << " provided in -polly-context "
1636 << "is '" << NameUserContext << "', but the name in the computed "
1637 << "context is '" << NameContext
1638 << "'. Due to this name mismatch, "
1639 << "the -polly-context option is ignored. Please provide "
1640 << "the context in the parameter space: " << SpaceStr << ".\n";
1641 free(SpaceStr);
1642 isl_set_free(UserContext);
1643 isl_space_free(Space);
1644 return;
1645 }
1646
1647 UserContext =
1648 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1649 isl_space_get_dim_id(Space, isl_dim_param, i));
1650 }
1651
1652 Context = isl_set_intersect(Context, UserContext);
1653 isl_space_free(Space);
1654}
1655
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001656void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001657 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1658
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001659 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001660 for (LoadInst *LInst : RIL) {
1661 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1662
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001663 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001664 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001665 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001666 continue;
1667 }
1668
1669 ClassRep = LInst;
1670 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1671 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001672 }
1673}
1674
Tobias Grosser6be480c2011-11-08 15:41:13 +00001675void Scop::buildContext() {
1676 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001677 Context = isl_set_universe(isl_space_copy(Space));
1678 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001679}
1680
Tobias Grosser18daaca2012-05-22 10:47:27 +00001681void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001682 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001683 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001684
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001685 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001686
Johannes Doerferte7044942015-02-24 11:58:30 +00001687 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001688 }
1689}
1690
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001691void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001692 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001693 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001694
Tobias Grosser083d3d32014-06-28 08:59:45 +00001695 for (const auto &ParamID : ParameterIds) {
1696 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001697 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001698 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001699 }
1700
1701 // Align the parameters of all data structures to the model.
1702 Context = isl_set_align_params(Context, Space);
1703
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001704 for (ScopStmt &Stmt : *this)
1705 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001706}
1707
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001708static __isl_give isl_set *
1709simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1710 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001711 // If we modelt all blocks in the SCoP that have side effects we can simplify
1712 // the context with the constraints that are needed for anything to be
1713 // executed at all. However, if we have error blocks in the SCoP we already
1714 // assumed some parameter combinations cannot occure and removed them from the
1715 // domains, thus we cannot use the remaining domain to simplify the
1716 // assumptions.
1717 if (!S.hasErrorBlock()) {
1718 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1719 AssumptionContext =
1720 isl_set_gist_params(AssumptionContext, DomainParameters);
1721 }
1722
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001723 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1724 return AssumptionContext;
1725}
1726
1727void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001728 // The parameter constraints of the iteration domains give us a set of
1729 // constraints that need to hold for all cases where at least a single
1730 // statement iteration is executed in the whole scop. We now simplify the
1731 // assumed context under the assumption that such constraints hold and at
1732 // least a single statement iteration is executed. For cases where no
1733 // statement instances are executed, the assumptions we have taken about
1734 // the executed code do not matter and can be changed.
1735 //
1736 // WARNING: This only holds if the assumptions we have taken do not reduce
1737 // the set of statement instances that are executed. Otherwise we
1738 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001739 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001740 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001741 // performed. In such a case, modifying the run-time conditions and
1742 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001743 // to not be executed.
1744 //
1745 // Example:
1746 //
1747 // When delinearizing the following code:
1748 //
1749 // for (long i = 0; i < 100; i++)
1750 // for (long j = 0; j < m; j++)
1751 // A[i+p][j] = 1.0;
1752 //
1753 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001754 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001755 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001756 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1757 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001758}
1759
Johannes Doerfertb164c792014-09-18 11:17:17 +00001760/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001761static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001762 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1763 isl_pw_multi_aff *MinPMA, *MaxPMA;
1764 isl_pw_aff *LastDimAff;
1765 isl_aff *OneAff;
1766 unsigned Pos;
1767
Johannes Doerfert9143d672014-09-27 11:02:39 +00001768 // Restrict the number of parameters involved in the access as the lexmin/
1769 // lexmax computation will take too long if this number is high.
1770 //
1771 // Experiments with a simple test case using an i7 4800MQ:
1772 //
1773 // #Parameters involved | Time (in sec)
1774 // 6 | 0.01
1775 // 7 | 0.04
1776 // 8 | 0.12
1777 // 9 | 0.40
1778 // 10 | 1.54
1779 // 11 | 6.78
1780 // 12 | 30.38
1781 //
1782 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1783 unsigned InvolvedParams = 0;
1784 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1785 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1786 InvolvedParams++;
1787
1788 if (InvolvedParams > RunTimeChecksMaxParameters) {
1789 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001790 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001791 }
1792 }
1793
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001794 Set = isl_set_remove_divs(Set);
1795
Johannes Doerfertb164c792014-09-18 11:17:17 +00001796 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1797 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1798
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001799 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1800 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1801
Johannes Doerfertb164c792014-09-18 11:17:17 +00001802 // Adjust the last dimension of the maximal access by one as we want to
1803 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1804 // we test during code generation might now point after the end of the
1805 // allocated array but we will never dereference it anyway.
1806 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1807 "Assumed at least one output dimension");
1808 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1809 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1810 OneAff = isl_aff_zero_on_domain(
1811 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1812 OneAff = isl_aff_add_constant_si(OneAff, 1);
1813 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1814 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1815
1816 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1817
1818 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001819 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001820}
1821
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001822static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1823 isl_set *Domain = MA->getStatement()->getDomain();
1824 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1825 return isl_set_reset_tuple_id(Domain);
1826}
1827
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001828/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1829static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001830 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001831 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001832
1833 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1834 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001835 Locations = isl_union_set_coalesce(Locations);
1836 Locations = isl_union_set_detect_equalities(Locations);
1837 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001838 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001839 isl_union_set_free(Locations);
1840 return Valid;
1841}
1842
Johannes Doerfert96425c22015-08-30 21:13:53 +00001843/// @brief Helper to treat non-affine regions and basic blocks the same.
1844///
1845///{
1846
1847/// @brief Return the block that is the representing block for @p RN.
1848static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1849 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1850 : RN->getNodeAs<BasicBlock>();
1851}
1852
1853/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001854static inline BasicBlock *
1855getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001856 if (RN->isSubRegion()) {
1857 assert(idx == 0);
1858 return RN->getNodeAs<Region>()->getExit();
1859 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001860 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001861}
1862
1863/// @brief Return the smallest loop surrounding @p RN.
1864static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1865 if (!RN->isSubRegion())
1866 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1867
1868 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1869 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1870 while (L && NonAffineSubRegion->contains(L))
1871 L = L->getParentLoop();
1872 return L;
1873}
1874
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001875static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1876 if (!RN->isSubRegion())
1877 return 1;
1878
1879 unsigned NumBlocks = 0;
1880 Region *R = RN->getNodeAs<Region>();
1881 for (auto BB : R->blocks()) {
1882 (void)BB;
1883 NumBlocks++;
1884 }
1885 return NumBlocks;
1886}
1887
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001888static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1889 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001890 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001891 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001892 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001893 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001894 return true;
1895 return false;
1896}
1897
Johannes Doerfert96425c22015-08-30 21:13:53 +00001898///}
1899
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001900static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1901 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001902 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001903 isl_id *DimId =
1904 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1905 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1906}
1907
Johannes Doerfert96425c22015-08-30 21:13:53 +00001908isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1909 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1910 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001911 return getDomainConditions(BB);
1912}
1913
1914isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1915 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001916 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001917}
1918
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001919void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001920
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001921 auto *EntryBB = R->getEntry();
1922 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1923 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001924
1925 Loop *L = LI.getLoopFor(EntryBB);
1926 while (LD-- >= 0) {
1927 S = addDomainDimId(S, LD + 1, L);
1928 L = L->getParentLoop();
1929 }
1930
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001931 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001932
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001933 if (SD.isNonAffineSubRegion(R, R))
1934 return;
1935
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001936 buildDomainsWithBranchConstraints(R);
1937 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001938}
1939
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001940void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001941 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001942
1943 // To create the domain for each block in R we iterate over all blocks and
1944 // subregions in R and propagate the conditions under which the current region
1945 // element is executed. To this end we iterate in reverse post order over R as
1946 // it ensures that we first visit all predecessors of a region node (either a
1947 // basic block or a subregion) before we visit the region node itself.
1948 // Initially, only the domain for the SCoP region entry block is set and from
1949 // there we propagate the current domain to all successors, however we add the
1950 // condition that the successor is actually executed next.
1951 // As we are only interested in non-loop carried constraints here we can
1952 // simply skip loop back edges.
1953
1954 ReversePostOrderTraversal<Region *> RTraversal(R);
1955 for (auto *RN : RTraversal) {
1956
1957 // Recurse for affine subregions but go on for basic blocks and non-affine
1958 // subregions.
1959 if (RN->isSubRegion()) {
1960 Region *SubRegion = RN->getNodeAs<Region>();
1961 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001962 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001963 continue;
1964 }
1965 }
1966
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001967 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001968 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00001969
Johannes Doerfert96425c22015-08-30 21:13:53 +00001970 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001971 TerminatorInst *TI = BB->getTerminator();
1972
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001973 if (isa<UnreachableInst>(TI))
1974 continue;
1975
Johannes Doerfertf5673802015-10-01 23:48:18 +00001976 isl_set *Domain = DomainMap.lookup(BB);
1977 if (!Domain) {
1978 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1979 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001980 continue;
1981 }
1982
Johannes Doerfert96425c22015-08-30 21:13:53 +00001983 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001984
1985 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1986 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1987
1988 // Build the condition sets for the successor nodes of the current region
1989 // node. If it is a non-affine subregion we will always execute the single
1990 // exit node, hence the single entry node domain is the condition set. For
1991 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001992 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001993 if (RN->isSubRegion())
1994 ConditionSets.push_back(isl_set_copy(Domain));
1995 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001996 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001997
1998 // Now iterate over the successors and set their initial domain based on
1999 // their condition set. We skip back edges here and have to be careful when
2000 // we leave a loop not to keep constraints over a dimension that doesn't
2001 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002002 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002003 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002004 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002005 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002006
2007 // Skip back edges.
2008 if (DT.dominates(SuccBB, BB)) {
2009 isl_set_free(CondSet);
2010 continue;
2011 }
2012
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002013 // Do not adjust the number of dimensions if we enter a boxed loop or are
2014 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002015 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002016 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002017 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2018 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2019 SuccBBLoop = SuccBBLoop->getParentLoop();
2020
2021 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002022
2023 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2024 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2025 // and enter a new one we need to drop the old constraints.
2026 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002027 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002028 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002029 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2030 isl_set_n_dim(CondSet) - LoopDepthDiff,
2031 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002032 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002033 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002034 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002035 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002036 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002037 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002038 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2039 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002040 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002041 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002042 }
2043
2044 // Set the domain for the successor or merge it with an existing domain in
2045 // case there are multiple paths (without loop back edges) to the
2046 // successor block.
2047 isl_set *&SuccDomain = DomainMap[SuccBB];
2048 if (!SuccDomain)
2049 SuccDomain = CondSet;
2050 else
2051 SuccDomain = isl_set_union(SuccDomain, CondSet);
2052
2053 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002054 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2055 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002056 }
2057 }
2058}
2059
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002060/// @brief Return the domain for @p BB wrt @p DomainMap.
2061///
2062/// This helper function will lookup @p BB in @p DomainMap but also handle the
2063/// case where @p BB is contained in a non-affine subregion using the region
2064/// tree obtained by @p RI.
2065static __isl_give isl_set *
2066getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2067 RegionInfo &RI) {
2068 auto DIt = DomainMap.find(BB);
2069 if (DIt != DomainMap.end())
2070 return isl_set_copy(DIt->getSecond());
2071
2072 Region *R = RI.getRegionFor(BB);
2073 while (R->getEntry() == BB)
2074 R = R->getParent();
2075 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2076}
2077
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002078void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002079 // Iterate over the region R and propagate the domain constrains from the
2080 // predecessors to the current node. In contrast to the
2081 // buildDomainsWithBranchConstraints function, this one will pull the domain
2082 // information from the predecessors instead of pushing it to the successors.
2083 // Additionally, we assume the domains to be already present in the domain
2084 // map here. However, we iterate again in reverse post order so we know all
2085 // predecessors have been visited before a block or non-affine subregion is
2086 // visited.
2087
2088 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2089 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2090
2091 ReversePostOrderTraversal<Region *> RTraversal(R);
2092 for (auto *RN : RTraversal) {
2093
2094 // Recurse for affine subregions but go on for basic blocks and non-affine
2095 // subregions.
2096 if (RN->isSubRegion()) {
2097 Region *SubRegion = RN->getNodeAs<Region>();
2098 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002099 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002100 continue;
2101 }
2102 }
2103
Johannes Doerfertf5673802015-10-01 23:48:18 +00002104 // Get the domain for the current block and check if it was initialized or
2105 // not. The only way it was not is if this block is only reachable via error
2106 // blocks, thus will not be executed under the assumptions we make. Such
2107 // blocks have to be skipped as their predecessors might not have domains
2108 // either. It would not benefit us to compute the domain anyway, only the
2109 // domains of the error blocks that are reachable from non-error blocks
2110 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002111 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002112 isl_set *&Domain = DomainMap[BB];
2113 if (!Domain) {
2114 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2115 << ", it is only reachable from error blocks.\n");
2116 DomainMap.erase(BB);
2117 continue;
2118 }
2119 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2120
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002121 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2122 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2123
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002124 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2125 for (auto *PredBB : predecessors(BB)) {
2126
2127 // Skip backedges
2128 if (DT.dominates(BB, PredBB))
2129 continue;
2130
2131 isl_set *PredBBDom = nullptr;
2132
2133 // Handle the SCoP entry block with its outside predecessors.
2134 if (!getRegion().contains(PredBB))
2135 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2136
2137 if (!PredBBDom) {
2138 // Determine the loop depth of the predecessor and adjust its domain to
2139 // the domain of the current block. This can mean we have to:
2140 // o) Drop a dimension if this block is the exit of a loop, not the
2141 // header of a new loop and the predecessor was part of the loop.
2142 // o) Add an unconstrainted new dimension if this block is the header
2143 // of a loop and the predecessor is not part of it.
2144 // o) Drop the information about the innermost loop dimension when the
2145 // predecessor and the current block are surrounded by different
2146 // loops in the same depth.
2147 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2148 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2149 while (BoxedLoops.count(PredBBLoop))
2150 PredBBLoop = PredBBLoop->getParentLoop();
2151
2152 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002153 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002154 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002155 PredBBDom = isl_set_project_out(
2156 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2157 LoopDepthDiff);
2158 else if (PredBBLoopDepth < BBLoopDepth) {
2159 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002160 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002161 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2162 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002163 PredBBDom = isl_set_drop_constraints_involving_dims(
2164 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002165 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002166 }
2167
2168 PredDom = isl_set_union(PredDom, PredBBDom);
2169 }
2170
2171 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002172 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002173
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002174 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002175 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002176
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002177 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002178 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002179 IsOptimized = true;
2180 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2181 addAssumption(isl_set_complement(DomPar));
2182 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002183 }
2184}
2185
2186/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2187/// is incremented by one and all other dimensions are equal, e.g.,
2188/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2189/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2190static __isl_give isl_map *
2191createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2192 auto *MapSpace = isl_space_map_from_set(SetSpace);
2193 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2194 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2195 if (u != Dim)
2196 NextIterationMap =
2197 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2198 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2199 C = isl_constraint_set_constant_si(C, 1);
2200 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2201 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2202 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2203 return NextIterationMap;
2204}
2205
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002206void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002207 int LoopDepth = getRelativeLoopDepth(L);
2208 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002209
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002210 BasicBlock *HeaderBB = L->getHeader();
2211 assert(DomainMap.count(HeaderBB));
2212 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002213
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002214 isl_map *NextIterationMap =
2215 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002216
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002217 isl_set *UnionBackedgeCondition =
2218 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002219
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002220 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2221 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002222
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002223 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002224
2225 // If the latch is only reachable via error statements we skip it.
2226 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2227 if (!LatchBBDom)
2228 continue;
2229
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002230 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002231
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002232 TerminatorInst *TI = LatchBB->getTerminator();
2233 BranchInst *BI = dyn_cast<BranchInst>(TI);
2234 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002235 BackedgeCondition = isl_set_copy(LatchBBDom);
2236 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002237 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002238 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002239 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002240
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002241 // Free the non back edge condition set as we do not need it.
2242 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002243
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002244 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002245 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002246
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002247 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2248 assert(LatchLoopDepth >= LoopDepth);
2249 BackedgeCondition =
2250 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2251 LatchLoopDepth - LoopDepth);
2252 UnionBackedgeCondition =
2253 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002254 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002255
2256 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2257 for (int i = 0; i < LoopDepth; i++)
2258 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2259
2260 isl_set *UnionBackedgeConditionComplement =
2261 isl_set_complement(UnionBackedgeCondition);
2262 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2263 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2264 UnionBackedgeConditionComplement =
2265 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2266 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2267 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2268
2269 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2270 HeaderBBDom = Parts.second;
2271
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002272 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2273 // the bounded assumptions to the context as they are already implied by the
2274 // <nsw> tag.
2275 if (Affinator.hasNSWAddRecForLoop(L)) {
2276 isl_set_free(Parts.first);
2277 return;
2278 }
2279
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002280 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2281 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002282 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002283}
2284
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002285void Scop::buildAliasChecks(AliasAnalysis &AA) {
2286 if (!PollyUseRuntimeAliasChecks)
2287 return;
2288
2289 if (buildAliasGroups(AA))
2290 return;
2291
2292 // If a problem occurs while building the alias groups we need to delete
2293 // this SCoP and pretend it wasn't valid in the first place. To this end
2294 // we make the assumed context infeasible.
2295 addAssumption(isl_set_empty(getParamSpace()));
2296
2297 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2298 << " could not be created as the number of parameters involved "
2299 "is too high. The SCoP will be "
2300 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2301 "the maximal number of parameters but be advised that the "
2302 "compile time might increase exponentially.\n\n");
2303}
2304
Johannes Doerfert9143d672014-09-27 11:02:39 +00002305bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002306 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002307 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002308 // for all memory accesses inside the SCoP.
2309 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002310 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002311 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002312 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002313 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002314 // if their access domains intersect, otherwise they are in different
2315 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002316 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002317 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002318 // and maximal accesses to each array of a group in read only and non
2319 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002320 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2321
2322 AliasSetTracker AST(AA);
2323
2324 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002325 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002326 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002327
2328 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002329 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002330 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2331 isl_set_free(StmtDomain);
2332 if (StmtDomainEmpty)
2333 continue;
2334
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002335 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002336 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002337 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002338 if (!MA->isRead())
2339 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002340 Instruction *Acc = MA->getAccessInstruction();
2341 PtrToAcc[getPointerOperand(*Acc)] = MA;
2342 AST.add(Acc);
2343 }
2344 }
2345
2346 SmallVector<AliasGroupTy, 4> AliasGroups;
2347 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002348 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002349 continue;
2350 AliasGroupTy AG;
2351 for (auto PR : AS)
2352 AG.push_back(PtrToAcc[PR.getValue()]);
2353 assert(AG.size() > 1 &&
2354 "Alias groups should contain at least two accesses");
2355 AliasGroups.push_back(std::move(AG));
2356 }
2357
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002358 // Split the alias groups based on their domain.
2359 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2360 AliasGroupTy NewAG;
2361 AliasGroupTy &AG = AliasGroups[u];
2362 AliasGroupTy::iterator AGI = AG.begin();
2363 isl_set *AGDomain = getAccessDomain(*AGI);
2364 while (AGI != AG.end()) {
2365 MemoryAccess *MA = *AGI;
2366 isl_set *MADomain = getAccessDomain(MA);
2367 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2368 NewAG.push_back(MA);
2369 AGI = AG.erase(AGI);
2370 isl_set_free(MADomain);
2371 } else {
2372 AGDomain = isl_set_union(AGDomain, MADomain);
2373 AGI++;
2374 }
2375 }
2376 if (NewAG.size() > 1)
2377 AliasGroups.push_back(std::move(NewAG));
2378 isl_set_free(AGDomain);
2379 }
2380
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002381 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002382 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2383 for (AliasGroupTy &AG : AliasGroups) {
2384 NonReadOnlyBaseValues.clear();
2385 ReadOnlyPairs.clear();
2386
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002387 if (AG.size() < 2) {
2388 AG.clear();
2389 continue;
2390 }
2391
Johannes Doerfert13771732014-10-01 12:40:46 +00002392 for (auto II = AG.begin(); II != AG.end();) {
2393 Value *BaseAddr = (*II)->getBaseAddr();
2394 if (HasWriteAccess.count(BaseAddr)) {
2395 NonReadOnlyBaseValues.insert(BaseAddr);
2396 II++;
2397 } else {
2398 ReadOnlyPairs[BaseAddr].insert(*II);
2399 II = AG.erase(II);
2400 }
2401 }
2402
2403 // If we don't have read only pointers check if there are at least two
2404 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002405 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002406 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002407 continue;
2408 }
2409
2410 // If we don't have non read only pointers clear the alias group.
2411 if (NonReadOnlyBaseValues.empty()) {
2412 AG.clear();
2413 continue;
2414 }
2415
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002416 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002417 MinMaxAliasGroups.emplace_back();
2418 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2419 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2420 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2421 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002422
2423 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002424
2425 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002426 for (MemoryAccess *MA : AG)
2427 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002428
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002429 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2430 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002431
2432 // Bail out if the number of values we need to compare is too large.
2433 // This is important as the number of comparisions grows quadratically with
2434 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002435 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2436 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002437 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002438
2439 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002440 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002441 Accesses = isl_union_map_empty(getParamSpace());
2442
2443 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2444 for (MemoryAccess *MA : ReadOnlyPair.second)
2445 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2446
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002447 Valid =
2448 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002449
2450 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002451 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002452 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002453
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002454 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002455}
2456
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002457static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2458 Loop *L = LI.getLoopFor(R.getEntry());
2459 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2460}
2461
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002462static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2463 ScopDetection &SD) {
2464
2465 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2466
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002467 unsigned MinLD = INT_MAX, MaxLD = 0;
2468 for (BasicBlock *BB : R.blocks()) {
2469 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002470 if (!R.contains(L))
2471 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002472 if (BoxedLoops && BoxedLoops->count(L))
2473 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002474 unsigned LD = L->getLoopDepth();
2475 MinLD = std::min(MinLD, LD);
2476 MaxLD = std::max(MaxLD, LD);
2477 }
2478 }
2479
2480 // Handle the case that there is no loop in the SCoP first.
2481 if (MaxLD == 0)
2482 return 1;
2483
2484 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2485 assert(MaxLD >= MinLD &&
2486 "Maximal loop depth was smaller than mininaml loop depth?");
2487 return MaxLD - MinLD + 1;
2488}
2489
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002490Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002491 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002492 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002493 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2494 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002495 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2496 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2497 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2498 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002499
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002500void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002501 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002502 buildInvariantEquivalenceClasses();
2503
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002504 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002505
Michael Krusecac948e2015-10-02 13:53:07 +00002506 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002507 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002508 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002509 if (Stmts.empty())
2510 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002511
Michael Krusecac948e2015-10-02 13:53:07 +00002512 // The ScopStmts now have enough information to initialize themselves.
2513 for (ScopStmt &Stmt : Stmts)
2514 Stmt.init();
2515
2516 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002517 Loop *L = getLoopSurroundingRegion(R, LI);
2518 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002519 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002520 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002521
Tobias Grosser8286b832015-11-02 11:29:32 +00002522 if (isl_set_is_empty(AssumedContext))
2523 return;
2524
2525 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002526 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002527 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002528 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002529 buildBoundaryContext();
2530 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002531 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002532
2533 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002534 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002535}
2536
2537Scop::~Scop() {
2538 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002539 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002540 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002541 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002542
Johannes Doerfert96425c22015-08-30 21:13:53 +00002543 for (auto It : DomainMap)
2544 isl_set_free(It.second);
2545
Johannes Doerfertb164c792014-09-18 11:17:17 +00002546 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002547 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002548 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002549 isl_pw_multi_aff_free(MMA.first);
2550 isl_pw_multi_aff_free(MMA.second);
2551 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002552 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002553 isl_pw_multi_aff_free(MMA.first);
2554 isl_pw_multi_aff_free(MMA.second);
2555 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002556 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002557
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002558 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002559 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002560}
2561
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002562void Scop::updateAccessDimensionality() {
2563 for (auto &Stmt : *this)
2564 for (auto &Access : Stmt)
2565 Access->updateDimensionality();
2566}
2567
Michael Krusecac948e2015-10-02 13:53:07 +00002568void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002569 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2570 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002571 RegionNode *RN = Stmt.isRegionStmt()
2572 ? Stmt.getRegion()->getNode()
2573 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002574
Johannes Doerferteca9e892015-11-03 16:54:49 +00002575 bool RemoveStmt = StmtIt->isEmpty();
2576 if (!RemoveStmt)
2577 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2578 if (!RemoveStmt)
2579 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002580
Johannes Doerferteca9e892015-11-03 16:54:49 +00002581 // Remove read only statements only after invariant loop hoisting.
2582 if (!RemoveStmt && !RemoveIgnoredStmts) {
2583 bool OnlyRead = true;
2584 for (MemoryAccess *MA : Stmt) {
2585 if (MA->isRead())
2586 continue;
2587
2588 OnlyRead = false;
2589 break;
2590 }
2591
2592 RemoveStmt = OnlyRead;
2593 }
2594
2595 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002596 // Remove the statement because it is unnecessary.
2597 if (Stmt.isRegionStmt())
2598 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2599 StmtMap.erase(BB);
2600 else
2601 StmtMap.erase(Stmt.getBasicBlock());
2602
2603 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002604 continue;
2605 }
2606
Michael Krusecac948e2015-10-02 13:53:07 +00002607 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002608 }
2609}
2610
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002611const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2612 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2613 if (!LInst)
2614 return nullptr;
2615
2616 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2617 LInst = cast<LoadInst>(Rep);
2618
2619 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2620 for (auto &IAClass : InvariantEquivClasses)
2621 if (PointerSCEV == std::get<0>(IAClass))
2622 return &IAClass;
2623
2624 return nullptr;
2625}
2626
2627void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2628
2629 // Get the context under which the statement is executed.
2630 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2631 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2632 DomainCtx = isl_set_detect_equalities(DomainCtx);
2633 DomainCtx = isl_set_coalesce(DomainCtx);
2634
2635 // Project out all parameters that relate to loads in the statement. Otherwise
2636 // we could have cyclic dependences on the constraints under which the
2637 // hoisted loads are executed and we could not determine an order in which to
2638 // pre-load them. This happens because not only lower bounds are part of the
2639 // domain but also upper bounds.
2640 for (MemoryAccess *MA : InvMAs) {
2641 Instruction *AccInst = MA->getAccessInstruction();
2642 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002643 SetVector<Value *> Values;
2644 for (const SCEV *Parameter : Parameters) {
2645 Values.clear();
2646 findValues(Parameter, Values);
2647 if (!Values.count(AccInst))
2648 continue;
2649
2650 if (isl_id *ParamId = getIdForParam(Parameter)) {
2651 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2652 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2653 isl_id_free(ParamId);
2654 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002655 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002656 }
2657 }
2658
2659 for (MemoryAccess *MA : InvMAs) {
2660 // Check for another invariant access that accesses the same location as
2661 // MA and if found consolidate them. Otherwise create a new equivalence
2662 // class at the end of InvariantEquivClasses.
2663 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2664 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2665
2666 bool Consolidated = false;
2667 for (auto &IAClass : InvariantEquivClasses) {
2668 if (PointerSCEV != std::get<0>(IAClass))
2669 continue;
2670
2671 Consolidated = true;
2672
2673 // Add MA to the list of accesses that are in this class.
2674 auto &MAs = std::get<1>(IAClass);
2675 MAs.push_front(MA);
2676
2677 // Unify the execution context of the class and this statement.
2678 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002679 if (IAClassDomainCtx)
2680 IAClassDomainCtx = isl_set_coalesce(
2681 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2682 else
2683 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002684 break;
2685 }
2686
2687 if (Consolidated)
2688 continue;
2689
2690 // If we did not consolidate MA, thus did not find an equivalence class
2691 // for it, we create a new one.
2692 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2693 isl_set_copy(DomainCtx));
2694 }
2695
2696 isl_set_free(DomainCtx);
2697}
2698
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002699void Scop::hoistInvariantLoads() {
2700 isl_union_map *Writes = getWrites();
2701 for (ScopStmt &Stmt : *this) {
2702
2703 // TODO: Loads that are not loop carried, hence are in a statement with
2704 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002705 // currently "hoist" them anyway. This is necessary because we allow
2706 // them to be treated as parameters (e.g., in conditions) and our code
2707 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002708
Johannes Doerfert8930f482015-10-02 14:51:00 +00002709 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2710 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002711 isl_set *Domain = Stmt.getDomain();
2712 MemoryAccessList InvMAs;
2713
2714 for (MemoryAccess *MA : Stmt) {
2715 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2716 continue;
2717
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002718 // Skip accesses that have an invariant base pointer which is defined but
2719 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2720 // returns a pointer that is used as a base address. However, as we want
2721 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002722 // the region if it is also a memory access. Each ScopArrayInfo object
2723 // that has a base pointer origin has a base pointer that is loaded and
2724 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002725 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002726 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002727 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002728 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2729 SAI = BasePtrOriginSAI;
2730
2731 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2732 if (R.contains(BasePtrInst))
2733 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002734
Johannes Doerfert8930f482015-10-02 14:51:00 +00002735 // Skip accesses in non-affine subregions as they might not be executed
2736 // under the same condition as the entry of the non-affine subregion.
2737 if (BB != MA->getAccessInstruction()->getParent())
2738 continue;
2739
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002740 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002741
2742 // Skip accesses that have an empty access relation. These can be caused
2743 // by multiple offsets with a type cast in-between that cause the overall
2744 // byte offset to be not divisible by the new types sizes.
2745 if (isl_map_is_empty(AccessRelation)) {
2746 isl_map_free(AccessRelation);
2747 continue;
2748 }
2749
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002750 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2751 Stmt.getNumIterators())) {
2752 isl_map_free(AccessRelation);
2753 continue;
2754 }
2755
2756 AccessRelation =
2757 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2758 isl_set *AccessRange = isl_map_range(AccessRelation);
2759
2760 isl_union_map *Written = isl_union_map_intersect_range(
2761 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2762 bool IsWritten = !isl_union_map_is_empty(Written);
2763 isl_union_map_free(Written);
2764
2765 if (IsWritten)
2766 continue;
2767
2768 InvMAs.push_front(MA);
2769 }
2770
2771 // We inserted invariant accesses always in the front but need them to be
2772 // sorted in a "natural order". The statements are already sorted in reverse
2773 // post order and that suffices for the accesses too. The reason we require
2774 // an order in the first place is the dependences between invariant loads
2775 // that can be caused by indirect loads.
2776 InvMAs.reverse();
2777
2778 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002779 Stmt.removeMemoryAccesses(InvMAs);
2780 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002781
2782 isl_set_free(Domain);
2783 }
2784 isl_union_map_free(Writes);
2785
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002786 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002787 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002788 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002789 assert(LI && getRegion().contains(LI));
2790 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2791 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2792 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2793 << ") is required to be invariant but was not marked as "
2794 "such. SCoP for "
2795 << getRegion() << " will be dropped\n\n");
2796 addAssumption(isl_set_empty(getParamSpace()));
2797 return;
2798 }
2799 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002800}
2801
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002802const ScopArrayInfo *
2803Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002804 ArrayRef<const SCEV *> Sizes,
2805 ScopArrayInfo::ARRAYKIND Kind) {
2806 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002807 if (!SAI) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002808 SAI.reset(
2809 new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002810 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002811 // In case of mismatching array sizes, we bail out by setting the run-time
2812 // context to false.
2813 if (!SAI->updateSizes(Sizes))
2814 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002815 }
Tobias Grosserab671442015-05-23 05:58:27 +00002816 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002817}
2818
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002819const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2820 ScopArrayInfo::ARRAYKIND Kind) {
2821 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002822 assert(SAI && "No ScopArrayInfo available for this base pointer");
2823 return SAI;
2824}
2825
Tobias Grosser74394f02013-01-14 22:40:23 +00002826std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002827std::string Scop::getAssumedContextStr() const {
2828 return stringFromIslObj(AssumedContext);
2829}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002830std::string Scop::getBoundaryContextStr() const {
2831 return stringFromIslObj(BoundaryContext);
2832}
Tobias Grosser75805372011-04-29 06:27:02 +00002833
2834std::string Scop::getNameStr() const {
2835 std::string ExitName, EntryName;
2836 raw_string_ostream ExitStr(ExitName);
2837 raw_string_ostream EntryStr(EntryName);
2838
Tobias Grosserf240b482014-01-09 10:42:15 +00002839 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002840 EntryStr.str();
2841
2842 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002843 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002844 ExitStr.str();
2845 } else
2846 ExitName = "FunctionExit";
2847
2848 return EntryName + "---" + ExitName;
2849}
2850
Tobias Grosser74394f02013-01-14 22:40:23 +00002851__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002852__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002853 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002854}
2855
Tobias Grossere86109f2013-10-29 21:05:49 +00002856__isl_give isl_set *Scop::getAssumedContext() const {
2857 return isl_set_copy(AssumedContext);
2858}
2859
Johannes Doerfert43788c52015-08-20 05:58:56 +00002860__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2861 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002862 RuntimeCheckContext =
2863 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2864 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002865 return RuntimeCheckContext;
2866}
2867
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002868bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002869 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002870 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002871 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2872 isl_set_free(RuntimeCheckContext);
2873 return IsFeasible;
2874}
2875
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002876void Scop::addAssumption(__isl_take isl_set *Set) {
2877 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002878 isl_basic_set_list *List = isl_set_get_basic_set_list(AssumedContext);
2879 int NSets = isl_basic_set_list_n_basic_set(List);
2880 isl_basic_set_list_free(List);
2881
2882 if (NSets >= MaxDisjunctsAssumed) {
2883 isl_space *Space = isl_set_get_space(AssumedContext);
2884 isl_set_free(AssumedContext);
2885 AssumedContext = isl_set_universe(Space);
2886 }
2887
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002888 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002889}
2890
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002891__isl_give isl_set *Scop::getBoundaryContext() const {
2892 return isl_set_copy(BoundaryContext);
2893}
2894
Tobias Grosser75805372011-04-29 06:27:02 +00002895void Scop::printContext(raw_ostream &OS) const {
2896 OS << "Context:\n";
2897
2898 if (!Context) {
2899 OS.indent(4) << "n/a\n\n";
2900 return;
2901 }
2902
2903 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002904
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002905 OS.indent(4) << "Assumed Context:\n";
2906 if (!AssumedContext) {
2907 OS.indent(4) << "n/a\n\n";
2908 return;
2909 }
2910
2911 OS.indent(4) << getAssumedContextStr() << "\n";
2912
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002913 OS.indent(4) << "Boundary Context:\n";
2914 if (!BoundaryContext) {
2915 OS.indent(4) << "n/a\n\n";
2916 return;
2917 }
2918
2919 OS.indent(4) << getBoundaryContextStr() << "\n";
2920
Tobias Grosser083d3d32014-06-28 08:59:45 +00002921 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002922 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002923 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2924 }
Tobias Grosser75805372011-04-29 06:27:02 +00002925}
2926
Johannes Doerfertb164c792014-09-18 11:17:17 +00002927void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002928 int noOfGroups = 0;
2929 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002930 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002931 noOfGroups += 1;
2932 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002933 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002934 }
2935
Tobias Grosserbb853c22015-07-25 12:31:03 +00002936 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002937 if (MinMaxAliasGroups.empty()) {
2938 OS.indent(8) << "n/a\n";
2939 return;
2940 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002941
Tobias Grosserbb853c22015-07-25 12:31:03 +00002942 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002943
2944 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002945 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002946 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002947 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002948 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2949 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002950 }
2951 OS << " ]]\n";
2952 }
2953
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002954 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002955 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002956 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002957 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002958 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2959 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002960 }
2961 OS << " ]]\n";
2962 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002963 }
2964}
2965
Tobias Grosser75805372011-04-29 06:27:02 +00002966void Scop::printStatements(raw_ostream &OS) const {
2967 OS << "Statements {\n";
2968
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002969 for (const ScopStmt &Stmt : *this)
2970 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002971
2972 OS.indent(4) << "}\n";
2973}
2974
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002975void Scop::printArrayInfo(raw_ostream &OS) const {
2976 OS << "Arrays {\n";
2977
Tobias Grosserab671442015-05-23 05:58:27 +00002978 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002979 Array.second->print(OS);
2980
2981 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002982
2983 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2984
2985 for (auto &Array : arrays())
2986 Array.second->print(OS, /* SizeAsPwAff */ true);
2987
2988 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002989}
2990
Tobias Grosser75805372011-04-29 06:27:02 +00002991void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002992 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
2993 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00002994 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00002995 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002996 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002997 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002998 const auto &MAs = std::get<1>(IAClass);
2999 if (MAs.empty()) {
3000 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003001 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003002 MAs.front()->print(OS);
3003 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003004 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003005 }
3006 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003007 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003008 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003009 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003010 printStatements(OS.indent(4));
3011}
3012
3013void Scop::dump() const { print(dbgs()); }
3014
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003015isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003016
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003017__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3018 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003019}
3020
Tobias Grosser808cd692015-07-14 09:33:13 +00003021__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003022 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003023
Tobias Grosser808cd692015-07-14 09:33:13 +00003024 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003025 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003026
3027 return Domain;
3028}
3029
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003030__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003031 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003032
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003033 for (ScopStmt &Stmt : *this) {
3034 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003035 if (!MA->isMustWrite())
3036 continue;
3037
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003038 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003039 isl_map *AccessDomain = MA->getAccessRelation();
3040 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3041 Write = isl_union_map_add_map(Write, AccessDomain);
3042 }
3043 }
3044 return isl_union_map_coalesce(Write);
3045}
3046
3047__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003048 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003049
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003050 for (ScopStmt &Stmt : *this) {
3051 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003052 if (!MA->isMayWrite())
3053 continue;
3054
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003055 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003056 isl_map *AccessDomain = MA->getAccessRelation();
3057 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3058 Write = isl_union_map_add_map(Write, AccessDomain);
3059 }
3060 }
3061 return isl_union_map_coalesce(Write);
3062}
3063
Tobias Grosser37eb4222014-02-20 21:43:54 +00003064__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003065 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003066
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003067 for (ScopStmt &Stmt : *this) {
3068 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003069 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003070 continue;
3071
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003072 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003073 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003074 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3075 Write = isl_union_map_add_map(Write, AccessDomain);
3076 }
3077 }
3078 return isl_union_map_coalesce(Write);
3079}
3080
3081__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003082 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003083
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003084 for (ScopStmt &Stmt : *this) {
3085 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003086 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003087 continue;
3088
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003089 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003090 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003091
3092 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3093 Read = isl_union_map_add_map(Read, AccessDomain);
3094 }
3095 }
3096 return isl_union_map_coalesce(Read);
3097}
3098
Tobias Grosser808cd692015-07-14 09:33:13 +00003099__isl_give isl_union_map *Scop::getSchedule() const {
3100 auto Tree = getScheduleTree();
3101 auto S = isl_schedule_get_map(Tree);
3102 isl_schedule_free(Tree);
3103 return S;
3104}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003105
Tobias Grosser808cd692015-07-14 09:33:13 +00003106__isl_give isl_schedule *Scop::getScheduleTree() const {
3107 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3108 getDomains());
3109}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003110
Tobias Grosser808cd692015-07-14 09:33:13 +00003111void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3112 auto *S = isl_schedule_from_domain(getDomains());
3113 S = isl_schedule_insert_partial_schedule(
3114 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3115 isl_schedule_free(Schedule);
3116 Schedule = S;
3117}
3118
3119void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3120 isl_schedule_free(Schedule);
3121 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003122}
3123
3124bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3125 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003126 for (ScopStmt &Stmt : *this) {
3127 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003128 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3129 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3130
3131 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3132 isl_union_set_free(StmtDomain);
3133 isl_union_set_free(NewStmtDomain);
3134 continue;
3135 }
3136
3137 Changed = true;
3138
3139 isl_union_set_free(StmtDomain);
3140 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3141
3142 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003143 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003144 isl_union_set_free(NewStmtDomain);
3145 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003146 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003147 }
3148 isl_union_set_free(Domain);
3149 return Changed;
3150}
3151
Tobias Grosser75805372011-04-29 06:27:02 +00003152ScalarEvolution *Scop::getSE() const { return SE; }
3153
Johannes Doerfertf5673802015-10-01 23:48:18 +00003154bool Scop::isIgnored(RegionNode *RN) {
3155 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003156
Johannes Doerfertf5673802015-10-01 23:48:18 +00003157 // Check if there are accesses contained.
3158 bool ContainsAccesses = false;
3159 if (!RN->isSubRegion())
3160 ContainsAccesses = getAccessFunctions(BB);
3161 else
3162 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3163 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3164 if (!ContainsAccesses)
3165 return true;
3166
3167 // Check for reachability via non-error blocks.
3168 if (!DomainMap.count(BB))
3169 return true;
3170
3171 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003172 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003173 return true;
3174
3175 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003176}
3177
Tobias Grosser808cd692015-07-14 09:33:13 +00003178struct MapToDimensionDataTy {
3179 int N;
3180 isl_union_pw_multi_aff *Res;
3181};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003182
Tobias Grosser808cd692015-07-14 09:33:13 +00003183// @brief Create a function that maps the elements of 'Set' to its N-th
3184// dimension.
3185//
3186// The result is added to 'User->Res'.
3187//
3188// @param Set The input set.
3189// @param N The dimension to map to.
3190//
3191// @returns Zero if no error occurred, non-zero otherwise.
3192static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3193 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3194 int Dim;
3195 isl_space *Space;
3196 isl_pw_multi_aff *PMA;
3197
3198 Dim = isl_set_dim(Set, isl_dim_set);
3199 Space = isl_set_get_space(Set);
3200 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3201 Dim - Data->N);
3202 if (Data->N > 1)
3203 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3204 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3205
3206 isl_set_free(Set);
3207
3208 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003209}
3210
Tobias Grosser808cd692015-07-14 09:33:13 +00003211// @brief Create a function that maps the elements of Domain to their Nth
3212// dimension.
3213//
3214// @param Domain The set of elements to map.
3215// @param N The dimension to map to.
3216static __isl_give isl_multi_union_pw_aff *
3217mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003218 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3219 isl_union_set_free(Domain);
3220 return nullptr;
3221 }
3222
Tobias Grosser808cd692015-07-14 09:33:13 +00003223 struct MapToDimensionDataTy Data;
3224 isl_space *Space;
3225
3226 Space = isl_union_set_get_space(Domain);
3227 Data.N = N;
3228 Data.Res = isl_union_pw_multi_aff_empty(Space);
3229 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3230 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3231
3232 isl_union_set_free(Domain);
3233 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3234}
3235
Michael Kruse9d080092015-09-11 21:41:48 +00003236ScopStmt *Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003237 ScopStmt *Stmt;
3238 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003239 Stmts.emplace_back(*this, *BB);
Tobias Grosser808cd692015-07-14 09:33:13 +00003240 Stmt = &Stmts.back();
3241 StmtMap[BB] = Stmt;
3242 } else {
3243 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003244 Stmts.emplace_back(*this, *R);
Tobias Grosser808cd692015-07-14 09:33:13 +00003245 Stmt = &Stmts.back();
3246 for (BasicBlock *BB : R->blocks())
3247 StmtMap[BB] = Stmt;
3248 }
3249 return Stmt;
3250}
3251
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003252void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003253 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003254 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003255
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003256 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003257 Loop *L = getLoopSurroundingRegion(*R, LI);
3258 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003259 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003260 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003261 auto *UDomain = isl_union_set_from_set(Domain);
3262 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003263 LSchedulePair.first = StmtSchedule;
3264 return;
3265 }
3266
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003267 ReversePostOrderTraversal<Region *> RTraversal(R);
3268 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003269
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003270 if (RN->isSubRegion()) {
3271 Region *SubRegion = RN->getNodeAs<Region>();
3272 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003273 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003274 continue;
3275 }
Tobias Grosser75805372011-04-29 06:27:02 +00003276 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003277
3278 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003279 if (!getRegion().contains(L))
3280 L = getLoopSurroundingRegion(getRegion(), LI);
3281
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003282 int LD = getRelativeLoopDepth(L);
3283 auto &LSchedulePair = LoopSchedules[L];
3284 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3285
Michael Krusecac948e2015-10-02 13:53:07 +00003286 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3287 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3288 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003289 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3290 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3291 LSchedulePair.first =
3292 combineInSequence(LSchedulePair.first, StmtSchedule);
3293 }
3294
3295 unsigned NumVisited = LSchedulePair.second;
3296 while (L && NumVisited == L->getNumBlocks()) {
3297 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3298 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3299 LSchedulePair.first =
3300 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3301
3302 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003303
3304 // Either we have a proper loop and we also build a schedule for the
3305 // parent loop or we have a infinite loop that does not have a proper
3306 // parent loop. In the former case this conditional will be skipped, in
3307 // the latter case however we will break here as we do not build a domain
3308 // nor a schedule for a infinite loop.
3309 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3310 if (!LoopSchedules.count(PL))
3311 break;
3312
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003313 auto &PSchedulePair = LoopSchedules[PL];
3314 PSchedulePair.first =
3315 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3316 PSchedulePair.second += NumVisited;
3317
3318 L = PL;
3319 NumVisited = PSchedulePair.second;
3320 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003321 }
Tobias Grosser75805372011-04-29 06:27:02 +00003322}
3323
Johannes Doerfert7c494212014-10-31 23:13:39 +00003324ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003325 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003326 if (StmtMapIt == StmtMap.end())
3327 return nullptr;
3328 return StmtMapIt->second;
3329}
3330
Johannes Doerfert96425c22015-08-30 21:13:53 +00003331int Scop::getRelativeLoopDepth(const Loop *L) const {
3332 Loop *OuterLoop =
3333 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3334 if (!OuterLoop)
3335 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003336 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3337}
3338
Michael Krused868b5d2015-09-10 15:25:24 +00003339void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003340 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003341
3342 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3343 // true, are not modeled as ordinary PHI nodes as they are not part of the
3344 // region. However, we model the operands in the predecessor blocks that are
3345 // part of the region as regular scalar accesses.
3346
3347 // If we can synthesize a PHI we can skip it, however only if it is in
3348 // the region. If it is not it can only be in the exit block of the region.
3349 // In this case we model the operands but not the PHI itself.
3350 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3351 return;
3352
3353 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3354 // detection. Hence, the PHI is a load of a new memory location in which the
3355 // incoming value was written at the end of the incoming basic block.
3356 bool OnlyNonAffineSubRegionOperands = true;
3357 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3358 Value *Op = PHI->getIncomingValue(u);
3359 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3360
3361 // Do not build scalar dependences inside a non-affine subregion.
3362 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3363 continue;
3364
3365 OnlyNonAffineSubRegionOperands = false;
3366
3367 if (!R.contains(OpBB))
3368 continue;
3369
3370 Instruction *OpI = dyn_cast<Instruction>(Op);
3371 if (OpI) {
3372 BasicBlock *OpIBB = OpI->getParent();
3373 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3374 // we have to insert a scalar dependence from the definition of OpI to
3375 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003376 if (scop->getStmtForBasicBlock(OpIBB) !=
3377 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003378 addScalarReadAccess(OpI, PHI, OpBB);
3379 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003380 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003381 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003382 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003383 }
3384
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003385 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003386 }
3387
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003388 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3389 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003390 }
3391}
3392
Michael Krused868b5d2015-09-10 15:25:24 +00003393bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3394 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003395 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3396 if (isIgnoredIntrinsic(Inst))
3397 return false;
3398
3399 bool AnyCrossStmtUse = false;
3400 BasicBlock *ParentBB = Inst->getParent();
3401
3402 for (User *U : Inst->users()) {
3403 Instruction *UI = dyn_cast<Instruction>(U);
3404
3405 // Ignore the strange user
3406 if (UI == 0)
3407 continue;
3408
3409 BasicBlock *UseParent = UI->getParent();
3410
Tobias Grosserbaffa092015-10-24 20:55:27 +00003411 // Ignore basic block local uses. A value that is defined in a scop, but
3412 // used in a PHI node in the same basic block does not count as basic block
3413 // local, as for such cases a control flow edge is passed between definition
3414 // and use.
3415 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003416 continue;
3417
Michael Krusef714d472015-11-05 13:18:43 +00003418 // Uses by PHI nodes in the entry node count as external uses in case the
3419 // use is through an incoming block that is itself not contained in the
3420 // region.
3421 if (R->getEntry() == UseParent) {
3422 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3423 bool ExternalUse = false;
3424 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3425 if (PHI->getIncomingValue(i) == Inst &&
3426 !R->contains(PHI->getIncomingBlock(i))) {
3427 ExternalUse = true;
3428 break;
3429 }
3430 }
3431
3432 if (ExternalUse) {
3433 AnyCrossStmtUse = true;
3434 continue;
3435 }
3436 }
3437 }
3438
Michael Kruse7bf39442015-09-10 12:46:52 +00003439 // Do not build scalar dependences inside a non-affine subregion.
3440 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3441 continue;
3442
Michael Kruse01cb3792015-10-17 21:07:08 +00003443 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003444 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003445 //
3446 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003447 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3448 // the control flow a different value will be assigned to the PHI node. In
3449 // case this is the case, there is no need to create an additional normal
3450 // scalar dependence. Hence, bail out before we register an "out-of-region"
3451 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003452 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3453 !R->getExitingBlock())
3454 continue;
3455
Michael Kruse7bf39442015-09-10 12:46:52 +00003456 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003457 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003458 AnyCrossStmtUse = true;
3459 continue;
3460 }
3461
3462 // If the instruction can be synthesized and the user is in the region
3463 // we do not need to add scalar dependences.
3464 if (canSynthesizeInst)
3465 continue;
3466
3467 // No need to translate these scalar dependences into polyhedral form,
3468 // because synthesizable scalars can be generated by the code generator.
3469 if (canSynthesize(UI, LI, SE, R))
3470 continue;
3471
3472 // Skip PHI nodes in the region as they handle their operands on their own.
3473 if (isa<PHINode>(UI))
3474 continue;
3475
3476 // Now U is used in another statement.
3477 AnyCrossStmtUse = true;
3478
3479 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003480 // Use the def instruction as base address of the MemoryAccess, so that it
3481 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003482 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003483 }
3484
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003485 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003486 for (Value *Op : Inst->operands()) {
3487 if (canSynthesize(Op, LI, SE, R))
3488 continue;
3489
3490 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3491 if (R->contains(OpInst))
3492 continue;
3493
3494 if (isa<Constant>(Op))
3495 continue;
3496
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003497 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003498 }
3499 }
3500
3501 return AnyCrossStmtUse;
3502}
3503
3504extern MapInsnToMemAcc InsnToMemAcc;
3505
Michael Krusee2bccbb2015-09-18 19:59:43 +00003506void ScopInfo::buildMemoryAccess(
3507 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003508 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3509 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003510 unsigned Size;
3511 Type *SizeType;
3512 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003513 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003514
3515 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3516 SizeType = Load->getType();
3517 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003518 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003519 Val = Load;
3520 } else {
3521 StoreInst *Store = cast<StoreInst>(Inst);
3522 SizeType = Store->getValueOperand()->getType();
3523 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003524 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003525 Val = Store->getValueOperand();
3526 }
3527
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003528 auto Address = getPointerOperand(*Inst);
3529
3530 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003531 const SCEVUnknown *BasePointer =
3532 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3533
3534 assert(BasePointer && "Could not find base pointer");
3535 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3536
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003537 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3538 auto NewAddress = Address;
3539 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3540 auto Src = BitCast->getOperand(0);
3541 auto SrcTy = Src->getType();
3542 auto DstTy = BitCast->getType();
3543 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3544 NewAddress = Src;
3545 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003546
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003547 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3548 std::vector<const SCEV *> Subscripts;
3549 std::vector<int> Sizes;
3550 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3551 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003552
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003553 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003554
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003555 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003556 for (auto Subscript : Subscripts) {
3557 InvariantLoadsSetTy AccessILS;
3558 AllAffineSubcripts =
3559 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3560
3561 for (LoadInst *LInst : AccessILS)
3562 if (!ScopRIL.count(LInst))
3563 AllAffineSubcripts = false;
3564
3565 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003566 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003567 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003568
3569 if (AllAffineSubcripts && Sizes.size() > 0) {
3570 for (auto V : Sizes)
3571 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3572 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003573 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003574 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003575
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003576 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3577 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003578 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003579 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003580 }
3581 }
3582
Michael Kruse7bf39442015-09-10 12:46:52 +00003583 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003584 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003585 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3586 AccItr->second.DelinearizedSubscripts,
3587 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003588 return;
3589 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003590
3591 // Check if the access depends on a loop contained in a non-affine subregion.
3592 bool isVariantInNonAffineLoop = false;
3593 if (BoxedLoops) {
3594 SetVector<const Loop *> Loops;
3595 findLoops(AccessFunction, Loops);
3596 for (const Loop *L : Loops)
3597 if (BoxedLoops->count(L))
3598 isVariantInNonAffineLoop = true;
3599 }
3600
Johannes Doerfert09e36972015-10-07 20:17:36 +00003601 InvariantLoadsSetTy AccessILS;
3602 bool IsAffine =
3603 !isVariantInNonAffineLoop &&
3604 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3605
3606 for (LoadInst *LInst : AccessILS)
3607 if (!ScopRIL.count(LInst))
3608 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003609
Michael Krusecaac2b62015-09-26 15:51:44 +00003610 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003611 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003612 const SCEV *SizeSCEV =
3613 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003614
Michael Krusee2bccbb2015-09-18 19:59:43 +00003615 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3616 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003617
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003618 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3619 ArrayRef<const SCEV *>(AccessFunction),
3620 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003621}
3622
Michael Krused868b5d2015-09-10 15:25:24 +00003623void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003624
3625 if (SD->isNonAffineSubRegion(&SR, &R)) {
3626 for (BasicBlock *BB : SR.blocks())
3627 buildAccessFunctions(R, *BB, &SR);
3628 return;
3629 }
3630
3631 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3632 if (I->isSubRegion())
3633 buildAccessFunctions(R, *I->getNodeAs<Region>());
3634 else
3635 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3636}
3637
Michael Krusecac948e2015-10-02 13:53:07 +00003638void ScopInfo::buildStmts(Region &SR) {
3639 Region *R = getRegion();
3640
3641 if (SD->isNonAffineSubRegion(&SR, R)) {
3642 scop->addScopStmt(nullptr, &SR);
3643 return;
3644 }
3645
3646 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3647 if (I->isSubRegion())
3648 buildStmts(*I->getNodeAs<Region>());
3649 else
3650 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3651}
3652
Michael Krused868b5d2015-09-10 15:25:24 +00003653void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3654 Region *NonAffineSubRegion,
3655 bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003656 Loop *L = LI->getLoopFor(&BB);
3657
3658 // The set of loops contained in non-affine subregions that are part of R.
3659 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3660
Johannes Doerfert09e36972015-10-07 20:17:36 +00003661 // The set of loads that are required to be invariant.
3662 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3663
Michael Kruse7bf39442015-09-10 12:46:52 +00003664 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003665 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003666
3667 PHINode *PHI = dyn_cast<PHINode>(Inst);
3668 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003669 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003670
3671 // For the exit block we stop modeling after the last PHI node.
3672 if (!PHI && IsExitBlock)
3673 break;
3674
Johannes Doerfert09e36972015-10-07 20:17:36 +00003675 // TODO: At this point we only know that elements of ScopRIL have to be
3676 // invariant and will be hoisted for the SCoP to be processed. Though,
3677 // there might be other invariant accesses that will be hoisted and
3678 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003679 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003680 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003681
3682 if (isIgnoredIntrinsic(Inst))
3683 continue;
3684
Johannes Doerfert09e36972015-10-07 20:17:36 +00003685 // Do not build scalar dependences for required invariant loads as we will
3686 // hoist them later on anyway or drop the SCoP if we cannot.
3687 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3688 continue;
3689
Michael Kruse7bf39442015-09-10 12:46:52 +00003690 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003691 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003692 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003693 }
3694 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003695}
Michael Kruse7bf39442015-09-10 12:46:52 +00003696
Michael Kruse2d0ece92015-09-24 11:41:21 +00003697void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3698 MemoryAccess::AccessType Type,
3699 Value *BaseAddress, unsigned ElemBytes,
3700 bool Affine, Value *AccessValue,
3701 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003702 ArrayRef<const SCEV *> Sizes,
3703 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003704 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3705
3706 // Do not create a memory access for anything not in the SCoP. It would be
3707 // ignored anyway.
3708 if (!Stmt)
3709 return;
3710
Michael Krusee2bccbb2015-09-18 19:59:43 +00003711 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003712 Value *BaseAddr = BaseAddress;
3713 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3714
Michael Krusecac948e2015-10-02 13:53:07 +00003715 bool isApproximated =
3716 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3717 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3718 Type = MemoryAccess::MAY_WRITE;
3719
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003720 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003721 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003722 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003723}
3724
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003725void ScopInfo::addExplicitAccess(
3726 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3727 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3728 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3729 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3730 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3731 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003732 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3733 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003734}
3735void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3736 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3737 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003738 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003739}
3740void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3741 assert(!isa<PHINode>(User));
3742 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3743 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003744 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003745}
3746void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3747 BasicBlock *UserBB) {
3748 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003749 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3750 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003751}
3752void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3753 Value *IncomingValue, bool IsExitBlock) {
3754 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3755 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3756 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003757 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003758}
3759void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3760 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003761 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3762 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003763}
3764
Michael Kruse76e924d2015-09-30 09:16:07 +00003765void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003766 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003767 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003768
Michael Krusecac948e2015-10-02 13:53:07 +00003769 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003770 buildAccessFunctions(R, R);
3771
3772 // In case the region does not have an exiting block we will later (during
3773 // code generation) split the exit block. This will move potential PHI nodes
3774 // from the current exit block into the new region exiting block. Hence, PHI
3775 // nodes that are at this point not part of the region will be.
3776 // To handle these PHI nodes later we will now model their operands as scalar
3777 // accesses. Note that we do not model anything in the exit block if we have
3778 // an exiting block in the region, as there will not be any splitting later.
3779 if (!R.getExitingBlock())
3780 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3781
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003782 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003783}
3784
Michael Krused868b5d2015-09-10 15:25:24 +00003785void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003786 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003787 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003788 return;
3789 }
3790
Michael Kruse9d080092015-09-11 21:41:48 +00003791 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003792}
3793
Michael Krused868b5d2015-09-10 15:25:24 +00003794void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003795 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003796 if (scop) {
3797 delete scop;
3798 scop = 0;
3799 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003800}
3801
3802//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003803ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003804 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003805 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003806}
3807
3808ScopInfo::~ScopInfo() {
3809 clear();
3810 isl_ctx_free(ctx);
3811}
3812
Tobias Grosser75805372011-04-29 06:27:02 +00003813void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003814 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003815 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003816 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003817 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3818 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003819 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003820 AU.setPreservesAll();
3821}
3822
3823bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003824 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003825
Michael Krused868b5d2015-09-10 15:25:24 +00003826 if (!SD->isMaxRegionInScop(*R))
3827 return false;
3828
3829 Function *F = R->getEntry()->getParent();
3830 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3831 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3832 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3833 TD = &F->getParent()->getDataLayout();
3834 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003835
Michael Kruse76e924d2015-09-30 09:16:07 +00003836 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003837
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003838 DEBUG(scop->print(dbgs()));
3839
Michael Kruseafe06702015-10-02 16:33:27 +00003840 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003841 delete scop;
3842 scop = nullptr;
3843 return false;
3844 }
3845
Johannes Doerfert120de4b2015-08-20 18:30:08 +00003846 // Statistics.
3847 ++ScopFound;
3848 if (scop->getMaxLoopDepth() > 0)
3849 ++RichScopFound;
Tobias Grosser75805372011-04-29 06:27:02 +00003850 return false;
3851}
3852
3853char ScopInfo::ID = 0;
3854
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003855Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3856
Tobias Grosser73600b82011-10-08 00:30:40 +00003857INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3858 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003859 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003860INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003861INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003862INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003863INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003864INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003865INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003866INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3867 "Polly - Create polyhedral description of Scops", false,
3868 false)