blob: 2eef4d36ac7b22a12cee57e7d979defd0417f925 [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"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000033#include "llvm/Analysis/AssumptionCache.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000035#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000036#include "llvm/Analysis/RegionIterator.h"
37#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000038#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000039#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000040#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000041#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000042#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000043#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000044#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000045#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000046#include "isl/schedule.h"
47#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/set.h"
49#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000050#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000051#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000052#include <sstream>
53#include <string>
54#include <vector>
55
56using namespace llvm;
57using namespace polly;
58
Chandler Carruth95fef942014-04-22 03:30:19 +000059#define DEBUG_TYPE "polly-scops"
60
Tobias Grosser74394f02013-01-14 22:40:23 +000061STATISTIC(ScopFound, "Number of valid Scops");
62STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000063
Michael Kruse7bf39442015-09-10 12:46:52 +000064static cl::opt<bool> ModelReadOnlyScalars(
65 "polly-analyze-read-only-scalars",
66 cl::desc("Model read-only scalar values in the scop description"),
67 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
68
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000069// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000070// operations can overflow easily. Additive reductions and bit operations
71// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000072static cl::opt<bool> DisableMultiplicativeReductions(
73 "polly-disable-multiplicative-reductions",
74 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
75 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000076
Johannes Doerfert9143d672014-09-27 11:02:39 +000077static cl::opt<unsigned> RunTimeChecksMaxParameters(
78 "polly-rtc-max-parameters",
79 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
80 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
81
Tobias Grosser71500722015-03-28 15:11:14 +000082static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
83 "polly-rtc-max-arrays-per-group",
84 cl::desc("The maximal number of arrays to compare in each alias group."),
85 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000086static cl::opt<std::string> UserContextStr(
87 "polly-context", cl::value_desc("isl parameter set"),
88 cl::desc("Provide additional constraints on the context parameters"),
89 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000090
Tobias Grosserd83b8a82015-08-20 19:08:11 +000091static cl::opt<bool> DetectReductions("polly-detect-reductions",
92 cl::desc("Detect and exploit reductions"),
93 cl::Hidden, cl::ZeroOrMore,
94 cl::init(true), cl::cat(PollyCategory));
95
Tobias Grosser20a4c0c2015-11-11 16:22:36 +000096static cl::opt<int> MaxDisjunctsAssumed(
97 "polly-max-disjuncts-assumed",
98 cl::desc("The maximal number of disjuncts we allow in the assumption "
99 "context (this bounds compile time)"),
100 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
101
Michael Kruse7bf39442015-09-10 12:46:52 +0000102//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000103
Michael Kruse046dde42015-08-10 13:01:57 +0000104// Create a sequence of two schedules. Either argument may be null and is
105// interpreted as the empty schedule. Can also return null if both schedules are
106// empty.
107static __isl_give isl_schedule *
108combineInSequence(__isl_take isl_schedule *Prev,
109 __isl_take isl_schedule *Succ) {
110 if (!Prev)
111 return Succ;
112 if (!Succ)
113 return Prev;
114
115 return isl_schedule_sequence(Prev, Succ);
116}
117
Johannes Doerferte7044942015-02-24 11:58:30 +0000118static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
119 const ConstantRange &Range,
120 int dim,
121 enum isl_dim_type type) {
122 isl_val *V;
123 isl_ctx *ctx = isl_set_get_ctx(S);
124
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000125 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
126 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000127 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000128 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
129
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000131 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000132 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000133 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000134 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
135
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000137 return isl_set_union(SLB, SUB);
138 else
139 return isl_set_intersect(SLB, SUB);
140}
141
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000142static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
143 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
144 if (!BasePtrLI)
145 return nullptr;
146
147 if (!S->getRegion().contains(BasePtrLI))
148 return nullptr;
149
150 ScalarEvolution &SE = *S->getSE();
151
152 auto *OriginBaseSCEV =
153 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
154 if (!OriginBaseSCEV)
155 return nullptr;
156
157 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
158 if (!OriginBaseSCEVUnknown)
159 return nullptr;
160
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000161 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
162 ScopArrayInfo::KIND_ARRAY);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000163}
164
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000165ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000166 ArrayRef<const SCEV *> Sizes, enum ARRAYKIND Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000167 const DataLayout &DL, Scop *S)
168 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000169 std::string BasePtrName =
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000170 getIslCompatibleName("MemRef_", BasePtr, Kind == KIND_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000171 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000172
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000173 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000174 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
175 if (BasePtrOriginSAI)
176 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000177}
178
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000179__isl_give isl_space *ScopArrayInfo::getSpace() const {
180 auto Space =
181 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
182 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
183 return Space;
184}
185
Tobias Grosser8286b832015-11-02 11:29:32 +0000186bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000187 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
188 int ExtraDimsNew = NewSizes.size() - SharedDims;
189 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000190 for (int i = 0; i < SharedDims; i++)
191 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
192 return false;
193
194 if (DimensionSizes.size() >= NewSizes.size())
195 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000196
197 DimensionSizes.clear();
198 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
199 NewSizes.end());
200 for (isl_pw_aff *Size : DimensionSizesPw)
201 isl_pw_aff_free(Size);
202 DimensionSizesPw.clear();
203 for (const SCEV *Expr : DimensionSizes) {
204 isl_pw_aff *Size = S.getPwAff(Expr);
205 DimensionSizesPw.push_back(Size);
206 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000207 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000208}
209
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000210ScopArrayInfo::~ScopArrayInfo() {
211 isl_id_free(Id);
212 for (isl_pw_aff *Size : DimensionSizesPw)
213 isl_pw_aff_free(Size);
214}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000215
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000216std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
217
218int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000219 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000220}
221
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000222isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
223
224void ScopArrayInfo::dump() const { print(errs()); }
225
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000226void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000227 OS.indent(8) << *getElementType() << " " << getName();
228 if (getNumberOfDimensions() > 0)
229 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000230 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000231 OS << "[";
232
Tobias Grosser26253842015-11-10 14:24:21 +0000233 if (SizeAsPwAff) {
234 auto Size = getDimensionSizePw(u);
235 OS << " " << Size << " ";
236 isl_pw_aff_free(Size);
237 } else {
238 OS << *getDimensionSize(u);
239 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000240
241 OS << "]";
242 }
243
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000244 OS << ";";
245
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000246 if (BasePtrOriginSAI)
247 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
248
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000249 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000250}
251
252const ScopArrayInfo *
253ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
254 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
255 assert(Id && "Output dimension didn't have an ID");
256 return getFromId(Id);
257}
258
259const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
260 void *User = isl_id_get_user(Id);
261 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
262 isl_id_free(Id);
263 return SAI;
264}
265
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000266void MemoryAccess::updateDimensionality() {
267 auto ArraySpace = getScopArrayInfo()->getSpace();
268 auto AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
269
270 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
271 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
272 auto DimsMissing = DimsArray - DimsAccess;
273
274 auto Map = isl_map_from_domain_and_range(isl_set_universe(AccessSpace),
275 isl_set_universe(ArraySpace));
276
277 for (unsigned i = 0; i < DimsMissing; i++)
278 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
279
280 for (unsigned i = DimsMissing; i < DimsArray; i++)
281 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
282
283 AccessRelation = isl_map_apply_range(AccessRelation, Map);
284}
285
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000286const std::string
287MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
288 switch (RT) {
289 case MemoryAccess::RT_NONE:
290 llvm_unreachable("Requested a reduction operator string for a memory "
291 "access which isn't a reduction");
292 case MemoryAccess::RT_ADD:
293 return "+";
294 case MemoryAccess::RT_MUL:
295 return "*";
296 case MemoryAccess::RT_BOR:
297 return "|";
298 case MemoryAccess::RT_BXOR:
299 return "^";
300 case MemoryAccess::RT_BAND:
301 return "&";
302 }
303 llvm_unreachable("Unknown reduction type");
304 return "";
305}
306
Johannes Doerfertf6183392014-07-01 20:52:51 +0000307/// @brief Return the reduction type for a given binary operator
308static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
309 const Instruction *Load) {
310 if (!BinOp)
311 return MemoryAccess::RT_NONE;
312 switch (BinOp->getOpcode()) {
313 case Instruction::FAdd:
314 if (!BinOp->hasUnsafeAlgebra())
315 return MemoryAccess::RT_NONE;
316 // Fall through
317 case Instruction::Add:
318 return MemoryAccess::RT_ADD;
319 case Instruction::Or:
320 return MemoryAccess::RT_BOR;
321 case Instruction::Xor:
322 return MemoryAccess::RT_BXOR;
323 case Instruction::And:
324 return MemoryAccess::RT_BAND;
325 case Instruction::FMul:
326 if (!BinOp->hasUnsafeAlgebra())
327 return MemoryAccess::RT_NONE;
328 // Fall through
329 case Instruction::Mul:
330 if (DisableMultiplicativeReductions)
331 return MemoryAccess::RT_NONE;
332 return MemoryAccess::RT_MUL;
333 default:
334 return MemoryAccess::RT_NONE;
335 }
336}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000337
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000338/// @brief Derive the individual index expressions from a GEP instruction
339///
340/// This function optimistically assumes the GEP references into a fixed size
341/// array. If this is actually true, this function returns a list of array
342/// subscript expressions as SCEV as well as a list of integers describing
343/// the size of the individual array dimensions. Both lists have either equal
344/// length of the size list is one element shorter in case there is no known
345/// size available for the outermost array dimension.
346///
347/// @param GEP The GetElementPtr instruction to analyze.
348///
349/// @return A tuple with the subscript expressions and the dimension sizes.
350static std::tuple<std::vector<const SCEV *>, std::vector<int>>
351getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
352 std::vector<const SCEV *> Subscripts;
353 std::vector<int> Sizes;
354
355 Type *Ty = GEP->getPointerOperandType();
356
357 bool DroppedFirstDim = false;
358
Michael Kruse26ed65e2015-09-24 17:32:49 +0000359 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000360
361 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
362
363 if (i == 1) {
364 if (auto PtrTy = dyn_cast<PointerType>(Ty)) {
365 Ty = PtrTy->getElementType();
366 } else if (auto ArrayTy = dyn_cast<ArrayType>(Ty)) {
367 Ty = ArrayTy->getElementType();
368 } else {
369 Subscripts.clear();
370 Sizes.clear();
371 break;
372 }
373 if (auto Const = dyn_cast<SCEVConstant>(Expr))
374 if (Const->getValue()->isZero()) {
375 DroppedFirstDim = true;
376 continue;
377 }
378 Subscripts.push_back(Expr);
379 continue;
380 }
381
382 auto ArrayTy = dyn_cast<ArrayType>(Ty);
383 if (!ArrayTy) {
384 Subscripts.clear();
385 Sizes.clear();
386 break;
387 }
388
389 Subscripts.push_back(Expr);
390 if (!(DroppedFirstDim && i == 2))
391 Sizes.push_back(ArrayTy->getNumElements());
392
393 Ty = ArrayTy->getElementType();
394 }
395
396 return std::make_tuple(Subscripts, Sizes);
397}
398
Tobias Grosser75805372011-04-29 06:27:02 +0000399MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000400 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000401 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000402 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000403}
404
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000405const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
406 isl_id *ArrayId = getArrayId();
407 void *User = isl_id_get_user(ArrayId);
408 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
409 isl_id_free(ArrayId);
410 return SAI;
411}
412
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000413__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000414 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
415}
416
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000417__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
418 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000419 isl_map *Schedule, *ScheduledAccRel;
420 isl_union_set *UDomain;
421
422 UDomain = isl_union_set_from_set(getStatement()->getDomain());
423 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
424 Schedule = isl_map_from_union_map(USchedule);
425 ScheduledAccRel = isl_map_apply_domain(getAccessRelation(), Schedule);
426 return isl_pw_multi_aff_from_map(ScheduledAccRel);
427}
428
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000429__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000430 return isl_map_copy(AccessRelation);
431}
432
Johannes Doerferta99130f2014-10-13 12:58:03 +0000433std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000434 return stringFromIslObj(AccessRelation);
435}
436
Johannes Doerferta99130f2014-10-13 12:58:03 +0000437__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000438 return isl_map_get_space(AccessRelation);
439}
440
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000441__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000442 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000443}
444
Tobias Grosser6f730082015-09-05 07:46:47 +0000445std::string MemoryAccess::getNewAccessRelationStr() const {
446 return stringFromIslObj(NewAccessRelation);
447}
448
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000449__isl_give isl_basic_map *
450MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000451 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000452 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000453
Tobias Grosser084d8f72012-05-29 09:29:44 +0000454 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000455 isl_basic_set_universe(Statement->getDomainSpace()),
456 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000457}
458
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000459// Formalize no out-of-bound access assumption
460//
461// When delinearizing array accesses we optimistically assume that the
462// delinearized accesses do not access out of bound locations (the subscript
463// expression of each array evaluates for each statement instance that is
464// executed to a value that is larger than zero and strictly smaller than the
465// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000466// dimension for which we do not need to assume any upper bound. At this point
467// we formalize this assumption to ensure that at code generation time the
468// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000469//
470// To find the set of constraints necessary to avoid out of bound accesses, we
471// first build the set of data locations that are not within array bounds. We
472// then apply the reverse access relation to obtain the set of iterations that
473// may contain invalid accesses and reduce this set of iterations to the ones
474// that are actually executed by intersecting them with the domain of the
475// statement. If we now project out all loop dimensions, we obtain a set of
476// parameters that may cause statement instances to be executed that may
477// possibly yield out of bound memory accesses. The complement of these
478// constraints is the set of constraints that needs to be assumed to ensure such
479// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000480void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000481 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000482 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Michael Krusee2bccbb2015-09-18 19:59:43 +0000483 for (int i = 1, Size = Subscripts.size(); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000484 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
485 isl_pw_aff *Var =
486 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
487 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
488
489 isl_set *DimOutside;
490
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000491 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Michael Krusee2bccbb2015-09-18 19:59:43 +0000492 isl_pw_aff *SizeE = Statement->getPwAff(Sizes[i - 1]);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000493
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000494 SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
495 Statement->getNumIterators());
496 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
497 isl_space_dim(Space, isl_dim_set));
498 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
499 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000500
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000501 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000502
503 Outside = isl_set_union(Outside, DimOutside);
504 }
505
506 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
507 Outside = isl_set_intersect(Outside, Statement->getDomain());
508 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000509
510 // Remove divs to avoid the construction of overly complicated assumptions.
511 // Doing so increases the set of parameter combinations that are assumed to
512 // not appear. This is always save, but may make the resulting run-time check
513 // bail out more often than strictly necessary.
514 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000515 Outside = isl_set_complement(Outside);
Johannes Doerfertd84493e2015-11-12 02:33:38 +0000516 Statement->getParent()->addAssumption(INBOUNDS, Outside,
517 getAccessInstruction()->getDebugLoc());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000518 isl_space_free(Space);
519}
520
Johannes Doerferte7044942015-02-24 11:58:30 +0000521void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
522 ScalarEvolution *SE = Statement->getParent()->getSE();
523
524 Value *Ptr = getPointerOperand(*getAccessInstruction());
525 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
526 return;
527
528 auto *PtrSCEV = SE->getSCEV(Ptr);
529 if (isa<SCEVCouldNotCompute>(PtrSCEV))
530 return;
531
532 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
533 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
534 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
535
536 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
537 if (Range.isFullSet())
538 return;
539
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000540 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000541 unsigned BW = Range.getBitWidth();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000542 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
543 const auto UB = isWrapping ? Range.getUpper() : Range.getSignedMax();
544
545 auto Min = LB.sdiv(APInt(BW, ElementSize));
546 auto Max = (UB - APInt(BW, 1)).sdiv(APInt(BW, ElementSize));
Johannes Doerferte7044942015-02-24 11:58:30 +0000547
548 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
549 AccessRange =
550 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
551 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
552}
553
Michael Krusee2bccbb2015-09-18 19:59:43 +0000554__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000555 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000556 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000557
558 for (int i = Size - 2; i >= 0; --i) {
559 isl_space *Space;
560 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000561 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000562
563 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
564 isl_pw_aff_free(DimSize);
565 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
566
567 Space = isl_map_get_space(AccessRelation);
568 Space = isl_space_map_from_set(isl_space_range(Space));
569 Space = isl_space_align_params(Space, SpaceSize);
570
571 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
572 isl_id_free(ParamId);
573
574 MapOne = isl_map_universe(isl_space_copy(Space));
575 for (int j = 0; j < Size; ++j)
576 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
577 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
578
579 MapTwo = isl_map_universe(isl_space_copy(Space));
580 for (int j = 0; j < Size; ++j)
581 if (j < i || j > i + 1)
582 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
583
584 isl_local_space *LS = isl_local_space_from_space(Space);
585 isl_constraint *C;
586 C = isl_equality_alloc(isl_local_space_copy(LS));
587 C = isl_constraint_set_constant_si(C, -1);
588 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
589 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
590 MapTwo = isl_map_add_constraint(MapTwo, C);
591 C = isl_equality_alloc(LS);
592 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
593 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
594 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
595 MapTwo = isl_map_add_constraint(MapTwo, C);
596 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
597
598 MapOne = isl_map_union(MapOne, MapTwo);
599 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
600 }
601 return AccessRelation;
602}
603
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000604/// @brief Check if @p Expr is divisible by @p Size.
605static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
606
607 // Only one factor needs to be divisible.
608 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
609 for (auto *FactorExpr : MulExpr->operands())
610 if (isDivisible(FactorExpr, Size, SE))
611 return true;
612 return false;
613 }
614
615 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
616 // to be divisble.
617 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
618 for (auto *OpExpr : NAryExpr->operands())
619 if (!isDivisible(OpExpr, Size, SE))
620 return false;
621 return true;
622 }
623
624 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
625 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
626 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
627 return MulSCEV == Expr;
628}
629
Michael Krusee2bccbb2015-09-18 19:59:43 +0000630void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
631 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000632
Michael Krusee2bccbb2015-09-18 19:59:43 +0000633 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000634 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000635
Michael Krusee2bccbb2015-09-18 19:59:43 +0000636 if (!isAffine()) {
Tobias Grosser4f967492013-06-23 05:21:18 +0000637 // We overapproximate non-affine accesses with a possible access to the
638 // whole array. For read accesses it does not make a difference, if an
639 // access must or may happen. However, for write accesses it is important to
640 // differentiate between writes that must happen and writes that may happen.
Tobias Grosser04d6ae62013-06-23 06:04:54 +0000641 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000642 AccessRelation =
643 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Johannes Doerferte7044942015-02-24 11:58:30 +0000644
Michael Krusee2bccbb2015-09-18 19:59:43 +0000645 computeBoundsOnAccessRelation(getElemSizeInBytes());
Tobias Grossera1879642011-12-20 10:43:14 +0000646 return;
647 }
648
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000649 Scop &S = *getStatement()->getParent();
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000650 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000651 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000652
Michael Krusee2bccbb2015-09-18 19:59:43 +0000653 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
654 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Tobias Grosser75805372011-04-29 06:27:02 +0000655
Sebastian Pop422e33f2014-06-03 18:16:31 +0000656 if (Size == 1) {
657 // For the non delinearized arrays, divide the access function of the last
658 // subscript by the size of the elements in the array.
Sebastian Pop18016682014-04-08 21:20:44 +0000659 //
660 // A stride one array access in C expressed as A[i] is expressed in
661 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
662 // two subsequent values of 'i' index two values that are stored next to
663 // each other in memory. By this division we make this characteristic
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000664 // obvious again. However, if the index is not divisible by the element
665 // size we will bail out.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000666 isl_val *v = isl_val_int_from_si(Ctx, getElemSizeInBytes());
Sebastian Pop18016682014-04-08 21:20:44 +0000667 Affine = isl_pw_aff_scale_down_val(Affine, v);
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000668
669 if (!isDivisible(Subscripts[0], getElemSizeInBytes(), *S.getSE()))
670 S.addAssumption(ALIGNMENT, isl_set_empty(S.getParamSpace()),
671 AccessInstruction->getDebugLoc());
Sebastian Pop18016682014-04-08 21:20:44 +0000672 }
673
674 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
675
Tobias Grosser79baa212014-04-10 08:38:02 +0000676 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000677 }
678
Michael Krusee2bccbb2015-09-18 19:59:43 +0000679 if (Sizes.size() > 1 && !isa<SCEVConstant>(Sizes[0]))
680 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000681
Tobias Grosser79baa212014-04-10 08:38:02 +0000682 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000683 AccessRelation = isl_map_set_tuple_id(
684 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000685 AccessRelation =
686 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
687
Michael Krusee2bccbb2015-09-18 19:59:43 +0000688 assumeNoOutOfBound();
Tobias Grosseraa660a92015-03-30 00:07:50 +0000689 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000690 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000691}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000692
Michael Krusecac948e2015-10-02 13:53:07 +0000693MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000694 AccessType Type, Value *BaseAddress,
695 unsigned ElemBytes, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000696 ArrayRef<const SCEV *> Subscripts,
697 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Michael Kruse8d0b7342015-09-25 21:21:00 +0000698 AccessOrigin Origin, StringRef BaseName)
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000699 : Origin(Origin), AccType(Type), RedType(RT_NONE), Statement(Stmt),
Michael Krusecac948e2015-10-02 13:53:07 +0000700 BaseAddr(BaseAddress), BaseName(BaseName), ElemBytes(ElemBytes),
701 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
702 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000703 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000704 NewAccessRelation(nullptr) {
705
706 std::string IdName = "__polly_array_ref";
707 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
708}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000709
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000710void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000711 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000712 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000713}
714
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000715const std::string MemoryAccess::getReductionOperatorStr() const {
716 return MemoryAccess::getReductionOperatorStr(getReductionType());
717}
718
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000719__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
720
Johannes Doerfertf6183392014-07-01 20:52:51 +0000721raw_ostream &polly::operator<<(raw_ostream &OS,
722 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000723 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000724 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000725 else
726 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000727 return OS;
728}
729
Tobias Grosser75805372011-04-29 06:27:02 +0000730void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000731 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000732 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000733 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000734 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000735 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000736 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000737 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000738 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000739 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000740 break;
741 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000742 OS << "[Reduction Type: " << getReductionType() << "] ";
Michael Kruse8d0b7342015-09-25 21:21:00 +0000743 OS << "[Scalar: " << isImplicit() << "]\n";
Johannes Doerferta99130f2014-10-13 12:58:03 +0000744 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000745 if (hasNewAccessRelation())
746 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000747}
748
Tobias Grosser74394f02013-01-14 22:40:23 +0000749void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000750
751// Create a map in the size of the provided set domain, that maps from the
752// one element of the provided set domain to another element of the provided
753// set domain.
754// The mapping is limited to all points that are equal in all but the last
755// dimension and for which the last dimension of the input is strict smaller
756// than the last dimension of the output.
757//
758// getEqualAndLarger(set[i0, i1, ..., iX]):
759//
760// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
761// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
762//
Tobias Grosserf5338802011-10-06 00:03:35 +0000763static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000764 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000765 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000766 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000767
768 // Set all but the last dimension to be equal for the input and output
769 //
770 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
771 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000772 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000773 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000774
775 // Set the last dimension of the input to be strict smaller than the
776 // last dimension of the output.
777 //
778 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000779 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
780 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000781 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000782}
783
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000784__isl_give isl_set *
785MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000786 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000787 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000788 isl_space *Space = isl_space_range(isl_map_get_space(S));
789 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000790
Sebastian Popa00a0292012-12-18 07:46:06 +0000791 S = isl_map_reverse(S);
792 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000793
Sebastian Popa00a0292012-12-18 07:46:06 +0000794 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
795 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
796 NextScatt = isl_map_apply_domain(NextScatt, S);
797 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000798
Sebastian Popa00a0292012-12-18 07:46:06 +0000799 isl_set *Deltas = isl_map_deltas(NextScatt);
800 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000801}
802
Sebastian Popa00a0292012-12-18 07:46:06 +0000803bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000804 int StrideWidth) const {
805 isl_set *Stride, *StrideX;
806 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000807
Sebastian Popa00a0292012-12-18 07:46:06 +0000808 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000809 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000810 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
811 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
812 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
813 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000814 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000815
Tobias Grosser28dd4862012-01-24 16:42:16 +0000816 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000817 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000818
Tobias Grosser28dd4862012-01-24 16:42:16 +0000819 return IsStrideX;
820}
821
Sebastian Popa00a0292012-12-18 07:46:06 +0000822bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
823 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000824}
825
Sebastian Popa00a0292012-12-18 07:46:06 +0000826bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
827 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000828}
829
Tobias Grosser166c4222015-09-05 07:46:40 +0000830void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
831 isl_map_free(NewAccessRelation);
832 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000833}
Tobias Grosser75805372011-04-29 06:27:02 +0000834
835//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000836
Tobias Grosser808cd692015-07-14 09:33:13 +0000837isl_map *ScopStmt::getSchedule() const {
838 isl_set *Domain = getDomain();
839 if (isl_set_is_empty(Domain)) {
840 isl_set_free(Domain);
841 return isl_map_from_aff(
842 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
843 }
844 auto *Schedule = getParent()->getSchedule();
845 Schedule = isl_union_map_intersect_domain(
846 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
847 if (isl_union_map_is_empty(Schedule)) {
848 isl_set_free(Domain);
849 isl_union_map_free(Schedule);
850 return isl_map_from_aff(
851 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
852 }
853 auto *M = isl_map_from_union_map(Schedule);
854 M = isl_map_coalesce(M);
855 M = isl_map_gist_domain(M, Domain);
856 M = isl_map_coalesce(M);
857 return M;
858}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000859
Johannes Doerfert574182d2015-08-12 10:19:50 +0000860__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Johannes Doerfertcef616f2015-09-15 22:49:04 +0000861 return getParent()->getPwAff(E, isBlockStmt() ? getBasicBlock()
862 : getRegion()->getEntry());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000863}
864
Tobias Grosser37eb4222014-02-20 21:43:54 +0000865void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
866 assert(isl_set_is_subset(NewDomain, Domain) &&
867 "New domain is not a subset of old domain!");
868 isl_set_free(Domain);
869 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000870}
871
Michael Krusecac948e2015-10-02 13:53:07 +0000872void ScopStmt::buildAccessRelations() {
873 for (MemoryAccess *Access : MemAccs) {
874 Type *ElementType = Access->getAccessValue()->getType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000875
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000876 ScopArrayInfo::ARRAYKIND Ty;
877 if (Access->isPHI())
878 Ty = ScopArrayInfo::KIND_PHI;
879 else if (Access->isImplicit())
880 Ty = ScopArrayInfo::KIND_SCALAR;
881 else
882 Ty = ScopArrayInfo::KIND_ARRAY;
883
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000884 const ScopArrayInfo *SAI = getParent()->getOrCreateScopArrayInfo(
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000885 Access->getBaseAddr(), ElementType, Access->Sizes, Ty);
Johannes Doerfert80ef1102014-11-07 08:31:31 +0000886
Michael Krusecac948e2015-10-02 13:53:07 +0000887 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000888 }
889}
890
Michael Krusecac948e2015-10-02 13:53:07 +0000891void ScopStmt::addAccess(MemoryAccess *Access) {
892 Instruction *AccessInst = Access->getAccessInstruction();
893
894 MemoryAccessList *&MAL = InstructionToAccess[AccessInst];
895 if (!MAL)
896 MAL = new MemoryAccessList();
897 MAL->emplace_front(Access);
898 MemAccs.push_back(MAL->front());
899}
900
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000901void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +0000902 for (MemoryAccess *MA : *this)
903 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000904
905 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000906}
907
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000908/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
909static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
910 void *User) {
911 isl_set **BoundedParts = static_cast<isl_set **>(User);
912 if (isl_basic_set_is_bounded(BSet))
913 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
914 else
915 isl_basic_set_free(BSet);
916 return isl_stat_ok;
917}
918
919/// @brief Return the bounded parts of @p S.
920static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
921 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
922 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
923 isl_set_free(S);
924 return BoundedParts;
925}
926
927/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
928///
929/// @returns A separation of @p S into first an unbounded then a bounded subset,
930/// both with regards to the dimension @p Dim.
931static std::pair<__isl_give isl_set *, __isl_give isl_set *>
932partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
933
934 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000935 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000936
937 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000938 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000939
940 // Remove dimensions that are greater than Dim as they are not interesting.
941 assert(NumDimsS >= Dim + 1);
942 OnlyDimS =
943 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
944
945 // Create artificial parametric upper bounds for dimensions smaller than Dim
946 // as we are not interested in them.
947 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
948 for (unsigned u = 0; u < Dim; u++) {
949 isl_constraint *C = isl_inequality_alloc(
950 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
951 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
952 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
953 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
954 }
955
956 // Collect all bounded parts of OnlyDimS.
957 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
958
959 // Create the dimensions greater than Dim again.
960 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
961 NumDimsS - Dim - 1);
962
963 // Remove the artificial upper bound parameters again.
964 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
965
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +0000966 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +0000967 return std::make_pair(UnboundedParts, BoundedParts);
968}
969
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000970/// @brief Set the dimension Ids from @p From in @p To.
971static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
972 __isl_take isl_set *To) {
973 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
974 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
975 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
976 }
977 return To;
978}
979
980/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +0000981static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +0000982 __isl_take isl_pw_aff *L,
983 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +0000984 switch (Pred) {
985 case ICmpInst::ICMP_EQ:
986 return isl_pw_aff_eq_set(L, R);
987 case ICmpInst::ICMP_NE:
988 return isl_pw_aff_ne_set(L, R);
989 case ICmpInst::ICMP_SLT:
990 return isl_pw_aff_lt_set(L, R);
991 case ICmpInst::ICMP_SLE:
992 return isl_pw_aff_le_set(L, R);
993 case ICmpInst::ICMP_SGT:
994 return isl_pw_aff_gt_set(L, R);
995 case ICmpInst::ICMP_SGE:
996 return isl_pw_aff_ge_set(L, R);
997 case ICmpInst::ICMP_ULT:
998 return isl_pw_aff_lt_set(L, R);
999 case ICmpInst::ICMP_UGT:
1000 return isl_pw_aff_gt_set(L, R);
1001 case ICmpInst::ICMP_ULE:
1002 return isl_pw_aff_le_set(L, R);
1003 case ICmpInst::ICMP_UGE:
1004 return isl_pw_aff_ge_set(L, R);
1005 default:
1006 llvm_unreachable("Non integer predicate not supported");
1007 }
1008}
1009
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001010/// @brief Create the conditions under which @p L @p Pred @p R is true.
1011///
1012/// Helper function that will make sure the dimensions of the result have the
1013/// same isl_id's as the @p Domain.
1014static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1015 __isl_take isl_pw_aff *L,
1016 __isl_take isl_pw_aff *R,
1017 __isl_keep isl_set *Domain) {
1018 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1019 return setDimensionIds(Domain, ConsequenceCondSet);
1020}
1021
1022/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001023///
1024/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001025/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1026/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001027static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001028buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001029 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1030
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001031 Value *Condition = getConditionFromTerminator(SI);
1032 assert(Condition && "No condition for switch");
1033
1034 ScalarEvolution &SE = *S.getSE();
1035 BasicBlock *BB = SI->getParent();
1036 isl_pw_aff *LHS, *RHS;
1037 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1038
1039 unsigned NumSuccessors = SI->getNumSuccessors();
1040 ConditionSets.resize(NumSuccessors);
1041 for (auto &Case : SI->cases()) {
1042 unsigned Idx = Case.getSuccessorIndex();
1043 ConstantInt *CaseValue = Case.getCaseValue();
1044
1045 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1046 isl_set *CaseConditionSet =
1047 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1048 ConditionSets[Idx] = isl_set_coalesce(
1049 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1050 }
1051
1052 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1053 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1054 for (unsigned u = 2; u < NumSuccessors; u++)
1055 ConditionSetUnion =
1056 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1057 ConditionSets[0] = setDimensionIds(
1058 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1059
1060 S.markAsOptimized();
1061 isl_pw_aff_free(LHS);
1062}
1063
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001064/// @brief Build the conditions sets for the branch condition @p Condition in
1065/// the @p Domain.
1066///
1067/// This will fill @p ConditionSets with the conditions under which control
1068/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001069/// have as many elements as @p TI has successors. If @p TI is nullptr the
1070/// context under which @p Condition is true/false will be returned as the
1071/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001072static void
1073buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1074 __isl_keep isl_set *Domain,
1075 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1076
1077 isl_set *ConsequenceCondSet = nullptr;
1078 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1079 if (CCond->isZero())
1080 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1081 else
1082 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1083 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1084 auto Opcode = BinOp->getOpcode();
1085 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1086
1087 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1088 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1089
1090 isl_set_free(ConditionSets.pop_back_val());
1091 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1092 isl_set_free(ConditionSets.pop_back_val());
1093 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1094
1095 if (Opcode == Instruction::And)
1096 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1097 else
1098 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1099 } else {
1100 auto *ICond = dyn_cast<ICmpInst>(Condition);
1101 assert(ICond &&
1102 "Condition of exiting branch was neither constant nor ICmp!");
1103
1104 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001105 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001106 isl_pw_aff *LHS, *RHS;
1107 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1108 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1109 ConsequenceCondSet =
1110 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1111 }
1112
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001113 // If no terminator was given we are only looking for parameter constraints
1114 // under which @p Condition is true/false.
1115 if (!TI)
1116 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1117
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001118 assert(ConsequenceCondSet);
1119 isl_set *AlternativeCondSet =
1120 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1121
1122 ConditionSets.push_back(isl_set_coalesce(
1123 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1124 ConditionSets.push_back(isl_set_coalesce(
1125 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1126}
1127
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001128/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1129///
1130/// This will fill @p ConditionSets with the conditions under which control
1131/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1132/// have as many elements as @p TI has successors.
1133static void
1134buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1135 __isl_keep isl_set *Domain,
1136 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1137
1138 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1139 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1140
1141 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1142
1143 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001144 ConditionSets.push_back(isl_set_copy(Domain));
1145 return;
1146 }
1147
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001148 Value *Condition = getConditionFromTerminator(TI);
1149 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001150
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001151 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001152}
1153
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001154void ScopStmt::buildDomain() {
Tobias Grosser084d8f72012-05-29 09:29:44 +00001155 isl_id *Id;
Tobias Grossere19661e2011-10-07 08:46:57 +00001156
Tobias Grosser084d8f72012-05-29 09:29:44 +00001157 Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1158
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001159 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001160 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001161}
1162
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001163void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001164 isl_ctx *Ctx = Parent.getIslCtx();
1165 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1166 Type *Ty = GEP->getPointerOperandType();
1167 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001168 ScopDetection &SD = Parent.getSD();
1169
1170 // The set of loads that are required to be invariant.
1171 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001172
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001173 std::vector<const SCEV *> Subscripts;
1174 std::vector<int> Sizes;
1175
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001176 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001177
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001178 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001179 Ty = PtrTy->getElementType();
1180 }
1181
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001182 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001183
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001184 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001185
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001186 for (size_t i = 0; i < Sizes.size(); i++) {
1187 auto Expr = Subscripts[i + IndexOffset];
1188 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001189
Johannes Doerfert09e36972015-10-07 20:17:36 +00001190 InvariantLoadsSetTy AccessILS;
1191 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1192 continue;
1193
1194 bool NonAffine = false;
1195 for (LoadInst *LInst : AccessILS)
1196 if (!ScopRIL.count(LInst))
1197 NonAffine = true;
1198
1199 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001200 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001201
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001202 isl_pw_aff *AccessOffset = getPwAff(Expr);
1203 AccessOffset =
1204 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001205
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001206 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1207 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001208
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001209 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1210 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1211 OutOfBound = isl_set_params(OutOfBound);
1212 isl_set *InBound = isl_set_complement(OutOfBound);
1213 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001214
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001215 // A => B == !A or B
1216 isl_set *InBoundIfExecuted =
1217 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001218
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001219 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001220 }
1221
1222 isl_local_space_free(LSpace);
1223}
1224
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001225void ScopStmt::deriveAssumptions(BasicBlock *Block) {
1226 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001227 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
1228 deriveAssumptionsFromGEP(GEP);
1229}
1230
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001231void ScopStmt::collectSurroundingLoops() {
1232 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1233 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1234 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1235 isl_id_free(DimId);
1236 }
1237}
1238
Michael Kruse9d080092015-09-11 21:41:48 +00001239ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001240 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001241
Tobias Grosser16c44032015-07-09 07:31:45 +00001242 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001243}
1244
Michael Kruse9d080092015-09-11 21:41:48 +00001245ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001246 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001247
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001248 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001249}
1250
1251void ScopStmt::init() {
1252 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001253
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001254 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001255 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001256 buildAccessRelations();
1257
1258 if (BB) {
1259 deriveAssumptions(BB);
1260 } else {
1261 for (BasicBlock *Block : R->blocks()) {
1262 deriveAssumptions(Block);
1263 }
1264 }
1265
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001266 if (DetectReductions)
1267 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001268}
1269
Johannes Doerferte58a0122014-06-27 20:31:28 +00001270/// @brief Collect loads which might form a reduction chain with @p StoreMA
1271///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001272/// Check if the stored value for @p StoreMA is a binary operator with one or
1273/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001274/// used only once (by @p StoreMA) and its load operands are also used only
1275/// once, we have found a possible reduction chain. It starts at an operand
1276/// load and includes the binary operator and @p StoreMA.
1277///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001278/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001279/// escape this block or into any other store except @p StoreMA.
1280void ScopStmt::collectCandiateReductionLoads(
1281 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1282 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1283 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001284 return;
1285
1286 // Skip if there is not one binary operator between the load and the store
1287 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001288 if (!BinOp)
1289 return;
1290
1291 // Skip if the binary operators has multiple uses
1292 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001293 return;
1294
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001295 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001296 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1297 return;
1298
Johannes Doerfert9890a052014-07-01 00:32:29 +00001299 // Skip if the binary operator is outside the current SCoP
1300 if (BinOp->getParent() != Store->getParent())
1301 return;
1302
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001303 // Skip if it is a multiplicative reduction and we disabled them
1304 if (DisableMultiplicativeReductions &&
1305 (BinOp->getOpcode() == Instruction::Mul ||
1306 BinOp->getOpcode() == Instruction::FMul))
1307 return;
1308
Johannes Doerferte58a0122014-06-27 20:31:28 +00001309 // Check the binary operator operands for a candidate load
1310 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1311 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1312 if (!PossibleLoad0 && !PossibleLoad1)
1313 return;
1314
1315 // A load is only a candidate if it cannot escape (thus has only this use)
1316 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001317 if (PossibleLoad0->getParent() == Store->getParent())
1318 Loads.push_back(lookupAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001319 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001320 if (PossibleLoad1->getParent() == Store->getParent())
1321 Loads.push_back(lookupAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001322}
1323
1324/// @brief Check for reductions in this ScopStmt
1325///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001326/// Iterate over all store memory accesses and check for valid binary reduction
1327/// like chains. For all candidates we check if they have the same base address
1328/// and there are no other accesses which overlap with them. The base address
1329/// check rules out impossible reductions candidates early. The overlap check,
1330/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001331/// guarantees that none of the intermediate results will escape during
1332/// execution of the loop nest. We basically check here that no other memory
1333/// access can access the same memory as the potential reduction.
1334void ScopStmt::checkForReductions() {
1335 SmallVector<MemoryAccess *, 2> Loads;
1336 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1337
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001338 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001339 // stores and collecting possible reduction loads.
1340 for (MemoryAccess *StoreMA : MemAccs) {
1341 if (StoreMA->isRead())
1342 continue;
1343
1344 Loads.clear();
1345 collectCandiateReductionLoads(StoreMA, Loads);
1346 for (MemoryAccess *LoadMA : Loads)
1347 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1348 }
1349
1350 // Then check each possible candidate pair.
1351 for (const auto &CandidatePair : Candidates) {
1352 bool Valid = true;
1353 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1354 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1355
1356 // Skip those with obviously unequal base addresses.
1357 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1358 isl_map_free(LoadAccs);
1359 isl_map_free(StoreAccs);
1360 continue;
1361 }
1362
1363 // And check if the remaining for overlap with other memory accesses.
1364 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1365 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1366 isl_set *AllAccs = isl_map_range(AllAccsRel);
1367
1368 for (MemoryAccess *MA : MemAccs) {
1369 if (MA == CandidatePair.first || MA == CandidatePair.second)
1370 continue;
1371
1372 isl_map *AccRel =
1373 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1374 isl_set *Accs = isl_map_range(AccRel);
1375
1376 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1377 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1378 Valid = Valid && isl_set_is_empty(OverlapAccs);
1379 isl_set_free(OverlapAccs);
1380 }
1381 }
1382
1383 isl_set_free(AllAccs);
1384 if (!Valid)
1385 continue;
1386
Johannes Doerfertf6183392014-07-01 20:52:51 +00001387 const LoadInst *Load =
1388 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1389 MemoryAccess::ReductionType RT =
1390 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1391
Johannes Doerferte58a0122014-06-27 20:31:28 +00001392 // If no overlapping access was found we mark the load and store as
1393 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001394 CandidatePair.first->markAsReductionLike(RT);
1395 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001396 }
Tobias Grosser75805372011-04-29 06:27:02 +00001397}
1398
Tobias Grosser74394f02013-01-14 22:40:23 +00001399std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001400
Tobias Grosser54839312015-04-21 11:37:25 +00001401std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001402 auto *S = getSchedule();
1403 auto Str = stringFromIslObj(S);
1404 isl_map_free(S);
1405 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001406}
1407
Tobias Grosser74394f02013-01-14 22:40:23 +00001408unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001409
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001410unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001411
Tobias Grosser75805372011-04-29 06:27:02 +00001412const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1413
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001414const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001415 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001416}
1417
Tobias Grosser74394f02013-01-14 22:40:23 +00001418isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001419
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001420__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001421
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001422__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001423 return isl_set_get_space(Domain);
1424}
1425
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001426__isl_give isl_id *ScopStmt::getDomainId() const {
1427 return isl_set_get_tuple_id(Domain);
1428}
Tobias Grossercd95b772012-08-30 11:49:38 +00001429
Tobias Grosser75805372011-04-29 06:27:02 +00001430ScopStmt::~ScopStmt() {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001431 DeleteContainerSeconds(InstructionToAccess);
Tobias Grosser75805372011-04-29 06:27:02 +00001432 isl_set_free(Domain);
Tobias Grosser75805372011-04-29 06:27:02 +00001433}
1434
1435void ScopStmt::print(raw_ostream &OS) const {
1436 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001437 OS.indent(12) << "Domain :=\n";
1438
1439 if (Domain) {
1440 OS.indent(16) << getDomainStr() << ";\n";
1441 } else
1442 OS.indent(16) << "n/a\n";
1443
Tobias Grosser54839312015-04-21 11:37:25 +00001444 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001445
1446 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001447 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001448 } else
1449 OS.indent(16) << "n/a\n";
1450
Tobias Grosser083d3d32014-06-28 08:59:45 +00001451 for (MemoryAccess *Access : MemAccs)
1452 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001453}
1454
1455void ScopStmt::dump() const { print(dbgs()); }
1456
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001457void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001458
1459 // Remove all memory accesses in @p InvMAs from this statement together
1460 // with all scalar accesses that were caused by them. The tricky iteration
1461 // order uses is needed because the MemAccs is a vector and the order in
1462 // which the accesses of each memory access list (MAL) are stored in this
1463 // vector is reversed.
1464 for (MemoryAccess *MA : InvMAs) {
1465 auto &MAL = *lookupAccessesFor(MA->getAccessInstruction());
1466 MAL.reverse();
1467
1468 auto MALIt = MAL.begin();
1469 auto MALEnd = MAL.end();
1470 auto MemAccsIt = MemAccs.begin();
1471 while (MALIt != MALEnd) {
1472 while (*MemAccsIt != *MALIt)
1473 MemAccsIt++;
1474
1475 MALIt++;
1476 MemAccs.erase(MemAccsIt);
1477 }
1478
1479 InstructionToAccess.erase(MA->getAccessInstruction());
1480 delete &MAL;
1481 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001482}
1483
Tobias Grosser75805372011-04-29 06:27:02 +00001484//===----------------------------------------------------------------------===//
1485/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001486
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001487void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001488 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1489 isl_set_free(Context);
1490 Context = NewContext;
1491}
1492
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001493/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1494struct SCEVSensitiveParameterRewriter
1495 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1496 ValueToValueMap &VMap;
1497 ScalarEvolution &SE;
1498
1499public:
1500 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1501 : VMap(VMap), SE(SE) {}
1502
1503 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1504 ValueToValueMap &VMap) {
1505 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1506 return SSPR.visit(E);
1507 }
1508
1509 const SCEV *visit(const SCEV *E) {
1510 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1511 }
1512
1513 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1514
1515 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1516 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1517 }
1518
1519 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1520 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1521 }
1522
1523 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1524 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1525 }
1526
1527 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1528 SmallVector<const SCEV *, 4> Operands;
1529 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1530 Operands.push_back(visit(E->getOperand(i)));
1531 return SE.getAddExpr(Operands);
1532 }
1533
1534 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1535 SmallVector<const SCEV *, 4> Operands;
1536 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1537 Operands.push_back(visit(E->getOperand(i)));
1538 return SE.getMulExpr(Operands);
1539 }
1540
1541 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1542 SmallVector<const SCEV *, 4> Operands;
1543 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1544 Operands.push_back(visit(E->getOperand(i)));
1545 return SE.getSMaxExpr(Operands);
1546 }
1547
1548 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1549 SmallVector<const SCEV *, 4> Operands;
1550 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1551 Operands.push_back(visit(E->getOperand(i)));
1552 return SE.getUMaxExpr(Operands);
1553 }
1554
1555 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1556 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1557 }
1558
1559 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1560 auto *Start = visit(E->getStart());
1561 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1562 visit(E->getStepRecurrence(SE)),
1563 E->getLoop(), SCEV::FlagAnyWrap);
1564 return SE.getAddExpr(Start, AddRec);
1565 }
1566
1567 const SCEV *visitUnknown(const SCEVUnknown *E) {
1568 if (auto *NewValue = VMap.lookup(E->getValue()))
1569 return SE.getUnknown(NewValue);
1570 return E;
1571 }
1572};
1573
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001574const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001575 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001576}
1577
Tobias Grosserabfbe632013-02-05 12:09:06 +00001578void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001579 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001580 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001581
1582 // Normalize the SCEV to get the representing element for an invariant load.
1583 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1584
Tobias Grosser60b54f12011-11-08 15:41:28 +00001585 if (ParameterIds.find(Parameter) != ParameterIds.end())
1586 continue;
1587
1588 int dimension = Parameters.size();
1589
1590 Parameters.push_back(Parameter);
1591 ParameterIds[Parameter] = dimension;
1592 }
1593}
1594
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001595__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001596 // Normalize the SCEV to get the representing element for an invariant load.
1597 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1598
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001599 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001600
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001601 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001602 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001603
Tobias Grosser8f99c162011-11-15 11:38:55 +00001604 std::string ParameterName;
1605
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001606 ParameterName = "p_" + utostr_32(IdIter->second);
1607
Tobias Grosser8f99c162011-11-15 11:38:55 +00001608 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1609 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001610
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001611 // If this parameter references a specific Value and this value has a name
1612 // we use this name as it is likely to be unique and more useful than just
1613 // a number.
1614 if (Val->hasName())
1615 ParameterName = Val->getName();
1616 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1617 auto LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1618 if (LoadOrigin->hasName()) {
1619 ParameterName += "_loaded_from_";
1620 ParameterName +=
1621 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1622 }
1623 }
1624 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001625
Tobias Grosser20532b82014-04-11 17:56:49 +00001626 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1627 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001628}
Tobias Grosser75805372011-04-29 06:27:02 +00001629
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001630isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1631 isl_set *DomainContext = isl_union_set_params(getDomains());
1632 return isl_set_intersect_params(C, DomainContext);
1633}
1634
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001635void Scop::buildBoundaryContext() {
1636 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001637
1638 // The isl_set_complement operation used to create the boundary context
1639 // can possibly become very expensive. We bound the compile time of
1640 // this operation by setting a compute out.
1641 //
1642 // TODO: We can probably get around using isl_set_complement and directly
1643 // AST generate BoundaryContext.
1644 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001645 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001646 isl_ctx_set_max_operations(getIslCtx(), 300000);
1647 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1648
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001649 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001650
Tobias Grossera52b4da2015-11-11 17:59:53 +00001651 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1652 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001653 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001654 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001655
1656 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1657 isl_ctx_reset_operations(getIslCtx());
1658 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001659 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001660 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001661}
1662
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001663void Scop::addUserAssumptions(AssumptionCache &AC) {
1664 auto *R = &getRegion();
1665 auto &F = *R->getEntry()->getParent();
1666 for (auto &Assumption : AC.assumptions()) {
1667 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1668 if (!CI || CI->getNumArgOperands() != 1)
1669 continue;
1670 if (!DT.dominates(CI->getParent(), R->getEntry()))
1671 continue;
1672
1673 auto *Val = CI->getArgOperand(0);
1674 std::vector<const SCEV *> Params;
1675 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1676 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1677 CI->getDebugLoc(),
1678 "Non-affine user assumption ignored.");
1679 continue;
1680 }
1681
1682 addParams(Params);
1683
1684 auto *L = LI.getLoopFor(CI->getParent());
1685 SmallVector<isl_set *, 2> ConditionSets;
1686 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1687 assert(ConditionSets.size() == 2);
1688 isl_set_free(ConditionSets[1]);
1689
1690 auto *AssumptionCtx = ConditionSets[0];
1691 emitOptimizationRemarkAnalysis(
1692 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1693 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1694 Context = isl_set_intersect(Context, AssumptionCtx);
1695 }
1696}
1697
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001698void Scop::addUserContext() {
1699 if (UserContextStr.empty())
1700 return;
1701
1702 isl_set *UserContext = isl_set_read_from_str(IslCtx, UserContextStr.c_str());
1703 isl_space *Space = getParamSpace();
1704 if (isl_space_dim(Space, isl_dim_param) !=
1705 isl_set_dim(UserContext, isl_dim_param)) {
1706 auto SpaceStr = isl_space_to_str(Space);
1707 errs() << "Error: the context provided in -polly-context has not the same "
1708 << "number of dimensions than the computed context. Due to this "
1709 << "mismatch, the -polly-context option is ignored. Please provide "
1710 << "the context in the parameter space: " << SpaceStr << ".\n";
1711 free(SpaceStr);
1712 isl_set_free(UserContext);
1713 isl_space_free(Space);
1714 return;
1715 }
1716
1717 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1718 auto NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1719 auto NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1720
1721 if (strcmp(NameContext, NameUserContext) != 0) {
1722 auto SpaceStr = isl_space_to_str(Space);
1723 errs() << "Error: the name of dimension " << i
1724 << " provided in -polly-context "
1725 << "is '" << NameUserContext << "', but the name in the computed "
1726 << "context is '" << NameContext
1727 << "'. Due to this name mismatch, "
1728 << "the -polly-context option is ignored. Please provide "
1729 << "the context in the parameter space: " << SpaceStr << ".\n";
1730 free(SpaceStr);
1731 isl_set_free(UserContext);
1732 isl_space_free(Space);
1733 return;
1734 }
1735
1736 UserContext =
1737 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1738 isl_space_get_dim_id(Space, isl_dim_param, i));
1739 }
1740
1741 Context = isl_set_intersect(Context, UserContext);
1742 isl_space_free(Space);
1743}
1744
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001745void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001746 DenseMap<const SCEV *, LoadInst *> EquivClasses;
1747
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001748 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001749 for (LoadInst *LInst : RIL) {
1750 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1751
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001752 LoadInst *&ClassRep = EquivClasses[PointerSCEV];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001753 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001754 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001755 continue;
1756 }
1757
1758 ClassRep = LInst;
1759 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(),
1760 nullptr);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001761 }
1762}
1763
Tobias Grosser6be480c2011-11-08 15:41:13 +00001764void Scop::buildContext() {
1765 isl_space *Space = isl_space_params_alloc(IslCtx, 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001766 Context = isl_set_universe(isl_space_copy(Space));
1767 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001768}
1769
Tobias Grosser18daaca2012-05-22 10:47:27 +00001770void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001771 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001772 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001773
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001774 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001775
Johannes Doerferte7044942015-02-24 11:58:30 +00001776 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001777 }
1778}
1779
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001780void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001781 // Add all parameters into a common model.
Tobias Grosser60b54f12011-11-08 15:41:28 +00001782 isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001783
Tobias Grosser083d3d32014-06-28 08:59:45 +00001784 for (const auto &ParamID : ParameterIds) {
1785 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001786 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001787 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001788 }
1789
1790 // Align the parameters of all data structures to the model.
1791 Context = isl_set_align_params(Context, Space);
1792
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001793 for (ScopStmt &Stmt : *this)
1794 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001795}
1796
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001797static __isl_give isl_set *
1798simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1799 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001800 // If we modelt all blocks in the SCoP that have side effects we can simplify
1801 // the context with the constraints that are needed for anything to be
1802 // executed at all. However, if we have error blocks in the SCoP we already
1803 // assumed some parameter combinations cannot occure and removed them from the
1804 // domains, thus we cannot use the remaining domain to simplify the
1805 // assumptions.
1806 if (!S.hasErrorBlock()) {
1807 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1808 AssumptionContext =
1809 isl_set_gist_params(AssumptionContext, DomainParameters);
1810 }
1811
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001812 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1813 return AssumptionContext;
1814}
1815
1816void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001817 // The parameter constraints of the iteration domains give us a set of
1818 // constraints that need to hold for all cases where at least a single
1819 // statement iteration is executed in the whole scop. We now simplify the
1820 // assumed context under the assumption that such constraints hold and at
1821 // least a single statement iteration is executed. For cases where no
1822 // statement instances are executed, the assumptions we have taken about
1823 // the executed code do not matter and can be changed.
1824 //
1825 // WARNING: This only holds if the assumptions we have taken do not reduce
1826 // the set of statement instances that are executed. Otherwise we
1827 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001828 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001829 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001830 // performed. In such a case, modifying the run-time conditions and
1831 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001832 // to not be executed.
1833 //
1834 // Example:
1835 //
1836 // When delinearizing the following code:
1837 //
1838 // for (long i = 0; i < 100; i++)
1839 // for (long j = 0; j < m; j++)
1840 // A[i+p][j] = 1.0;
1841 //
1842 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001843 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001844 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001845 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1846 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001847}
1848
Johannes Doerfertb164c792014-09-18 11:17:17 +00001849/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001850static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001851 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1852 isl_pw_multi_aff *MinPMA, *MaxPMA;
1853 isl_pw_aff *LastDimAff;
1854 isl_aff *OneAff;
1855 unsigned Pos;
1856
Johannes Doerfert9143d672014-09-27 11:02:39 +00001857 // Restrict the number of parameters involved in the access as the lexmin/
1858 // lexmax computation will take too long if this number is high.
1859 //
1860 // Experiments with a simple test case using an i7 4800MQ:
1861 //
1862 // #Parameters involved | Time (in sec)
1863 // 6 | 0.01
1864 // 7 | 0.04
1865 // 8 | 0.12
1866 // 9 | 0.40
1867 // 10 | 1.54
1868 // 11 | 6.78
1869 // 12 | 30.38
1870 //
1871 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1872 unsigned InvolvedParams = 0;
1873 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1874 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1875 InvolvedParams++;
1876
1877 if (InvolvedParams > RunTimeChecksMaxParameters) {
1878 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001879 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00001880 }
1881 }
1882
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00001883 Set = isl_set_remove_divs(Set);
1884
Johannes Doerfertb164c792014-09-18 11:17:17 +00001885 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
1886 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
1887
Johannes Doerfert219b20e2014-10-07 14:37:59 +00001888 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
1889 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
1890
Johannes Doerfertb164c792014-09-18 11:17:17 +00001891 // Adjust the last dimension of the maximal access by one as we want to
1892 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
1893 // we test during code generation might now point after the end of the
1894 // allocated array but we will never dereference it anyway.
1895 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
1896 "Assumed at least one output dimension");
1897 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
1898 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
1899 OneAff = isl_aff_zero_on_domain(
1900 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
1901 OneAff = isl_aff_add_constant_si(OneAff, 1);
1902 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
1903 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
1904
1905 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
1906
1907 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001908 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00001909}
1910
Johannes Doerferteeab05a2014-10-01 12:42:37 +00001911static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
1912 isl_set *Domain = MA->getStatement()->getDomain();
1913 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
1914 return isl_set_reset_tuple_id(Domain);
1915}
1916
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001917/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
1918static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00001919 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001920 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001921
1922 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
1923 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001924 Locations = isl_union_set_coalesce(Locations);
1925 Locations = isl_union_set_detect_equalities(Locations);
1926 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00001927 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00001928 isl_union_set_free(Locations);
1929 return Valid;
1930}
1931
Johannes Doerfert96425c22015-08-30 21:13:53 +00001932/// @brief Helper to treat non-affine regions and basic blocks the same.
1933///
1934///{
1935
1936/// @brief Return the block that is the representing block for @p RN.
1937static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
1938 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
1939 : RN->getNodeAs<BasicBlock>();
1940}
1941
1942/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001943static inline BasicBlock *
1944getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001945 if (RN->isSubRegion()) {
1946 assert(idx == 0);
1947 return RN->getNodeAs<Region>()->getExit();
1948 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001949 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001950}
1951
1952/// @brief Return the smallest loop surrounding @p RN.
1953static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
1954 if (!RN->isSubRegion())
1955 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
1956
1957 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
1958 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
1959 while (L && NonAffineSubRegion->contains(L))
1960 L = L->getParentLoop();
1961 return L;
1962}
1963
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001964static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
1965 if (!RN->isSubRegion())
1966 return 1;
1967
1968 unsigned NumBlocks = 0;
1969 Region *R = RN->getNodeAs<Region>();
1970 for (auto BB : R->blocks()) {
1971 (void)BB;
1972 NumBlocks++;
1973 }
1974 return NumBlocks;
1975}
1976
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001977static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
1978 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00001979 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001980 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00001981 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00001982 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00001983 return true;
1984 return false;
1985}
1986
Johannes Doerfert96425c22015-08-30 21:13:53 +00001987///}
1988
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001989static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
1990 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001991 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001992 isl_id *DimId =
1993 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
1994 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
1995}
1996
Johannes Doerfert96425c22015-08-30 21:13:53 +00001997isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
1998 BasicBlock *BB = Stmt->isBlockStmt() ? Stmt->getBasicBlock()
1999 : Stmt->getRegion()->getEntry();
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002000 return getDomainConditions(BB);
2001}
2002
2003isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2004 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002005 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002006}
2007
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002008void Scop::buildDomains(Region *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002009
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002010 auto *EntryBB = R->getEntry();
2011 int LD = getRelativeLoopDepth(LI.getLoopFor(EntryBB));
2012 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002013
2014 Loop *L = LI.getLoopFor(EntryBB);
2015 while (LD-- >= 0) {
2016 S = addDomainDimId(S, LD + 1, L);
2017 L = L->getParentLoop();
2018 }
2019
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002020 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002021
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002022 if (SD.isNonAffineSubRegion(R, R))
2023 return;
2024
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002025 buildDomainsWithBranchConstraints(R);
2026 propagateDomainConstraints(R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002027}
2028
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002029void Scop::buildDomainsWithBranchConstraints(Region *R) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002030 RegionInfo &RI = *R->getRegionInfo();
Johannes Doerfert96425c22015-08-30 21:13:53 +00002031
2032 // To create the domain for each block in R we iterate over all blocks and
2033 // subregions in R and propagate the conditions under which the current region
2034 // element is executed. To this end we iterate in reverse post order over R as
2035 // it ensures that we first visit all predecessors of a region node (either a
2036 // basic block or a subregion) before we visit the region node itself.
2037 // Initially, only the domain for the SCoP region entry block is set and from
2038 // there we propagate the current domain to all successors, however we add the
2039 // condition that the successor is actually executed next.
2040 // As we are only interested in non-loop carried constraints here we can
2041 // simply skip loop back edges.
2042
2043 ReversePostOrderTraversal<Region *> RTraversal(R);
2044 for (auto *RN : RTraversal) {
2045
2046 // Recurse for affine subregions but go on for basic blocks and non-affine
2047 // subregions.
2048 if (RN->isSubRegion()) {
2049 Region *SubRegion = RN->getNodeAs<Region>();
2050 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002051 buildDomainsWithBranchConstraints(SubRegion);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002052 continue;
2053 }
2054 }
2055
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002056 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002057 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002058
Johannes Doerfert96425c22015-08-30 21:13:53 +00002059 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002060 TerminatorInst *TI = BB->getTerminator();
2061
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002062 if (isa<UnreachableInst>(TI))
2063 continue;
2064
Johannes Doerfertf5673802015-10-01 23:48:18 +00002065 isl_set *Domain = DomainMap.lookup(BB);
2066 if (!Domain) {
2067 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2068 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002069 continue;
2070 }
2071
Johannes Doerfert96425c22015-08-30 21:13:53 +00002072 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002073
2074 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2075 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2076
2077 // Build the condition sets for the successor nodes of the current region
2078 // node. If it is a non-affine subregion we will always execute the single
2079 // exit node, hence the single entry node domain is the condition set. For
2080 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002081 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002082 if (RN->isSubRegion())
2083 ConditionSets.push_back(isl_set_copy(Domain));
2084 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002085 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002086
2087 // Now iterate over the successors and set their initial domain based on
2088 // their condition set. We skip back edges here and have to be careful when
2089 // we leave a loop not to keep constraints over a dimension that doesn't
2090 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002091 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002092 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002093 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002094 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002095
2096 // Skip back edges.
2097 if (DT.dominates(SuccBB, BB)) {
2098 isl_set_free(CondSet);
2099 continue;
2100 }
2101
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002102 // Do not adjust the number of dimensions if we enter a boxed loop or are
2103 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002104 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002105 Region *SuccRegion = RI.getRegionFor(SuccBB);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002106 if (SD.isNonAffineSubRegion(SuccRegion, &getRegion()))
2107 while (SuccBBLoop && SuccRegion->contains(SuccBBLoop))
2108 SuccBBLoop = SuccBBLoop->getParentLoop();
2109
2110 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002111
2112 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2113 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2114 // and enter a new one we need to drop the old constraints.
2115 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002116 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002117 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002118 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2119 isl_set_n_dim(CondSet) - LoopDepthDiff,
2120 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002121 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002122 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002123 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002124 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002125 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002126 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002127 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2128 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002129 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002130 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002131 }
2132
2133 // Set the domain for the successor or merge it with an existing domain in
2134 // case there are multiple paths (without loop back edges) to the
2135 // successor block.
2136 isl_set *&SuccDomain = DomainMap[SuccBB];
2137 if (!SuccDomain)
2138 SuccDomain = CondSet;
2139 else
2140 SuccDomain = isl_set_union(SuccDomain, CondSet);
2141
2142 SuccDomain = isl_set_coalesce(SuccDomain);
Johannes Doerfert634909c2015-10-04 14:57:41 +00002143 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2144 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002145 }
2146 }
2147}
2148
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002149/// @brief Return the domain for @p BB wrt @p DomainMap.
2150///
2151/// This helper function will lookup @p BB in @p DomainMap but also handle the
2152/// case where @p BB is contained in a non-affine subregion using the region
2153/// tree obtained by @p RI.
2154static __isl_give isl_set *
2155getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2156 RegionInfo &RI) {
2157 auto DIt = DomainMap.find(BB);
2158 if (DIt != DomainMap.end())
2159 return isl_set_copy(DIt->getSecond());
2160
2161 Region *R = RI.getRegionFor(BB);
2162 while (R->getEntry() == BB)
2163 R = R->getParent();
2164 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2165}
2166
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002167void Scop::propagateDomainConstraints(Region *R) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002168 // Iterate over the region R and propagate the domain constrains from the
2169 // predecessors to the current node. In contrast to the
2170 // buildDomainsWithBranchConstraints function, this one will pull the domain
2171 // information from the predecessors instead of pushing it to the successors.
2172 // Additionally, we assume the domains to be already present in the domain
2173 // map here. However, we iterate again in reverse post order so we know all
2174 // predecessors have been visited before a block or non-affine subregion is
2175 // visited.
2176
2177 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2178 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2179
2180 ReversePostOrderTraversal<Region *> RTraversal(R);
2181 for (auto *RN : RTraversal) {
2182
2183 // Recurse for affine subregions but go on for basic blocks and non-affine
2184 // subregions.
2185 if (RN->isSubRegion()) {
2186 Region *SubRegion = RN->getNodeAs<Region>();
2187 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002188 propagateDomainConstraints(SubRegion);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002189 continue;
2190 }
2191 }
2192
Johannes Doerfertf5673802015-10-01 23:48:18 +00002193 // Get the domain for the current block and check if it was initialized or
2194 // not. The only way it was not is if this block is only reachable via error
2195 // blocks, thus will not be executed under the assumptions we make. Such
2196 // blocks have to be skipped as their predecessors might not have domains
2197 // either. It would not benefit us to compute the domain anyway, only the
2198 // domains of the error blocks that are reachable from non-error blocks
2199 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002200 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002201 isl_set *&Domain = DomainMap[BB];
2202 if (!Domain) {
2203 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2204 << ", it is only reachable from error blocks.\n");
2205 DomainMap.erase(BB);
2206 continue;
2207 }
2208 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2209
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002210 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2211 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2212
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002213 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2214 for (auto *PredBB : predecessors(BB)) {
2215
2216 // Skip backedges
2217 if (DT.dominates(BB, PredBB))
2218 continue;
2219
2220 isl_set *PredBBDom = nullptr;
2221
2222 // Handle the SCoP entry block with its outside predecessors.
2223 if (!getRegion().contains(PredBB))
2224 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2225
2226 if (!PredBBDom) {
2227 // Determine the loop depth of the predecessor and adjust its domain to
2228 // the domain of the current block. This can mean we have to:
2229 // o) Drop a dimension if this block is the exit of a loop, not the
2230 // header of a new loop and the predecessor was part of the loop.
2231 // o) Add an unconstrainted new dimension if this block is the header
2232 // of a loop and the predecessor is not part of it.
2233 // o) Drop the information about the innermost loop dimension when the
2234 // predecessor and the current block are surrounded by different
2235 // loops in the same depth.
2236 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2237 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2238 while (BoxedLoops.count(PredBBLoop))
2239 PredBBLoop = PredBBLoop->getParentLoop();
2240
2241 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002242 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002243 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002244 PredBBDom = isl_set_project_out(
2245 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2246 LoopDepthDiff);
2247 else if (PredBBLoopDepth < BBLoopDepth) {
2248 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002249 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002250 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2251 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002252 PredBBDom = isl_set_drop_constraints_involving_dims(
2253 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002254 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002255 }
2256
2257 PredDom = isl_set_union(PredDom, PredBBDom);
2258 }
2259
2260 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002261 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002262
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002263 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002264 addLoopBoundsToHeaderDomain(BBLoop);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002265
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002266 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002267 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002268 IsOptimized = true;
2269 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002270 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2271 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002272 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002273 }
2274}
2275
2276/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2277/// is incremented by one and all other dimensions are equal, e.g.,
2278/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2279/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2280static __isl_give isl_map *
2281createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2282 auto *MapSpace = isl_space_map_from_set(SetSpace);
2283 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2284 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2285 if (u != Dim)
2286 NextIterationMap =
2287 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2288 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2289 C = isl_constraint_set_constant_si(C, 1);
2290 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2291 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2292 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2293 return NextIterationMap;
2294}
2295
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002296void Scop::addLoopBoundsToHeaderDomain(Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002297 int LoopDepth = getRelativeLoopDepth(L);
2298 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002299
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002300 BasicBlock *HeaderBB = L->getHeader();
2301 assert(DomainMap.count(HeaderBB));
2302 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002303
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002304 isl_map *NextIterationMap =
2305 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002306
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002307 isl_set *UnionBackedgeCondition =
2308 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002309
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002310 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2311 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002312
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002313 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002314
2315 // If the latch is only reachable via error statements we skip it.
2316 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2317 if (!LatchBBDom)
2318 continue;
2319
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002320 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002321
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002322 TerminatorInst *TI = LatchBB->getTerminator();
2323 BranchInst *BI = dyn_cast<BranchInst>(TI);
2324 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002325 BackedgeCondition = isl_set_copy(LatchBBDom);
2326 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002327 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002328 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002329 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002330
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002331 // Free the non back edge condition set as we do not need it.
2332 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002333
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002334 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002335 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002336
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002337 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2338 assert(LatchLoopDepth >= LoopDepth);
2339 BackedgeCondition =
2340 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2341 LatchLoopDepth - LoopDepth);
2342 UnionBackedgeCondition =
2343 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002344 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002345
2346 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2347 for (int i = 0; i < LoopDepth; i++)
2348 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2349
2350 isl_set *UnionBackedgeConditionComplement =
2351 isl_set_complement(UnionBackedgeCondition);
2352 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2353 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2354 UnionBackedgeConditionComplement =
2355 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2356 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2357 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2358
2359 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2360 HeaderBBDom = Parts.second;
2361
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002362 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2363 // the bounded assumptions to the context as they are already implied by the
2364 // <nsw> tag.
2365 if (Affinator.hasNSWAddRecForLoop(L)) {
2366 isl_set_free(Parts.first);
2367 return;
2368 }
2369
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002370 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2371 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002372 addAssumption(INFINITELOOP, BoundedCtx,
2373 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002374}
2375
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002376void Scop::buildAliasChecks(AliasAnalysis &AA) {
2377 if (!PollyUseRuntimeAliasChecks)
2378 return;
2379
2380 if (buildAliasGroups(AA))
2381 return;
2382
2383 // If a problem occurs while building the alias groups we need to delete
2384 // this SCoP and pretend it wasn't valid in the first place. To this end
2385 // we make the assumed context infeasible.
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002386 addAssumption(ALIASING, isl_set_empty(getParamSpace()), DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002387
2388 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2389 << " could not be created as the number of parameters involved "
2390 "is too high. The SCoP will be "
2391 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2392 "the maximal number of parameters but be advised that the "
2393 "compile time might increase exponentially.\n\n");
2394}
2395
Johannes Doerfert9143d672014-09-27 11:02:39 +00002396bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002397 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002398 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002399 // for all memory accesses inside the SCoP.
2400 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002401 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002402 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002403 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002404 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002405 // if their access domains intersect, otherwise they are in different
2406 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002407 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002408 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002409 // and maximal accesses to each array of a group in read only and non
2410 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002411 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2412
2413 AliasSetTracker AST(AA);
2414
2415 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002416 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002417 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002418
2419 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002420 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002421 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2422 isl_set_free(StmtDomain);
2423 if (StmtDomainEmpty)
2424 continue;
2425
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002426 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00002427 if (MA->isImplicit())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002428 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002429 if (!MA->isRead())
2430 HasWriteAccess.insert(MA->getBaseAddr());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002431 Instruction *Acc = MA->getAccessInstruction();
2432 PtrToAcc[getPointerOperand(*Acc)] = MA;
2433 AST.add(Acc);
2434 }
2435 }
2436
2437 SmallVector<AliasGroupTy, 4> AliasGroups;
2438 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002439 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002440 continue;
2441 AliasGroupTy AG;
2442 for (auto PR : AS)
2443 AG.push_back(PtrToAcc[PR.getValue()]);
2444 assert(AG.size() > 1 &&
2445 "Alias groups should contain at least two accesses");
2446 AliasGroups.push_back(std::move(AG));
2447 }
2448
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002449 // Split the alias groups based on their domain.
2450 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2451 AliasGroupTy NewAG;
2452 AliasGroupTy &AG = AliasGroups[u];
2453 AliasGroupTy::iterator AGI = AG.begin();
2454 isl_set *AGDomain = getAccessDomain(*AGI);
2455 while (AGI != AG.end()) {
2456 MemoryAccess *MA = *AGI;
2457 isl_set *MADomain = getAccessDomain(MA);
2458 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2459 NewAG.push_back(MA);
2460 AGI = AG.erase(AGI);
2461 isl_set_free(MADomain);
2462 } else {
2463 AGDomain = isl_set_union(AGDomain, MADomain);
2464 AGI++;
2465 }
2466 }
2467 if (NewAG.size() > 1)
2468 AliasGroups.push_back(std::move(NewAG));
2469 isl_set_free(AGDomain);
2470 }
2471
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002472 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002473 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002474 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2475 for (AliasGroupTy &AG : AliasGroups) {
2476 NonReadOnlyBaseValues.clear();
2477 ReadOnlyPairs.clear();
2478
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002479 if (AG.size() < 2) {
2480 AG.clear();
2481 continue;
2482 }
2483
Johannes Doerfert13771732014-10-01 12:40:46 +00002484 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002485 emitOptimizationRemarkAnalysis(
2486 F.getContext(), DEBUG_TYPE, F,
2487 (*II)->getAccessInstruction()->getDebugLoc(),
2488 "Possibly aliasing pointer, use restrict keyword.");
2489
Johannes Doerfert13771732014-10-01 12:40:46 +00002490 Value *BaseAddr = (*II)->getBaseAddr();
2491 if (HasWriteAccess.count(BaseAddr)) {
2492 NonReadOnlyBaseValues.insert(BaseAddr);
2493 II++;
2494 } else {
2495 ReadOnlyPairs[BaseAddr].insert(*II);
2496 II = AG.erase(II);
2497 }
2498 }
2499
2500 // If we don't have read only pointers check if there are at least two
2501 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002502 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002503 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002504 continue;
2505 }
2506
2507 // If we don't have non read only pointers clear the alias group.
2508 if (NonReadOnlyBaseValues.empty()) {
2509 AG.clear();
2510 continue;
2511 }
2512
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002513 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002514 MinMaxAliasGroups.emplace_back();
2515 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2516 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2517 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2518 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002519
2520 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002521
2522 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002523 for (MemoryAccess *MA : AG)
2524 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002525
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002526 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2527 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002528
2529 // Bail out if the number of values we need to compare is too large.
2530 // This is important as the number of comparisions grows quadratically with
2531 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002532 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2533 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002534 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002535
2536 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002537 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002538 Accesses = isl_union_map_empty(getParamSpace());
2539
2540 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2541 for (MemoryAccess *MA : ReadOnlyPair.second)
2542 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2543
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002544 Valid =
2545 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002546
2547 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002548 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002549 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002550
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002551 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002552}
2553
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002554/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002555static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002556 // Start with the smallest loop containing the entry and expand that
2557 // loop until it contains all blocks in the region. If there is a loop
2558 // containing all blocks in the region check if it is itself contained
2559 // and if so take the parent loop as it will be the smallest containing
2560 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002561 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002562 while (L) {
2563 bool AllContained = true;
2564 for (auto *BB : R.blocks())
2565 AllContained &= L->contains(BB);
2566 if (AllContained)
2567 break;
2568 L = L->getParentLoop();
2569 }
2570
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002571 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2572}
2573
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002574static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2575 ScopDetection &SD) {
2576
2577 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2578
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002579 unsigned MinLD = INT_MAX, MaxLD = 0;
2580 for (BasicBlock *BB : R.blocks()) {
2581 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002582 if (!R.contains(L))
2583 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002584 if (BoxedLoops && BoxedLoops->count(L))
2585 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002586 unsigned LD = L->getLoopDepth();
2587 MinLD = std::min(MinLD, LD);
2588 MaxLD = std::max(MaxLD, LD);
2589 }
2590 }
2591
2592 // Handle the case that there is no loop in the SCoP first.
2593 if (MaxLD == 0)
2594 return 1;
2595
2596 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2597 assert(MaxLD >= MinLD &&
2598 "Maximal loop depth was smaller than mininaml loop depth?");
2599 return MaxLD - MinLD + 1;
2600}
2601
Johannes Doerfert478a7de2015-10-02 13:09:31 +00002602Scop::Scop(Region &R, AccFuncMapType &AccFuncMap, ScopDetection &SD,
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002603 ScalarEvolution &ScalarEvolution, DominatorTree &DT, LoopInfo &LI,
Johannes Doerfert96425c22015-08-30 21:13:53 +00002604 isl_ctx *Context, unsigned MaxLoopDepth)
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002605 : LI(LI), DT(DT), SE(&ScalarEvolution), SD(SD), R(R),
2606 AccFuncMap(AccFuncMap), IsOptimized(false),
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002607 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
2608 MaxLoopDepth(MaxLoopDepth), IslCtx(Context), Context(nullptr),
2609 Affinator(this), AssumedContext(nullptr), BoundaryContext(nullptr),
2610 Schedule(nullptr) {}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002611
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002612void Scop::init(AliasAnalysis &AA, AssumptionCache &AC) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00002613 buildContext();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00002614 addUserAssumptions(AC);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002615 buildInvariantEquivalenceClasses();
2616
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002617 buildDomains(&R);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002618
Michael Krusecac948e2015-10-02 13:53:07 +00002619 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002620 // Exit early in case there are no executable statements left in this scop.
Michael Krusecac948e2015-10-02 13:53:07 +00002621 simplifySCoP(true);
Michael Kruseafe06702015-10-02 16:33:27 +00002622 if (Stmts.empty())
2623 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002624
Michael Krusecac948e2015-10-02 13:53:07 +00002625 // The ScopStmts now have enough information to initialize themselves.
2626 for (ScopStmt &Stmt : Stmts)
2627 Stmt.init();
2628
2629 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> LoopSchedules;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002630 Loop *L = getLoopSurroundingRegion(R, LI);
2631 LoopSchedules[L];
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00002632 buildSchedule(&R, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002633 Schedule = LoopSchedules[L].first;
Tobias Grosser75805372011-04-29 06:27:02 +00002634
Tobias Grosser8286b832015-11-02 11:29:32 +00002635 if (isl_set_is_empty(AssumedContext))
2636 return;
2637
2638 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002639 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002640 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002641 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002642 buildBoundaryContext();
2643 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002644 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002645
2646 hoistInvariantLoads();
Michael Krusecac948e2015-10-02 13:53:07 +00002647 simplifySCoP(false);
Tobias Grosser75805372011-04-29 06:27:02 +00002648}
2649
2650Scop::~Scop() {
2651 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002652 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002653 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002654 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002655
Johannes Doerfert96425c22015-08-30 21:13:53 +00002656 for (auto It : DomainMap)
2657 isl_set_free(It.second);
2658
Johannes Doerfertb164c792014-09-18 11:17:17 +00002659 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002660 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002661 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002662 isl_pw_multi_aff_free(MMA.first);
2663 isl_pw_multi_aff_free(MMA.second);
2664 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002665 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002666 isl_pw_multi_aff_free(MMA.first);
2667 isl_pw_multi_aff_free(MMA.second);
2668 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002669 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002670
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002671 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002672 isl_set_free(std::get<2>(IAClass));
Tobias Grosser75805372011-04-29 06:27:02 +00002673}
2674
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002675void Scop::updateAccessDimensionality() {
2676 for (auto &Stmt : *this)
2677 for (auto &Access : Stmt)
2678 Access->updateDimensionality();
2679}
2680
Michael Krusecac948e2015-10-02 13:53:07 +00002681void Scop::simplifySCoP(bool RemoveIgnoredStmts) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002682 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2683 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002684 RegionNode *RN = Stmt.isRegionStmt()
2685 ? Stmt.getRegion()->getNode()
2686 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002687
Johannes Doerferteca9e892015-11-03 16:54:49 +00002688 bool RemoveStmt = StmtIt->isEmpty();
2689 if (!RemoveStmt)
2690 RemoveStmt = isl_set_is_empty(DomainMap[getRegionNodeBasicBlock(RN)]);
2691 if (!RemoveStmt)
2692 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002693
Johannes Doerferteca9e892015-11-03 16:54:49 +00002694 // Remove read only statements only after invariant loop hoisting.
2695 if (!RemoveStmt && !RemoveIgnoredStmts) {
2696 bool OnlyRead = true;
2697 for (MemoryAccess *MA : Stmt) {
2698 if (MA->isRead())
2699 continue;
2700
2701 OnlyRead = false;
2702 break;
2703 }
2704
2705 RemoveStmt = OnlyRead;
2706 }
2707
2708 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002709 // Remove the statement because it is unnecessary.
2710 if (Stmt.isRegionStmt())
2711 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2712 StmtMap.erase(BB);
2713 else
2714 StmtMap.erase(Stmt.getBasicBlock());
2715
2716 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002717 continue;
2718 }
2719
Michael Krusecac948e2015-10-02 13:53:07 +00002720 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002721 }
2722}
2723
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002724const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2725 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2726 if (!LInst)
2727 return nullptr;
2728
2729 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2730 LInst = cast<LoadInst>(Rep);
2731
2732 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2733 for (auto &IAClass : InvariantEquivClasses)
2734 if (PointerSCEV == std::get<0>(IAClass))
2735 return &IAClass;
2736
2737 return nullptr;
2738}
2739
2740void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2741
2742 // Get the context under which the statement is executed.
2743 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2744 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2745 DomainCtx = isl_set_detect_equalities(DomainCtx);
2746 DomainCtx = isl_set_coalesce(DomainCtx);
2747
2748 // Project out all parameters that relate to loads in the statement. Otherwise
2749 // we could have cyclic dependences on the constraints under which the
2750 // hoisted loads are executed and we could not determine an order in which to
2751 // pre-load them. This happens because not only lower bounds are part of the
2752 // domain but also upper bounds.
2753 for (MemoryAccess *MA : InvMAs) {
2754 Instruction *AccInst = MA->getAccessInstruction();
2755 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002756 SetVector<Value *> Values;
2757 for (const SCEV *Parameter : Parameters) {
2758 Values.clear();
2759 findValues(Parameter, Values);
2760 if (!Values.count(AccInst))
2761 continue;
2762
2763 if (isl_id *ParamId = getIdForParam(Parameter)) {
2764 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2765 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2766 isl_id_free(ParamId);
2767 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002768 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002769 }
2770 }
2771
2772 for (MemoryAccess *MA : InvMAs) {
2773 // Check for another invariant access that accesses the same location as
2774 // MA and if found consolidate them. Otherwise create a new equivalence
2775 // class at the end of InvariantEquivClasses.
2776 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
2777 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2778
2779 bool Consolidated = false;
2780 for (auto &IAClass : InvariantEquivClasses) {
2781 if (PointerSCEV != std::get<0>(IAClass))
2782 continue;
2783
2784 Consolidated = true;
2785
2786 // Add MA to the list of accesses that are in this class.
2787 auto &MAs = std::get<1>(IAClass);
2788 MAs.push_front(MA);
2789
2790 // Unify the execution context of the class and this statement.
2791 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002792 if (IAClassDomainCtx)
2793 IAClassDomainCtx = isl_set_coalesce(
2794 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2795 else
2796 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002797 break;
2798 }
2799
2800 if (Consolidated)
2801 continue;
2802
2803 // If we did not consolidate MA, thus did not find an equivalence class
2804 // for it, we create a new one.
2805 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
2806 isl_set_copy(DomainCtx));
2807 }
2808
2809 isl_set_free(DomainCtx);
2810}
2811
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002812void Scop::hoistInvariantLoads() {
2813 isl_union_map *Writes = getWrites();
2814 for (ScopStmt &Stmt : *this) {
2815
2816 // TODO: Loads that are not loop carried, hence are in a statement with
2817 // zero iterators, are by construction invariant, though we
Johannes Doerfert09e36972015-10-07 20:17:36 +00002818 // currently "hoist" them anyway. This is necessary because we allow
2819 // them to be treated as parameters (e.g., in conditions) and our code
2820 // generation would otherwise use the old value.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002821
Johannes Doerfert8930f482015-10-02 14:51:00 +00002822 BasicBlock *BB = Stmt.isBlockStmt() ? Stmt.getBasicBlock()
2823 : Stmt.getRegion()->getEntry();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002824 isl_set *Domain = Stmt.getDomain();
2825 MemoryAccessList InvMAs;
2826
2827 for (MemoryAccess *MA : Stmt) {
2828 if (MA->isImplicit() || MA->isWrite() || !MA->isAffine())
2829 continue;
2830
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002831 // Skip accesses that have an invariant base pointer which is defined but
2832 // not loaded inside the SCoP. This can happened e.g., if a readnone call
2833 // returns a pointer that is used as a base address. However, as we want
2834 // to hoist indirect pointers, we allow the base pointer to be defined in
Johannes Doerfert654c3282015-10-21 22:14:57 +00002835 // the region if it is also a memory access. Each ScopArrayInfo object
2836 // that has a base pointer origin has a base pointer that is loaded and
2837 // that it is invariant, thus it will be hoisted too. However, if there is
Tobias Grosser27e19a02015-10-25 12:05:14 +00002838 // no base pointer origin we check that the base pointer is defined
Johannes Doerfert654c3282015-10-21 22:14:57 +00002839 // outside the region.
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002840 const ScopArrayInfo *SAI = MA->getScopArrayInfo();
Johannes Doerfert654c3282015-10-21 22:14:57 +00002841 while (auto *BasePtrOriginSAI = SAI->getBasePtrOriginSAI())
2842 SAI = BasePtrOriginSAI;
2843
2844 if (auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr()))
2845 if (R.contains(BasePtrInst))
2846 continue;
Johannes Doerfertbc7cff42015-10-18 19:49:25 +00002847
Johannes Doerfert8930f482015-10-02 14:51:00 +00002848 // Skip accesses in non-affine subregions as they might not be executed
2849 // under the same condition as the entry of the non-affine subregion.
2850 if (BB != MA->getAccessInstruction()->getParent())
2851 continue;
2852
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002853 isl_map *AccessRelation = MA->getAccessRelation();
Johannes Doerfertb864c2c2015-10-18 19:50:18 +00002854
2855 // Skip accesses that have an empty access relation. These can be caused
2856 // by multiple offsets with a type cast in-between that cause the overall
2857 // byte offset to be not divisible by the new types sizes.
2858 if (isl_map_is_empty(AccessRelation)) {
2859 isl_map_free(AccessRelation);
2860 continue;
2861 }
2862
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002863 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
2864 Stmt.getNumIterators())) {
2865 isl_map_free(AccessRelation);
2866 continue;
2867 }
2868
2869 AccessRelation =
2870 isl_map_intersect_domain(AccessRelation, isl_set_copy(Domain));
2871 isl_set *AccessRange = isl_map_range(AccessRelation);
2872
2873 isl_union_map *Written = isl_union_map_intersect_range(
2874 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
2875 bool IsWritten = !isl_union_map_is_empty(Written);
2876 isl_union_map_free(Written);
2877
2878 if (IsWritten)
2879 continue;
2880
2881 InvMAs.push_front(MA);
2882 }
2883
2884 // We inserted invariant accesses always in the front but need them to be
2885 // sorted in a "natural order". The statements are already sorted in reverse
2886 // post order and that suffices for the accesses too. The reason we require
2887 // an order in the first place is the dependences between invariant loads
2888 // that can be caused by indirect loads.
2889 InvMAs.reverse();
2890
2891 // Transfer the memory access from the statement to the SCoP.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002892 Stmt.removeMemoryAccesses(InvMAs);
2893 addInvariantLoads(Stmt, InvMAs);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002894
2895 isl_set_free(Domain);
2896 }
2897 isl_union_map_free(Writes);
2898
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002899 auto &ScopRIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002900 // Check required invariant loads that were tagged during SCoP detection.
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002901 for (LoadInst *LI : ScopRIL) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00002902 assert(LI && getRegion().contains(LI));
2903 ScopStmt *Stmt = getStmtForBasicBlock(LI->getParent());
2904 if (Stmt && Stmt->lookupAccessesFor(LI) != nullptr) {
2905 DEBUG(dbgs() << "\n\nWARNING: Load (" << *LI
2906 << ") is required to be invariant but was not marked as "
2907 "such. SCoP for "
2908 << getRegion() << " will be dropped\n\n");
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002909 addAssumption(INVARIANTLOAD, isl_set_empty(getParamSpace()),
2910 LI->getDebugLoc());
Johannes Doerfert09e36972015-10-07 20:17:36 +00002911 return;
2912 }
2913 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002914}
2915
Johannes Doerfert80ef1102014-11-07 08:31:31 +00002916const ScopArrayInfo *
2917Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *AccessType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002918 ArrayRef<const SCEV *> Sizes,
2919 ScopArrayInfo::ARRAYKIND Kind) {
2920 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002921 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00002922 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
2923 SAI.reset(new ScopArrayInfo(BasePtr, AccessType, getIslCtx(), Sizes, Kind,
2924 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002925 } else {
Tobias Grosser8286b832015-11-02 11:29:32 +00002926 // In case of mismatching array sizes, we bail out by setting the run-time
2927 // context to false.
2928 if (!SAI->updateSizes(Sizes))
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002929 addAssumption(DELINEARIZATION, isl_set_empty(getParamSpace()),
2930 DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002931 }
Tobias Grosserab671442015-05-23 05:58:27 +00002932 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002933}
2934
Tobias Grosser6abc75a2015-11-10 17:31:31 +00002935const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
2936 ScopArrayInfo::ARRAYKIND Kind) {
2937 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00002938 assert(SAI && "No ScopArrayInfo available for this base pointer");
2939 return SAI;
2940}
2941
Tobias Grosser74394f02013-01-14 22:40:23 +00002942std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002943std::string Scop::getAssumedContextStr() const {
2944 return stringFromIslObj(AssumedContext);
2945}
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002946std::string Scop::getBoundaryContextStr() const {
2947 return stringFromIslObj(BoundaryContext);
2948}
Tobias Grosser75805372011-04-29 06:27:02 +00002949
2950std::string Scop::getNameStr() const {
2951 std::string ExitName, EntryName;
2952 raw_string_ostream ExitStr(ExitName);
2953 raw_string_ostream EntryStr(EntryName);
2954
Tobias Grosserf240b482014-01-09 10:42:15 +00002955 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002956 EntryStr.str();
2957
2958 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00002959 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00002960 ExitStr.str();
2961 } else
2962 ExitName = "FunctionExit";
2963
2964 return EntryName + "---" + ExitName;
2965}
2966
Tobias Grosser74394f02013-01-14 22:40:23 +00002967__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00002968__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00002969 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00002970}
2971
Tobias Grossere86109f2013-10-29 21:05:49 +00002972__isl_give isl_set *Scop::getAssumedContext() const {
2973 return isl_set_copy(AssumedContext);
2974}
2975
Johannes Doerfert43788c52015-08-20 05:58:56 +00002976__isl_give isl_set *Scop::getRuntimeCheckContext() const {
2977 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002978 RuntimeCheckContext =
2979 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
2980 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002981 return RuntimeCheckContext;
2982}
2983
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002984bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00002985 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00002986 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00002987 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
2988 isl_set_free(RuntimeCheckContext);
2989 return IsFeasible;
2990}
2991
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002992static std::string toString(AssumptionKind Kind) {
2993 switch (Kind) {
2994 case ALIASING:
2995 return "No-aliasing";
2996 case INBOUNDS:
2997 return "Inbounds";
2998 case WRAPPING:
2999 return "No-overflows";
Johannes Doerferta4b77c02015-11-12 20:15:32 +00003000 case ALIGNMENT:
3001 return "Alignment";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003002 case ERRORBLOCK:
3003 return "No-error";
3004 case INFINITELOOP:
3005 return "Finite loop";
3006 case INVARIANTLOAD:
3007 return "Invariant load";
3008 case DELINEARIZATION:
3009 return "Delinearization";
3010 }
3011 llvm_unreachable("Unknown AssumptionKind!");
3012}
3013
3014void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3015 DebugLoc Loc) {
3016 if (isl_set_is_subset(Context, Set))
3017 return;
3018
3019 if (isl_set_is_subset(AssumedContext, Set))
3020 return;
3021
3022 auto &F = *getRegion().getEntry()->getParent();
3023 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3024 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3025}
3026
3027void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3028 DebugLoc Loc) {
3029 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003030 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003031
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003032 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003033 if (NSets >= MaxDisjunctsAssumed) {
3034 isl_space *Space = isl_set_get_space(AssumedContext);
3035 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003036 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003037 }
3038
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003039 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003040}
3041
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003042__isl_give isl_set *Scop::getBoundaryContext() const {
3043 return isl_set_copy(BoundaryContext);
3044}
3045
Tobias Grosser75805372011-04-29 06:27:02 +00003046void Scop::printContext(raw_ostream &OS) const {
3047 OS << "Context:\n";
3048
3049 if (!Context) {
3050 OS.indent(4) << "n/a\n\n";
3051 return;
3052 }
3053
3054 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003055
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003056 OS.indent(4) << "Assumed Context:\n";
3057 if (!AssumedContext) {
3058 OS.indent(4) << "n/a\n\n";
3059 return;
3060 }
3061
3062 OS.indent(4) << getAssumedContextStr() << "\n";
3063
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003064 OS.indent(4) << "Boundary Context:\n";
3065 if (!BoundaryContext) {
3066 OS.indent(4) << "n/a\n\n";
3067 return;
3068 }
3069
3070 OS.indent(4) << getBoundaryContextStr() << "\n";
3071
Tobias Grosser083d3d32014-06-28 08:59:45 +00003072 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003073 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003074 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3075 }
Tobias Grosser75805372011-04-29 06:27:02 +00003076}
3077
Johannes Doerfertb164c792014-09-18 11:17:17 +00003078void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003079 int noOfGroups = 0;
3080 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003081 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003082 noOfGroups += 1;
3083 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003084 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003085 }
3086
Tobias Grosserbb853c22015-07-25 12:31:03 +00003087 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003088 if (MinMaxAliasGroups.empty()) {
3089 OS.indent(8) << "n/a\n";
3090 return;
3091 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003092
Tobias Grosserbb853c22015-07-25 12:31:03 +00003093 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003094
3095 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003096 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003097 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003098 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003099 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3100 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003101 }
3102 OS << " ]]\n";
3103 }
3104
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003105 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003106 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003107 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003108 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003109 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3110 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003111 }
3112 OS << " ]]\n";
3113 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003114 }
3115}
3116
Tobias Grosser75805372011-04-29 06:27:02 +00003117void Scop::printStatements(raw_ostream &OS) const {
3118 OS << "Statements {\n";
3119
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003120 for (const ScopStmt &Stmt : *this)
3121 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003122
3123 OS.indent(4) << "}\n";
3124}
3125
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003126void Scop::printArrayInfo(raw_ostream &OS) const {
3127 OS << "Arrays {\n";
3128
Tobias Grosserab671442015-05-23 05:58:27 +00003129 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003130 Array.second->print(OS);
3131
3132 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003133
3134 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3135
3136 for (auto &Array : arrays())
3137 Array.second->print(OS, /* SizeAsPwAff */ true);
3138
3139 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003140}
3141
Tobias Grosser75805372011-04-29 06:27:02 +00003142void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003143 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3144 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003145 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003146 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003147 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003148 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003149 const auto &MAs = std::get<1>(IAClass);
3150 if (MAs.empty()) {
3151 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003152 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003153 MAs.front()->print(OS);
3154 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003155 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003156 }
3157 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003158 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003159 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003160 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003161 printStatements(OS.indent(4));
3162}
3163
3164void Scop::dump() const { print(dbgs()); }
3165
Tobias Grosser9a38ab82011-11-08 15:41:03 +00003166isl_ctx *Scop::getIslCtx() const { return IslCtx; }
Tobias Grosser75805372011-04-29 06:27:02 +00003167
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003168__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3169 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003170}
3171
Tobias Grosser808cd692015-07-14 09:33:13 +00003172__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003173 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003174
Tobias Grosser808cd692015-07-14 09:33:13 +00003175 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003176 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003177
3178 return Domain;
3179}
3180
Tobias Grossere5a35142015-11-12 14:07:09 +00003181__isl_give isl_union_map *
3182Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3183 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003184
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003185 for (ScopStmt &Stmt : *this) {
3186 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003187 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003188 continue;
3189
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003190 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003191 isl_map *AccessDomain = MA->getAccessRelation();
3192 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003193 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003194 }
3195 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003196 return isl_union_map_coalesce(Accesses);
3197}
3198
3199__isl_give isl_union_map *Scop::getMustWrites() {
3200 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003201}
3202
3203__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003204 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003205}
3206
Tobias Grosser37eb4222014-02-20 21:43:54 +00003207__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003208 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003209}
3210
3211__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003212 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003213}
3214
Tobias Grosser2ac23382015-11-12 14:07:13 +00003215__isl_give isl_union_map *Scop::getAccesses() {
3216 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3217}
3218
Tobias Grosser808cd692015-07-14 09:33:13 +00003219__isl_give isl_union_map *Scop::getSchedule() const {
3220 auto Tree = getScheduleTree();
3221 auto S = isl_schedule_get_map(Tree);
3222 isl_schedule_free(Tree);
3223 return S;
3224}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003225
Tobias Grosser808cd692015-07-14 09:33:13 +00003226__isl_give isl_schedule *Scop::getScheduleTree() const {
3227 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3228 getDomains());
3229}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003230
Tobias Grosser808cd692015-07-14 09:33:13 +00003231void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3232 auto *S = isl_schedule_from_domain(getDomains());
3233 S = isl_schedule_insert_partial_schedule(
3234 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3235 isl_schedule_free(Schedule);
3236 Schedule = S;
3237}
3238
3239void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3240 isl_schedule_free(Schedule);
3241 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003242}
3243
3244bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3245 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003246 for (ScopStmt &Stmt : *this) {
3247 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003248 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3249 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3250
3251 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3252 isl_union_set_free(StmtDomain);
3253 isl_union_set_free(NewStmtDomain);
3254 continue;
3255 }
3256
3257 Changed = true;
3258
3259 isl_union_set_free(StmtDomain);
3260 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3261
3262 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003263 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003264 isl_union_set_free(NewStmtDomain);
3265 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003266 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003267 }
3268 isl_union_set_free(Domain);
3269 return Changed;
3270}
3271
Tobias Grosser75805372011-04-29 06:27:02 +00003272ScalarEvolution *Scop::getSE() const { return SE; }
3273
Johannes Doerfertf5673802015-10-01 23:48:18 +00003274bool Scop::isIgnored(RegionNode *RN) {
3275 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Tobias Grosser75805372011-04-29 06:27:02 +00003276
Johannes Doerfertf5673802015-10-01 23:48:18 +00003277 // Check if there are accesses contained.
3278 bool ContainsAccesses = false;
3279 if (!RN->isSubRegion())
3280 ContainsAccesses = getAccessFunctions(BB);
3281 else
3282 for (BasicBlock *RBB : RN->getNodeAs<Region>()->blocks())
3283 ContainsAccesses |= (getAccessFunctions(RBB) != nullptr);
3284 if (!ContainsAccesses)
3285 return true;
3286
3287 // Check for reachability via non-error blocks.
3288 if (!DomainMap.count(BB))
3289 return true;
3290
3291 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003292 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003293 return true;
3294
3295 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003296}
3297
Tobias Grosser808cd692015-07-14 09:33:13 +00003298struct MapToDimensionDataTy {
3299 int N;
3300 isl_union_pw_multi_aff *Res;
3301};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003302
Tobias Grosser808cd692015-07-14 09:33:13 +00003303// @brief Create a function that maps the elements of 'Set' to its N-th
3304// dimension.
3305//
3306// The result is added to 'User->Res'.
3307//
3308// @param Set The input set.
3309// @param N The dimension to map to.
3310//
3311// @returns Zero if no error occurred, non-zero otherwise.
3312static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3313 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3314 int Dim;
3315 isl_space *Space;
3316 isl_pw_multi_aff *PMA;
3317
3318 Dim = isl_set_dim(Set, isl_dim_set);
3319 Space = isl_set_get_space(Set);
3320 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3321 Dim - Data->N);
3322 if (Data->N > 1)
3323 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3324 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3325
3326 isl_set_free(Set);
3327
3328 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003329}
3330
Tobias Grosser808cd692015-07-14 09:33:13 +00003331// @brief Create a function that maps the elements of Domain to their Nth
3332// dimension.
3333//
3334// @param Domain The set of elements to map.
3335// @param N The dimension to map to.
3336static __isl_give isl_multi_union_pw_aff *
3337mapToDimension(__isl_take isl_union_set *Domain, int N) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003338 if (N <= 0 || isl_union_set_is_empty(Domain)) {
3339 isl_union_set_free(Domain);
3340 return nullptr;
3341 }
3342
Tobias Grosser808cd692015-07-14 09:33:13 +00003343 struct MapToDimensionDataTy Data;
3344 isl_space *Space;
3345
3346 Space = isl_union_set_get_space(Domain);
3347 Data.N = N;
3348 Data.Res = isl_union_pw_multi_aff_empty(Space);
3349 if (isl_union_set_foreach_set(Domain, &mapToDimension_AddSet, &Data) < 0)
3350 Data.Res = isl_union_pw_multi_aff_free(Data.Res);
3351
3352 isl_union_set_free(Domain);
3353 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3354}
3355
Tobias Grosser316b5b22015-11-11 19:28:14 +00003356void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003357 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003358 Stmts.emplace_back(*this, *BB);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003359 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003360 StmtMap[BB] = Stmt;
3361 } else {
3362 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003363 Stmts.emplace_back(*this, *R);
Tobias Grosser316b5b22015-11-11 19:28:14 +00003364 auto Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003365 for (BasicBlock *BB : R->blocks())
3366 StmtMap[BB] = Stmt;
3367 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003368}
3369
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003370void Scop::buildSchedule(
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003371 Region *R,
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003372 DenseMap<Loop *, std::pair<isl_schedule *, unsigned>> &LoopSchedules) {
Michael Kruse046dde42015-08-10 13:01:57 +00003373
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003374 if (SD.isNonAffineSubRegion(R, &getRegion())) {
Johannes Doerfertc6987c12015-09-26 13:41:43 +00003375 Loop *L = getLoopSurroundingRegion(*R, LI);
3376 auto &LSchedulePair = LoopSchedules[L];
Michael Krusecac948e2015-10-02 13:53:07 +00003377 ScopStmt *Stmt = getStmtForBasicBlock(R->getEntry());
Michael Kruseafe06702015-10-02 16:33:27 +00003378 isl_set *Domain = Stmt->getDomain();
Michael Krusecac948e2015-10-02 13:53:07 +00003379 auto *UDomain = isl_union_set_from_set(Domain);
3380 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00003381 LSchedulePair.first = StmtSchedule;
3382 return;
3383 }
3384
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003385 ReversePostOrderTraversal<Region *> RTraversal(R);
3386 for (auto *RN : RTraversal) {
Michael Kruse046dde42015-08-10 13:01:57 +00003387
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003388 if (RN->isSubRegion()) {
3389 Region *SubRegion = RN->getNodeAs<Region>();
3390 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003391 buildSchedule(SubRegion, LoopSchedules);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003392 continue;
3393 }
Tobias Grosser75805372011-04-29 06:27:02 +00003394 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003395
3396 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert30c22652015-10-18 21:17:11 +00003397 if (!getRegion().contains(L))
3398 L = getLoopSurroundingRegion(getRegion(), LI);
3399
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003400 int LD = getRelativeLoopDepth(L);
3401 auto &LSchedulePair = LoopSchedules[L];
3402 LSchedulePair.second += getNumBlocksInRegionNode(RN);
3403
Michael Krusecac948e2015-10-02 13:53:07 +00003404 BasicBlock *BB = getRegionNodeBasicBlock(RN);
3405 ScopStmt *Stmt = getStmtForBasicBlock(BB);
3406 if (Stmt) {
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003407 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3408 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
3409 LSchedulePair.first =
3410 combineInSequence(LSchedulePair.first, StmtSchedule);
3411 }
3412
3413 unsigned NumVisited = LSchedulePair.second;
3414 while (L && NumVisited == L->getNumBlocks()) {
3415 auto *LDomain = isl_schedule_get_domain(LSchedulePair.first);
3416 if (auto *MUPA = mapToDimension(LDomain, LD + 1))
3417 LSchedulePair.first =
3418 isl_schedule_insert_partial_schedule(LSchedulePair.first, MUPA);
3419
3420 auto *PL = L->getParentLoop();
Johannes Doerfertdca28372015-11-03 00:28:07 +00003421
3422 // Either we have a proper loop and we also build a schedule for the
3423 // parent loop or we have a infinite loop that does not have a proper
3424 // parent loop. In the former case this conditional will be skipped, in
3425 // the latter case however we will break here as we do not build a domain
3426 // nor a schedule for a infinite loop.
3427 assert(LoopSchedules.count(PL) || LSchedulePair.first == nullptr);
3428 if (!LoopSchedules.count(PL))
3429 break;
3430
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003431 auto &PSchedulePair = LoopSchedules[PL];
3432 PSchedulePair.first =
3433 combineInSequence(PSchedulePair.first, LSchedulePair.first);
3434 PSchedulePair.second += NumVisited;
3435
3436 L = PL;
3437 NumVisited = PSchedulePair.second;
3438 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003439 }
Tobias Grosser75805372011-04-29 06:27:02 +00003440}
3441
Johannes Doerfert7c494212014-10-31 23:13:39 +00003442ScopStmt *Scop::getStmtForBasicBlock(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003443 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003444 if (StmtMapIt == StmtMap.end())
3445 return nullptr;
3446 return StmtMapIt->second;
3447}
3448
Johannes Doerfert96425c22015-08-30 21:13:53 +00003449int Scop::getRelativeLoopDepth(const Loop *L) const {
3450 Loop *OuterLoop =
3451 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3452 if (!OuterLoop)
3453 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003454 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3455}
3456
Michael Krused868b5d2015-09-10 15:25:24 +00003457void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003458 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003459
3460 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3461 // true, are not modeled as ordinary PHI nodes as they are not part of the
3462 // region. However, we model the operands in the predecessor blocks that are
3463 // part of the region as regular scalar accesses.
3464
3465 // If we can synthesize a PHI we can skip it, however only if it is in
3466 // the region. If it is not it can only be in the exit block of the region.
3467 // In this case we model the operands but not the PHI itself.
3468 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3469 return;
3470
3471 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3472 // detection. Hence, the PHI is a load of a new memory location in which the
3473 // incoming value was written at the end of the incoming basic block.
3474 bool OnlyNonAffineSubRegionOperands = true;
3475 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3476 Value *Op = PHI->getIncomingValue(u);
3477 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3478
3479 // Do not build scalar dependences inside a non-affine subregion.
3480 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3481 continue;
3482
3483 OnlyNonAffineSubRegionOperands = false;
3484
3485 if (!R.contains(OpBB))
3486 continue;
3487
3488 Instruction *OpI = dyn_cast<Instruction>(Op);
3489 if (OpI) {
3490 BasicBlock *OpIBB = OpI->getParent();
3491 // As we pretend there is a use (or more precise a write) of OpI in OpBB
3492 // we have to insert a scalar dependence from the definition of OpI to
3493 // OpBB if the definition is not in OpBB.
Michael Kruse668af712015-10-15 14:45:48 +00003494 if (scop->getStmtForBasicBlock(OpIBB) !=
3495 scop->getStmtForBasicBlock(OpBB)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003496 addScalarReadAccess(OpI, PHI, OpBB);
3497 addScalarWriteAccess(OpI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003498 }
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003499 } else if (ModelReadOnlyScalars && !isa<Constant>(Op)) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003500 addScalarReadAccess(Op, PHI, OpBB);
Michael Kruse7bf39442015-09-10 12:46:52 +00003501 }
3502
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003503 addPHIWriteAccess(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003504 }
3505
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003506 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3507 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003508 }
3509}
3510
Michael Krused868b5d2015-09-10 15:25:24 +00003511bool ScopInfo::buildScalarDependences(Instruction *Inst, Region *R,
3512 Region *NonAffineSubRegion) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003513 bool canSynthesizeInst = canSynthesize(Inst, LI, SE, R);
3514 if (isIgnoredIntrinsic(Inst))
3515 return false;
3516
3517 bool AnyCrossStmtUse = false;
3518 BasicBlock *ParentBB = Inst->getParent();
3519
3520 for (User *U : Inst->users()) {
3521 Instruction *UI = dyn_cast<Instruction>(U);
3522
3523 // Ignore the strange user
3524 if (UI == 0)
3525 continue;
3526
3527 BasicBlock *UseParent = UI->getParent();
3528
Tobias Grosserbaffa092015-10-24 20:55:27 +00003529 // Ignore basic block local uses. A value that is defined in a scop, but
3530 // used in a PHI node in the same basic block does not count as basic block
3531 // local, as for such cases a control flow edge is passed between definition
3532 // and use.
3533 if (UseParent == ParentBB && !isa<PHINode>(UI))
Michael Kruse7bf39442015-09-10 12:46:52 +00003534 continue;
3535
Michael Krusef714d472015-11-05 13:18:43 +00003536 // Uses by PHI nodes in the entry node count as external uses in case the
3537 // use is through an incoming block that is itself not contained in the
3538 // region.
3539 if (R->getEntry() == UseParent) {
3540 if (auto *PHI = dyn_cast<PHINode>(UI)) {
3541 bool ExternalUse = false;
3542 for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
3543 if (PHI->getIncomingValue(i) == Inst &&
3544 !R->contains(PHI->getIncomingBlock(i))) {
3545 ExternalUse = true;
3546 break;
3547 }
3548 }
3549
3550 if (ExternalUse) {
3551 AnyCrossStmtUse = true;
3552 continue;
3553 }
3554 }
3555 }
3556
Michael Kruse7bf39442015-09-10 12:46:52 +00003557 // Do not build scalar dependences inside a non-affine subregion.
3558 if (NonAffineSubRegion && NonAffineSubRegion->contains(UseParent))
3559 continue;
3560
Michael Kruse01cb3792015-10-17 21:07:08 +00003561 // Check for PHI nodes in the region exit and skip them, if they will be
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003562 // modeled as PHI nodes.
Michael Kruse01cb3792015-10-17 21:07:08 +00003563 //
3564 // PHI nodes in the region exit that have more than two incoming edges need
Tobias Grosser05d7fa72015-10-17 21:46:28 +00003565 // to be modeled as PHI-Nodes to correctly model the fact that depending on
3566 // the control flow a different value will be assigned to the PHI node. In
3567 // case this is the case, there is no need to create an additional normal
3568 // scalar dependence. Hence, bail out before we register an "out-of-region"
3569 // use for this definition.
Michael Kruse01cb3792015-10-17 21:07:08 +00003570 if (isa<PHINode>(UI) && UI->getParent() == R->getExit() &&
3571 !R->getExitingBlock())
3572 continue;
3573
Michael Kruse7bf39442015-09-10 12:46:52 +00003574 // Check whether or not the use is in the SCoP.
Tobias Grosserc73d8b02015-10-23 22:36:22 +00003575 if (!R->contains(UseParent)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003576 AnyCrossStmtUse = true;
3577 continue;
3578 }
3579
3580 // If the instruction can be synthesized and the user is in the region
3581 // we do not need to add scalar dependences.
3582 if (canSynthesizeInst)
3583 continue;
3584
3585 // No need to translate these scalar dependences into polyhedral form,
3586 // because synthesizable scalars can be generated by the code generator.
3587 if (canSynthesize(UI, LI, SE, R))
3588 continue;
3589
3590 // Skip PHI nodes in the region as they handle their operands on their own.
3591 if (isa<PHINode>(UI))
3592 continue;
3593
3594 // Now U is used in another statement.
3595 AnyCrossStmtUse = true;
3596
3597 // Do not build a read access that is not in the current SCoP
Michael Krusee2bccbb2015-09-18 19:59:43 +00003598 // Use the def instruction as base address of the MemoryAccess, so that it
3599 // will become the name of the scalar access in the polyhedral form.
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003600 addScalarReadAccess(Inst, UI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003601 }
3602
Tobias Grosserda95a4a2015-09-24 20:59:59 +00003603 if (ModelReadOnlyScalars && !isa<PHINode>(Inst)) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003604 for (Value *Op : Inst->operands()) {
3605 if (canSynthesize(Op, LI, SE, R))
3606 continue;
3607
3608 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
3609 if (R->contains(OpInst))
3610 continue;
3611
3612 if (isa<Constant>(Op))
3613 continue;
3614
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003615 addScalarReadAccess(Op, Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003616 }
3617 }
3618
3619 return AnyCrossStmtUse;
3620}
3621
3622extern MapInsnToMemAcc InsnToMemAcc;
3623
Michael Krusee2bccbb2015-09-18 19:59:43 +00003624void ScopInfo::buildMemoryAccess(
3625 Instruction *Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003626 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3627 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003628 unsigned Size;
3629 Type *SizeType;
3630 Value *Val;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003631 enum MemoryAccess::AccessType Type;
Michael Kruse7bf39442015-09-10 12:46:52 +00003632
3633 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
3634 SizeType = Load->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003635 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003636 Type = MemoryAccess::READ;
Michael Kruse7bf39442015-09-10 12:46:52 +00003637 Val = Load;
3638 } else {
3639 StoreInst *Store = cast<StoreInst>(Inst);
3640 SizeType = Store->getValueOperand()->getType();
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003641 Size = TD->getTypeAllocSize(SizeType);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003642 Type = MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003643 Val = Store->getValueOperand();
3644 }
3645
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003646 auto Address = getPointerOperand(*Inst);
3647
3648 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003649 const SCEVUnknown *BasePointer =
3650 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3651
3652 assert(BasePointer && "Could not find base pointer");
3653 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
3654
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003655 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
3656 auto NewAddress = Address;
3657 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3658 auto Src = BitCast->getOperand(0);
3659 auto SrcTy = Src->getType();
3660 auto DstTy = BitCast->getType();
3661 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3662 NewAddress = Src;
3663 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003664
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003665 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3666 std::vector<const SCEV *> Subscripts;
3667 std::vector<int> Sizes;
3668 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
3669 auto BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003670
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003671 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003672
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003673 bool AllAffineSubcripts = true;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003674 for (auto Subscript : Subscripts) {
3675 InvariantLoadsSetTy AccessILS;
3676 AllAffineSubcripts =
3677 isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS);
3678
3679 for (LoadInst *LInst : AccessILS)
3680 if (!ScopRIL.count(LInst))
3681 AllAffineSubcripts = false;
3682
3683 if (!AllAffineSubcripts)
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003684 break;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003685 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003686
3687 if (AllAffineSubcripts && Sizes.size() > 0) {
3688 for (auto V : Sizes)
3689 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3690 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003691 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003692 IntegerType::getInt64Ty(BasePtr->getContext()), Size)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003693
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003694 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3695 Subscripts, SizesSCEV, Val);
Tobias Grosserb1c39422015-09-21 16:19:25 +00003696 return;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003697 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003698 }
3699 }
3700
Michael Kruse7bf39442015-09-10 12:46:52 +00003701 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003702 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003703 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, true,
3704 AccItr->second.DelinearizedSubscripts,
3705 AccItr->second.Shape->DelinearizedSizes, Val);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003706 return;
3707 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003708
3709 // Check if the access depends on a loop contained in a non-affine subregion.
3710 bool isVariantInNonAffineLoop = false;
3711 if (BoxedLoops) {
3712 SetVector<const Loop *> Loops;
3713 findLoops(AccessFunction, Loops);
3714 for (const Loop *L : Loops)
3715 if (BoxedLoops->count(L))
3716 isVariantInNonAffineLoop = true;
3717 }
3718
Johannes Doerfert09e36972015-10-07 20:17:36 +00003719 InvariantLoadsSetTy AccessILS;
3720 bool IsAffine =
3721 !isVariantInNonAffineLoop &&
3722 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3723
3724 for (LoadInst *LInst : AccessILS)
3725 if (!ScopRIL.count(LInst))
3726 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003727
Michael Krusecaac2b62015-09-26 15:51:44 +00003728 // FIXME: Size of the number of bytes of an array element, not the number of
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003729 // elements as probably intended here.
Tobias Grossera43b6e92015-09-27 17:54:50 +00003730 const SCEV *SizeSCEV =
3731 SE->getConstant(TD->getIntPtrType(Inst->getContext()), Size);
Michael Kruse7bf39442015-09-10 12:46:52 +00003732
Michael Krusee2bccbb2015-09-18 19:59:43 +00003733 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3734 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003735
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003736 addExplicitAccess(Inst, Type, BasePointer->getValue(), Size, IsAffine,
3737 ArrayRef<const SCEV *>(AccessFunction),
3738 ArrayRef<const SCEV *>(SizeSCEV), Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003739}
3740
Michael Krused868b5d2015-09-10 15:25:24 +00003741void ScopInfo::buildAccessFunctions(Region &R, Region &SR) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003742
3743 if (SD->isNonAffineSubRegion(&SR, &R)) {
3744 for (BasicBlock *BB : SR.blocks())
3745 buildAccessFunctions(R, *BB, &SR);
3746 return;
3747 }
3748
3749 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3750 if (I->isSubRegion())
3751 buildAccessFunctions(R, *I->getNodeAs<Region>());
3752 else
3753 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>());
3754}
3755
Michael Krusecac948e2015-10-02 13:53:07 +00003756void ScopInfo::buildStmts(Region &SR) {
3757 Region *R = getRegion();
3758
3759 if (SD->isNonAffineSubRegion(&SR, R)) {
3760 scop->addScopStmt(nullptr, &SR);
3761 return;
3762 }
3763
3764 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
3765 if (I->isSubRegion())
3766 buildStmts(*I->getNodeAs<Region>());
3767 else
3768 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
3769}
3770
Michael Krused868b5d2015-09-10 15:25:24 +00003771void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
3772 Region *NonAffineSubRegion,
3773 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00003774 // We do not build access functions for error blocks, as they may contain
3775 // instructions we can not model.
3776 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3777 if (isErrorBlock(BB, R, *LI, DT) && !IsExitBlock)
3778 return;
3779
Michael Kruse7bf39442015-09-10 12:46:52 +00003780 Loop *L = LI->getLoopFor(&BB);
3781
3782 // The set of loops contained in non-affine subregions that are part of R.
3783 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
3784
Johannes Doerfert09e36972015-10-07 20:17:36 +00003785 // The set of loads that are required to be invariant.
3786 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
3787
Michael Kruse7bf39442015-09-10 12:46:52 +00003788 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00003789 Instruction *Inst = &*I;
Michael Kruse7bf39442015-09-10 12:46:52 +00003790
3791 PHINode *PHI = dyn_cast<PHINode>(Inst);
3792 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00003793 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003794
3795 // For the exit block we stop modeling after the last PHI node.
3796 if (!PHI && IsExitBlock)
3797 break;
3798
Johannes Doerfert09e36972015-10-07 20:17:36 +00003799 // TODO: At this point we only know that elements of ScopRIL have to be
3800 // invariant and will be hoisted for the SCoP to be processed. Though,
3801 // there might be other invariant accesses that will be hoisted and
3802 // that would allow to make a non-affine access affine.
Michael Kruse7bf39442015-09-10 12:46:52 +00003803 if (isa<LoadInst>(Inst) || isa<StoreInst>(Inst))
Johannes Doerfert09e36972015-10-07 20:17:36 +00003804 buildMemoryAccess(Inst, L, &R, BoxedLoops, ScopRIL);
Michael Kruse7bf39442015-09-10 12:46:52 +00003805
3806 if (isIgnoredIntrinsic(Inst))
3807 continue;
3808
Johannes Doerfert09e36972015-10-07 20:17:36 +00003809 // Do not build scalar dependences for required invariant loads as we will
3810 // hoist them later on anyway or drop the SCoP if we cannot.
3811 if (ScopRIL.count(dyn_cast<LoadInst>(Inst)))
3812 continue;
3813
Michael Kruse7bf39442015-09-10 12:46:52 +00003814 if (buildScalarDependences(Inst, &R, NonAffineSubRegion)) {
Michael Krusee2bccbb2015-09-18 19:59:43 +00003815 if (!isa<StoreInst>(Inst))
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003816 addScalarWriteAccess(Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00003817 }
3818 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00003819}
Michael Kruse7bf39442015-09-10 12:46:52 +00003820
Michael Kruse2d0ece92015-09-24 11:41:21 +00003821void ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
3822 MemoryAccess::AccessType Type,
3823 Value *BaseAddress, unsigned ElemBytes,
3824 bool Affine, Value *AccessValue,
3825 ArrayRef<const SCEV *> Subscripts,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003826 ArrayRef<const SCEV *> Sizes,
3827 MemoryAccess::AccessOrigin Origin) {
Michael Krusecac948e2015-10-02 13:53:07 +00003828 ScopStmt *Stmt = scop->getStmtForBasicBlock(BB);
3829
3830 // Do not create a memory access for anything not in the SCoP. It would be
3831 // ignored anyway.
3832 if (!Stmt)
3833 return;
3834
Michael Krusee2bccbb2015-09-18 19:59:43 +00003835 AccFuncSetType &AccList = AccFuncMap[BB];
Michael Krusee2bccbb2015-09-18 19:59:43 +00003836 Value *BaseAddr = BaseAddress;
3837 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
3838
Michael Krusecac948e2015-10-02 13:53:07 +00003839 bool isApproximated =
3840 Stmt->isRegionStmt() && (Stmt->getRegion()->getEntry() != BB);
3841 if (isApproximated && Type == MemoryAccess::MUST_WRITE)
3842 Type = MemoryAccess::MAY_WRITE;
3843
Tobias Grosserf1bfd752015-11-05 20:15:37 +00003844 AccList.emplace_back(Stmt, Inst, Type, BaseAddress, ElemBytes, Affine,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003845 Subscripts, Sizes, AccessValue, Origin, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00003846 Stmt->addAccess(&AccList.back());
Michael Kruse7bf39442015-09-10 12:46:52 +00003847}
3848
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003849void ScopInfo::addExplicitAccess(
3850 Instruction *MemAccInst, MemoryAccess::AccessType Type, Value *BaseAddress,
3851 unsigned ElemBytes, bool IsAffine, ArrayRef<const SCEV *> Subscripts,
3852 ArrayRef<const SCEV *> Sizes, Value *AccessValue) {
3853 assert(isa<LoadInst>(MemAccInst) || isa<StoreInst>(MemAccInst));
3854 assert(isa<LoadInst>(MemAccInst) == (Type == MemoryAccess::READ));
3855 addMemoryAccess(MemAccInst->getParent(), MemAccInst, Type, BaseAddress,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003856 ElemBytes, IsAffine, AccessValue, Subscripts, Sizes,
3857 MemoryAccess::EXPLICIT);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003858}
3859void ScopInfo::addScalarWriteAccess(Instruction *Value) {
3860 addMemoryAccess(Value->getParent(), Value, MemoryAccess::MUST_WRITE, Value, 1,
3861 true, Value, ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003862 ArrayRef<const SCEV *>(), MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003863}
3864void ScopInfo::addScalarReadAccess(Value *Value, Instruction *User) {
3865 assert(!isa<PHINode>(User));
3866 addMemoryAccess(User->getParent(), User, MemoryAccess::READ, Value, 1, true,
3867 Value, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003868 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003869}
3870void ScopInfo::addScalarReadAccess(Value *Value, PHINode *User,
3871 BasicBlock *UserBB) {
3872 addMemoryAccess(UserBB, User, MemoryAccess::READ, Value, 1, true, Value,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003873 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3874 MemoryAccess::SCALAR);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003875}
3876void ScopInfo::addPHIWriteAccess(PHINode *PHI, BasicBlock *IncomingBlock,
3877 Value *IncomingValue, bool IsExitBlock) {
3878 addMemoryAccess(IncomingBlock, IncomingBlock->getTerminator(),
3879 MemoryAccess::MUST_WRITE, PHI, 1, true, IncomingValue,
3880 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Michael Kruse8d0b7342015-09-25 21:21:00 +00003881 IsExitBlock ? MemoryAccess::SCALAR : MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003882}
3883void ScopInfo::addPHIReadAccess(PHINode *PHI) {
3884 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI, 1, true, PHI,
Michael Kruse8d0b7342015-09-25 21:21:00 +00003885 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
3886 MemoryAccess::PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003887}
3888
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003889void ScopInfo::buildScop(Region &R, DominatorTree &DT, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00003890 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Johannes Doerfertd8dd8632015-10-07 20:31:36 +00003891 scop = new Scop(R, AccFuncMap, *SD, *SE, DT, *LI, ctx, MaxLoopDepth);
Michael Kruse7bf39442015-09-10 12:46:52 +00003892
Michael Krusecac948e2015-10-02 13:53:07 +00003893 buildStmts(R);
Michael Kruse7bf39442015-09-10 12:46:52 +00003894 buildAccessFunctions(R, R);
3895
3896 // In case the region does not have an exiting block we will later (during
3897 // code generation) split the exit block. This will move potential PHI nodes
3898 // from the current exit block into the new region exiting block. Hence, PHI
3899 // nodes that are at this point not part of the region will be.
3900 // To handle these PHI nodes later we will now model their operands as scalar
3901 // accesses. Note that we do not model anything in the exit block if we have
3902 // an exiting block in the region, as there will not be any splitting later.
3903 if (!R.getExitingBlock())
3904 buildAccessFunctions(R, *R.getExit(), nullptr, /* IsExitBlock */ true);
3905
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003906 scop->init(*AA, AC);
Michael Kruse7bf39442015-09-10 12:46:52 +00003907}
3908
Michael Krused868b5d2015-09-10 15:25:24 +00003909void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00003910 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00003911 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00003912 return;
3913 }
3914
Michael Kruse9d080092015-09-11 21:41:48 +00003915 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00003916}
3917
Michael Krused868b5d2015-09-10 15:25:24 +00003918void ScopInfo::clear() {
Michael Kruse7bf39442015-09-10 12:46:52 +00003919 AccFuncMap.clear();
Michael Krused868b5d2015-09-10 15:25:24 +00003920 if (scop) {
3921 delete scop;
3922 scop = 0;
3923 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003924}
3925
3926//===----------------------------------------------------------------------===//
Michael Kruse9d080092015-09-11 21:41:48 +00003927ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
Tobias Grosserb76f38532011-08-20 11:11:25 +00003928 ctx = isl_ctx_alloc();
Tobias Grosser4a8e3562011-12-07 07:42:51 +00003929 isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
Tobias Grosserb76f38532011-08-20 11:11:25 +00003930}
3931
3932ScopInfo::~ScopInfo() {
3933 clear();
3934 isl_ctx_free(ctx);
3935}
3936
Tobias Grosser75805372011-04-29 06:27:02 +00003937void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00003938 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00003939 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00003940 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00003941 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
3942 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003943 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003944 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00003945 AU.setPreservesAll();
3946}
3947
3948bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00003949 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00003950
Michael Krused868b5d2015-09-10 15:25:24 +00003951 if (!SD->isMaxRegionInScop(*R))
3952 return false;
3953
3954 Function *F = R->getEntry()->getParent();
3955 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3956 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3957 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3958 TD = &F->getParent()->getDataLayout();
3959 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003960 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00003961
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003962 DebugLoc Beg, End;
3963 getDebugLocations(R, Beg, End);
3964 std::string Msg = "SCoP begins here.";
3965 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
3966
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003967 buildScop(*R, DT, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00003968
Tobias Grosserd6a50b32015-05-30 06:26:21 +00003969 DEBUG(scop->print(dbgs()));
3970
Michael Kruseafe06702015-10-02 16:33:27 +00003971 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003972 Msg = "SCoP ends here but was dismissed.";
Johannes Doerfert43788c52015-08-20 05:58:56 +00003973 delete scop;
3974 scop = nullptr;
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003975 } else {
3976 Msg = "SCoP ends here.";
3977 ++ScopFound;
3978 if (scop->getMaxLoopDepth() > 0)
3979 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00003980 }
3981
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00003982 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
3983
Tobias Grosser75805372011-04-29 06:27:02 +00003984 return false;
3985}
3986
3987char ScopInfo::ID = 0;
3988
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003989Pass *polly::createScopInfoPass() { return new ScopInfo(); }
3990
Tobias Grosser73600b82011-10-08 00:30:40 +00003991INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
3992 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00003993 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00003994INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00003995INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00003996INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00003997INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00003998INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003999INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004000INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004001INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4002 "Polly - Create polyhedral description of Scops", false,
4003 false)