blob: 5b6cd49c2594d1c7f3d581a4d52eca7deb99af3d [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"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000037#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000038#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000039#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000040#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000041#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000043#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000045#include "isl/schedule.h"
46#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000047#include "isl/set.h"
48#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000049#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000050#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000051#include <sstream>
52#include <string>
53#include <vector>
54
55using namespace llvm;
56using namespace polly;
57
Chandler Carruth95fef942014-04-22 03:30:19 +000058#define DEBUG_TYPE "polly-scops"
59
Tobias Grosser74394f02013-01-14 22:40:23 +000060STATISTIC(ScopFound, "Number of valid Scops");
61STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000062
Michael Kruse7bf39442015-09-10 12:46:52 +000063static cl::opt<bool> ModelReadOnlyScalars(
64 "polly-analyze-read-only-scalars",
65 cl::desc("Model read-only scalar values in the scop description"),
66 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
67
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000068// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000069// operations can overflow easily. Additive reductions and bit operations
70// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000071static cl::opt<bool> DisableMultiplicativeReductions(
72 "polly-disable-multiplicative-reductions",
73 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
74 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075
Johannes Doerfert9143d672014-09-27 11:02:39 +000076static cl::opt<unsigned> RunTimeChecksMaxParameters(
77 "polly-rtc-max-parameters",
78 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
79 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
80
Tobias Grosser71500722015-03-28 15:11:14 +000081static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
82 "polly-rtc-max-arrays-per-group",
83 cl::desc("The maximal number of arrays to compare in each alias group."),
84 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000085static cl::opt<std::string> UserContextStr(
86 "polly-context", cl::value_desc("isl parameter set"),
87 cl::desc("Provide additional constraints on the context parameters"),
88 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000089
Tobias Grosserd83b8a82015-08-20 19:08:11 +000090static cl::opt<bool> DetectReductions("polly-detect-reductions",
91 cl::desc("Detect and exploit reductions"),
92 cl::Hidden, cl::ZeroOrMore,
93 cl::init(true), cl::cat(PollyCategory));
94
Tobias Grosser20a4c0c2015-11-11 16:22:36 +000095static cl::opt<int> MaxDisjunctsAssumed(
96 "polly-max-disjuncts-assumed",
97 cl::desc("The maximal number of disjuncts we allow in the assumption "
98 "context (this bounds compile time)"),
99 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
100
Michael Kruse7bf39442015-09-10 12:46:52 +0000101//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000102
Michael Kruse046dde42015-08-10 13:01:57 +0000103// Create a sequence of two schedules. Either argument may be null and is
104// interpreted as the empty schedule. Can also return null if both schedules are
105// empty.
106static __isl_give isl_schedule *
107combineInSequence(__isl_take isl_schedule *Prev,
108 __isl_take isl_schedule *Succ) {
109 if (!Prev)
110 return Succ;
111 if (!Succ)
112 return Prev;
113
114 return isl_schedule_sequence(Prev, Succ);
115}
116
Johannes Doerferte7044942015-02-24 11:58:30 +0000117static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
118 const ConstantRange &Range,
119 int dim,
120 enum isl_dim_type type) {
121 isl_val *V;
122 isl_ctx *ctx = isl_set_get_ctx(S);
123
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000124 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
125 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000126 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000127 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
128
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000129 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000130 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000131 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000132 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000133 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
134
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000135 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000136 return isl_set_union(SLB, SUB);
137 else
138 return isl_set_intersect(SLB, SUB);
139}
140
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000141static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
142 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
143 if (!BasePtrLI)
144 return nullptr;
145
146 if (!S->getRegion().contains(BasePtrLI))
147 return nullptr;
148
149 ScalarEvolution &SE = *S->getSE();
150
151 auto *OriginBaseSCEV =
152 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
153 if (!OriginBaseSCEV)
154 return nullptr;
155
156 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
157 if (!OriginBaseSCEVUnknown)
158 return nullptr;
159
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000160 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
161 ScopArrayInfo::KIND_ARRAY);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000162}
163
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000164ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000165 ArrayRef<const SCEV *> Sizes, enum ARRAYKIND Kind,
166 Scop *S)
167 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000168 std::string BasePtrName =
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000169 getIslCompatibleName("MemRef_", BasePtr, Kind == KIND_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000170 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000171
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000172 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000173 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
174 if (BasePtrOriginSAI)
175 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000176}
177
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000178__isl_give isl_space *ScopArrayInfo::getSpace() const {
179 auto Space =
180 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
181 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
182 return Space;
183}
184
Tobias Grosser8286b832015-11-02 11:29:32 +0000185bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000186 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
187 int ExtraDimsNew = NewSizes.size() - SharedDims;
188 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000189 for (int i = 0; i < SharedDims; i++)
190 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
191 return false;
192
193 if (DimensionSizes.size() >= NewSizes.size())
194 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000195
196 DimensionSizes.clear();
197 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
198 NewSizes.end());
199 for (isl_pw_aff *Size : DimensionSizesPw)
200 isl_pw_aff_free(Size);
201 DimensionSizesPw.clear();
202 for (const SCEV *Expr : DimensionSizes) {
203 isl_pw_aff *Size = S.getPwAff(Expr);
204 DimensionSizesPw.push_back(Size);
205 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000206 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000207}
208
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000209ScopArrayInfo::~ScopArrayInfo() {
210 isl_id_free(Id);
211 for (isl_pw_aff *Size : DimensionSizesPw)
212 isl_pw_aff_free(Size);
213}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000214
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000215std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
216
217int ScopArrayInfo::getElemSizeInBytes() const {
218 return ElementType->getPrimitiveSizeInBits() / 8;
219}
220
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000221isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
222
223void ScopArrayInfo::dump() const { print(errs()); }
224
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000225void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000226 OS.indent(8) << *getElementType() << " " << getName();
227 if (getNumberOfDimensions() > 0)
228 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000229 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000230 OS << "[";
231
Tobias Grosser26253842015-11-10 14:24:21 +0000232 if (SizeAsPwAff) {
233 auto Size = getDimensionSizePw(u);
234 OS << " " << Size << " ";
235 isl_pw_aff_free(Size);
236 } else {
237 OS << *getDimensionSize(u);
238 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000239
240 OS << "]";
241 }
242
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000243 OS << ";";
244
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000245 if (BasePtrOriginSAI)
246 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
247
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000248 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000249}
250
251const ScopArrayInfo *
252ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
253 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
254 assert(Id && "Output dimension didn't have an ID");
255 return getFromId(Id);
256}
257
258const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
259 void *User = isl_id_get_user(Id);
260 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
261 isl_id_free(Id);
262 return SAI;
263}
264
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000265void MemoryAccess::updateDimensionality() {
266 auto ArraySpace = getScopArrayInfo()->getSpace();
267 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
268
269 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
270 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
271 auto DimsMissing = DimsArray - DimsAccess;
272
273 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
274 isl_set_universe(ArraySpace));
275
276 for (unsigned i = 0; i < DimsMissing; i++)
277 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
278
279 for (unsigned i = DimsMissing; i < DimsArray; i++)
280 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
281
282 AccessRelation = isl_map_apply_range(AccessRelation, Map);
283}
284
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000285const std::string
286MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
287 switch (RT) {
288 case MemoryAccess::RT_NONE:
289 llvm_unreachable("Requested a reduction operator string for a memory "
290 "access which isn't a reduction");
291 case MemoryAccess::RT_ADD:
292 return "+";
293 case MemoryAccess::RT_MUL:
294 return "*";
295 case MemoryAccess::RT_BOR:
296 return "|";
297 case MemoryAccess::RT_BXOR:
298 return "^";
299 case MemoryAccess::RT_BAND:
300 return "&";
301 }
302 llvm_unreachable("Unknown reduction type");
303 return "";
304}
305
Johannes Doerfertf6183392014-07-01 20:52:51 +0000306/// @brief Return the reduction type for a given binary operator
307static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
308 const Instruction *Load) {
309 if (!BinOp)
310 return MemoryAccess::RT_NONE;
311 switch (BinOp->getOpcode()) {
312 case Instruction::FAdd:
313 if (!BinOp->hasUnsafeAlgebra())
314 return MemoryAccess::RT_NONE;
315 // Fall through
316 case Instruction::Add:
317 return MemoryAccess::RT_ADD;
318 case Instruction::Or:
319 return MemoryAccess::RT_BOR;
320 case Instruction::Xor:
321 return MemoryAccess::RT_BXOR;
322 case Instruction::And:
323 return MemoryAccess::RT_BAND;
324 case Instruction::FMul:
325 if (!BinOp->hasUnsafeAlgebra())
326 return MemoryAccess::RT_NONE;
327 // Fall through
328 case Instruction::Mul:
329 if (DisableMultiplicativeReductions)
330 return MemoryAccess::RT_NONE;
331 return MemoryAccess::RT_MUL;
332 default:
333 return MemoryAccess::RT_NONE;
334 }
335}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000336
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000337/// @brief Derive the individual index expressions from a GEP instruction
338///
339/// This function optimistically assumes the GEP references into a fixed size
340/// array. If this is actually true, this function returns a list of array
341/// subscript expressions as SCEV as well as a list of integers describing
342/// the size of the individual array dimensions. Both lists have either equal
343/// length of the size list is one element shorter in case there is no known
344/// size available for the outermost array dimension.
345///
346/// @param GEP The GetElementPtr instruction to analyze.
347///
348/// @return A tuple with the subscript expressions and the dimension sizes.
349static std::tuple<std::vector<const SCEV *>, std::vector<int>>
350getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
351 std::vector<const SCEV *> Subscripts;
352 std::vector<int> Sizes;
353
354 Type *Ty = GEP->getPointerOperandType();
355
356 bool DroppedFirstDim = false;
357
Michael Kruse26ed65e2015-09-24 17:32:49 +0000358 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000359
360 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
361
362 if (i == 1) {
363 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
364 Ty = PtrTy->getElementType();
365 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
366 Ty = ArrayTy->getElementType();
367 } else {
368 Subscripts.clear();
369 Sizes.clear();
370 break;
371 }
372 if (auto Const = dyn_cast<SCEVConstant>(Expr))
373 if (Const->getValue()->isZero()) {
374 DroppedFirstDim = true;
375 continue;
376 }
377 Subscripts.push_back(Expr);
378 continue;
379 }
380
381 auto ArrayTy = dyn_cast<ArrayType>(Ty);
382 if (!ArrayTy) {
383 Subscripts.clear();
384 Sizes.clear();
385 break;
386 }
387
388 Subscripts.push_back(Expr);
389 if (!(DroppedFirstDim && i == 2))
390 Sizes.push_back(ArrayTy->getNumElements());
391
392 Ty = ArrayTy->getElementType();
393 }
394
395 return std::make_tuple(Subscripts, Sizes);
396}
397
Tobias Grosser75805372011-04-29 06:27:02 +0000398MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000399 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000400 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000401 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000402}
403
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000404const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
405 isl_id *ArrayId = getArrayId();
406 void *User = isl_id_get_user(ArrayId);
407 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
408 isl_id_free(ArrayId);
409 return SAI;
410}
411
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000412__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000413 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
414}
415
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000416__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
417 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000418 isl_map *Schedule, *ScheduledAccRel;
419 isl_union_set *UDomain;
420
421 UDomain = isl_union_set_from_set(getStatement()->getDomain());
422 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
423 Schedule = isl_map_from_union_map(USchedule);
424 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
425 return isl_pw_multi_aff_from_map(ScheduledAccRel);
426}
427
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000428__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000429 return isl_map_copy(AccessRelation);
430}
431
Johannes Doerferta99130f2014-10-13 12:58:03 +0000432std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000433 return stringFromIslObj(AccessRelation);
434}
435
Johannes Doerferta99130f2014-10-13 12:58:03 +0000436__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000437 return isl_map_get_space(AccessRelation);
438}
439
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000440__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000441 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000442}
443
Tobias Grosser6f730082015-09-05 07:46:47 +0000444std::string MemoryAccess::getNewAccessRelationStr() const {
445 return stringFromIslObj(NewAccessRelation);
446}
447
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000448__isl_give isl_basic_map *
449MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000450 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000451 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000452
Tobias Grosser084d8f72012-05-29 09:29:44 +0000453 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000454 isl_basic_set_universe(Statement->getDomainSpace()),
455 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000456}
457
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000458// Formalize no out-of-bound access assumption
459//
460// When delinearizing array accesses we optimistically assume that the
461// delinearized accesses do not access out of bound locations (the subscript
462// expression of each array evaluates for each statement instance that is
463// executed to a value that is larger than zero and strictly smaller than the
464// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000465// dimension for which we do not need to assume any upper bound. At this point
466// we formalize this assumption to ensure that at code generation time the
467// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000468//
469// To find the set of constraints necessary to avoid out of bound accesses, we
470// first build the set of data locations that are not within array bounds. We
471// then apply the reverse access relation to obtain the set of iterations that
472// may contain invalid accesses and reduce this set of iterations to the ones
473// that are actually executed by intersecting them with the domain of the
474// statement. If we now project out all loop dimensions, we obtain a set of
475// parameters that may cause statement instances to be executed that may
476// possibly yield out of bound memory accesses. The complement of these
477// constraints is the set of constraints that needs to be assumed to ensure such
478// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000479void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000480 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000481 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000482 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000483 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
484 isl_pw_aff *Var =
485 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
486 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
487
488 isl_set *DimOutside;
489
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000490 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000491 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000492
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000493 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
494 Statement->getNumIterators());
495 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
496 isl_space_dim(Space, isl_dim_set));
497 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
498 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000499
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000500 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000501
502 Outside = isl_set_union(Outside, DimOutside);
503 }
504
505 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
506 Outside = isl_set_intersect(Outside, Statement->getDomain());
507 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000508
509 // Remove divs to avoid the construction of overly complicated assumptions.
510 // Doing so increases the set of parameter combinations that are assumed to
511 // not appear. This is always save, but may make the resulting run-time check
512 // bail out more often than strictly necessary.
513 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000514 Outside = isl_set_complement(Outside);
515 Statement->getParent()->addAssumption(Outside);
516 isl_space_free(Space);
517}
518
Johannes Doerferte7044942015-02-24 11:58:30 +0000519void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
520 ScalarEvolution *SE = Statement->getParent()->getSE();
521
522 Value *Ptr = getPointerOperand(*getAccessInstruction());
523 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
524 return;
525
526 auto *PtrSCEV = SE->getSCEV(Ptr);
527 if (isa<SCEVCouldNotCompute>(PtrSCEV))
528 return;
529
530 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
531 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
532 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
533
534 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
535 if (Range.isFullSet())
536 return;
537
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000538 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000539 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000540 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
541 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
542
543 auto Min = LB.sdiv(APInt(BW, ElementSize));
544 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000545
546 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
547 AccessRange =
548 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
549 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
550}
551
Michael Krusee2bccbb2015-09-18 19:59:43 +0000552__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000553 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000554 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000555
556 for (int i = Size - 2; i >= 0; --i) {
557 isl_space *Space;
558 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000559 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000560
561 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
562 isl_pw_aff_free(DimSize);
563 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
564
565 Space = isl_map_get_space(AccessRelation);
566 Space = isl_space_map_from_set(isl_space_range(Space));
567 Space = isl_space_align_params(Space, SpaceSize);
568
569 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
570 isl_id_free(ParamId);
571
572 MapOne = isl_map_universe(isl_space_copy(Space));
573 for (int j = 0; j < Size; ++j)
574 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
575 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
576
577 MapTwo = isl_map_universe(isl_space_copy(Space));
578 for (int j = 0; j < Size; ++j)
579 if (j < i || j > i + 1)
580 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
581
582 isl_local_space *LS = isl_local_space_from_space(Space);
583 isl_constraint *C;
584 C = isl_equality_alloc(isl_local_space_copy(LS));
585 C = isl_constraint_set_constant_si(C, -1);
586 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
587 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
588 MapTwo = isl_map_add_constraint(MapTwo, C);
589 C = isl_equality_alloc(LS);
590 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
591 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
592 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
593 MapTwo = isl_map_add_constraint(MapTwo, C);
594 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
595
596 MapOne = isl_map_union(MapOne, MapTwo);
597 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
598 }
599 return AccessRelation;
600}
601
Michael Krusee2bccbb2015-09-18 19:59:43 +0000602void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
603 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000604
Michael Krusee2bccbb2015-09-18 19:59:43 +0000605 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000606 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000607
Michael Krusee2bccbb2015-09-18 19:59:43 +0000608 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000609 // We overapproximate non-affine accesses with a possible access to the
610 // whole array. For read accesses it does not make a difference, if an
611 // access must or may happen. However, for write accesses it is important to
612 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000613 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000614 AccessRelation =
615 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000616
Michael Krusee2bccbb2015-09-18 19:59:43 +0000617 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000618 return;
619 }
620
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000621 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000622 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000623
Michael Krusee2bccbb2015-09-18 19:59:43 +0000624 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
625 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000626
Sebastian Pop422e33f2014-06-03 18:16:31 +0000627 if (Size == 1) {
628 // For the non delinearized arrays, divide the access function of the last
629 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000630 //
631 // A stride one array access in C expressed as A[i] is expressed in
632 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
633 // two subsequent values of 'i' index two values that are stored next to
634 // each other in memory. By this division we make this characteristic
635 // obvious again.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000636 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000637 Affine = isl_pw_aff_scale_down_val(Affine, v);
638 }
639
640 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
641
Tobias Grosser79baa212014-04-10 08:38:02 +0000642 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000643 }
644
Michael Krusee2bccbb2015-09-18 19:59:43 +0000645 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
646 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000647
Tobias Grosser79baa212014-04-10 08:38:02 +0000648 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000649 AccessRelation = isl_map_set_tuple_id(
650 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000651 AccessRelation =
652 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
653
Michael Krusee2bccbb2015-09-18 19:59:43 +0000654 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000655 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000656 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000657}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000658
Michael Krusecac948e2015-10-02 13:53:07 +0000659MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000660 AccessType Type, Value *BaseAddress,
661 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000662 ArrayRef<const SCEV *> Subscripts,
663 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000664 AccessOrigin Origin, StringRef BaseName)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000665 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000666 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
667 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
668 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000669 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000670 NewAccessRelation(nullptr) {
671
672 std::string IdName = "__polly_array_ref";
673 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
674}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000675
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000676void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000677 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000678 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000679}
680
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000681const std::string MemoryAccess::getReductionOperatorStr() const {
682 return MemoryAccess::getReductionOperatorStr(getReductionType());
683}
684
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000685__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
686
Johannes Doerfertf6183392014-07-01 20:52:51 +0000687raw_ostream &polly::operator<<(raw_ostream &OS,
688 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000689 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000690 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000691 else
692 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000693 return OS;
694}
695
Tobias Grosser75805372011-04-29 06:27:02 +0000696void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000697 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000698 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000699 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000700 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000701 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000702 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000703 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000704 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000705 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000706 break;
707 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000708 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000709 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000710 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000711 if (hasNewAccessRelation())
712 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000713}
714
Tobias Grosser74394f02013-01-14 22:40:23 +0000715void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000716
717// Create a map in the size of the provided set domain, that maps from the
718// one element of the provided set domain to another element of the provided
719// set domain.
720// The mapping is limited to all points that are equal in all but the last
721// dimension and for which the last dimension of the input is strict smaller
722// than the last dimension of the output.
723//
724// getEqualAndLarger(set[i0, i1, ..., iX]):
725//
726// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
727// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
728//
Tobias Grosserf5338802011-10-06 00:03:35 +0000729static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000730 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000731 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000732 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000733
734 // Set all but the last dimension to be equal for the input and output
735 //
736 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
737 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000738 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000739 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000740
741 // Set the last dimension of the input to be strict smaller than the
742 // last dimension of the output.
743 //
744 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000745 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
746 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000747 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000748}
749
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000750__isl_give isl_set *
751MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000752 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000753 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000754 isl_space *Space = isl_space_range(isl_map_get_space(S));
755 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000756
Sebastian Popa00a0292012-12-18 07:46:06 +0000757 S = isl_map_reverse(S);
758 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000759
Sebastian Popa00a0292012-12-18 07:46:06 +0000760 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
761 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
762 NextScatt = isl_map_apply_domain(NextScatt, S);
763 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000764
Sebastian Popa00a0292012-12-18 07:46:06 +0000765 isl_set *Deltas = isl_map_deltas(NextScatt);
766 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000767}
768
Sebastian Popa00a0292012-12-18 07:46:06 +0000769bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000770 int StrideWidth) const {
771 isl_set *Stride, *StrideX;
772 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000773
Sebastian Popa00a0292012-12-18 07:46:06 +0000774 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000775 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000776 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
777 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
778 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
779 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000780 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000781
Tobias Grosser28dd4862012-01-24 16:42:16 +0000782 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000783 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000784
Tobias Grosser28dd4862012-01-24 16:42:16 +0000785 return IsStrideX;
786}
787
Sebastian Popa00a0292012-12-18 07:46:06 +0000788bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
789 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000790}
791
Sebastian Popa00a0292012-12-18 07:46:06 +0000792bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
793 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000794}
795
Tobias Grosser166c4222015-09-05 07:46:40 +0000796void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
797 isl_map_free(NewAccessRelation);
798 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000799}
Tobias Grosser75805372011-04-29 06:27:02 +0000800
801//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000802
Tobias Grosser808cd692015-07-14 09:33:13 +0000803isl_map *ScopStmt::getSchedule() const {
804 isl_set *Domain = getDomain();
805 if (isl_set_is_empty(Domain)) {
806 isl_set_free(Domain);
807 return isl_map_from_aff(
808 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
809 }
810 auto *Schedule = getParent()->getSchedule();
811 Schedule = isl_union_map_intersect_domain(
812 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
813 if (isl_union_map_is_empty(Schedule)) {
814 isl_set_free(Domain);
815 isl_union_map_free(Schedule);
816 return isl_map_from_aff(
817 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
818 }
819 auto *M = isl_map_from_union_map(Schedule);
820 M = isl_map_coalesce(M);
821 M = isl_map_gist_domain(M, Domain);
822 M = isl_map_coalesce(M);
823 return M;
824}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000825
Johannes Doerfert574182d2015-08-12 10:19:50 +0000826__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000827 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
828 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000829}
830
Tobias Grosser37eb4222014-02-20 21:43:54 +0000831void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
832 assert(isl_set_is_subset(NewDomain, Domain) &&
833 "New domain is not a subset of old domain!");
834 isl_set_free(Domain);
835 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000836}
837
Michael Krusecac948e2015-10-02 13:53:07 +0000838void ScopStmt::buildAccessRelations() {
839 for (MemoryAccess *Access : MemAccs) {
840 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000841
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000842 ScopArrayInfo::ARRAYKIND Ty;
843 if (Access->isPHI())
844 Ty = ScopArrayInfo::KIND_PHI;
845 else if (Access->isImplicit())
846 Ty = ScopArrayInfo::KIND_SCALAR;
847 else
848 Ty = ScopArrayInfo::KIND_ARRAY;
849
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000850 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000851 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000852
Michael Krusecac948e2015-10-02 13:53:07 +0000853 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000854 }
855}
856
Michael Krusecac948e2015-10-02 13:53:07 +0000857void ScopStmt::addAccess(MemoryAccess *Access) {
858 Instruction *AccessInst = Access->getAccessInstruction();
859
860 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
861 if (!MAL)
862 MAL = new MemoryAccessList();
863 MAL->emplace_front(Access);
864 MemAccs.push_back(MAL->front());
865}
866
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000867void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000868 for (MemoryAccess *MA : *this)
869 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000870
871 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000872}
873
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000874/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
875static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
876 void *User) {
877 isl_set **BoundedParts = static_cast<isl_set **>(User);
878 if (isl_basic_set_is_bounded(BSet))
879 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
880 else
881 isl_basic_set_free(BSet);
882 return isl_stat_ok;
883}
884
885/// @brief Return the bounded parts of @p S.
886static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
887 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
888 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
889 isl_set_free(S);
890 return BoundedParts;
891}
892
893/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
894///
895/// @returns A separation of @p S into first an unbounded then a bounded subset,
896/// both with regards to the dimension @p Dim.
897static std::pair<__isl_give isl_set *, __isl_give isl_set *>
898partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
899
900 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000901 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000902
903 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000904 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000905
906 // Remove dimensions that are greater than Dim as they are not interesting.
907 assert(NumDimsS >= Dim + 1);
908 OnlyDimS =
909 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
910
911 // Create artificial parametric upper bounds for dimensions smaller than Dim
912 // as we are not interested in them.
913 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
914 for (unsigned u = 0; u < Dim; u++) {
915 isl_constraint *C = isl_inequality_alloc(
916 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
917 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
918 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
919 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
920 }
921
922 // Collect all bounded parts of OnlyDimS.
923 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
924
925 // Create the dimensions greater than Dim again.
926 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
927 NumDimsS - Dim - 1);
928
929 // Remove the artificial upper bound parameters again.
930 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
931
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000932 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000933 return std::make_pair(UnboundedParts, BoundedParts);
934}
935
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000936/// @brief Set the dimension Ids from @p From in @p To.
937static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
938 __isl_take isl_set *To) {
939 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
940 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
941 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
942 }
943 return To;
944}
945
946/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000947static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000948 __isl_take isl_pw_aff *L,
949 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000950 switch (Pred) {
951 case ICmpInst::ICMP_EQ:
952 return isl_pw_aff_eq_set(L, R);
953 case ICmpInst::ICMP_NE:
954 return isl_pw_aff_ne_set(L, R);
955 case ICmpInst::ICMP_SLT:
956 return isl_pw_aff_lt_set(L, R);
957 case ICmpInst::ICMP_SLE:
958 return isl_pw_aff_le_set(L, R);
959 case ICmpInst::ICMP_SGT:
960 return isl_pw_aff_gt_set(L, R);
961 case ICmpInst::ICMP_SGE:
962 return isl_pw_aff_ge_set(L, R);
963 case ICmpInst::ICMP_ULT:
964 return isl_pw_aff_lt_set(L, R);
965 case ICmpInst::ICMP_UGT:
966 return isl_pw_aff_gt_set(L, R);
967 case ICmpInst::ICMP_ULE:
968 return isl_pw_aff_le_set(L, R);
969 case ICmpInst::ICMP_UGE:
970 return isl_pw_aff_ge_set(L, R);
971 default:
972 llvm_unreachable("Non integer predicate not supported");
973 }
974}
975
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000976/// @brief Create the conditions under which @p L @p Pred @p R is true.
977///
978/// Helper function that will make sure the dimensions of the result have the
979/// same isl_id's as the @p Domain.
980static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
981 __isl_take isl_pw_aff *L,
982 __isl_take isl_pw_aff *R,
983 __isl_keep isl_set *Domain) {
984 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
985 return setDimensionIds(Domain, ConsequenceCondSet);
986}
987
988/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000989///
990/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000991/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
992/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000993static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000994buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +0000995 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
996
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000997 Value *Condition = getConditionFromTerminator(SI);
998 assert(Condition && "No condition for switch");
999
1000 ScalarEvolution &SE = *S.getSE();
1001 BasicBlock *BB = SI->getParent();
1002 isl_pw_aff *LHS, *RHS;
1003 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1004
1005 unsigned NumSuccessors = SI->getNumSuccessors();
1006 ConditionSets.resize(NumSuccessors);
1007 for (auto &Case : SI->cases()) {
1008 unsigned Idx = Case.getSuccessorIndex();
1009 ConstantInt *CaseValue = Case.getCaseValue();
1010
1011 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1012 isl_set *CaseConditionSet =
1013 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1014 ConditionSets[Idx] = isl_set_coalesce(
1015 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1016 }
1017
1018 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1019 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1020 for (unsigned u = 2; u < NumSuccessors; u++)
1021 ConditionSetUnion =
1022 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1023 ConditionSets[0] = setDimensionIds(
1024 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1025
1026 S.markAsOptimized();
1027 isl_pw_aff_free(LHS);
1028}
1029
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001030/// @brief Build the conditions sets for the branch condition @p Condition in
1031/// the @p Domain.
1032///
1033/// This will fill @p ConditionSets with the conditions under which control
1034/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1035/// have as many elements as @p TI has successors.
1036static void
1037buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1038 __isl_keep isl_set *Domain,
1039 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1040
1041 isl_set *ConsequenceCondSet = nullptr;
1042 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1043 if (CCond->isZero())
1044 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1045 else
1046 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1047 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1048 auto Opcode = BinOp->getOpcode();
1049 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1050
1051 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1052 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1053
1054 isl_set_free(ConditionSets.pop_back_val());
1055 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1056 isl_set_free(ConditionSets.pop_back_val());
1057 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1058
1059 if (Opcode == Instruction::And)
1060 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1061 else
1062 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1063 } else {
1064 auto *ICond = dyn_cast<ICmpInst>(Condition);
1065 assert(ICond &&
1066 "Condition of exiting branch was neither constant nor ICmp!");
1067
1068 ScalarEvolution &SE = *S.getSE();
1069 BasicBlock *BB = TI->getParent();
1070 isl_pw_aff *LHS, *RHS;
1071 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1072 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1073 ConsequenceCondSet =
1074 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1075 }
1076
1077 assert(ConsequenceCondSet);
1078 isl_set *AlternativeCondSet =
1079 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1080
1081 ConditionSets.push_back(isl_set_coalesce(
1082 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1083 ConditionSets.push_back(isl_set_coalesce(
1084 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1085}
1086
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001087/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1088///
1089/// This will fill @p ConditionSets with the conditions under which control
1090/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1091/// have as many elements as @p TI has successors.
1092static void
1093buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1094 __isl_keep isl_set *Domain,
1095 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1096
1097 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1098 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1099
1100 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1101
1102 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001103 ConditionSets.push_back(isl_set_copy(Domain));
1104 return;
1105 }
1106
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001107 Value *Condition = getConditionFromTerminator(TI);
1108 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001109
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001110 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001111}
1112
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001113void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001114 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001115
Tobias Grosser084d8f72012-05-29 09:29:44 +00001116 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1117
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001118 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001119 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001120}
1121
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001122void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001123 isl_ctx *Ctx = Parent.getIslCtx();
1124 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1125 Type *Ty = GEP->getPointerOperandType();
1126 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001127 ScopDetection &SD = Parent.getSD();
1128
1129 // The set of loads that are required to be invariant.
1130 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001131
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001132 std::vector<const SCEV *> Subscripts;
1133 std::vector<int> Sizes;
1134
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001135 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001136
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001137 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001138 Ty = PtrTy->getElementType();
1139 }
1140
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001141 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001142
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001143 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001144
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001145 for (size_t i = 0; i < Sizes.size(); i++) {
1146 auto Expr = Subscripts[i + IndexOffset];
1147 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001148
Johannes Doerfert09e36972015-10-07 20:17:36 +00001149 InvariantLoadsSetTy AccessILS;
1150 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1151 continue;
1152
1153 bool NonAffine = false;
1154 for (LoadInst *LInst : AccessILS)
1155 if (!ScopRIL.count(LInst))
1156 NonAffine = true;
1157
1158 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001159 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001160
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001161 isl_pw_aff *AccessOffset = getPwAff(Expr);
1162 AccessOffset =
1163 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001164
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001165 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1166 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001167
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001168 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1169 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1170 OutOfBound = isl_set_params(OutOfBound);
1171 isl_set *InBound = isl_set_complement(OutOfBound);
1172 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001173
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001174 // A => B == !A or B
1175 isl_set *InBoundIfExecuted =
1176 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001177
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001178 Parent.addAssumption(InBoundIfExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001179 }
1180
1181 isl_local_space_free(LSpace);
1182}
1183
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001184void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1185 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001186 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1187 deriveAssumptionsFromGEP(GEP);
1188}
1189
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001190void ScopStmt::collectSurroundingLoops() {
1191 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1192 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1193 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1194 isl_id_free(DimId);
1195 }
1196}
1197
Michael Kruse9d080092015-09-11 21:41:48 +00001198ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001199 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001200
Tobias Grosser16c44032015-07-09 07:31:45 +00001201 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001202}
1203
Michael Kruse9d080092015-09-11 21:41:48 +00001204ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001205 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001206
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001207 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001208}
1209
1210void ScopStmt::init() {
1211 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001212
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001213 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001214 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001215 buildAccessRelations();
1216
1217 if (BB) {
1218 deriveAssumptions(BB);
1219 } else {
1220 for (BasicBlock *Block : R->blocks()) {
1221 deriveAssumptions(Block);
1222 }
1223 }
1224
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001225 if (DetectReductions)
1226 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001227}
1228
Johannes Doerferte58a0122014-06-27 20:31:28 +00001229/// @brief Collect loads which might form a reduction chain with @p StoreMA
1230///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001231/// Check if the stored value for @p StoreMA is a binary operator with one or
1232/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001233/// used only once (by @p StoreMA) and its load operands are also used only
1234/// once, we have found a possible reduction chain. It starts at an operand
1235/// load and includes the binary operator and @p StoreMA.
1236///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001237/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001238/// escape this block or into any other store except @p StoreMA.
1239void ScopStmt::collectCandiateReductionLoads(
1240 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1241 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1242 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001243 return;
1244
1245 // Skip if there is not one binary operator between the load and the store
1246 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001247 if (!BinOp)
1248 return;
1249
1250 // Skip if the binary operators has multiple uses
1251 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001252 return;
1253
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001254 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001255 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1256 return;
1257
Johannes Doerfert9890a052014-07-01 00:32:29 +00001258 // Skip if the binary operator is outside the current SCoP
1259 if (BinOp->getParent() != Store->getParent())
1260 return;
1261
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001262 // Skip if it is a multiplicative reduction and we disabled them
1263 if (DisableMultiplicativeReductions &&
1264 (BinOp->getOpcode() == Instruction::Mul ||
1265 BinOp->getOpcode() == Instruction::FMul))
1266 return;
1267
Johannes Doerferte58a0122014-06-27 20:31:28 +00001268 // Check the binary operator operands for a candidate load
1269 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1270 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1271 if (!PossibleLoad0 && !PossibleLoad1)
1272 return;
1273
1274 // A load is only a candidate if it cannot escape (thus has only this use)
1275 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001276 if (PossibleLoad0->getParent() == Store->getParent())
1277 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001278 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001279 if (PossibleLoad1->getParent() == Store->getParent())
1280 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001281}
1282
1283/// @brief Check for reductions in this ScopStmt
1284///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001285/// Iterate over all store memory accesses and check for valid binary reduction
1286/// like chains. For all candidates we check if they have the same base address
1287/// and there are no other accesses which overlap with them. The base address
1288/// check rules out impossible reductions candidates early. The overlap check,
1289/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001290/// guarantees that none of the intermediate results will escape during
1291/// execution of the loop nest. We basically check here that no other memory
1292/// access can access the same memory as the potential reduction.
1293void ScopStmt::checkForReductions() {
1294 SmallVector<MemoryAccess *, 2> Loads;
1295 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1296
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001297 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001298 // stores and collecting possible reduction loads.
1299 for (MemoryAccess *StoreMA : MemAccs) {
1300 if (StoreMA->isRead())
1301 continue;
1302
1303 Loads.clear();
1304 collectCandiateReductionLoads(StoreMA, Loads);
1305 for (MemoryAccess *LoadMA : Loads)
1306 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1307 }
1308
1309 // Then check each possible candidate pair.
1310 for (const auto &CandidatePair : Candidates) {
1311 bool Valid = true;
1312 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1313 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1314
1315 // Skip those with obviously unequal base addresses.
1316 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1317 isl_map_free(LoadAccs);
1318 isl_map_free(StoreAccs);
1319 continue;
1320 }
1321
1322 // And check if the remaining for overlap with other memory accesses.
1323 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1324 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1325 isl_set *AllAccs = isl_map_range(AllAccsRel);
1326
1327 for (MemoryAccess *MA : MemAccs) {
1328 if (MA == CandidatePair.first || MA == CandidatePair.second)
1329 continue;
1330
1331 isl_map *AccRel =
1332 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1333 isl_set *Accs = isl_map_range(AccRel);
1334
1335 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1336 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1337 Valid = Valid && isl_set_is_empty(OverlapAccs);
1338 isl_set_free(OverlapAccs);
1339 }
1340 }
1341
1342 isl_set_free(AllAccs);
1343 if (!Valid)
1344 continue;
1345
Johannes Doerfertf6183392014-07-01 20:52:51 +00001346 const LoadInst *Load =
1347 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1348 MemoryAccess::ReductionType RT =
1349 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1350
Johannes Doerferte58a0122014-06-27 20:31:28 +00001351 // If no overlapping access was found we mark the load and store as
1352 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001353 CandidatePair.first->markAsReductionLike(RT);
1354 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001355 }
Tobias Grosser75805372011-04-29 06:27:02 +00001356}
1357
Tobias Grosser74394f02013-01-14 22:40:23 +00001358std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001359
Tobias Grosser54839312015-04-21 11:37:25 +00001360std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001361 auto *S = getSchedule();
1362 auto Str = stringFromIslObj(S);
1363 isl_map_free(S);
1364 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001365}
1366
Tobias Grosser74394f02013-01-14 22:40:23 +00001367unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001368
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001369unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001370
Tobias Grosser75805372011-04-29 06:27:02 +00001371const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1372
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001373const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001374 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001375}
1376
Tobias Grosser74394f02013-01-14 22:40:23 +00001377isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001378
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001379__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001380
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001381__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001382 return isl_set_get_space(Domain);
1383}
1384
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001385__isl_give isl_id *ScopStmt::getDomainId() const {
1386 return isl_set_get_tuple_id(Domain);
1387}
Tobias Grossercd95b772012-08-30 11:49:38 +00001388
Tobias Grosser75805372011-04-29 06:27:02 +00001389ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001390 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001391 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001392}
1393
1394void ScopStmt::print(raw_ostream &OS) const {
1395 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001396 OS.indent(12) << "Domain :=\n";
1397
1398 if (Domain) {
1399 OS.indent(16) << getDomainStr() << ";\n";
1400 } else
1401 OS.indent(16) << "n/a\n";
1402
Tobias Grosser54839312015-04-21 11:37:25 +00001403 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001404
1405 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001406 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001407 } else
1408 OS.indent(16) << "n/a\n";
1409
Tobias Grosser083d3d32014-06-28 08:59:45 +00001410 for (MemoryAccess *Access : MemAccs)
1411 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001412}
1413
1414void ScopStmt::dump() const { print(dbgs()); }
1415
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001416void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001417
1418 // Remove all memory accesses in @p InvMAs from this statement together
1419 // with all scalar accesses that were caused by them. The tricky iteration
1420 // order uses is needed because the MemAccs is a vector and the order in
1421 // which the accesses of each memory access list (MAL) are stored in this
1422 // vector is reversed.
1423 for (MemoryAccess *MA : InvMAs) {
1424 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1425 MAL.reverse();
1426
1427 auto MALIt = MAL.begin();
1428 auto MALEnd = MAL.end();
1429 auto MemAccsIt = MemAccs.begin();
1430 while (MALIt != MALEnd) {
1431 while (*MemAccsIt != *MALIt)
1432 MemAccsIt++;
1433
1434 MALIt++;
1435 MemAccs.erase(MemAccsIt);
1436 }
1437
1438 InstructionToAccess.erase(MA->getAccessInstruction());
1439 delete &MAL;
1440 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001441}
1442
Tobias Grosser75805372011-04-29 06:27:02 +00001443//===----------------------------------------------------------------------===//
1444/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001445
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001446void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001447 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1448 isl_set_free(Context);
1449 Context = NewContext;
1450}
1451
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001452/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1453struct SCEVSensitiveParameterRewriter
1454 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1455 ValueToValueMap &VMap;
1456 ScalarEvolution &SE;
1457
1458public:
1459 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1460 : VMap(VMap), SE(SE) {}
1461
1462 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1463 ValueToValueMap &VMap) {
1464 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1465 return SSPR.visit(E);
1466 }
1467
1468 const SCEV *visit(const SCEV *E) {
1469 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1470 }
1471
1472 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1473
1474 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1475 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1476 }
1477
1478 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1479 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1480 }
1481
1482 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1483 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1484 }
1485
1486 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1487 SmallVector<const SCEV *, 4> Operands;
1488 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1489 Operands.push_back(visit(E->getOperand(i)));
1490 return SE.getAddExpr(Operands);
1491 }
1492
1493 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1494 SmallVector<const SCEV *, 4> Operands;
1495 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1496 Operands.push_back(visit(E->getOperand(i)));
1497 return SE.getMulExpr(Operands);
1498 }
1499
1500 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1501 SmallVector<const SCEV *, 4> Operands;
1502 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1503 Operands.push_back(visit(E->getOperand(i)));
1504 return SE.getSMaxExpr(Operands);
1505 }
1506
1507 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1508 SmallVector<const SCEV *, 4> Operands;
1509 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1510 Operands.push_back(visit(E->getOperand(i)));
1511 return SE.getUMaxExpr(Operands);
1512 }
1513
1514 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1515 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1516 }
1517
1518 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1519 auto *Start = visit(E->getStart());
1520 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1521 visit(E->getStepRecurrence(SE)),
1522 E->getLoop(), SCEV::FlagAnyWrap);
1523 return SE.getAddExpr(Start, AddRec);
1524 }
1525
1526 const SCEV *visitUnknown(const SCEVUnknown *E) {
1527 if (auto *NewValue = VMap.lookup(E->getValue()))
1528 return SE.getUnknown(NewValue);
1529 return E;
1530 }
1531};
1532
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001533const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001534 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001535}
1536
Tobias Grosserabfbe632013-02-05 12:09:06 +00001537void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001538 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001539 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001540
1541 // Normalize the SCEV to get the representing element for an invariant load.
1542 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1543
Tobias Grosser60b54f12011-11-08 15:41:28 +00001544 if (ParameterIds.find(Parameter) != ParameterIds.end())
1545 continue;
1546
1547 int dimension = Parameters.size();
1548
1549 Parameters.push_back(Parameter);
1550 ParameterIds[Parameter] = dimension;
1551 }
1552}
1553
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001554__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001555 // Normalize the SCEV to get the representing element for an invariant load.
1556 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1557
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001558 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001559
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001560 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001561 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001562
Tobias Grosser8f99c162011-11-15 11:38:55 +00001563 std::string ParameterName;
1564
1565 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1566 Value *Val = ValueParameter->getValue();
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001567 ParameterName = Val->getName();
Johannes Doerferte071f6d2015-11-03 16:49:59 +00001568 if (!Val->hasName())
1569 if (LoadInst *LI = dyn_cast<LoadInst>(Val))
1570 ParameterName =
1571 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001572 }
1573
1574 if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
Hongbin Zheng86a37742012-04-25 08:01:38 +00001575 ParameterName = "p_" + utostr_32(IdIter->second);
Tobias Grosser8f99c162011-11-15 11:38:55 +00001576
Tobias Grosser20532b82014-04-11 17:56:49 +00001577 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1578 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001579}
Tobias Grosser75805372011-04-29 06:27:02 +00001580
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001581isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1582 isl_set *DomainContext = isl_union_set_params(getDomains());
1583 return isl_set_intersect_params(C, DomainContext);
1584}
1585
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001586void Scop::buildBoundaryContext() {
1587 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001588
1589 // The isl_set_complement operation used to create the boundary context
1590 // can possibly become very expensive. We bound the compile time of
1591 // this operation by setting a compute out.
1592 //
1593 // TODO: We can probably get around using isl_set_complement and directly
1594 // AST generate BoundaryContext.
1595 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
1596 isl_ctx_set_max_operations(getIslCtx(), 300000);
1597 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1598
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001599 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001600
Tobias Grossera52b4da2015-11-11 17:59:53 +00001601 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1602 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001603 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001604 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001605
1606 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1607 isl_ctx_reset_operations(getIslCtx());
1608 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001609 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
1610}
1611
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001612void Scop::addUserContext() {
1613 if (UserContextStr.empty())
1614 return;
1615
1616 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1617 isl_space *Space = getParamSpace();
1618 if (isl_space_dim(Space, isl_dim_param) !=
1619 isl_set_dim(UserContext, isl_dim_param)) {
1620 auto SpaceStr = isl_space_to_str(Space);
1621 errs() << "Error: the context provided in -polly-context has not the same "
1622 << "number of dimensions than the computed context. Due to this "
1623 << "mismatch, the -polly-context option is ignored. Please provide "
1624 << "the context in the parameter space: " << SpaceStr << ".\n";
1625 free(SpaceStr);
1626 isl_set_free(UserContext);
1627 isl_space_free(Space);
1628 return;
1629 }
1630
1631 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1632 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1633 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1634
1635 if (strcmp(NameContext, NameUserContext) != 0) {
1636 auto SpaceStr = isl_space_to_str(Space);
1637 errs() << "Error: the name of dimension " << i
1638 << " provided in -polly-context "
1639 << "is '" << NameUserContext << "', but the name in the computed "
1640 << "context is '" << NameContext
1641 << "'. Due to this name mismatch, "
1642 << "the -polly-context option is ignored. Please provide "
1643 << "the context in the parameter space: " << SpaceStr << ".\n";
1644 free(SpaceStr);
1645 isl_set_free(UserContext);
1646 isl_space_free(Space);
1647 return;
1648 }
1649
1650 UserContext =
1651 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1652 isl_space_get_dim_id(Space, isl_dim_param, i));
1653 }
1654
1655 Context = isl_set_intersect(Context, UserContext);
1656 isl_space_free(Space);
1657}
1658
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001659void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001660 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1661
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001662 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001663 for (LoadInst *LInst : RIL) {
1664 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1665
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001666 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001667 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001668 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001669 continue;
1670 }
1671
1672 ClassRep = LInst;
1673 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1674 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001675 }
1676}
1677
Tobias Grosser6be480c2011-11-08 15:41:13 +00001678void Scop::buildContext() {
1679 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001680 Context = isl_set_universe(isl_space_copy(Space));
1681 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001682}
1683
Tobias Grosser18daaca2012-05-22 10:47:27 +00001684void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001685 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001686 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001687
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001688 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001689
Johannes Doerferte7044942015-02-24 11:58:30 +00001690 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001691 }
1692}
1693
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001694void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001695 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001696 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001697
Tobias Grosser083d3d32014-06-28 08:59:45 +00001698 for (const auto &ParamID : ParameterIds) {
1699 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001700 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001701 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001702 }
1703
1704 // Align the parameters of all data structures to the model.
1705 Context = isl_set_align_params(Context, Space);
1706
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001707 for (ScopStmt &Stmt : *this)
1708 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001709}
1710
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001711static __isl_give isl_set *
1712simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1713 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001714 // If we modelt all blocks in the SCoP that have side effects we can simplify
1715 // the context with the constraints that are needed for anything to be
1716 // executed at all. However, if we have error blocks in the SCoP we already
1717 // assumed some parameter combinations cannot occure and removed them from the
1718 // domains, thus we cannot use the remaining domain to simplify the
1719 // assumptions.
1720 if (!S.hasErrorBlock()) {
1721 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1722 AssumptionContext =
1723 isl_set_gist_params(AssumptionContext, DomainParameters);
1724 }
1725
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001726 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1727 return AssumptionContext;
1728}
1729
1730void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001731 // The parameter constraints of the iteration domains give us a set of
1732 // constraints that need to hold for all cases where at least a single
1733 // statement iteration is executed in the whole scop. We now simplify the
1734 // assumed context under the assumption that such constraints hold and at
1735 // least a single statement iteration is executed. For cases where no
1736 // statement instances are executed, the assumptions we have taken about
1737 // the executed code do not matter and can be changed.
1738 //
1739 // WARNING: This only holds if the assumptions we have taken do not reduce
1740 // the set of statement instances that are executed. Otherwise we
1741 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001742 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001743 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001744 // performed. In such a case, modifying the run-time conditions and
1745 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001746 // to not be executed.
1747 //
1748 // Example:
1749 //
1750 // When delinearizing the following code:
1751 //
1752 // for (long i = 0; i < 100; i++)
1753 // for (long j = 0; j < m; j++)
1754 // A[i+p][j] = 1.0;
1755 //
1756 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001757 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001758 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001759 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1760 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001761}
1762
Johannes Doerfertb164c792014-09-18 11:17:17 +00001763/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001764static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001765 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1766 isl_pw_multi_aff *MinPMA, *MaxPMA;
1767 isl_pw_aff *LastDimAff;
1768 isl_aff *OneAff;
1769 unsigned Pos;
1770
Johannes Doerfert9143d672014-09-27 11:02:39 +00001771 // Restrict the number of parameters involved in the access as the lexmin/
1772 // lexmax computation will take too long if this number is high.
1773 //
1774 // Experiments with a simple test case using an i7 4800MQ:
1775 //
1776 // #Parameters involved | Time (in sec)
1777 // 6 | 0.01
1778 // 7 | 0.04
1779 // 8 | 0.12
1780 // 9 | 0.40
1781 // 10 | 1.54
1782 // 11 | 6.78
1783 // 12 | 30.38
1784 //
1785 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1786 unsigned InvolvedParams = 0;
1787 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1788 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1789 InvolvedParams++;
1790
1791 if (InvolvedParams > RunTimeChecksMaxParameters) {
1792 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001793 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001794 }
1795 }
1796
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001797 Set = isl_set_remove_divs(Set);
1798
Johannes Doerfertb164c792014-09-18 11:17:17 +00001799 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1800 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1801
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001802 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1803 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1804
Johannes Doerfertb164c792014-09-18 11:17:17 +00001805 // Adjust the last dimension of the maximal access by one as we want to
1806 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1807 // we test during code generation might now point after the end of the
1808 // allocated array but we will never dereference it anyway.
1809 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1810 "Assumed at least one output dimension");
1811 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1812 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1813 OneAff = isl_aff_zero_on_domain(
1814 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1815 OneAff = isl_aff_add_constant_si(OneAff, 1);
1816 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1817 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1818
1819 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1820
1821 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001822 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001823}
1824
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001825static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1826 isl_set *Domain = MA->getStatement()->getDomain();
1827 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1828 return isl_set_reset_tuple_id(Domain);
1829}
1830
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001831/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1832static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001833 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001834 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001835
1836 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1837 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001838 Locations = isl_union_set_coalesce(Locations);
1839 Locations = isl_union_set_detect_equalities(Locations);
1840 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001841 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001842 isl_union_set_free(Locations);
1843 return Valid;
1844}
1845
Johannes Doerfert96425c22015-08-30 21:13:53 +00001846/// @brief Helper to treat non-affine regions and basic blocks the same.
1847///
1848///{
1849
1850/// @brief Return the block that is the representing block for @p RN.
1851static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1852 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1853 : RN->getNodeAs<BasicBlock>();
1854}
1855
1856/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001857static inline BasicBlock *
1858getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001859 if (RN->isSubRegion()) {
1860 assert(idx == 0);
1861 return RN->getNodeAs<Region>()->getExit();
1862 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001863 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001864}
1865
1866/// @brief Return the smallest loop surrounding @p RN.
1867static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1868 if (!RN->isSubRegion())
1869 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1870
1871 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1872 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1873 while (L && NonAffineSubRegion->contains(L))
1874 L = L->getParentLoop();
1875 return L;
1876}
1877
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001878static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1879 if (!RN->isSubRegion())
1880 return 1;
1881
1882 unsigned NumBlocks = 0;
1883 Region *R = RN->getNodeAs<Region>();
1884 for (auto BB : R->blocks()) {
1885 (void)BB;
1886 NumBlocks++;
1887 }
1888 return NumBlocks;
1889}
1890
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001891static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1892 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001893 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001894 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001895 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001896 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001897 return true;
1898 return false;
1899}
1900
Johannes Doerfert96425c22015-08-30 21:13:53 +00001901///}
1902
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001903static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1904 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001905 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001906 isl_id *DimId =
1907 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1908 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1909}
1910
Johannes Doerfert96425c22015-08-30 21:13:53 +00001911isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1912 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1913 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00001914 return getDomainConditions(BB);
1915}
1916
1917isl_set *Scop::getDomainConditions(BasicBlock *BB) {
1918 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001919 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001920}
1921
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001922void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001923
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001924 auto *EntryBB = R->getEntry();
1925 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
1926 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001927
1928 Loop *L = LI.getLoopFor(EntryBB);
1929 while (LD-- >= 0) {
1930 S = addDomainDimId(S, LD + 1, L);
1931 L = L->getParentLoop();
1932 }
1933
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001934 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001935
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00001936 if (SD.isNonAffineSubRegion(R, R))
1937 return;
1938
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001939 buildDomainsWithBranchConstraints(R);
1940 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001941}
1942
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001943void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00001944 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00001945
1946 // To create the domain for each block in R we iterate over all blocks and
1947 // subregions in R and propagate the conditions under which the current region
1948 // element is executed. To this end we iterate in reverse post order over R as
1949 // it ensures that we first visit all predecessors of a region node (either a
1950 // basic block or a subregion) before we visit the region node itself.
1951 // Initially, only the domain for the SCoP region entry block is set and from
1952 // there we propagate the current domain to all successors, however we add the
1953 // condition that the successor is actually executed next.
1954 // As we are only interested in non-loop carried constraints here we can
1955 // simply skip loop back edges.
1956
1957 ReversePostOrderTraversal<Region *> RTraversal(R);
1958 for (auto *RN : RTraversal) {
1959
1960 // Recurse for affine subregions but go on for basic blocks and non-affine
1961 // subregions.
1962 if (RN->isSubRegion()) {
1963 Region *SubRegion = RN->getNodeAs<Region>();
1964 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00001965 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001966 continue;
1967 }
1968 }
1969
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001970 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001971 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00001972
Johannes Doerfert96425c22015-08-30 21:13:53 +00001973 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001974 TerminatorInst *TI = BB->getTerminator();
1975
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00001976 if (isa<UnreachableInst>(TI))
1977 continue;
1978
Johannes Doerfertf5673802015-10-01 23:48:18 +00001979 isl_set *Domain = DomainMap.lookup(BB);
1980 if (!Domain) {
1981 DEBUG(dbgs() << "\tSkip: " << BB->getName()
1982 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00001983 continue;
1984 }
1985
Johannes Doerfert96425c22015-08-30 21:13:53 +00001986 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001987
1988 Loop *BBLoop = getRegionNodeLoop(RN, LI);
1989 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
1990
1991 // Build the condition sets for the successor nodes of the current region
1992 // node. If it is a non-affine subregion we will always execute the single
1993 // exit node, hence the single entry node domain is the condition set. For
1994 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001995 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001996 if (RN->isSubRegion())
1997 ConditionSets.push_back(isl_set_copy(Domain));
1998 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001999 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002000
2001 // Now iterate over the successors and set their initial domain based on
2002 // their condition set. We skip back edges here and have to be careful when
2003 // we leave a loop not to keep constraints over a dimension that doesn't
2004 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002005 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002006 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002007 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002008 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002009
2010 // Skip back edges.
2011 if (DT.dominates(SuccBB, BB)) {
2012 isl_set_free(CondSet);
2013 continue;
2014 }
2015
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002016 // Do not adjust the number of dimensions if we enter a boxed loop or are
2017 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002018 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002019 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002020 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2021 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2022 SuccBBLoop = SuccBBLoop->getParentLoop();
2023
2024 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002025
2026 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2027 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2028 // and enter a new one we need to drop the old constraints.
2029 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002030 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002031 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002032 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2033 isl_set_n_dim(CondSet) - LoopDepthDiff,
2034 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002035 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002036 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002037 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002038 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002039 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002040 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002041 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2042 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002043 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002044 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002045 }
2046
2047 // Set the domain for the successor or merge it with an existing domain in
2048 // case there are multiple paths (without loop back edges) to the
2049 // successor block.
2050 isl_set *&SuccDomain = DomainMap[SuccBB];
2051 if (!SuccDomain)
2052 SuccDomain = CondSet;
2053 else
2054 SuccDomain = isl_set_union(SuccDomain, CondSet);
2055
2056 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002057 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2058 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002059 }
2060 }
2061}
2062
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002063/// @brief Return the domain for @p BB wrt @p DomainMap.
2064///
2065/// This helper function will lookup @p BB in @p DomainMap but also handle the
2066/// case where @p BB is contained in a non-affine subregion using the region
2067/// tree obtained by @p RI.
2068static __isl_give isl_set *
2069getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2070 RegionInfo &RI) {
2071 auto DIt = DomainMap.find(BB);
2072 if (DIt != DomainMap.end())
2073 return isl_set_copy(DIt->getSecond());
2074
2075 Region *R = RI.getRegionFor(BB);
2076 while (R->getEntry() == BB)
2077 R = R->getParent();
2078 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2079}
2080
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002081void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002082 // Iterate over the region R and propagate the domain constrains from the
2083 // predecessors to the current node. In contrast to the
2084 // buildDomainsWithBranchConstraints function, this one will pull the domain
2085 // information from the predecessors instead of pushing it to the successors.
2086 // Additionally, we assume the domains to be already present in the domain
2087 // map here. However, we iterate again in reverse post order so we know all
2088 // predecessors have been visited before a block or non-affine subregion is
2089 // visited.
2090
2091 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2092 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2093
2094 ReversePostOrderTraversal<Region *> RTraversal(R);
2095 for (auto *RN : RTraversal) {
2096
2097 // Recurse for affine subregions but go on for basic blocks and non-affine
2098 // subregions.
2099 if (RN->isSubRegion()) {
2100 Region *SubRegion = RN->getNodeAs<Region>();
2101 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002102 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002103 continue;
2104 }
2105 }
2106
Johannes Doerfertf5673802015-10-01 23:48:18 +00002107 // Get the domain for the current block and check if it was initialized or
2108 // not. The only way it was not is if this block is only reachable via error
2109 // blocks, thus will not be executed under the assumptions we make. Such
2110 // blocks have to be skipped as their predecessors might not have domains
2111 // either. It would not benefit us to compute the domain anyway, only the
2112 // domains of the error blocks that are reachable from non-error blocks
2113 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002114 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002115 isl_set *&Domain = DomainMap[BB];
2116 if (!Domain) {
2117 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2118 << ", it is only reachable from error blocks.\n");
2119 DomainMap.erase(BB);
2120 continue;
2121 }
2122 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2123
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002124 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2125 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2126
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002127 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2128 for (auto *PredBB : predecessors(BB)) {
2129
2130 // Skip backedges
2131 if (DT.dominates(BB, PredBB))
2132 continue;
2133
2134 isl_set *PredBBDom = nullptr;
2135
2136 // Handle the SCoP entry block with its outside predecessors.
2137 if (!getRegion().contains(PredBB))
2138 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2139
2140 if (!PredBBDom) {
2141 // Determine the loop depth of the predecessor and adjust its domain to
2142 // the domain of the current block. This can mean we have to:
2143 // o) Drop a dimension if this block is the exit of a loop, not the
2144 // header of a new loop and the predecessor was part of the loop.
2145 // o) Add an unconstrainted new dimension if this block is the header
2146 // of a loop and the predecessor is not part of it.
2147 // o) Drop the information about the innermost loop dimension when the
2148 // predecessor and the current block are surrounded by different
2149 // loops in the same depth.
2150 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2151 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2152 while (BoxedLoops.count(PredBBLoop))
2153 PredBBLoop = PredBBLoop->getParentLoop();
2154
2155 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002156 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002157 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002158 PredBBDom = isl_set_project_out(
2159 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2160 LoopDepthDiff);
2161 else if (PredBBLoopDepth < BBLoopDepth) {
2162 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002163 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002164 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2165 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002166 PredBBDom = isl_set_drop_constraints_involving_dims(
2167 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002168 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002169 }
2170
2171 PredDom = isl_set_union(PredDom, PredBBDom);
2172 }
2173
2174 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002175 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002176
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002177 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002178 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002179
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002180 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002181 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002182 IsOptimized = true;
2183 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2184 addAssumption(isl_set_complement(DomPar));
2185 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002186 }
2187}
2188
2189/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2190/// is incremented by one and all other dimensions are equal, e.g.,
2191/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2192/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2193static __isl_give isl_map *
2194createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2195 auto *MapSpace = isl_space_map_from_set(SetSpace);
2196 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2197 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2198 if (u != Dim)
2199 NextIterationMap =
2200 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2201 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2202 C = isl_constraint_set_constant_si(C, 1);
2203 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2204 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2205 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2206 return NextIterationMap;
2207}
2208
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002209void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002210 int LoopDepth = getRelativeLoopDepth(L);
2211 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002212
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002213 BasicBlock *HeaderBB = L->getHeader();
2214 assert(DomainMap.count(HeaderBB));
2215 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002216
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002217 isl_map *NextIterationMap =
2218 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002219
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002220 isl_set *UnionBackedgeCondition =
2221 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002222
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002223 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2224 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002225
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002226 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002227
2228 // If the latch is only reachable via error statements we skip it.
2229 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2230 if (!LatchBBDom)
2231 continue;
2232
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002233 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002234
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002235 TerminatorInst *TI = LatchBB->getTerminator();
2236 BranchInst *BI = dyn_cast<BranchInst>(TI);
2237 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002238 BackedgeCondition = isl_set_copy(LatchBBDom);
2239 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002240 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002241 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002242 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002243
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002244 // Free the non back edge condition set as we do not need it.
2245 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002246
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002247 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002248 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002249
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002250 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2251 assert(LatchLoopDepth >= LoopDepth);
2252 BackedgeCondition =
2253 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2254 LatchLoopDepth - LoopDepth);
2255 UnionBackedgeCondition =
2256 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002257 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002258
2259 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2260 for (int i = 0; i < LoopDepth; i++)
2261 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2262
2263 isl_set *UnionBackedgeConditionComplement =
2264 isl_set_complement(UnionBackedgeCondition);
2265 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2266 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2267 UnionBackedgeConditionComplement =
2268 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2269 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2270 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2271
2272 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2273 HeaderBBDom = Parts.second;
2274
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002275 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2276 // the bounded assumptions to the context as they are already implied by the
2277 // <nsw> tag.
2278 if (Affinator.hasNSWAddRecForLoop(L)) {
2279 isl_set_free(Parts.first);
2280 return;
2281 }
2282
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002283 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2284 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfert707a4062015-09-20 16:38:19 +00002285 addAssumption(BoundedCtx);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002286}
2287
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002288void Scop::buildAliasChecks(AliasAnalysis &AA) {
2289 if (!PollyUseRuntimeAliasChecks)
2290 return;
2291
2292 if (buildAliasGroups(AA))
2293 return;
2294
2295 // If a problem occurs while building the alias groups we need to delete
2296 // this SCoP and pretend it wasn't valid in the first place. To this end
2297 // we make the assumed context infeasible.
2298 addAssumption(isl_set_empty(getParamSpace()));
2299
2300 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2301 << " could not be created as the number of parameters involved "
2302 "is too high. The SCoP will be "
2303 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2304 "the maximal number of parameters but be advised that the "
2305 "compile time might increase exponentially.\n\n");
2306}
2307
Johannes Doerfert9143d672014-09-27 11:02:39 +00002308bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002309 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002310 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002311 // for all memory accesses inside the SCoP.
2312 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002313 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002314 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002315 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002316 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002317 // if their access domains intersect, otherwise they are in different
2318 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002319 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002320 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002321 // and maximal accesses to each array of a group in read only and non
2322 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002323 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2324
2325 AliasSetTracker AST(AA);
2326
2327 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002328 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002329 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002330
2331 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002332 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002333 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2334 isl_set_free(StmtDomain);
2335 if (StmtDomainEmpty)
2336 continue;
2337
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002338 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002339 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002340 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002341 if (!MA->isRead())
2342 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002343 Instruction *Acc = MA->getAccessInstruction();
2344 PtrToAcc[getPointerOperand(*Acc)] = MA;
2345 AST.add(Acc);
2346 }
2347 }
2348
2349 SmallVector<AliasGroupTy, 4> AliasGroups;
2350 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002351 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002352 continue;
2353 AliasGroupTy AG;
2354 for (auto PR : AS)
2355 AG.push_back(PtrToAcc[PR.getValue()]);
2356 assert(AG.size() > 1 &&
2357 "Alias groups should contain at least two accesses");
2358 AliasGroups.push_back(std::move(AG));
2359 }
2360
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002361 // Split the alias groups based on their domain.
2362 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2363 AliasGroupTy NewAG;
2364 AliasGroupTy &AG = AliasGroups[u];
2365 AliasGroupTy::iterator AGI = AG.begin();
2366 isl_set *AGDomain = getAccessDomain(*AGI);
2367 while (AGI != AG.end()) {
2368 MemoryAccess *MA = *AGI;
2369 isl_set *MADomain = getAccessDomain(MA);
2370 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2371 NewAG.push_back(MA);
2372 AGI = AG.erase(AGI);
2373 isl_set_free(MADomain);
2374 } else {
2375 AGDomain = isl_set_union(AGDomain, MADomain);
2376 AGI++;
2377 }
2378 }
2379 if (NewAG.size() > 1)
2380 AliasGroups.push_back(std::move(NewAG));
2381 isl_set_free(AGDomain);
2382 }
2383
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002384 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002385 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002386 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2387 for (AliasGroupTy &AG : AliasGroups) {
2388 NonReadOnlyBaseValues.clear();
2389 ReadOnlyPairs.clear();
2390
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002391 if (AG.size() < 2) {
2392 AG.clear();
2393 continue;
2394 }
2395
Johannes Doerfert13771732014-10-01 12:40:46 +00002396 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002397 emitOptimizationRemarkAnalysis(
2398 F.getContext(), DEBUG_TYPE, F,
2399 (*II)->getAccessInstruction()->getDebugLoc(),
2400 "Possibly aliasing pointer, use restrict keyword.");
2401
Johannes Doerfert13771732014-10-01 12:40:46 +00002402 Value *BaseAddr = (*II)->getBaseAddr();
2403 if (HasWriteAccess.count(BaseAddr)) {
2404 NonReadOnlyBaseValues.insert(BaseAddr);
2405 II++;
2406 } else {
2407 ReadOnlyPairs[BaseAddr].insert(*II);
2408 II = AG.erase(II);
2409 }
2410 }
2411
2412 // If we don't have read only pointers check if there are at least two
2413 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002414 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002415 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002416 continue;
2417 }
2418
2419 // If we don't have non read only pointers clear the alias group.
2420 if (NonReadOnlyBaseValues.empty()) {
2421 AG.clear();
2422 continue;
2423 }
2424
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002425 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002426 MinMaxAliasGroups.emplace_back();
2427 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2428 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2429 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2430 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002431
2432 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002433
2434 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002435 for (MemoryAccess *MA : AG)
2436 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002437
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002438 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2439 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002440
2441 // Bail out if the number of values we need to compare is too large.
2442 // This is important as the number of comparisions grows quadratically with
2443 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002444 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2445 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002446 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002447
2448 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002449 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002450 Accesses = isl_union_map_empty(getParamSpace());
2451
2452 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2453 for (MemoryAccess *MA : ReadOnlyPair.second)
2454 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2455
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002456 Valid =
2457 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002458
2459 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002460 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002461 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002462
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002463 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002464}
2465
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002466static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
2467 Loop *L = LI.getLoopFor(R.getEntry());
2468 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2469}
2470
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002471static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2472 ScopDetection &SD) {
2473
2474 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2475
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002476 unsigned MinLD = INT_MAX, MaxLD = 0;
2477 for (BasicBlock *BB : R.blocks()) {
2478 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002479 if (!R.contains(L))
2480 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002481 if (BoxedLoops && BoxedLoops->count(L))
2482 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002483 unsigned LD = L->getLoopDepth();
2484 MinLD = std::min(MinLD, LD);
2485 MaxLD = std::max(MaxLD, LD);
2486 }
2487 }
2488
2489 // Handle the case that there is no loop in the SCoP first.
2490 if (MaxLD == 0)
2491 return 1;
2492
2493 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2494 assert(MaxLD >= MinLD &&
2495 "Maximal loop depth was smaller than mininaml loop depth?");
2496 return MaxLD - MinLD + 1;
2497}
2498
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002499Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002500 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002501 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002502 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2503 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002504 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2505 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2506 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2507 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002508
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002509void Scop::init(AliasAnalysis &AA) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002510 buildContext();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002511 buildInvariantEquivalenceClasses();
2512
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002513 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002514
Michael Krusecac948e2015-10-02 13:53:07 +00002515 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002516 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002517 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002518 if (Stmts.empty())
2519 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002520
Michael Krusecac948e2015-10-02 13:53:07 +00002521 // The ScopStmts now have enough information to initialize themselves.
2522 for (ScopStmt &Stmt : Stmts)
2523 Stmt.init();
2524
2525 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002526 Loop *L = getLoopSurroundingRegion(R, LI);
2527 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002528 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002529 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002530
Tobias Grosser8286b832015-11-02 11:29:32 +00002531 if (isl_set_is_empty(AssumedContext))
2532 return;
2533
2534 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002535 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002536 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002537 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002538 buildBoundaryContext();
2539 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002540 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002541
2542 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002543 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002544}
2545
2546Scop::~Scop() {
2547 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002548 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002549 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002550 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002551
Johannes Doerfert96425c22015-08-30 21:13:53 +00002552 for (auto It : DomainMap)
2553 isl_set_free(It.second);
2554
Johannes Doerfertb164c792014-09-18 11:17:17 +00002555 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002556 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002557 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002558 isl_pw_multi_aff_free(MMA.first);
2559 isl_pw_multi_aff_free(MMA.second);
2560 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002561 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002562 isl_pw_multi_aff_free(MMA.first);
2563 isl_pw_multi_aff_free(MMA.second);
2564 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002565 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002566
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002567 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002568 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002569}
2570
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002571void Scop::updateAccessDimensionality() {
2572 for (auto &Stmt : *this)
2573 for (auto &Access : Stmt)
2574 Access->updateDimensionality();
2575}
2576
Michael Krusecac948e2015-10-02 13:53:07 +00002577void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002578 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2579 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002580 RegionNode *RN = Stmt.isRegionStmt()
2581 ? Stmt.getRegion()->getNode()
2582 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002583
Johannes Doerferteca9e892015-11-03 16:54:49 +00002584 bool RemoveStmt = StmtIt->isEmpty();
2585 if (!RemoveStmt)
2586 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2587 if (!RemoveStmt)
2588 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002589
Johannes Doerferteca9e892015-11-03 16:54:49 +00002590 // Remove read only statements only after invariant loop hoisting.
2591 if (!RemoveStmt && !RemoveIgnoredStmts) {
2592 bool OnlyRead = true;
2593 for (MemoryAccess *MA : Stmt) {
2594 if (MA->isRead())
2595 continue;
2596
2597 OnlyRead = false;
2598 break;
2599 }
2600
2601 RemoveStmt = OnlyRead;
2602 }
2603
2604 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002605 // Remove the statement because it is unnecessary.
2606 if (Stmt.isRegionStmt())
2607 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2608 StmtMap.erase(BB);
2609 else
2610 StmtMap.erase(Stmt.getBasicBlock());
2611
2612 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002613 continue;
2614 }
2615
Michael Krusecac948e2015-10-02 13:53:07 +00002616 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002617 }
2618}
2619
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002620const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2621 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2622 if (!LInst)
2623 return nullptr;
2624
2625 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2626 LInst = cast<LoadInst>(Rep);
2627
2628 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2629 for (auto &IAClass : InvariantEquivClasses)
2630 if (PointerSCEV == std::get<0>(IAClass))
2631 return &IAClass;
2632
2633 return nullptr;
2634}
2635
2636void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2637
2638 // Get the context under which the statement is executed.
2639 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2640 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2641 DomainCtx = isl_set_detect_equalities(DomainCtx);
2642 DomainCtx = isl_set_coalesce(DomainCtx);
2643
2644 // Project out all parameters that relate to loads in the statement. Otherwise
2645 // we could have cyclic dependences on the constraints under which the
2646 // hoisted loads are executed and we could not determine an order in which to
2647 // pre-load them. This happens because not only lower bounds are part of the
2648 // domain but also upper bounds.
2649 for (MemoryAccess *MA : InvMAs) {
2650 Instruction *AccInst = MA->getAccessInstruction();
2651 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002652 SetVector<Value *> Values;
2653 for (const SCEV *Parameter : Parameters) {
2654 Values.clear();
2655 findValues(Parameter, Values);
2656 if (!Values.count(AccInst))
2657 continue;
2658
2659 if (isl_id *ParamId = getIdForParam(Parameter)) {
2660 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2661 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2662 isl_id_free(ParamId);
2663 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002664 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002665 }
2666 }
2667
2668 for (MemoryAccess *MA : InvMAs) {
2669 // Check for another invariant access that accesses the same location as
2670 // MA and if found consolidate them. Otherwise create a new equivalence
2671 // class at the end of InvariantEquivClasses.
2672 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2673 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2674
2675 bool Consolidated = false;
2676 for (auto &IAClass : InvariantEquivClasses) {
2677 if (PointerSCEV != std::get<0>(IAClass))
2678 continue;
2679
2680 Consolidated = true;
2681
2682 // Add MA to the list of accesses that are in this class.
2683 auto &MAs = std::get<1>(IAClass);
2684 MAs.push_front(MA);
2685
2686 // Unify the execution context of the class and this statement.
2687 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002688 if (IAClassDomainCtx)
2689 IAClassDomainCtx = isl_set_coalesce(
2690 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2691 else
2692 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002693 break;
2694 }
2695
2696 if (Consolidated)
2697 continue;
2698
2699 // If we did not consolidate MA, thus did not find an equivalence class
2700 // for it, we create a new one.
2701 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2702 isl_set_copy(DomainCtx));
2703 }
2704
2705 isl_set_free(DomainCtx);
2706}
2707
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002708void Scop::hoistInvariantLoads() {
2709 isl_union_map *Writes = getWrites();
2710 for (ScopStmt &Stmt : *this) {
2711
2712 // TODO: Loads that are not loop carried, hence are in a statement with
2713 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002714 // currently "hoist" them anyway. This is necessary because we allow
2715 // them to be treated as parameters (e.g., in conditions) and our code
2716 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002717
Johannes Doerfert8930f482015-10-02 14:51:00 +00002718 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2719 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002720 isl_set *Domain = Stmt.getDomain();
2721 MemoryAccessList InvMAs;
2722
2723 for (MemoryAccess *MA : Stmt) {
2724 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2725 continue;
2726
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002727 // Skip accesses that have an invariant base pointer which is defined but
2728 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2729 // returns a pointer that is used as a base address. However, as we want
2730 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002731 // the region if it is also a memory access. Each ScopArrayInfo object
2732 // that has a base pointer origin has a base pointer that is loaded and
2733 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002734 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002735 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002736 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002737 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2738 SAI = BasePtrOriginSAI;
2739
2740 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2741 if (R.contains(BasePtrInst))
2742 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002743
Johannes Doerfert8930f482015-10-02 14:51:00 +00002744 // Skip accesses in non-affine subregions as they might not be executed
2745 // under the same condition as the entry of the non-affine subregion.
2746 if (BB != MA->getAccessInstruction()->getParent())
2747 continue;
2748
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002749 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002750
2751 // Skip accesses that have an empty access relation. These can be caused
2752 // by multiple offsets with a type cast in-between that cause the overall
2753 // byte offset to be not divisible by the new types sizes.
2754 if (isl_map_is_empty(AccessRelation)) {
2755 isl_map_free(AccessRelation);
2756 continue;
2757 }
2758
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002759 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2760 Stmt.getNumIterators())) {
2761 isl_map_free(AccessRelation);
2762 continue;
2763 }
2764
2765 AccessRelation =
2766 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2767 isl_set *AccessRange = isl_map_range(AccessRelation);
2768
2769 isl_union_map *Written = isl_union_map_intersect_range(
2770 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2771 bool IsWritten = !isl_union_map_is_empty(Written);
2772 isl_union_map_free(Written);
2773
2774 if (IsWritten)
2775 continue;
2776
2777 InvMAs.push_front(MA);
2778 }
2779
2780 // We inserted invariant accesses always in the front but need them to be
2781 // sorted in a "natural order". The statements are already sorted in reverse
2782 // post order and that suffices for the accesses too. The reason we require
2783 // an order in the first place is the dependences between invariant loads
2784 // that can be caused by indirect loads.
2785 InvMAs.reverse();
2786
2787 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002788 Stmt.removeMemoryAccesses(InvMAs);
2789 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002790
2791 isl_set_free(Domain);
2792 }
2793 isl_union_map_free(Writes);
2794
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002795 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002796 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002797 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002798 assert(LI && getRegion().contains(LI));
2799 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2800 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2801 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2802 << ") is required to be invariant but was not marked as "
2803 "such. SCoP for "
2804 << getRegion() << " will be dropped\n\n");
2805 addAssumption(isl_set_empty(getParamSpace()));
2806 return;
2807 }
2808 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002809}
2810
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002811const ScopArrayInfo *
2812Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002813 ArrayRef<const SCEV *> Sizes,
2814 ScopArrayInfo::ARRAYKIND Kind) {
2815 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002816 if (!SAI) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002817 SAI.reset(
2818 new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002819 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002820 // In case of mismatching array sizes, we bail out by setting the run-time
2821 // context to false.
2822 if (!SAI->updateSizes(Sizes))
2823 addAssumption(isl_set_empty(getParamSpace()));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002824 }
Tobias Grosserab671442015-05-23 05:58:27 +00002825 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002826}
2827
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002828const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2829 ScopArrayInfo::ARRAYKIND Kind) {
2830 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002831 assert(SAI && "No ScopArrayInfo available for this base pointer");
2832 return SAI;
2833}
2834
Tobias Grosser74394f02013-01-14 22:40:23 +00002835std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002836std::string Scop::getAssumedContextStr() const {
2837 return stringFromIslObj(AssumedContext);
2838}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002839std::string Scop::getBoundaryContextStr() const {
2840 return stringFromIslObj(BoundaryContext);
2841}
Tobias Grosser75805372011-04-29 06:27:02 +00002842
2843std::string Scop::getNameStr() const {
2844 std::string ExitName, EntryName;
2845 raw_string_ostream ExitStr(ExitName);
2846 raw_string_ostream EntryStr(EntryName);
2847
Tobias Grosserf240b482014-01-09 10:42:15 +00002848 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002849 EntryStr.str();
2850
2851 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002852 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002853 ExitStr.str();
2854 } else
2855 ExitName = "FunctionExit";
2856
2857 return EntryName + "---" + ExitName;
2858}
2859
Tobias Grosser74394f02013-01-14 22:40:23 +00002860__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002861__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002862 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002863}
2864
Tobias Grossere86109f2013-10-29 21:05:49 +00002865__isl_give isl_set *Scop::getAssumedContext() const {
2866 return isl_set_copy(AssumedContext);
2867}
2868
Johannes Doerfert43788c52015-08-20 05:58:56 +00002869__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2870 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002871 RuntimeCheckContext =
2872 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2873 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002874 return RuntimeCheckContext;
2875}
2876
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002877bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002878 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002879 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002880 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2881 isl_set_free(RuntimeCheckContext);
2882 return IsFeasible;
2883}
2884
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002885void Scop::addAssumption(__isl_take isl_set *Set) {
2886 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002887
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00002888 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002889 if (NSets >= MaxDisjunctsAssumed) {
2890 isl_space *Space = isl_set_get_space(AssumedContext);
2891 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00002892 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00002893 }
2894
Tobias Grosser7b50bee2014-11-25 10:51:12 +00002895 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002896}
2897
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002898__isl_give isl_set *Scop::getBoundaryContext() const {
2899 return isl_set_copy(BoundaryContext);
2900}
2901
Tobias Grosser75805372011-04-29 06:27:02 +00002902void Scop::printContext(raw_ostream &OS) const {
2903 OS << "Context:\n";
2904
2905 if (!Context) {
2906 OS.indent(4) << "n/a\n\n";
2907 return;
2908 }
2909
2910 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00002911
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002912 OS.indent(4) << "Assumed Context:\n";
2913 if (!AssumedContext) {
2914 OS.indent(4) << "n/a\n\n";
2915 return;
2916 }
2917
2918 OS.indent(4) << getAssumedContextStr() << "\n";
2919
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002920 OS.indent(4) << "Boundary Context:\n";
2921 if (!BoundaryContext) {
2922 OS.indent(4) << "n/a\n\n";
2923 return;
2924 }
2925
2926 OS.indent(4) << getBoundaryContextStr() << "\n";
2927
Tobias Grosser083d3d32014-06-28 08:59:45 +00002928 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00002929 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00002930 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
2931 }
Tobias Grosser75805372011-04-29 06:27:02 +00002932}
2933
Johannes Doerfertb164c792014-09-18 11:17:17 +00002934void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002935 int noOfGroups = 0;
2936 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002937 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002938 noOfGroups += 1;
2939 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002940 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002941 }
2942
Tobias Grosserbb853c22015-07-25 12:31:03 +00002943 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00002944 if (MinMaxAliasGroups.empty()) {
2945 OS.indent(8) << "n/a\n";
2946 return;
2947 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002948
Tobias Grosserbb853c22015-07-25 12:31:03 +00002949 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002950
2951 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002952 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002953 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002954 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002955 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2956 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002957 }
2958 OS << " ]]\n";
2959 }
2960
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002961 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002962 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00002963 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002964 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00002965 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
2966 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002967 }
2968 OS << " ]]\n";
2969 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002970 }
2971}
2972
Tobias Grosser75805372011-04-29 06:27:02 +00002973void Scop::printStatements(raw_ostream &OS) const {
2974 OS << "Statements {\n";
2975
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002976 for (const ScopStmt &Stmt : *this)
2977 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00002978
2979 OS.indent(4) << "}\n";
2980}
2981
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002982void Scop::printArrayInfo(raw_ostream &OS) const {
2983 OS << "Arrays {\n";
2984
Tobias Grosserab671442015-05-23 05:58:27 +00002985 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002986 Array.second->print(OS);
2987
2988 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00002989
2990 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
2991
2992 for (auto &Array : arrays())
2993 Array.second->print(OS, /* SizeAsPwAff */ true);
2994
2995 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00002996}
2997
Tobias Grosser75805372011-04-29 06:27:02 +00002998void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00002999 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3000 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003001 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003002 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003003 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003004 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003005 const auto &MAs = std::get<1>(IAClass);
3006 if (MAs.empty()) {
3007 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003008 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003009 MAs.front()->print(OS);
3010 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003011 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003012 }
3013 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003014 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003015 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003016 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003017 printStatements(OS.indent(4));
3018}
3019
3020void Scop::dump() const { print(dbgs()); }
3021
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003022isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003023
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003024__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3025 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003026}
3027
Tobias Grosser808cd692015-07-14 09:33:13 +00003028__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003029 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003030
Tobias Grosser808cd692015-07-14 09:33:13 +00003031 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003032 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003033
3034 return Domain;
3035}
3036
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003037__isl_give isl_union_map *Scop::getMustWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003038 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003039
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003040 for (ScopStmt &Stmt : *this) {
3041 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003042 if (!MA->isMustWrite())
3043 continue;
3044
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003045 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003046 isl_map *AccessDomain = MA->getAccessRelation();
3047 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3048 Write = isl_union_map_add_map(Write, AccessDomain);
3049 }
3050 }
3051 return isl_union_map_coalesce(Write);
3052}
3053
3054__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003055 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003056
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003057 for (ScopStmt &Stmt : *this) {
3058 for (MemoryAccess *MA : Stmt) {
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003059 if (!MA->isMayWrite())
3060 continue;
3061
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003062 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003063 isl_map *AccessDomain = MA->getAccessRelation();
3064 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3065 Write = isl_union_map_add_map(Write, AccessDomain);
3066 }
3067 }
3068 return isl_union_map_coalesce(Write);
3069}
3070
Tobias Grosser37eb4222014-02-20 21:43:54 +00003071__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003072 isl_union_map *Write = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003073
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003074 for (ScopStmt &Stmt : *this) {
3075 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003076 if (!MA->isWrite())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003077 continue;
3078
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003079 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003080 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003081 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3082 Write = isl_union_map_add_map(Write, AccessDomain);
3083 }
3084 }
3085 return isl_union_map_coalesce(Write);
3086}
3087
3088__isl_give isl_union_map *Scop::getReads() {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003089 isl_union_map *Read = isl_union_map_empty(getParamSpace());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003090
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003091 for (ScopStmt &Stmt : *this) {
3092 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertf6752892014-06-13 18:01:45 +00003093 if (!MA->isRead())
Tobias Grosser37eb4222014-02-20 21:43:54 +00003094 continue;
3095
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003096 isl_set *Domain = Stmt.getDomain();
Johannes Doerfertf6752892014-06-13 18:01:45 +00003097 isl_map *AccessDomain = MA->getAccessRelation();
Tobias Grosser37eb4222014-02-20 21:43:54 +00003098
3099 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
3100 Read = isl_union_map_add_map(Read, AccessDomain);
3101 }
3102 }
3103 return isl_union_map_coalesce(Read);
3104}
3105
Tobias Grosser808cd692015-07-14 09:33:13 +00003106__isl_give isl_union_map *Scop::getSchedule() const {
3107 auto Tree = getScheduleTree();
3108 auto S = isl_schedule_get_map(Tree);
3109 isl_schedule_free(Tree);
3110 return S;
3111}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003112
Tobias Grosser808cd692015-07-14 09:33:13 +00003113__isl_give isl_schedule *Scop::getScheduleTree() const {
3114 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3115 getDomains());
3116}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003117
Tobias Grosser808cd692015-07-14 09:33:13 +00003118void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3119 auto *S = isl_schedule_from_domain(getDomains());
3120 S = isl_schedule_insert_partial_schedule(
3121 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3122 isl_schedule_free(Schedule);
3123 Schedule = S;
3124}
3125
3126void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3127 isl_schedule_free(Schedule);
3128 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003129}
3130
3131bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3132 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003133 for (ScopStmt &Stmt : *this) {
3134 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003135 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3136 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3137
3138 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3139 isl_union_set_free(StmtDomain);
3140 isl_union_set_free(NewStmtDomain);
3141 continue;
3142 }
3143
3144 Changed = true;
3145
3146 isl_union_set_free(StmtDomain);
3147 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3148
3149 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003150 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003151 isl_union_set_free(NewStmtDomain);
3152 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003153 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003154 }
3155 isl_union_set_free(Domain);
3156 return Changed;
3157}
3158
Tobias Grosser75805372011-04-29 06:27:02 +00003159ScalarEvolution *Scop::getSE() const { return SE; }
3160
Johannes Doerfertf5673802015-10-01 23:48:18 +00003161bool Scop::isIgnored(RegionNode *RN) {
3162 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003163
Johannes Doerfertf5673802015-10-01 23:48:18 +00003164 // Check if there are accesses contained.
3165 bool ContainsAccesses = false;
3166 if (!RN->isSubRegion())
3167 ContainsAccesses = getAccessFunctions(BB);
3168 else
3169 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3170 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3171 if (!ContainsAccesses)
3172 return true;
3173
3174 // Check for reachability via non-error blocks.
3175 if (!DomainMap.count(BB))
3176 return true;
3177
3178 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003179 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003180 return true;
3181
3182 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003183}
3184
Tobias Grosser808cd692015-07-14 09:33:13 +00003185struct MapToDimensionDataTy {
3186 int N;
3187 isl_union_pw_multi_aff *Res;
3188};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003189
Tobias Grosser808cd692015-07-14 09:33:13 +00003190// @brief Create a function that maps the elements of 'Set' to its N-th
3191// dimension.
3192//
3193// The result is added to 'User->Res'.
3194//
3195// @param Set The input set.
3196// @param N The dimension to map to.
3197//
3198// @returns Zero if no error occurred, non-zero otherwise.
3199static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3200 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3201 int Dim;
3202 isl_space *Space;
3203 isl_pw_multi_aff *PMA;
3204
3205 Dim = isl_set_dim(Set, isl_dim_set);
3206 Space = isl_set_get_space(Set);
3207 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3208 Dim - Data->N);
3209 if (Data->N > 1)
3210 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3211 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3212
3213 isl_set_free(Set);
3214
3215 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003216}
3217
Tobias Grosser808cd692015-07-14 09:33:13 +00003218// @brief Create a function that maps the elements of Domain to their Nth
3219// dimension.
3220//
3221// @param Domain The set of elements to map.
3222// @param N The dimension to map to.
3223static __isl_give isl_multi_union_pw_aff *
3224mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003225 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3226 isl_union_set_free(Domain);
3227 return nullptr;
3228 }
3229
Tobias Grosser808cd692015-07-14 09:33:13 +00003230 struct MapToDimensionDataTy Data;
3231 isl_space *Space;
3232
3233 Space = isl_union_set_get_space(Domain);
3234 Data.N = N;
3235 Data.Res = isl_union_pw_multi_aff_empty(Space);
3236 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3237 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3238
3239 isl_union_set_free(Domain);
3240 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3241}
3242
Tobias Grosser316b5b22015-11-11 19:28:14 +00003243void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003244 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003245 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003246 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003247 StmtMap[BB] = Stmt;
3248 } else {
3249 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003250 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003251 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003252 for (BasicBlock *BB : R->blocks())
3253 StmtMap[BB] = Stmt;
3254 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003255}
3256
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003257void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003258 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003259 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003260
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003261 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003262 Loop *L = getLoopSurroundingRegion(*R, LI);
3263 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003264 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003265 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003266 auto *UDomain = isl_union_set_from_set(Domain);
3267 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003268 LSchedulePair.first = StmtSchedule;
3269 return;
3270 }
3271
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003272 ReversePostOrderTraversal<Region *> RTraversal(R);
3273 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003274
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003275 if (RN->isSubRegion()) {
3276 Region *SubRegion = RN->getNodeAs<Region>();
3277 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003278 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003279 continue;
3280 }
Tobias Grosser75805372011-04-29 06:27:02 +00003281 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003282
3283 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003284 if (!getRegion().contains(L))
3285 L = getLoopSurroundingRegion(getRegion(), LI);
3286
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003287 int LD = getRelativeLoopDepth(L);
3288 auto &LSchedulePair = LoopSchedules[L];
3289 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3290
Michael Krusecac948e2015-10-02 13:53:07 +00003291 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3292 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3293 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003294 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3295 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3296 LSchedulePair.first =
3297 combineInSequence(LSchedulePair.first, StmtSchedule);
3298 }
3299
3300 unsigned NumVisited = LSchedulePair.second;
3301 while (L && NumVisited == L->getNumBlocks()) {
3302 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3303 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3304 LSchedulePair.first =
3305 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3306
3307 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003308
3309 // Either we have a proper loop and we also build a schedule for the
3310 // parent loop or we have a infinite loop that does not have a proper
3311 // parent loop. In the former case this conditional will be skipped, in
3312 // the latter case however we will break here as we do not build a domain
3313 // nor a schedule for a infinite loop.
3314 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3315 if (!LoopSchedules.count(PL))
3316 break;
3317
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003318 auto &PSchedulePair = LoopSchedules[PL];
3319 PSchedulePair.first =
3320 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3321 PSchedulePair.second += NumVisited;
3322
3323 L = PL;
3324 NumVisited = PSchedulePair.second;
3325 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003326 }
Tobias Grosser75805372011-04-29 06:27:02 +00003327}
3328
Johannes Doerfert7c494212014-10-31 23:13:39 +00003329ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003330 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003331 if (StmtMapIt == StmtMap.end())
3332 return nullptr;
3333 return StmtMapIt->second;
3334}
3335
Johannes Doerfert96425c22015-08-30 21:13:53 +00003336int Scop::getRelativeLoopDepth(const Loop *L) const {
3337 Loop *OuterLoop =
3338 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3339 if (!OuterLoop)
3340 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003341 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3342}
3343
Michael Krused868b5d2015-09-10 15:25:24 +00003344void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003345 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003346
3347 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3348 // true, are not modeled as ordinary PHI nodes as they are not part of the
3349 // region. However, we model the operands in the predecessor blocks that are
3350 // part of the region as regular scalar accesses.
3351
3352 // If we can synthesize a PHI we can skip it, however only if it is in
3353 // the region. If it is not it can only be in the exit block of the region.
3354 // In this case we model the operands but not the PHI itself.
3355 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3356 return;
3357
3358 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3359 // detection. Hence, the PHI is a load of a new memory location in which the
3360 // incoming value was written at the end of the incoming basic block.
3361 bool OnlyNonAffineSubRegionOperands = true;
3362 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3363 Value *Op = PHI->getIncomingValue(u);
3364 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3365
3366 // Do not build scalar dependences inside a non-affine subregion.
3367 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3368 continue;
3369
3370 OnlyNonAffineSubRegionOperands = false;
3371
3372 if (!R.contains(OpBB))
3373 continue;
3374
3375 Instruction *OpI = dyn_cast<Instruction>(Op);
3376 if (OpI) {
3377 BasicBlock *OpIBB = OpI->getParent();
3378 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3379 // we have to insert a scalar dependence from the definition of OpI to
3380 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003381 if (scop->getStmtForBasicBlock(OpIBB) !=
3382 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003383 addScalarReadAccess(OpI, PHI, OpBB);
3384 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003385 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003386 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003387 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003388 }
3389
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003390 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003391 }
3392
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003393 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3394 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003395 }
3396}
3397
Michael Krused868b5d2015-09-10 15:25:24 +00003398bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3399 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003400 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3401 if (isIgnoredIntrinsic(Inst))
3402 return false;
3403
3404 bool AnyCrossStmtUse = false;
3405 BasicBlock *ParentBB = Inst->getParent();
3406
3407 for (User *U : Inst->users()) {
3408 Instruction *UI = dyn_cast<Instruction>(U);
3409
3410 // Ignore the strange user
3411 if (UI == 0)
3412 continue;
3413
3414 BasicBlock *UseParent = UI->getParent();
3415
Tobias Grosserbaffa092015-10-24 20:55:27 +00003416 // Ignore basic block local uses. A value that is defined in a scop, but
3417 // used in a PHI node in the same basic block does not count as basic block
3418 // local, as for such cases a control flow edge is passed between definition
3419 // and use.
3420 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003421 continue;
3422
Michael Krusef714d472015-11-05 13:18:43 +00003423 // Uses by PHI nodes in the entry node count as external uses in case the
3424 // use is through an incoming block that is itself not contained in the
3425 // region.
3426 if (R->getEntry() == UseParent) {
3427 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3428 bool ExternalUse = false;
3429 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3430 if (PHI->getIncomingValue(i) == Inst &&
3431 !R->contains(PHI->getIncomingBlock(i))) {
3432 ExternalUse = true;
3433 break;
3434 }
3435 }
3436
3437 if (ExternalUse) {
3438 AnyCrossStmtUse = true;
3439 continue;
3440 }
3441 }
3442 }
3443
Michael Kruse7bf39442015-09-10 12:46:52 +00003444 // Do not build scalar dependences inside a non-affine subregion.
3445 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3446 continue;
3447
Michael Kruse01cb3792015-10-17 21:07:08 +00003448 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003449 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003450 //
3451 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003452 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3453 // the control flow a different value will be assigned to the PHI node. In
3454 // case this is the case, there is no need to create an additional normal
3455 // scalar dependence. Hence, bail out before we register an "out-of-region"
3456 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003457 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3458 !R->getExitingBlock())
3459 continue;
3460
Michael Kruse7bf39442015-09-10 12:46:52 +00003461 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003462 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003463 AnyCrossStmtUse = true;
3464 continue;
3465 }
3466
3467 // If the instruction can be synthesized and the user is in the region
3468 // we do not need to add scalar dependences.
3469 if (canSynthesizeInst)
3470 continue;
3471
3472 // No need to translate these scalar dependences into polyhedral form,
3473 // because synthesizable scalars can be generated by the code generator.
3474 if (canSynthesize(UI, LI, SE, R))
3475 continue;
3476
3477 // Skip PHI nodes in the region as they handle their operands on their own.
3478 if (isa<PHINode>(UI))
3479 continue;
3480
3481 // Now U is used in another statement.
3482 AnyCrossStmtUse = true;
3483
3484 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003485 // Use the def instruction as base address of the MemoryAccess, so that it
3486 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003487 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003488 }
3489
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003490 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003491 for (Value *Op : Inst->operands()) {
3492 if (canSynthesize(Op, LI, SE, R))
3493 continue;
3494
3495 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3496 if (R->contains(OpInst))
3497 continue;
3498
3499 if (isa<Constant>(Op))
3500 continue;
3501
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003502 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003503 }
3504 }
3505
3506 return AnyCrossStmtUse;
3507}
3508
3509extern MapInsnToMemAcc InsnToMemAcc;
3510
Michael Krusee2bccbb2015-09-18 19:59:43 +00003511void ScopInfo::buildMemoryAccess(
3512 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003513 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3514 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003515 unsigned Size;
3516 Type *SizeType;
3517 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003518 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003519
3520 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3521 SizeType = Load->getType();
3522 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003523 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003524 Val = Load;
3525 } else {
3526 StoreInst *Store = cast<StoreInst>(Inst);
3527 SizeType = Store->getValueOperand()->getType();
3528 Size = TD->getTypeStoreSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003529 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003530 Val = Store->getValueOperand();
3531 }
3532
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003533 auto Address = getPointerOperand(*Inst);
3534
3535 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003536 const SCEVUnknown *BasePointer =
3537 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3538
3539 assert(BasePointer && "Could not find base pointer");
3540 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3541
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003542 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3543 auto NewAddress = Address;
3544 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3545 auto Src = BitCast->getOperand(0);
3546 auto SrcTy = Src->getType();
3547 auto DstTy = BitCast->getType();
3548 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3549 NewAddress = Src;
3550 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003551
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003552 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3553 std::vector<const SCEV *> Subscripts;
3554 std::vector<int> Sizes;
3555 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3556 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003557
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003558 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003559
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003560 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003561 for (auto Subscript : Subscripts) {
3562 InvariantLoadsSetTy AccessILS;
3563 AllAffineSubcripts =
3564 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3565
3566 for (LoadInst *LInst : AccessILS)
3567 if (!ScopRIL.count(LInst))
3568 AllAffineSubcripts = false;
3569
3570 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003571 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003572 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003573
3574 if (AllAffineSubcripts && Sizes.size() > 0) {
3575 for (auto V : Sizes)
3576 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3577 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003578 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003579 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003580
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003581 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3582 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003583 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003584 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003585 }
3586 }
3587
Michael Kruse7bf39442015-09-10 12:46:52 +00003588 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003589 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003590 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3591 AccItr->second.DelinearizedSubscripts,
3592 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003593 return;
3594 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003595
3596 // Check if the access depends on a loop contained in a non-affine subregion.
3597 bool isVariantInNonAffineLoop = false;
3598 if (BoxedLoops) {
3599 SetVector<const Loop *> Loops;
3600 findLoops(AccessFunction, Loops);
3601 for (const Loop *L : Loops)
3602 if (BoxedLoops->count(L))
3603 isVariantInNonAffineLoop = true;
3604 }
3605
Johannes Doerfert09e36972015-10-07 20:17:36 +00003606 InvariantLoadsSetTy AccessILS;
3607 bool IsAffine =
3608 !isVariantInNonAffineLoop &&
3609 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3610
3611 for (LoadInst *LInst : AccessILS)
3612 if (!ScopRIL.count(LInst))
3613 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003614
Michael Krusecaac2b62015-09-26 15:51:44 +00003615 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003616 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003617 const SCEV *SizeSCEV =
3618 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003619
Michael Krusee2bccbb2015-09-18 19:59:43 +00003620 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3621 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003622
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003623 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3624 ArrayRef<const SCEV *>(AccessFunction),
3625 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003626}
3627
Michael Krused868b5d2015-09-10 15:25:24 +00003628void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003629
3630 if (SD->isNonAffineSubRegion(&SR, &R)) {
3631 for (BasicBlock *BB : SR.blocks())
3632 buildAccessFunctions(R, *BB, &SR);
3633 return;
3634 }
3635
3636 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3637 if (I->isSubRegion())
3638 buildAccessFunctions(R, *I->getNodeAs<Region>());
3639 else
3640 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3641}
3642
Michael Krusecac948e2015-10-02 13:53:07 +00003643void ScopInfo::buildStmts(Region &SR) {
3644 Region *R = getRegion();
3645
3646 if (SD->isNonAffineSubRegion(&SR, R)) {
3647 scop->addScopStmt(nullptr, &SR);
3648 return;
3649 }
3650
3651 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3652 if (I->isSubRegion())
3653 buildStmts(*I->getNodeAs<Region>());
3654 else
3655 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3656}
3657
Michael Krused868b5d2015-09-10 15:25:24 +00003658void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3659 Region *NonAffineSubRegion,
3660 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003661 // We do not build access functions for error blocks, as they may contain
3662 // instructions we can not model.
3663 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3664 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3665 return;
3666
Michael Kruse7bf39442015-09-10 12:46:52 +00003667 Loop *L = LI->getLoopFor(&BB);
3668
3669 // The set of loops contained in non-affine subregions that are part of R.
3670 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3671
Johannes Doerfert09e36972015-10-07 20:17:36 +00003672 // The set of loads that are required to be invariant.
3673 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3674
Michael Kruse7bf39442015-09-10 12:46:52 +00003675 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003676 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003677
3678 PHINode *PHI = dyn_cast<PHINode>(Inst);
3679 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003680 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003681
3682 // For the exit block we stop modeling after the last PHI node.
3683 if (!PHI && IsExitBlock)
3684 break;
3685
Johannes Doerfert09e36972015-10-07 20:17:36 +00003686 // TODO: At this point we only know that elements of ScopRIL have to be
3687 // invariant and will be hoisted for the SCoP to be processed. Though,
3688 // there might be other invariant accesses that will be hoisted and
3689 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003690 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003691 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003692
3693 if (isIgnoredIntrinsic(Inst))
3694 continue;
3695
Johannes Doerfert09e36972015-10-07 20:17:36 +00003696 // Do not build scalar dependences for required invariant loads as we will
3697 // hoist them later on anyway or drop the SCoP if we cannot.
3698 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3699 continue;
3700
Michael Kruse7bf39442015-09-10 12:46:52 +00003701 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003702 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003703 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003704 }
3705 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003706}
Michael Kruse7bf39442015-09-10 12:46:52 +00003707
Michael Kruse2d0ece92015-09-24 11:41:21 +00003708void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3709 MemoryAccess::AccessType Type,
3710 Value *BaseAddress, unsigned ElemBytes,
3711 bool Affine, Value *AccessValue,
3712 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003713 ArrayRef<const SCEV *> Sizes,
3714 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003715 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3716
3717 // Do not create a memory access for anything not in the SCoP. It would be
3718 // ignored anyway.
3719 if (!Stmt)
3720 return;
3721
Michael Krusee2bccbb2015-09-18 19:59:43 +00003722 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003723 Value *BaseAddr = BaseAddress;
3724 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3725
Michael Krusecac948e2015-10-02 13:53:07 +00003726 bool isApproximated =
3727 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3728 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3729 Type = MemoryAccess::MAY_WRITE;
3730
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003731 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003732 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003733 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003734}
3735
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003736void ScopInfo::addExplicitAccess(
3737 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3738 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3739 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3740 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3741 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3742 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003743 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3744 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003745}
3746void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3747 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3748 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003749 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003750}
3751void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3752 assert(!isa<PHINode>(User));
3753 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3754 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003755 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003756}
3757void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3758 BasicBlock *UserBB) {
3759 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003760 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3761 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003762}
3763void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3764 Value *IncomingValue, bool IsExitBlock) {
3765 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3766 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3767 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003768 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003769}
3770void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3771 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003772 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3773 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003774}
3775
Michael Kruse76e924d2015-09-30 09:16:07 +00003776void ScopInfo::buildScop(Region &R, DominatorTree &DT) {
Michael Kruse9d080092015-09-11 21:41:48 +00003777 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003778 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003779
Michael Krusecac948e2015-10-02 13:53:07 +00003780 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003781 buildAccessFunctions(R, R);
3782
3783 // In case the region does not have an exiting block we will later (during
3784 // code generation) split the exit block. This will move potential PHI nodes
3785 // from the current exit block into the new region exiting block. Hence, PHI
3786 // nodes that are at this point not part of the region will be.
3787 // To handle these PHI nodes later we will now model their operands as scalar
3788 // accesses. Note that we do not model anything in the exit block if we have
3789 // an exiting block in the region, as there will not be any splitting later.
3790 if (!R.getExitingBlock())
3791 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3792
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003793 scop->init(*AA);
Michael Kruse7bf39442015-09-10 12:46:52 +00003794}
3795
Michael Krused868b5d2015-09-10 15:25:24 +00003796void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003797 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003798 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003799 return;
3800 }
3801
Michael Kruse9d080092015-09-11 21:41:48 +00003802 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003803}
3804
Michael Krused868b5d2015-09-10 15:25:24 +00003805void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003806 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003807 if (scop) {
3808 delete scop;
3809 scop = 0;
3810 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003811}
3812
3813//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003814ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003815 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003816 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003817}
3818
3819ScopInfo::~ScopInfo() {
3820 clear();
3821 isl_ctx_free(ctx);
3822}
3823
Tobias Grosser75805372011-04-29 06:27:02 +00003824void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003825 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003826 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003827 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003828 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3829 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003830 AU.addRequired<AAResultsWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00003831 AU.setPreservesAll();
3832}
3833
3834bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003835 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003836
Michael Krused868b5d2015-09-10 15:25:24 +00003837 if (!SD->isMaxRegionInScop(*R))
3838 return false;
3839
3840 Function *F = R->getEntry()->getParent();
3841 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3842 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3843 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3844 TD = &F->getParent()->getDataLayout();
3845 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Michael Krused868b5d2015-09-10 15:25:24 +00003846
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003847 DebugLoc Beg, End;
3848 getDebugLocations(R, Beg, End);
3849 std::string Msg = "SCoP begins here.";
3850 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
3851
Michael Kruse76e924d2015-09-30 09:16:07 +00003852 buildScop(*R, DT);
Tobias Grosser75805372011-04-29 06:27:02 +00003853
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003854 DEBUG(scop->print(dbgs()));
3855
Michael Kruseafe06702015-10-02 16:33:27 +00003856 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003857 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00003858 delete scop;
3859 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003860 } else {
3861 Msg = "SCoP ends here.";
3862 ++ScopFound;
3863 if (scop->getMaxLoopDepth() > 0)
3864 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00003865 }
3866
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003867 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
3868
Tobias Grosser75805372011-04-29 06:27:02 +00003869 return false;
3870}
3871
3872char ScopInfo::ID = 0;
3873
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003874Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3875
Tobias Grosser73600b82011-10-08 00:30:40 +00003876INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3877 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003878 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003879INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Chandler Carruthf5579872015-01-17 14:16:56 +00003880INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003881INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003882INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003883INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00003884INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00003885INITIALIZE_PASS_END(ScopInfo, "polly-scops",
3886 "Polly - Create polyhedral description of Scops", false,
3887 false)