blob: 24cd721e557f1e553ad96d8f07e8f08553e760b3 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000026#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000034#include "llvm/Analysis/AssumptionCache.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000036#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000037#include "llvm/Analysis/RegionIterator.h"
38#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000039#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000040#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000045#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000047#include "isl/schedule.h"
48#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "isl/set.h"
50#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000051#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000052#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include <sstream>
54#include <string>
55#include <vector>
56
57using namespace llvm;
58using namespace polly;
59
Chandler Carruth95fef942014-04-22 03:30:19 +000060#define DEBUG_TYPE "polly-scops"
61
Tobias Grosser74394f02013-01-14 22:40:23 +000062STATISTIC(ScopFound, "Number of valid Scops");
63STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000064
Tobias Grosser75dc40c2015-12-20 13:31:48 +000065// The maximal number of basic sets we allow during domain construction to
66// be created. More complex scops will result in very high compile time and
67// are also unlikely to result in good code
68static int const MaxConjunctsInDomain = 20;
69
Michael Kruse7bf39442015-09-10 12:46:52 +000070static cl::opt<bool> ModelReadOnlyScalars(
71 "polly-analyze-read-only-scalars",
72 cl::desc("Model read-only scalar values in the scop description"),
73 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
74
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000075// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000076// operations can overflow easily. Additive reductions and bit operations
77// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000078static cl::opt<bool> DisableMultiplicativeReductions(
79 "polly-disable-multiplicative-reductions",
80 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
81 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000082
Johannes Doerfert9143d672014-09-27 11:02:39 +000083static cl::opt<unsigned> RunTimeChecksMaxParameters(
84 "polly-rtc-max-parameters",
85 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
86 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
87
Tobias Grosser71500722015-03-28 15:11:14 +000088static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
89 "polly-rtc-max-arrays-per-group",
90 cl::desc("The maximal number of arrays to compare in each alias group."),
91 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser4927c8e2015-11-24 12:50:02 +0000102static cl::opt<bool> IgnoreIntegerWrapping(
103 "polly-ignore-integer-wrapping",
104 cl::desc("Do not build run-time checks to proof absence of integer "
105 "wrapping"),
106 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
107
Michael Kruse7bf39442015-09-10 12:46:52 +0000108//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000109
Michael Kruse046dde42015-08-10 13:01:57 +0000110// Create a sequence of two schedules. Either argument may be null and is
111// interpreted as the empty schedule. Can also return null if both schedules are
112// empty.
113static __isl_give isl_schedule *
114combineInSequence(__isl_take isl_schedule *Prev,
115 __isl_take isl_schedule *Succ) {
116 if (!Prev)
117 return Succ;
118 if (!Succ)
119 return Prev;
120
121 return isl_schedule_sequence(Prev, Succ);
122}
123
Johannes Doerferte7044942015-02-24 11:58:30 +0000124static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
125 const ConstantRange &Range,
126 int dim,
127 enum isl_dim_type type) {
128 isl_val *V;
129 isl_ctx *ctx = isl_set_get_ctx(S);
130
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000131 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
132 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000133 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000134 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
135
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000136 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000137 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000138 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000143 return isl_set_union(SLB, SUB);
144 else
145 return isl_set_intersect(SLB, SUB);
146}
147
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000148static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
149 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
150 if (!BasePtrLI)
151 return nullptr;
152
153 if (!S->getRegion().contains(BasePtrLI))
154 return nullptr;
155
156 ScalarEvolution &SE = *S->getSE();
157
158 auto *OriginBaseSCEV =
159 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
160 if (!OriginBaseSCEV)
161 return nullptr;
162
163 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
164 if (!OriginBaseSCEVUnknown)
165 return nullptr;
166
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000167 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000168 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000169}
170
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000171ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000172 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000173 const DataLayout &DL, Scop *S)
174 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000175 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000176 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000177 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000178
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000179 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000180 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
181 if (BasePtrOriginSAI)
182 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183}
184
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000185__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000186 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000187 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
188 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
189 return Space;
190}
191
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000192void ScopArrayInfo::updateElementType(Type *NewElementType) {
193 if (NewElementType == ElementType)
194 return;
195
Tobias Grosserd840fc72016-02-04 13:18:42 +0000196 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
197 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
198
Johannes Doerferta7920982016-02-25 14:08:48 +0000199 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000200 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000201
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000202 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
203 ElementType = NewElementType;
204 } else {
205 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
206 ElementType = IntegerType::get(ElementType->getContext(), GCD);
207 }
208}
209
210bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000211 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
212 int ExtraDimsNew = NewSizes.size() - SharedDims;
213 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000214 for (int i = 0; i < SharedDims; i++)
215 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
216 return false;
217
218 if (DimensionSizes.size() >= NewSizes.size())
219 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000220
221 DimensionSizes.clear();
222 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
223 NewSizes.end());
224 for (isl_pw_aff *Size : DimensionSizesPw)
225 isl_pw_aff_free(Size);
226 DimensionSizesPw.clear();
227 for (const SCEV *Expr : DimensionSizes) {
228 isl_pw_aff *Size = S.getPwAff(Expr);
229 DimensionSizesPw.push_back(Size);
230 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000231 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000232}
233
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000234ScopArrayInfo::~ScopArrayInfo() {
235 isl_id_free(Id);
236 for (isl_pw_aff *Size : DimensionSizesPw)
237 isl_pw_aff_free(Size);
238}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000239
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000240std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
241
242int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000243 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000244}
245
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000246isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
247
248void ScopArrayInfo::dump() const { print(errs()); }
249
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000250void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000251 OS.indent(8) << *getElementType() << " " << getName();
252 if (getNumberOfDimensions() > 0)
253 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000254 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000255 OS << "[";
256
Tobias Grosser26253842015-11-10 14:24:21 +0000257 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000258 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000259 OS << " " << Size << " ";
260 isl_pw_aff_free(Size);
261 } else {
262 OS << *getDimensionSize(u);
263 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000264
265 OS << "]";
266 }
267
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000268 OS << ";";
269
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000270 if (BasePtrOriginSAI)
271 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
272
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000273 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000274}
275
276const ScopArrayInfo *
277ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
278 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
279 assert(Id && "Output dimension didn't have an ID");
280 return getFromId(Id);
281}
282
283const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
284 void *User = isl_id_get_user(Id);
285 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
286 isl_id_free(Id);
287 return SAI;
288}
289
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000290void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000291 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000292 auto *ArraySpace = SAI->getSpace();
293 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000294 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000295
296 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
297 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
298 auto DimsMissing = DimsArray - DimsAccess;
299
Michael Kruse375cb5f2016-02-24 22:08:24 +0000300 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000301 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000302 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000303 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000304
Johannes Doerferta90943d2016-02-21 16:37:25 +0000305 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000306 isl_set_universe(AccessSpace),
307 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000308
309 for (unsigned i = 0; i < DimsMissing; i++)
310 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
311
312 for (unsigned i = DimsMissing; i < DimsArray; i++)
313 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
314
315 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000316
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000317 // For the non delinearized arrays, divide the access function of the last
318 // subscript by the size of the elements in the array.
319 //
320 // A stride one array access in C expressed as A[i] is expressed in
321 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
322 // two subsequent values of 'i' index two values that are stored next to
323 // each other in memory. By this division we make this characteristic
324 // obvious again. If the base pointer was accessed with offsets not divisible
325 // by the accesses element size, we will have choosen a smaller ArrayElemSize
326 // that divides the offsets of all accesses to this base pointer.
327 if (DimsAccess == 1) {
328 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
329 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
330 }
331
332 if (!isAffine())
333 computeBoundsOnAccessRelation(ArrayElemSize);
334
Tobias Grosserd840fc72016-02-04 13:18:42 +0000335 // Introduce multi-element accesses in case the type loaded by this memory
336 // access is larger than the canonical element type of the array.
337 //
338 // An access ((float *)A)[i] to an array char *A is modeled as
339 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000340 if (ElemBytes > ArrayElemSize) {
341 assert(ElemBytes % ArrayElemSize == 0 &&
342 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000343 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000344 isl_set_universe(isl_space_copy(ArraySpace)),
345 isl_set_universe(isl_space_copy(ArraySpace)));
346 for (unsigned i = 0; i < DimsArray - 1; i++)
347 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
348
Tobias Grosserd840fc72016-02-04 13:18:42 +0000349 isl_constraint *C;
350 isl_local_space *LS;
351
352 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000353 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
354
355 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
356 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000357 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000358 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
359 Map = isl_map_add_constraint(Map, C);
360
361 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000362 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000363 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
364 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
365 Map = isl_map_add_constraint(Map, C);
366 AccessRelation = isl_map_apply_range(AccessRelation, Map);
367 }
368
369 isl_space_free(ArraySpace);
370
Roman Gareev10595a12016-01-08 14:01:59 +0000371 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000372}
373
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000374const std::string
375MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
376 switch (RT) {
377 case MemoryAccess::RT_NONE:
378 llvm_unreachable("Requested a reduction operator string for a memory "
379 "access which isn't a reduction");
380 case MemoryAccess::RT_ADD:
381 return "+";
382 case MemoryAccess::RT_MUL:
383 return "*";
384 case MemoryAccess::RT_BOR:
385 return "|";
386 case MemoryAccess::RT_BXOR:
387 return "^";
388 case MemoryAccess::RT_BAND:
389 return "&";
390 }
391 llvm_unreachable("Unknown reduction type");
392 return "";
393}
394
Johannes Doerfertf6183392014-07-01 20:52:51 +0000395/// @brief Return the reduction type for a given binary operator
396static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
397 const Instruction *Load) {
398 if (!BinOp)
399 return MemoryAccess::RT_NONE;
400 switch (BinOp->getOpcode()) {
401 case Instruction::FAdd:
402 if (!BinOp->hasUnsafeAlgebra())
403 return MemoryAccess::RT_NONE;
404 // Fall through
405 case Instruction::Add:
406 return MemoryAccess::RT_ADD;
407 case Instruction::Or:
408 return MemoryAccess::RT_BOR;
409 case Instruction::Xor:
410 return MemoryAccess::RT_BXOR;
411 case Instruction::And:
412 return MemoryAccess::RT_BAND;
413 case Instruction::FMul:
414 if (!BinOp->hasUnsafeAlgebra())
415 return MemoryAccess::RT_NONE;
416 // Fall through
417 case Instruction::Mul:
418 if (DisableMultiplicativeReductions)
419 return MemoryAccess::RT_NONE;
420 return MemoryAccess::RT_MUL;
421 default:
422 return MemoryAccess::RT_NONE;
423 }
424}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000425
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000426/// @brief Derive the individual index expressions from a GEP instruction
427///
428/// This function optimistically assumes the GEP references into a fixed size
429/// array. If this is actually true, this function returns a list of array
430/// subscript expressions as SCEV as well as a list of integers describing
431/// the size of the individual array dimensions. Both lists have either equal
432/// length of the size list is one element shorter in case there is no known
433/// size available for the outermost array dimension.
434///
435/// @param GEP The GetElementPtr instruction to analyze.
436///
437/// @return A tuple with the subscript expressions and the dimension sizes.
438static std::tuple<std::vector<const SCEV *>, std::vector<int>>
439getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
440 std::vector<const SCEV *> Subscripts;
441 std::vector<int> Sizes;
442
443 Type *Ty = GEP->getPointerOperandType();
444
445 bool DroppedFirstDim = false;
446
Michael Kruse26ed65e2015-09-24 17:32:49 +0000447 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000448
449 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
450
451 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000452 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000453 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000454 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000455 Ty = ArrayTy->getElementType();
456 } else {
457 Subscripts.clear();
458 Sizes.clear();
459 break;
460 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000461 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000462 if (Const->getValue()->isZero()) {
463 DroppedFirstDim = true;
464 continue;
465 }
466 Subscripts.push_back(Expr);
467 continue;
468 }
469
Johannes Doerferta90943d2016-02-21 16:37:25 +0000470 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000471 if (!ArrayTy) {
472 Subscripts.clear();
473 Sizes.clear();
474 break;
475 }
476
477 Subscripts.push_back(Expr);
478 if (!(DroppedFirstDim && i == 2))
479 Sizes.push_back(ArrayTy->getNumElements());
480
481 Ty = ArrayTy->getElementType();
482 }
483
484 return std::make_tuple(Subscripts, Sizes);
485}
486
Tobias Grosser75805372011-04-29 06:27:02 +0000487MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000488 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000489 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000490 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000491}
492
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000493const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
494 isl_id *ArrayId = getArrayId();
495 void *User = isl_id_get_user(ArrayId);
496 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
497 isl_id_free(ArrayId);
498 return SAI;
499}
500
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000501__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000502 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
503}
504
Tobias Grosserd840fc72016-02-04 13:18:42 +0000505__isl_give isl_map *MemoryAccess::getAddressFunction() const {
506 return isl_map_lexmin(getAccessRelation());
507}
508
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000509__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
510 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000511 isl_map *Schedule, *ScheduledAccRel;
512 isl_union_set *UDomain;
513
514 UDomain = isl_union_set_from_set(getStatement()->getDomain());
515 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
516 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000517 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000518 return isl_pw_multi_aff_from_map(ScheduledAccRel);
519}
520
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000521__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000522 return isl_map_copy(AccessRelation);
523}
524
Johannes Doerferta99130f2014-10-13 12:58:03 +0000525std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000526 return stringFromIslObj(AccessRelation);
527}
528
Johannes Doerferta99130f2014-10-13 12:58:03 +0000529__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000530 return isl_map_get_space(AccessRelation);
531}
532
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000533__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000534 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000535}
536
Tobias Grosser6f730082015-09-05 07:46:47 +0000537std::string MemoryAccess::getNewAccessRelationStr() const {
538 return stringFromIslObj(NewAccessRelation);
539}
540
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000541__isl_give isl_basic_map *
542MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000543 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000544 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000545
Tobias Grosser084d8f72012-05-29 09:29:44 +0000546 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000547 isl_basic_set_universe(Statement->getDomainSpace()),
548 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000549}
550
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000551// Formalize no out-of-bound access assumption
552//
553// When delinearizing array accesses we optimistically assume that the
554// delinearized accesses do not access out of bound locations (the subscript
555// expression of each array evaluates for each statement instance that is
556// executed to a value that is larger than zero and strictly smaller than the
557// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000558// dimension for which we do not need to assume any upper bound. At this point
559// we formalize this assumption to ensure that at code generation time the
560// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000561//
562// To find the set of constraints necessary to avoid out of bound accesses, we
563// first build the set of data locations that are not within array bounds. We
564// then apply the reverse access relation to obtain the set of iterations that
565// may contain invalid accesses and reduce this set of iterations to the ones
566// that are actually executed by intersecting them with the domain of the
567// statement. If we now project out all loop dimensions, we obtain a set of
568// parameters that may cause statement instances to be executed that may
569// possibly yield out of bound memory accesses. The complement of these
570// constraints is the set of constraints that needs to be assumed to ensure such
571// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000572void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000573 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000574 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000575 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000576 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000577 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
578 isl_pw_aff *Var =
579 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
580 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
581
582 isl_set *DimOutside;
583
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000584 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000585 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000586 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
587 isl_space_dim(Space, isl_dim_set));
588 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
589 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000590
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000591 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000592
593 Outside = isl_set_union(Outside, DimOutside);
594 }
595
596 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
597 Outside = isl_set_intersect(Outside, Statement->getDomain());
598 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000599
600 // Remove divs to avoid the construction of overly complicated assumptions.
601 // Doing so increases the set of parameter combinations that are assumed to
602 // not appear. This is always save, but may make the resulting run-time check
603 // bail out more often than strictly necessary.
604 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000605 Outside = isl_set_complement(Outside);
Johannes Doerfert066dbf32016-03-01 13:06:28 +0000606 auto &Loc = getAccessInstruction() ? getAccessInstruction()->getDebugLoc()
607 : DebugLoc();
608 Statement->getParent()->addAssumption(INBOUNDS, Outside, Loc, AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000609 isl_space_free(Space);
610}
611
Johannes Doerfertcea61932016-02-21 19:13:19 +0000612void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000613 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000614 assert(Subscripts.size() == 2 && Sizes.size() == 0);
615
Johannes Doerfertcea61932016-02-21 19:13:19 +0000616 auto *SubscriptPWA = Statement->getPwAff(Subscripts[0]);
617 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000618
619 isl_map *LengthMap;
620 if (Subscripts[1] == nullptr) {
621 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
622 } else {
623 auto *LengthPWA = Statement->getPwAff(Subscripts[1]);
624 LengthMap = isl_map_from_pw_aff(LengthPWA);
625 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
626 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
627 }
628 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
629 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000630 SubscriptMap =
631 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000632 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
633 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
634 getStatement()->getDomainId());
635}
636
Johannes Doerferte7044942015-02-24 11:58:30 +0000637void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
638 ScalarEvolution *SE = Statement->getParent()->getSE();
639
Johannes Doerfertcea61932016-02-21 19:13:19 +0000640 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000641 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000642 return;
643
644 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000645 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
646 return;
647
648 auto *PtrSCEV = SE->getSCEV(Ptr);
649 if (isa<SCEVCouldNotCompute>(PtrSCEV))
650 return;
651
652 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
653 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
654 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
655
656 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
657 if (Range.isFullSet())
658 return;
659
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000660 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000661 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000662 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000663 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000664 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000665
666 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000667 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000668
669 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
670 AccessRange =
671 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
672 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
673}
674
Michael Krusee2bccbb2015-09-18 19:59:43 +0000675__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000676 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000677 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000678
679 for (int i = Size - 2; i >= 0; --i) {
680 isl_space *Space;
681 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000682 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000683
684 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
685 isl_pw_aff_free(DimSize);
686 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
687
688 Space = isl_map_get_space(AccessRelation);
689 Space = isl_space_map_from_set(isl_space_range(Space));
690 Space = isl_space_align_params(Space, SpaceSize);
691
692 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
693 isl_id_free(ParamId);
694
695 MapOne = isl_map_universe(isl_space_copy(Space));
696 for (int j = 0; j < Size; ++j)
697 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
698 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
699
700 MapTwo = isl_map_universe(isl_space_copy(Space));
701 for (int j = 0; j < Size; ++j)
702 if (j < i || j > i + 1)
703 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
704
705 isl_local_space *LS = isl_local_space_from_space(Space);
706 isl_constraint *C;
707 C = isl_equality_alloc(isl_local_space_copy(LS));
708 C = isl_constraint_set_constant_si(C, -1);
709 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
710 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
711 MapTwo = isl_map_add_constraint(MapTwo, C);
712 C = isl_equality_alloc(LS);
713 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
714 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
715 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
716 MapTwo = isl_map_add_constraint(MapTwo, C);
717 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
718
719 MapOne = isl_map_union(MapOne, MapTwo);
720 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
721 }
722 return AccessRelation;
723}
724
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000725/// @brief Check if @p Expr is divisible by @p Size.
726static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000727 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000728 if (Size == 1)
729 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000730
731 // Only one factor needs to be divisible.
732 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
733 for (auto *FactorExpr : MulExpr->operands())
734 if (isDivisible(FactorExpr, Size, SE))
735 return true;
736 return false;
737 }
738
739 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
740 // to be divisble.
741 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
742 for (auto *OpExpr : NAryExpr->operands())
743 if (!isDivisible(OpExpr, Size, SE))
744 return false;
745 return true;
746 }
747
748 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
749 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
750 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
751 return MulSCEV == Expr;
752}
753
Michael Krusee2bccbb2015-09-18 19:59:43 +0000754void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
755 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000756
Michael Krusee2bccbb2015-09-18 19:59:43 +0000757 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000758 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000759
Michael Krusee2bccbb2015-09-18 19:59:43 +0000760 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000761 if (isa<MemIntrinsic>(getAccessInstruction()))
762 buildMemIntrinsicAccessRelation();
763
Tobias Grosser4f967492013-06-23 05:21:18 +0000764 // We overapproximate non-affine accesses with a possible access to the
765 // whole array. For read accesses it does not make a difference, if an
766 // access must or may happen. However, for write accesses it is important to
767 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000768 if (!AccessRelation)
769 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
770
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000771 AccessRelation =
772 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000773 return;
774 }
775
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000776 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000777 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000778
Michael Krusee2bccbb2015-09-18 19:59:43 +0000779 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
780 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000781 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000782 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000783 }
784
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000785 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000786 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000787
Tobias Grosser79baa212014-04-10 08:38:02 +0000788 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000789 AccessRelation = isl_map_set_tuple_id(
790 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000791 AccessRelation =
792 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
793
Tobias Grosseraa660a92015-03-30 00:07:50 +0000794 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000795 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000796}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000797
Michael Krusecac948e2015-10-02 13:53:07 +0000798MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000799 AccessType AccType, Value *BaseAddress,
800 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000801 ArrayRef<const SCEV *> Subscripts,
802 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000803 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000804 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
805 BaseAddr(BaseAddress), BaseName(BaseName), ElementType(ElementType),
Michael Krusecac948e2015-10-02 13:53:07 +0000806 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
807 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000808 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000809 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000810 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000811 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000812
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000813 std::string IdName =
814 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000815 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
816}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000817
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000818void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000819 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000820 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000821}
822
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000823const std::string MemoryAccess::getReductionOperatorStr() const {
824 return MemoryAccess::getReductionOperatorStr(getReductionType());
825}
826
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000827__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
828
Johannes Doerfertf6183392014-07-01 20:52:51 +0000829raw_ostream &polly::operator<<(raw_ostream &OS,
830 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000831 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000832 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000833 else
834 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000835 return OS;
836}
837
Tobias Grosser75805372011-04-29 06:27:02 +0000838void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000839 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000840 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000841 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000842 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000843 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000844 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000845 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000846 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000847 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000848 break;
849 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000850 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000851 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000852 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000853 if (hasNewAccessRelation())
854 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000855}
856
Tobias Grosser74394f02013-01-14 22:40:23 +0000857void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000858
859// Create a map in the size of the provided set domain, that maps from the
860// one element of the provided set domain to another element of the provided
861// set domain.
862// The mapping is limited to all points that are equal in all but the last
863// dimension and for which the last dimension of the input is strict smaller
864// than the last dimension of the output.
865//
866// getEqualAndLarger(set[i0, i1, ..., iX]):
867//
868// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
869// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
870//
Tobias Grosserf5338802011-10-06 00:03:35 +0000871static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000872 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000873 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000874 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000875
876 // Set all but the last dimension to be equal for the input and output
877 //
878 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
879 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000880 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000881 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000882
883 // Set the last dimension of the input to be strict smaller than the
884 // last dimension of the output.
885 //
886 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000887 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
888 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000889 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000890}
891
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000892__isl_give isl_set *
893MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000894 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000895 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000896 isl_space *Space = isl_space_range(isl_map_get_space(S));
897 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000898
Sebastian Popa00a0292012-12-18 07:46:06 +0000899 S = isl_map_reverse(S);
900 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000901
Sebastian Popa00a0292012-12-18 07:46:06 +0000902 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
903 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
904 NextScatt = isl_map_apply_domain(NextScatt, S);
905 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000906
Sebastian Popa00a0292012-12-18 07:46:06 +0000907 isl_set *Deltas = isl_map_deltas(NextScatt);
908 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000909}
910
Sebastian Popa00a0292012-12-18 07:46:06 +0000911bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000912 int StrideWidth) const {
913 isl_set *Stride, *StrideX;
914 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000915
Sebastian Popa00a0292012-12-18 07:46:06 +0000916 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000917 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000918 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
919 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
920 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
921 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000922 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000923
Tobias Grosser28dd4862012-01-24 16:42:16 +0000924 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000925 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000926
Tobias Grosser28dd4862012-01-24 16:42:16 +0000927 return IsStrideX;
928}
929
Sebastian Popa00a0292012-12-18 07:46:06 +0000930bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
931 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000932}
933
Sebastian Popa00a0292012-12-18 07:46:06 +0000934bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
935 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000936}
937
Tobias Grosser166c4222015-09-05 07:46:40 +0000938void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
939 isl_map_free(NewAccessRelation);
940 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000941}
Tobias Grosser75805372011-04-29 06:27:02 +0000942
943//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000944
Tobias Grosser808cd692015-07-14 09:33:13 +0000945isl_map *ScopStmt::getSchedule() const {
946 isl_set *Domain = getDomain();
947 if (isl_set_is_empty(Domain)) {
948 isl_set_free(Domain);
949 return isl_map_from_aff(
950 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
951 }
952 auto *Schedule = getParent()->getSchedule();
953 Schedule = isl_union_map_intersect_domain(
954 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
955 if (isl_union_map_is_empty(Schedule)) {
956 isl_set_free(Domain);
957 isl_union_map_free(Schedule);
958 return isl_map_from_aff(
959 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
960 }
961 auto *M = isl_map_from_union_map(Schedule);
962 M = isl_map_coalesce(M);
963 M = isl_map_gist_domain(M, Domain);
964 M = isl_map_coalesce(M);
965 return M;
966}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000967
Johannes Doerfert574182d2015-08-12 10:19:50 +0000968__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Michael Kruse375cb5f2016-02-24 22:08:24 +0000969 return getParent()->getPwAff(E, getEntryBlock());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000970}
971
Tobias Grosser37eb4222014-02-20 21:43:54 +0000972void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
973 assert(isl_set_is_subset(NewDomain, Domain) &&
974 "New domain is not a subset of old domain!");
975 isl_set_free(Domain);
976 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000977}
978
Michael Krusecac948e2015-10-02 13:53:07 +0000979void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000980 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000981 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000982 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000983
Tobias Grossera535dff2015-12-13 19:59:01 +0000984 ScopArrayInfo::MemoryKind Ty;
985 if (Access->isPHIKind())
986 Ty = ScopArrayInfo::MK_PHI;
987 else if (Access->isExitPHIKind())
988 Ty = ScopArrayInfo::MK_ExitPHI;
989 else if (Access->isValueKind())
990 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000991 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000992 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000993
Johannes Doerfertadeab372016-02-07 13:57:32 +0000994 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
995 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +0000996 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000997 }
998}
999
Michael Krusecac948e2015-10-02 13:53:07 +00001000void ScopStmt::addAccess(MemoryAccess *Access) {
1001 Instruction *AccessInst = Access->getAccessInstruction();
1002
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001003 if (Access->isArrayKind()) {
1004 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1005 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001006 } else if (Access->isValueKind() && Access->isWrite()) {
1007 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001008 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001009 assert(!ValueWrites.lookup(AccessVal));
1010
1011 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001012 } else if (Access->isValueKind() && Access->isRead()) {
1013 Value *AccessVal = Access->getAccessValue();
1014 assert(!ValueReads.lookup(AccessVal));
1015
1016 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001017 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1018 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1019 assert(!PHIWrites.lookup(PHI));
1020
1021 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001022 }
1023
1024 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001025}
1026
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001027void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001028 for (MemoryAccess *MA : *this)
1029 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001030
1031 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001032}
1033
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001034/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1035static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1036 void *User) {
1037 isl_set **BoundedParts = static_cast<isl_set **>(User);
1038 if (isl_basic_set_is_bounded(BSet))
1039 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1040 else
1041 isl_basic_set_free(BSet);
1042 return isl_stat_ok;
1043}
1044
1045/// @brief Return the bounded parts of @p S.
1046static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1047 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1048 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1049 isl_set_free(S);
1050 return BoundedParts;
1051}
1052
1053/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1054///
1055/// @returns A separation of @p S into first an unbounded then a bounded subset,
1056/// both with regards to the dimension @p Dim.
1057static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1058partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1059
1060 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001061 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001062
1063 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001064 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001065
1066 // Remove dimensions that are greater than Dim as they are not interesting.
1067 assert(NumDimsS >= Dim + 1);
1068 OnlyDimS =
1069 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1070
1071 // Create artificial parametric upper bounds for dimensions smaller than Dim
1072 // as we are not interested in them.
1073 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1074 for (unsigned u = 0; u < Dim; u++) {
1075 isl_constraint *C = isl_inequality_alloc(
1076 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1077 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1078 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1079 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1080 }
1081
1082 // Collect all bounded parts of OnlyDimS.
1083 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1084
1085 // Create the dimensions greater than Dim again.
1086 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1087 NumDimsS - Dim - 1);
1088
1089 // Remove the artificial upper bound parameters again.
1090 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1091
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001092 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001093 return std::make_pair(UnboundedParts, BoundedParts);
1094}
1095
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001096/// @brief Set the dimension Ids from @p From in @p To.
1097static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1098 __isl_take isl_set *To) {
1099 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1100 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1101 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1102 }
1103 return To;
1104}
1105
1106/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001107static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001108 __isl_take isl_pw_aff *L,
1109 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001110 switch (Pred) {
1111 case ICmpInst::ICMP_EQ:
1112 return isl_pw_aff_eq_set(L, R);
1113 case ICmpInst::ICMP_NE:
1114 return isl_pw_aff_ne_set(L, R);
1115 case ICmpInst::ICMP_SLT:
1116 return isl_pw_aff_lt_set(L, R);
1117 case ICmpInst::ICMP_SLE:
1118 return isl_pw_aff_le_set(L, R);
1119 case ICmpInst::ICMP_SGT:
1120 return isl_pw_aff_gt_set(L, R);
1121 case ICmpInst::ICMP_SGE:
1122 return isl_pw_aff_ge_set(L, R);
1123 case ICmpInst::ICMP_ULT:
1124 return isl_pw_aff_lt_set(L, R);
1125 case ICmpInst::ICMP_UGT:
1126 return isl_pw_aff_gt_set(L, R);
1127 case ICmpInst::ICMP_ULE:
1128 return isl_pw_aff_le_set(L, R);
1129 case ICmpInst::ICMP_UGE:
1130 return isl_pw_aff_ge_set(L, R);
1131 default:
1132 llvm_unreachable("Non integer predicate not supported");
1133 }
1134}
1135
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001136/// @brief Create the conditions under which @p L @p Pred @p R is true.
1137///
1138/// Helper function that will make sure the dimensions of the result have the
1139/// same isl_id's as the @p Domain.
1140static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1141 __isl_take isl_pw_aff *L,
1142 __isl_take isl_pw_aff *R,
1143 __isl_keep isl_set *Domain) {
1144 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1145 return setDimensionIds(Domain, ConsequenceCondSet);
1146}
1147
1148/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001149///
1150/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001151/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1152/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001153static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001154buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001155 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1156
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001157 Value *Condition = getConditionFromTerminator(SI);
1158 assert(Condition && "No condition for switch");
1159
1160 ScalarEvolution &SE = *S.getSE();
1161 BasicBlock *BB = SI->getParent();
1162 isl_pw_aff *LHS, *RHS;
1163 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1164
1165 unsigned NumSuccessors = SI->getNumSuccessors();
1166 ConditionSets.resize(NumSuccessors);
1167 for (auto &Case : SI->cases()) {
1168 unsigned Idx = Case.getSuccessorIndex();
1169 ConstantInt *CaseValue = Case.getCaseValue();
1170
1171 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1172 isl_set *CaseConditionSet =
1173 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1174 ConditionSets[Idx] = isl_set_coalesce(
1175 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1176 }
1177
1178 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1179 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1180 for (unsigned u = 2; u < NumSuccessors; u++)
1181 ConditionSetUnion =
1182 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1183 ConditionSets[0] = setDimensionIds(
1184 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1185
1186 S.markAsOptimized();
1187 isl_pw_aff_free(LHS);
1188}
1189
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001190/// @brief Build the conditions sets for the branch condition @p Condition in
1191/// the @p Domain.
1192///
1193/// This will fill @p ConditionSets with the conditions under which control
1194/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001195/// have as many elements as @p TI has successors. If @p TI is nullptr the
1196/// context under which @p Condition is true/false will be returned as the
1197/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001198static void
1199buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1200 __isl_keep isl_set *Domain,
1201 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1202
1203 isl_set *ConsequenceCondSet = nullptr;
1204 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1205 if (CCond->isZero())
1206 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1207 else
1208 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1209 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1210 auto Opcode = BinOp->getOpcode();
1211 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1212
1213 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1214 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1215
1216 isl_set_free(ConditionSets.pop_back_val());
1217 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1218 isl_set_free(ConditionSets.pop_back_val());
1219 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1220
1221 if (Opcode == Instruction::And)
1222 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1223 else
1224 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1225 } else {
1226 auto *ICond = dyn_cast<ICmpInst>(Condition);
1227 assert(ICond &&
1228 "Condition of exiting branch was neither constant nor ICmp!");
1229
1230 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001231 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001232 isl_pw_aff *LHS, *RHS;
1233 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1234 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1235 ConsequenceCondSet =
1236 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1237 }
1238
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001239 // If no terminator was given we are only looking for parameter constraints
1240 // under which @p Condition is true/false.
1241 if (!TI)
1242 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001243 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001244 ConsequenceCondSet = isl_set_coalesce(
1245 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001246
Johannes Doerfert15194912016-04-04 07:59:41 +00001247 isl_set *AlternativeCondSet;
1248 unsigned NumParams = isl_set_n_param(ConsequenceCondSet);
1249 unsigned NumBasicSets = isl_set_n_basic_set(ConsequenceCondSet);
1250 if (NumBasicSets + NumParams < MaxConjunctsInDomain) {
1251 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1252 isl_set_copy(ConsequenceCondSet));
1253 } else {
1254 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
1255 AlternativeCondSet = isl_set_empty(isl_set_get_space(ConsequenceCondSet));
1256 }
1257
1258 ConditionSets.push_back(ConsequenceCondSet);
1259 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001260}
1261
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001262/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1263///
1264/// This will fill @p ConditionSets with the conditions under which control
1265/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1266/// have as many elements as @p TI has successors.
1267static void
1268buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1269 __isl_keep isl_set *Domain,
1270 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1271
1272 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1273 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1274
1275 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1276
1277 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001278 ConditionSets.push_back(isl_set_copy(Domain));
1279 return;
1280 }
1281
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001282 Value *Condition = getConditionFromTerminator(TI);
1283 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001284
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001285 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001286}
1287
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001288void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001289 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001290
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001291 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001292 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001293}
1294
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001295void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1296 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001297 isl_ctx *Ctx = Parent.getIslCtx();
1298 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1299 Type *Ty = GEP->getPointerOperandType();
1300 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001301
1302 // The set of loads that are required to be invariant.
1303 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001304
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001305 std::vector<const SCEV *> Subscripts;
1306 std::vector<int> Sizes;
1307
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001308 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001309
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001310 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001311 Ty = PtrTy->getElementType();
1312 }
1313
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001314 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001315
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001316 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001317
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001318 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001319 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001320 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001321 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001322
Michael Kruse09eb4452016-03-03 22:10:47 +00001323 auto *Scope = SD.getLI()->getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001324 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00001325 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, nullptr,
1326 &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001327 continue;
1328
1329 bool NonAffine = false;
1330 for (LoadInst *LInst : AccessILS)
1331 if (!ScopRIL.count(LInst))
1332 NonAffine = true;
1333
1334 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001335 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001336
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001337 isl_pw_aff *AccessOffset = getPwAff(Expr);
1338 AccessOffset =
1339 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001340
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001341 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1342 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001343
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001344 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1345 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1346 OutOfBound = isl_set_params(OutOfBound);
1347 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001348
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001349 // A => B == !A or B
1350 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001351 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001352
Roman Gareev10595a12016-01-08 14:01:59 +00001353 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001354 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1355 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001356 }
1357
1358 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001359 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001360}
1361
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001362void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001363 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001364 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001365 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001366}
1367
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001368void ScopStmt::collectSurroundingLoops() {
1369 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1370 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1371 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1372 isl_id_free(DimId);
1373 }
1374}
1375
Michael Kruse9d080092015-09-11 21:41:48 +00001376ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001377 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001378
Tobias Grosser16c44032015-07-09 07:31:45 +00001379 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001380}
1381
Michael Kruse9d080092015-09-11 21:41:48 +00001382ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001383 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001384
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001385 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001386}
1387
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001388void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001389 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001390
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001391 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001392 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001393 buildAccessRelations();
1394
1395 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001396 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001397 } else {
1398 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001399 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001400 }
1401 }
1402
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001403 if (DetectReductions)
1404 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001405}
1406
Johannes Doerferte58a0122014-06-27 20:31:28 +00001407/// @brief Collect loads which might form a reduction chain with @p StoreMA
1408///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001409/// Check if the stored value for @p StoreMA is a binary operator with one or
1410/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001411/// used only once (by @p StoreMA) and its load operands are also used only
1412/// once, we have found a possible reduction chain. It starts at an operand
1413/// load and includes the binary operator and @p StoreMA.
1414///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001415/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001416/// escape this block or into any other store except @p StoreMA.
1417void ScopStmt::collectCandiateReductionLoads(
1418 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1419 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1420 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001421 return;
1422
1423 // Skip if there is not one binary operator between the load and the store
1424 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001425 if (!BinOp)
1426 return;
1427
1428 // Skip if the binary operators has multiple uses
1429 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001430 return;
1431
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001432 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001433 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1434 return;
1435
Johannes Doerfert9890a052014-07-01 00:32:29 +00001436 // Skip if the binary operator is outside the current SCoP
1437 if (BinOp->getParent() != Store->getParent())
1438 return;
1439
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001440 // Skip if it is a multiplicative reduction and we disabled them
1441 if (DisableMultiplicativeReductions &&
1442 (BinOp->getOpcode() == Instruction::Mul ||
1443 BinOp->getOpcode() == Instruction::FMul))
1444 return;
1445
Johannes Doerferte58a0122014-06-27 20:31:28 +00001446 // Check the binary operator operands for a candidate load
1447 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1448 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1449 if (!PossibleLoad0 && !PossibleLoad1)
1450 return;
1451
1452 // A load is only a candidate if it cannot escape (thus has only this use)
1453 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001454 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001455 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001456 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001457 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001458 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001459}
1460
1461/// @brief Check for reductions in this ScopStmt
1462///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001463/// Iterate over all store memory accesses and check for valid binary reduction
1464/// like chains. For all candidates we check if they have the same base address
1465/// and there are no other accesses which overlap with them. The base address
1466/// check rules out impossible reductions candidates early. The overlap check,
1467/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001468/// guarantees that none of the intermediate results will escape during
1469/// execution of the loop nest. We basically check here that no other memory
1470/// access can access the same memory as the potential reduction.
1471void ScopStmt::checkForReductions() {
1472 SmallVector<MemoryAccess *, 2> Loads;
1473 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1474
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001475 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001476 // stores and collecting possible reduction loads.
1477 for (MemoryAccess *StoreMA : MemAccs) {
1478 if (StoreMA->isRead())
1479 continue;
1480
1481 Loads.clear();
1482 collectCandiateReductionLoads(StoreMA, Loads);
1483 for (MemoryAccess *LoadMA : Loads)
1484 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1485 }
1486
1487 // Then check each possible candidate pair.
1488 for (const auto &CandidatePair : Candidates) {
1489 bool Valid = true;
1490 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1491 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1492
1493 // Skip those with obviously unequal base addresses.
1494 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1495 isl_map_free(LoadAccs);
1496 isl_map_free(StoreAccs);
1497 continue;
1498 }
1499
1500 // And check if the remaining for overlap with other memory accesses.
1501 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1502 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1503 isl_set *AllAccs = isl_map_range(AllAccsRel);
1504
1505 for (MemoryAccess *MA : MemAccs) {
1506 if (MA == CandidatePair.first || MA == CandidatePair.second)
1507 continue;
1508
1509 isl_map *AccRel =
1510 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1511 isl_set *Accs = isl_map_range(AccRel);
1512
1513 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1514 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1515 Valid = Valid && isl_set_is_empty(OverlapAccs);
1516 isl_set_free(OverlapAccs);
1517 }
1518 }
1519
1520 isl_set_free(AllAccs);
1521 if (!Valid)
1522 continue;
1523
Johannes Doerfertf6183392014-07-01 20:52:51 +00001524 const LoadInst *Load =
1525 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1526 MemoryAccess::ReductionType RT =
1527 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1528
Johannes Doerferte58a0122014-06-27 20:31:28 +00001529 // If no overlapping access was found we mark the load and store as
1530 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001531 CandidatePair.first->markAsReductionLike(RT);
1532 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001533 }
Tobias Grosser75805372011-04-29 06:27:02 +00001534}
1535
Tobias Grosser74394f02013-01-14 22:40:23 +00001536std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001537
Tobias Grosser54839312015-04-21 11:37:25 +00001538std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001539 auto *S = getSchedule();
1540 auto Str = stringFromIslObj(S);
1541 isl_map_free(S);
1542 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001543}
1544
Michael Kruse375cb5f2016-02-24 22:08:24 +00001545BasicBlock *ScopStmt::getEntryBlock() const {
1546 if (isBlockStmt())
1547 return getBasicBlock();
1548 return getRegion()->getEntry();
1549}
1550
Michael Kruse7b5caa42016-02-24 22:08:28 +00001551RegionNode *ScopStmt::getRegionNode() const {
1552 if (isRegionStmt())
1553 return getRegion()->getNode();
1554 return getParent()->getRegion().getBBNode(getBasicBlock());
1555}
1556
Tobias Grosser74394f02013-01-14 22:40:23 +00001557unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001558
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001559unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001560
Tobias Grosser75805372011-04-29 06:27:02 +00001561const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1562
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001563const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001564 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001565}
1566
Tobias Grosser74394f02013-01-14 22:40:23 +00001567isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001568
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001569__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001570
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001571__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001572 return isl_set_get_space(Domain);
1573}
1574
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001575__isl_give isl_id *ScopStmt::getDomainId() const {
1576 return isl_set_get_tuple_id(Domain);
1577}
Tobias Grossercd95b772012-08-30 11:49:38 +00001578
Tobias Grosser10120182015-12-16 16:14:03 +00001579ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001580
1581void ScopStmt::print(raw_ostream &OS) const {
1582 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001583 OS.indent(12) << "Domain :=\n";
1584
1585 if (Domain) {
1586 OS.indent(16) << getDomainStr() << ";\n";
1587 } else
1588 OS.indent(16) << "n/a\n";
1589
Tobias Grosser54839312015-04-21 11:37:25 +00001590 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001591
1592 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001593 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001594 } else
1595 OS.indent(16) << "n/a\n";
1596
Tobias Grosser083d3d32014-06-28 08:59:45 +00001597 for (MemoryAccess *Access : MemAccs)
1598 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001599}
1600
1601void ScopStmt::dump() const { print(dbgs()); }
1602
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001603void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001604 // Remove all memory accesses in @p InvMAs from this statement
1605 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001606 // MK_Value READs have no access instruction, hence would not be removed by
1607 // this function. However, it is only used for invariant LoadInst accesses,
1608 // its arguments are always affine, hence synthesizable, and therefore there
1609 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001610 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001611 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001612 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001613 };
1614 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1615 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001616 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001617 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001618}
1619
Tobias Grosser75805372011-04-29 06:27:02 +00001620//===----------------------------------------------------------------------===//
1621/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001622
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001623void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001624 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1625 isl_set_free(Context);
1626 Context = NewContext;
1627}
1628
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001629/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1630struct SCEVSensitiveParameterRewriter
1631 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1632 ValueToValueMap &VMap;
1633 ScalarEvolution &SE;
1634
1635public:
1636 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1637 : VMap(VMap), SE(SE) {}
1638
1639 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1640 ValueToValueMap &VMap) {
1641 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1642 return SSPR.visit(E);
1643 }
1644
1645 const SCEV *visit(const SCEV *E) {
1646 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1647 }
1648
1649 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1650
1651 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1652 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1653 }
1654
1655 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1656 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1657 }
1658
1659 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1660 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1661 }
1662
1663 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1664 SmallVector<const SCEV *, 4> Operands;
1665 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1666 Operands.push_back(visit(E->getOperand(i)));
1667 return SE.getAddExpr(Operands);
1668 }
1669
1670 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1671 SmallVector<const SCEV *, 4> Operands;
1672 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1673 Operands.push_back(visit(E->getOperand(i)));
1674 return SE.getMulExpr(Operands);
1675 }
1676
1677 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1678 SmallVector<const SCEV *, 4> Operands;
1679 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1680 Operands.push_back(visit(E->getOperand(i)));
1681 return SE.getSMaxExpr(Operands);
1682 }
1683
1684 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1685 SmallVector<const SCEV *, 4> Operands;
1686 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1687 Operands.push_back(visit(E->getOperand(i)));
1688 return SE.getUMaxExpr(Operands);
1689 }
1690
1691 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1692 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1693 }
1694
1695 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1696 auto *Start = visit(E->getStart());
1697 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1698 visit(E->getStepRecurrence(SE)),
1699 E->getLoop(), SCEV::FlagAnyWrap);
1700 return SE.getAddExpr(Start, AddRec);
1701 }
1702
1703 const SCEV *visitUnknown(const SCEVUnknown *E) {
1704 if (auto *NewValue = VMap.lookup(E->getValue()))
1705 return SE.getUnknown(NewValue);
1706 return E;
1707 }
1708};
1709
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001710const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001711 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001712}
1713
Tobias Grosserabfbe632013-02-05 12:09:06 +00001714void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001715 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001716 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001717
1718 // Normalize the SCEV to get the representing element for an invariant load.
1719 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1720
Tobias Grosser60b54f12011-11-08 15:41:28 +00001721 if (ParameterIds.find(Parameter) != ParameterIds.end())
1722 continue;
1723
1724 int dimension = Parameters.size();
1725
1726 Parameters.push_back(Parameter);
1727 ParameterIds[Parameter] = dimension;
1728 }
1729}
1730
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001731__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001732 // Normalize the SCEV to get the representing element for an invariant load.
1733 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1734
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001735 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001736
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001737 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001738 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001739
Tobias Grosser8f99c162011-11-15 11:38:55 +00001740 std::string ParameterName;
1741
Craig Topper7fb6e472016-01-31 20:36:20 +00001742 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001743
Tobias Grosser8f99c162011-11-15 11:38:55 +00001744 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1745 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001746
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001747 // If this parameter references a specific Value and this value has a name
1748 // we use this name as it is likely to be unique and more useful than just
1749 // a number.
1750 if (Val->hasName())
1751 ParameterName = Val->getName();
1752 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001753 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001754 if (LoadOrigin->hasName()) {
1755 ParameterName += "_loaded_from_";
1756 ParameterName +=
1757 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1758 }
1759 }
1760 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001761
Tobias Grosser20532b82014-04-11 17:56:49 +00001762 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1763 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001764}
Tobias Grosser75805372011-04-29 06:27:02 +00001765
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001766isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1767 isl_set *DomainContext = isl_union_set_params(getDomains());
1768 return isl_set_intersect_params(C, DomainContext);
1769}
1770
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001771void Scop::addWrappingContext() {
1772 if (IgnoreIntegerWrapping)
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001773 return;
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001774
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001775 auto *WrappingContext = Affinator.getWrappingContext();
1776 addAssumption(WRAPPING, WrappingContext, DebugLoc(), AS_RESTRICTION);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001777}
1778
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001779void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1780 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001781 auto *R = &getRegion();
1782 auto &F = *R->getEntry()->getParent();
1783 for (auto &Assumption : AC.assumptions()) {
1784 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1785 if (!CI || CI->getNumArgOperands() != 1)
1786 continue;
1787 if (!DT.dominates(CI->getParent(), R->getEntry()))
1788 continue;
1789
Michael Kruse09eb4452016-03-03 22:10:47 +00001790 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001791 auto *Val = CI->getArgOperand(0);
1792 std::vector<const SCEV *> Params;
Michael Kruse09eb4452016-03-03 22:10:47 +00001793 if (!isAffineParamConstraint(Val, R, L, *SE, Params)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001794 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1795 CI->getDebugLoc(),
1796 "Non-affine user assumption ignored.");
1797 continue;
1798 }
1799
1800 addParams(Params);
1801
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001802 SmallVector<isl_set *, 2> ConditionSets;
1803 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1804 assert(ConditionSets.size() == 2);
1805 isl_set_free(ConditionSets[1]);
1806
1807 auto *AssumptionCtx = ConditionSets[0];
1808 emitOptimizationRemarkAnalysis(
1809 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1810 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1811 Context = isl_set_intersect(Context, AssumptionCtx);
1812 }
1813}
1814
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001815void Scop::addUserContext() {
1816 if (UserContextStr.empty())
1817 return;
1818
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001819 isl_set *UserContext =
1820 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001821 isl_space *Space = getParamSpace();
1822 if (isl_space_dim(Space, isl_dim_param) !=
1823 isl_set_dim(UserContext, isl_dim_param)) {
1824 auto SpaceStr = isl_space_to_str(Space);
1825 errs() << "Error: the context provided in -polly-context has not the same "
1826 << "number of dimensions than the computed context. Due to this "
1827 << "mismatch, the -polly-context option is ignored. Please provide "
1828 << "the context in the parameter space: " << SpaceStr << ".\n";
1829 free(SpaceStr);
1830 isl_set_free(UserContext);
1831 isl_space_free(Space);
1832 return;
1833 }
1834
1835 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001836 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1837 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001838
1839 if (strcmp(NameContext, NameUserContext) != 0) {
1840 auto SpaceStr = isl_space_to_str(Space);
1841 errs() << "Error: the name of dimension " << i
1842 << " provided in -polly-context "
1843 << "is '" << NameUserContext << "', but the name in the computed "
1844 << "context is '" << NameContext
1845 << "'. Due to this name mismatch, "
1846 << "the -polly-context option is ignored. Please provide "
1847 << "the context in the parameter space: " << SpaceStr << ".\n";
1848 free(SpaceStr);
1849 isl_set_free(UserContext);
1850 isl_space_free(Space);
1851 return;
1852 }
1853
1854 UserContext =
1855 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1856 isl_space_get_dim_id(Space, isl_dim_param, i));
1857 }
1858
1859 Context = isl_set_intersect(Context, UserContext);
1860 isl_space_free(Space);
1861}
1862
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001863void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001864 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001865
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001866 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001867 for (LoadInst *LInst : RIL) {
1868 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1869
Johannes Doerfert96e54712016-02-07 17:30:13 +00001870 Type *Ty = LInst->getType();
1871 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001872 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001873 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001874 continue;
1875 }
1876
1877 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001878 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1879 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001880 }
1881}
1882
Tobias Grosser6be480c2011-11-08 15:41:13 +00001883void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001884 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001885 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001886 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001887 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001888}
1889
Tobias Grosser18daaca2012-05-22 10:47:27 +00001890void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001891 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001892 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001893
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001894 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001895
Johannes Doerferte7044942015-02-24 11:58:30 +00001896 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001897 }
1898}
1899
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001900void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001901 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001902 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001903
Tobias Grosser083d3d32014-06-28 08:59:45 +00001904 for (const auto &ParamID : ParameterIds) {
1905 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001906 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001907 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001908 }
1909
1910 // Align the parameters of all data structures to the model.
1911 Context = isl_set_align_params(Context, Space);
1912
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001913 for (ScopStmt &Stmt : *this)
1914 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001915}
1916
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001917static __isl_give isl_set *
1918simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1919 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001920 // If we modelt all blocks in the SCoP that have side effects we can simplify
1921 // the context with the constraints that are needed for anything to be
1922 // executed at all. However, if we have error blocks in the SCoP we already
1923 // assumed some parameter combinations cannot occure and removed them from the
1924 // domains, thus we cannot use the remaining domain to simplify the
1925 // assumptions.
1926 if (!S.hasErrorBlock()) {
1927 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1928 AssumptionContext =
1929 isl_set_gist_params(AssumptionContext, DomainParameters);
1930 }
1931
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001932 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1933 return AssumptionContext;
1934}
1935
1936void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001937 // The parameter constraints of the iteration domains give us a set of
1938 // constraints that need to hold for all cases where at least a single
1939 // statement iteration is executed in the whole scop. We now simplify the
1940 // assumed context under the assumption that such constraints hold and at
1941 // least a single statement iteration is executed. For cases where no
1942 // statement instances are executed, the assumptions we have taken about
1943 // the executed code do not matter and can be changed.
1944 //
1945 // WARNING: This only holds if the assumptions we have taken do not reduce
1946 // the set of statement instances that are executed. Otherwise we
1947 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001948 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001949 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001950 // performed. In such a case, modifying the run-time conditions and
1951 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001952 // to not be executed.
1953 //
1954 // Example:
1955 //
1956 // When delinearizing the following code:
1957 //
1958 // for (long i = 0; i < 100; i++)
1959 // for (long j = 0; j < m; j++)
1960 // A[i+p][j] = 1.0;
1961 //
1962 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001963 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001964 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001965 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001966 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001967}
1968
Johannes Doerfertb164c792014-09-18 11:17:17 +00001969/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001970static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001971 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1972 isl_pw_multi_aff *MinPMA, *MaxPMA;
1973 isl_pw_aff *LastDimAff;
1974 isl_aff *OneAff;
1975 unsigned Pos;
1976
Johannes Doerfert9143d672014-09-27 11:02:39 +00001977 // Restrict the number of parameters involved in the access as the lexmin/
1978 // lexmax computation will take too long if this number is high.
1979 //
1980 // Experiments with a simple test case using an i7 4800MQ:
1981 //
1982 // #Parameters involved | Time (in sec)
1983 // 6 | 0.01
1984 // 7 | 0.04
1985 // 8 | 0.12
1986 // 9 | 0.40
1987 // 10 | 1.54
1988 // 11 | 6.78
1989 // 12 | 30.38
1990 //
1991 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1992 unsigned InvolvedParams = 0;
1993 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
1994 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
1995 InvolvedParams++;
1996
1997 if (InvolvedParams > RunTimeChecksMaxParameters) {
1998 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00001999 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002000 }
2001 }
2002
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00002003 Set = isl_set_remove_divs(Set);
2004
Johannes Doerfertb164c792014-09-18 11:17:17 +00002005 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2006 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2007
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002008 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2009 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2010
Johannes Doerfertb164c792014-09-18 11:17:17 +00002011 // Adjust the last dimension of the maximal access by one as we want to
2012 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2013 // we test during code generation might now point after the end of the
2014 // allocated array but we will never dereference it anyway.
2015 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2016 "Assumed at least one output dimension");
2017 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2018 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2019 OneAff = isl_aff_zero_on_domain(
2020 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2021 OneAff = isl_aff_add_constant_si(OneAff, 1);
2022 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2023 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2024
2025 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2026
2027 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002028 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002029}
2030
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002031static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2032 isl_set *Domain = MA->getStatement()->getDomain();
2033 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2034 return isl_set_reset_tuple_id(Domain);
2035}
2036
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002037/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2038static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002039 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002040 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002041
2042 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2043 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002044 Locations = isl_union_set_coalesce(Locations);
2045 Locations = isl_union_set_detect_equalities(Locations);
2046 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002047 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002048 isl_union_set_free(Locations);
2049 return Valid;
2050}
2051
Johannes Doerfert96425c22015-08-30 21:13:53 +00002052/// @brief Helper to treat non-affine regions and basic blocks the same.
2053///
2054///{
2055
2056/// @brief Return the block that is the representing block for @p RN.
2057static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2058 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2059 : RN->getNodeAs<BasicBlock>();
2060}
2061
2062/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002063static inline BasicBlock *
2064getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002065 if (RN->isSubRegion()) {
2066 assert(idx == 0);
2067 return RN->getNodeAs<Region>()->getExit();
2068 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002069 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002070}
2071
2072/// @brief Return the smallest loop surrounding @p RN.
2073static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2074 if (!RN->isSubRegion())
2075 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2076
2077 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2078 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2079 while (L && NonAffineSubRegion->contains(L))
2080 L = L->getParentLoop();
2081 return L;
2082}
2083
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002084static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2085 if (!RN->isSubRegion())
2086 return 1;
2087
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002088 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002089 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002090}
2091
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002092static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2093 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002094 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002095 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002096 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002097 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002098 return true;
2099 return false;
2100}
2101
Johannes Doerfert96425c22015-08-30 21:13:53 +00002102///}
2103
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002104static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2105 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002106 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002107 isl_id *DimId =
2108 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2109 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2110}
2111
Johannes Doerfert96425c22015-08-30 21:13:53 +00002112isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002113 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002114}
2115
2116isl_set *Scop::getDomainConditions(BasicBlock *BB) {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002117 auto DIt = DomainMap.find(BB);
2118 if (DIt != DomainMap.end())
2119 return isl_set_copy(DIt->getSecond());
2120
2121 auto &RI = *R.getRegionInfo();
2122 auto *BBR = RI.getRegionFor(BB);
2123 while (BBR->getEntry() == BB)
2124 BBR = BBR->getParent();
2125 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002126}
2127
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002128bool Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002129 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002130
Johannes Doerfert432658d2016-01-26 11:01:41 +00002131 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002132 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002133 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2134 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002135 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002136
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002137 while (LD-- >= 0) {
2138 S = addDomainDimId(S, LD + 1, L);
2139 L = L->getParentLoop();
2140 }
2141
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002142 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002143
Johannes Doerfert432658d2016-01-26 11:01:41 +00002144 if (IsOnlyNonAffineRegion)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002145 return true;
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002146
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002147 if (!buildDomainsWithBranchConstraints(R, SD, DT, LI))
2148 return false;
2149
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002150 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002151
2152 // Error blocks and blocks dominated by them have been assumed to never be
2153 // executed. Representing them in the Scop does not add any value. In fact,
2154 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002155 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002156 // will cause problems when building up a ScopStmt for them.
2157 // Furthermore, basic blocks dominated by error blocks may reference
2158 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002159 // can themselves not be constructed properly. To this end we will replace
2160 // the domains of error blocks and those only reachable via error blocks
2161 // with an empty set. Additionally, we will record for each block under which
2162 // parameter combination it would be reached via an error block in the
2163 // ErrorDomainCtxMap map. This information is needed during load hoisting.
2164 propagateErrorConstraints(R, SD, DT, LI);
2165
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002166 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002167}
2168
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002169static Loop *
2170getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2171 const ScopDetection::BoxedLoopsSetTy &BoxedLoops) {
2172 auto *L = LI.getLoopFor(BB);
2173 while (BoxedLoops.count(L))
2174 L = L->getParentLoop();
2175 return L;
2176}
2177
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002178/// @brief Adjust the dimensions of @p Dom that was constructed for @p OldL
2179/// to be compatible to domains constructed for loop @p NewL.
2180///
2181/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2182/// edge from @p OldL to @p NewL.
2183static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2184 __isl_take isl_set *Dom,
2185 Loop *OldL, Loop *NewL) {
2186
2187 // If the loops are the same there is nothing to do.
2188 if (NewL == OldL)
2189 return Dom;
2190
2191 int OldDepth = S.getRelativeLoopDepth(OldL);
2192 int NewDepth = S.getRelativeLoopDepth(NewL);
2193 // If both loops are non-affine loops there is nothing to do.
2194 if (OldDepth == -1 && NewDepth == -1)
2195 return Dom;
2196
2197 // Distinguish three cases:
2198 // 1) The depth is the same but the loops are not.
2199 // => One loop was left one was entered.
2200 // 2) The depth increased from OldL to NewL.
2201 // => One loop was entered, none was left.
2202 // 3) The depth decreased from OldL to NewL.
2203 // => Loops were left were difference of the depths defines how many.
2204 if (OldDepth == NewDepth) {
2205 assert(OldL->getParentLoop() == NewL->getParentLoop());
2206 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2207 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2208 Dom = addDomainDimId(Dom, NewDepth, NewL);
2209 } else if (OldDepth < NewDepth) {
2210 assert(OldDepth + 1 == NewDepth);
2211 auto &R = S.getRegion();
2212 (void)R;
2213 assert(NewL->getParentLoop() == OldL ||
2214 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2215 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2216 Dom = addDomainDimId(Dom, NewDepth, NewL);
2217 } else {
2218 assert(OldDepth > NewDepth);
2219 int Diff = OldDepth - NewDepth;
2220 int NumDim = isl_set_n_dim(Dom);
2221 assert(NumDim >= Diff);
2222 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2223 }
2224
2225 return Dom;
2226}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002227
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002228void Scop::propagateErrorConstraints(Region *R, ScopDetection &SD,
2229 DominatorTree &DT, LoopInfo &LI) {
2230
2231 ReversePostOrderTraversal<Region *> RTraversal(R);
2232 for (auto *RN : RTraversal) {
2233
2234 // Recurse for affine subregions but go on for basic blocks and non-affine
2235 // subregions.
2236 if (RN->isSubRegion()) {
2237 Region *SubRegion = RN->getNodeAs<Region>();
2238 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2239 propagateErrorConstraints(SubRegion, SD, DT, LI);
2240 continue;
2241 }
2242 }
2243
2244 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2245 BasicBlock *BB = getRegionNodeBasicBlock(RN);
2246 isl_set *&Domain = DomainMap[BB];
2247 assert(Domain && "Cannot propagate a nullptr");
2248
2249 auto *&ErrorCtx = ErrorDomainCtxMap[BB];
2250 auto *DomainCtx = isl_set_params(isl_set_copy(Domain));
2251 bool IsErrorBlock = ContainsErrorBlock ||
2252 (ErrorCtx && isl_set_is_subset(DomainCtx, ErrorCtx));
2253
2254 if (IsErrorBlock) {
2255 ErrorCtx = ErrorCtx ? isl_set_union(ErrorCtx, DomainCtx) : DomainCtx;
2256 auto *EmptyDom = isl_set_empty(isl_set_get_space(Domain));
2257 isl_set_free(Domain);
2258 Domain = EmptyDom;
2259 } else {
2260 isl_set_free(DomainCtx);
2261 }
2262
2263 if (!ErrorCtx)
2264 continue;
2265
2266 auto *TI = BB->getTerminator();
2267 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2268 for (unsigned u = 0; u < NumSuccs; u++) {
2269 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
2270 auto *&SuccErrorCtx = ErrorDomainCtxMap[SuccBB];
2271 auto *CurErrorCtx = isl_set_copy(ErrorCtx);
2272 SuccErrorCtx =
2273 SuccErrorCtx ? isl_set_union(SuccErrorCtx, CurErrorCtx) : CurErrorCtx;
2274 SuccErrorCtx = isl_set_coalesce(SuccErrorCtx);
2275
2276 // Check if the maximal number of domain conjuncts was reached.
2277 // In case this happens we will bail.
2278 if (isl_set_n_basic_set(SuccErrorCtx) < MaxConjunctsInDomain)
2279 continue;
2280
2281 invalidate(COMPLEXITY, TI->getDebugLoc());
2282 return;
2283 }
2284 }
2285}
2286
Johannes Doerfert642594a2016-04-04 07:57:39 +00002287void Scop::propagateDomainConstraintsToRegionExit(
2288 BasicBlock *BB, Loop *BBLoop,
2289 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, ScopDetection &SD,
2290 LoopInfo &LI) {
2291
2292 // Check if the block @p BB is the entry of a region. If so we propagate it's
2293 // domain to the exit block of the region. Otherwise we are done.
2294 auto *RI = R.getRegionInfo();
2295 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2296 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
2297 if (!BBReg || BBReg->getEntry() != BB || !R.contains(ExitBB))
2298 return;
2299
2300 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2301 // Do not propagate the domain if there is a loop backedge inside the region
2302 // that would prevent the exit block from beeing executed.
2303 auto *L = BBLoop;
2304 while (L && R.contains(L)) {
2305 SmallVector<BasicBlock *, 4> LatchBBs;
2306 BBLoop->getLoopLatches(LatchBBs);
2307 for (auto *LatchBB : LatchBBs)
2308 if (BB != LatchBB && BBReg->contains(LatchBB))
2309 return;
2310 L = L->getParentLoop();
2311 }
2312
2313 auto *Domain = DomainMap[BB];
2314 assert(Domain && "Cannot propagate a nullptr");
2315
2316 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2317
2318 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2319 // adjust the domain before we can propagate it.
2320 auto *AdjustedDomain =
2321 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2322 auto *&ExitDomain = DomainMap[ExitBB];
2323
2324 // If the exit domain is not yet created we set it otherwise we "add" the
2325 // current domain.
2326 ExitDomain =
2327 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2328
2329 FinishedExitBlocks.insert(ExitBB);
2330}
2331
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002332bool Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002333 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002334 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002335
2336 // To create the domain for each block in R we iterate over all blocks and
2337 // subregions in R and propagate the conditions under which the current region
2338 // element is executed. To this end we iterate in reverse post order over R as
2339 // it ensures that we first visit all predecessors of a region node (either a
2340 // basic block or a subregion) before we visit the region node itself.
2341 // Initially, only the domain for the SCoP region entry block is set and from
2342 // there we propagate the current domain to all successors, however we add the
2343 // condition that the successor is actually executed next.
2344 // As we are only interested in non-loop carried constraints here we can
2345 // simply skip loop back edges.
2346
Johannes Doerfert642594a2016-04-04 07:57:39 +00002347 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002348 ReversePostOrderTraversal<Region *> RTraversal(R);
2349 for (auto *RN : RTraversal) {
2350
2351 // Recurse for affine subregions but go on for basic blocks and non-affine
2352 // subregions.
2353 if (RN->isSubRegion()) {
2354 Region *SubRegion = RN->getNodeAs<Region>();
2355 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002356 if (!buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI))
2357 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002358 continue;
2359 }
2360 }
2361
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002362 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002363 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002364
Johannes Doerfert96425c22015-08-30 21:13:53 +00002365 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002366 TerminatorInst *TI = BB->getTerminator();
2367
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002368 if (isa<UnreachableInst>(TI))
2369 continue;
2370
Johannes Doerfertf5673802015-10-01 23:48:18 +00002371 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002372 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002373 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002374
Johannes Doerfert642594a2016-04-04 07:57:39 +00002375 auto *BBLoop = getRegionNodeLoop(RN, LI);
2376 // Propagate the domain from BB directly to blocks that have a superset
2377 // domain, at the moment only region exit nodes of regions that start in BB.
2378 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, SD,
2379 LI);
2380
2381 // If all successors of BB have been set a domain through the propagation
2382 // above we do not need to build condition sets but can just skip this
2383 // block. However, it is important to note that this is a local property
2384 // with regards to the region @p R. To this end FinishedExitBlocks is a
2385 // local variable.
2386 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2387 return FinishedExitBlocks.count(SuccBB);
2388 };
2389 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2390 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002391
2392 // Build the condition sets for the successor nodes of the current region
2393 // node. If it is a non-affine subregion we will always execute the single
2394 // exit node, hence the single entry node domain is the condition set. For
2395 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002396 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002397 if (RN->isSubRegion())
2398 ConditionSets.push_back(isl_set_copy(Domain));
2399 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002400 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002401
2402 // Now iterate over the successors and set their initial domain based on
2403 // their condition set. We skip back edges here and have to be careful when
2404 // we leave a loop not to keep constraints over a dimension that doesn't
2405 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002406 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002407 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002408 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002409 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002410
Johannes Doerfert642594a2016-04-04 07:57:39 +00002411 // If we propagate the domain of some block to "SuccBB" we do not have to
2412 // adjust the domain.
2413 if (FinishedExitBlocks.count(SuccBB)) {
2414 isl_set_free(CondSet);
2415 continue;
2416 }
2417
Johannes Doerfert96425c22015-08-30 21:13:53 +00002418 // Skip back edges.
2419 if (DT.dominates(SuccBB, BB)) {
2420 isl_set_free(CondSet);
2421 continue;
2422 }
2423
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002424 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002425 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002426
2427 // Set the domain for the successor or merge it with an existing domain in
2428 // case there are multiple paths (without loop back edges) to the
2429 // successor block.
2430 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002431
Johannes Doerfert96425c22015-08-30 21:13:53 +00002432 if (!SuccDomain)
2433 SuccDomain = CondSet;
2434 else
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002435 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002436
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002437 // Check if the maximal number of domain conjuncts was reached.
2438 // In case this happens we will clean up and bail.
Johannes Doerfert15194912016-04-04 07:59:41 +00002439 if (isl_set_n_basic_set(SuccDomain) < MaxConjunctsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002440 continue;
2441
2442 invalidate(COMPLEXITY, DebugLoc());
2443 while (++u < ConditionSets.size())
2444 isl_set_free(ConditionSets[u]);
2445 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002446 }
2447 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002448
2449 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002450}
2451
Johannes Doerfert642594a2016-04-04 07:57:39 +00002452isl_set *Scop::getPredecessorDomainConstraints(BasicBlock *BB, isl_set *Domain,
2453 ScopDetection &SD,
2454 DominatorTree &DT,
2455 LoopInfo &LI) {
2456 // If @p BB is the ScopEntry we are done
2457 if (R.getEntry() == BB)
2458 return isl_set_universe(isl_set_get_space(Domain));
2459
2460 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2461 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2462
2463 // The region info of this function.
2464 auto &RI = *R.getRegionInfo();
2465
2466 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2467
2468 // A domain to collect all predecessor domains, thus all conditions under
2469 // which the block is executed. To this end we start with the empty domain.
2470 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2471
2472 // Set of regions of which the entry block domain has been propagated to BB.
2473 // all predecessors inside any of the regions can be skipped.
2474 SmallSet<Region *, 8> PropagatedRegions;
2475
2476 for (auto *PredBB : predecessors(BB)) {
2477 // Skip backedges.
2478 if (DT.dominates(BB, PredBB))
2479 continue;
2480
2481 // If the predecessor is in a region we used for propagation we can skip it.
2482 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2483 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2484 PredBBInRegion)) {
2485 continue;
2486 }
2487
2488 // Check if there is a valid region we can use for propagation, thus look
2489 // for a region that contains the predecessor and has @p BB as exit block.
2490 auto *PredR = RI.getRegionFor(PredBB);
2491 while (PredR->getExit() != BB && !PredR->contains(BB))
2492 PredR->getParent();
2493
2494 // If a valid region for propagation was found use the entry of that region
2495 // for propagation, otherwise the PredBB directly.
2496 if (PredR->getExit() == BB) {
2497 PredBB = PredR->getEntry();
2498 PropagatedRegions.insert(PredR);
2499 }
2500
Johannes Doerfert41cda152016-04-08 10:32:26 +00002501 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002502 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2503 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2504
2505 PredDom = isl_set_union(PredDom, PredBBDom);
2506 }
2507
2508 return PredDom;
2509}
2510
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002511void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002512 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002513 // Iterate over the region R and propagate the domain constrains from the
2514 // predecessors to the current node. In contrast to the
2515 // buildDomainsWithBranchConstraints function, this one will pull the domain
2516 // information from the predecessors instead of pushing it to the successors.
2517 // Additionally, we assume the domains to be already present in the domain
2518 // map here. However, we iterate again in reverse post order so we know all
2519 // predecessors have been visited before a block or non-affine subregion is
2520 // visited.
2521
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002522 ReversePostOrderTraversal<Region *> RTraversal(R);
2523 for (auto *RN : RTraversal) {
2524
2525 // Recurse for affine subregions but go on for basic blocks and non-affine
2526 // subregions.
2527 if (RN->isSubRegion()) {
2528 Region *SubRegion = RN->getNodeAs<Region>();
2529 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002530 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002531 continue;
2532 }
2533 }
2534
2535 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002536 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002537 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002538
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002539 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfert642594a2016-04-04 07:57:39 +00002540 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, SD, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002541 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002542 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002543
Johannes Doerfert642594a2016-04-04 07:57:39 +00002544 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002545 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002546 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002547
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002548 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002549 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002550 IsOptimized = true;
2551 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002552 addAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2553 AS_RESTRICTION);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002554 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002555 }
2556}
2557
2558/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2559/// is incremented by one and all other dimensions are equal, e.g.,
2560/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2561/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2562static __isl_give isl_map *
2563createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2564 auto *MapSpace = isl_space_map_from_set(SetSpace);
2565 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2566 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2567 if (u != Dim)
2568 NextIterationMap =
2569 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2570 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2571 C = isl_constraint_set_constant_si(C, 1);
2572 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2573 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2574 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2575 return NextIterationMap;
2576}
2577
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002578void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002579 int LoopDepth = getRelativeLoopDepth(L);
2580 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002581
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002582 BasicBlock *HeaderBB = L->getHeader();
2583 assert(DomainMap.count(HeaderBB));
2584 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002585
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002586 isl_map *NextIterationMap =
2587 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002588
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002589 isl_set *UnionBackedgeCondition =
2590 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002591
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002592 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2593 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002594
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002595 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002596
2597 // If the latch is only reachable via error statements we skip it.
2598 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2599 if (!LatchBBDom)
2600 continue;
2601
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002602 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002603
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002604 TerminatorInst *TI = LatchBB->getTerminator();
2605 BranchInst *BI = dyn_cast<BranchInst>(TI);
2606 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002607 BackedgeCondition = isl_set_copy(LatchBBDom);
2608 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002609 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002610 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002611 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002612
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002613 // Free the non back edge condition set as we do not need it.
2614 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002615
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002616 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002617 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002618
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002619 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2620 assert(LatchLoopDepth >= LoopDepth);
2621 BackedgeCondition =
2622 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2623 LatchLoopDepth - LoopDepth);
2624 UnionBackedgeCondition =
2625 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002626 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002627
2628 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2629 for (int i = 0; i < LoopDepth; i++)
2630 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2631
2632 isl_set *UnionBackedgeConditionComplement =
2633 isl_set_complement(UnionBackedgeCondition);
2634 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2635 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2636 UnionBackedgeConditionComplement =
2637 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2638 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2639 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2640
2641 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2642 HeaderBBDom = Parts.second;
2643
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002644 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2645 // the bounded assumptions to the context as they are already implied by the
2646 // <nsw> tag.
2647 if (Affinator.hasNSWAddRecForLoop(L)) {
2648 isl_set_free(Parts.first);
2649 return;
2650 }
2651
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002652 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002653 addAssumption(INFINITELOOP, UnboundedCtx,
2654 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002655}
2656
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002657void Scop::buildAliasChecks(AliasAnalysis &AA) {
2658 if (!PollyUseRuntimeAliasChecks)
2659 return;
2660
2661 if (buildAliasGroups(AA))
2662 return;
2663
2664 // If a problem occurs while building the alias groups we need to delete
2665 // this SCoP and pretend it wasn't valid in the first place. To this end
2666 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002667 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002668
2669 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2670 << " could not be created as the number of parameters involved "
2671 "is too high. The SCoP will be "
2672 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2673 "the maximal number of parameters but be advised that the "
2674 "compile time might increase exponentially.\n\n");
2675}
2676
Johannes Doerfert9143d672014-09-27 11:02:39 +00002677bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002678 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002679 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002680 // for all memory accesses inside the SCoP.
2681 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002682 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002683 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002684 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002685 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002686 // if their access domains intersect, otherwise they are in different
2687 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002688 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002689 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002690 // and maximal accesses to each array of a group in read only and non
2691 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002692 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2693
2694 AliasSetTracker AST(AA);
2695
2696 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002697 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002698 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002699
2700 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002701 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002702 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2703 isl_set_free(StmtDomain);
2704 if (StmtDomainEmpty)
2705 continue;
2706
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002707 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002708 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002709 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002710 if (!MA->isRead())
2711 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002712 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002713 if (MA->isRead() && isa<MemTransferInst>(Acc))
2714 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002715 else
2716 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002717 AST.add(Acc);
2718 }
2719 }
2720
2721 SmallVector<AliasGroupTy, 4> AliasGroups;
2722 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002723 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002724 continue;
2725 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002726 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002727 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002728 if (AG.size() < 2)
2729 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002730 AliasGroups.push_back(std::move(AG));
2731 }
2732
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002733 // Split the alias groups based on their domain.
2734 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2735 AliasGroupTy NewAG;
2736 AliasGroupTy &AG = AliasGroups[u];
2737 AliasGroupTy::iterator AGI = AG.begin();
2738 isl_set *AGDomain = getAccessDomain(*AGI);
2739 while (AGI != AG.end()) {
2740 MemoryAccess *MA = *AGI;
2741 isl_set *MADomain = getAccessDomain(MA);
2742 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2743 NewAG.push_back(MA);
2744 AGI = AG.erase(AGI);
2745 isl_set_free(MADomain);
2746 } else {
2747 AGDomain = isl_set_union(AGDomain, MADomain);
2748 AGI++;
2749 }
2750 }
2751 if (NewAG.size() > 1)
2752 AliasGroups.push_back(std::move(NewAG));
2753 isl_set_free(AGDomain);
2754 }
2755
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002756 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002757 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002758 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2759 for (AliasGroupTy &AG : AliasGroups) {
2760 NonReadOnlyBaseValues.clear();
2761 ReadOnlyPairs.clear();
2762
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002763 if (AG.size() < 2) {
2764 AG.clear();
2765 continue;
2766 }
2767
Johannes Doerfert13771732014-10-01 12:40:46 +00002768 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002769 emitOptimizationRemarkAnalysis(
2770 F.getContext(), DEBUG_TYPE, F,
2771 (*II)->getAccessInstruction()->getDebugLoc(),
2772 "Possibly aliasing pointer, use restrict keyword.");
2773
Johannes Doerfert13771732014-10-01 12:40:46 +00002774 Value *BaseAddr = (*II)->getBaseAddr();
2775 if (HasWriteAccess.count(BaseAddr)) {
2776 NonReadOnlyBaseValues.insert(BaseAddr);
2777 II++;
2778 } else {
2779 ReadOnlyPairs[BaseAddr].insert(*II);
2780 II = AG.erase(II);
2781 }
2782 }
2783
2784 // If we don't have read only pointers check if there are at least two
2785 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002786 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002787 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002788 continue;
2789 }
2790
2791 // If we don't have non read only pointers clear the alias group.
2792 if (NonReadOnlyBaseValues.empty()) {
2793 AG.clear();
2794 continue;
2795 }
2796
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002797 // Check if we have non-affine accesses left, if so bail out as we cannot
2798 // generate a good access range yet.
2799 for (auto *MA : AG)
2800 if (!MA->isAffine()) {
2801 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2802 return false;
2803 }
2804 for (auto &ReadOnlyPair : ReadOnlyPairs)
2805 for (auto *MA : ReadOnlyPair.second)
2806 if (!MA->isAffine()) {
2807 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2808 return false;
2809 }
2810
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002811 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002812 MinMaxAliasGroups.emplace_back();
2813 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2814 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2815 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2816 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002817
2818 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002819
2820 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002821 for (MemoryAccess *MA : AG)
2822 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002823
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002824 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2825 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002826
2827 // Bail out if the number of values we need to compare is too large.
2828 // This is important as the number of comparisions grows quadratically with
2829 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002830 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2831 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002832 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002833
2834 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002835 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002836 Accesses = isl_union_map_empty(getParamSpace());
2837
2838 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2839 for (MemoryAccess *MA : ReadOnlyPair.second)
2840 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2841
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002842 Valid =
2843 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002844
2845 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002846 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002847 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002848
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002849 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002850}
2851
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002852/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002853static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002854 // Start with the smallest loop containing the entry and expand that
2855 // loop until it contains all blocks in the region. If there is a loop
2856 // containing all blocks in the region check if it is itself contained
2857 // and if so take the parent loop as it will be the smallest containing
2858 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002859 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002860 while (L) {
2861 bool AllContained = true;
2862 for (auto *BB : R.blocks())
2863 AllContained &= L->contains(BB);
2864 if (AllContained)
2865 break;
2866 L = L->getParentLoop();
2867 }
2868
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002869 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2870}
2871
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002872static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2873 ScopDetection &SD) {
2874
2875 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2876
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002877 unsigned MinLD = INT_MAX, MaxLD = 0;
2878 for (BasicBlock *BB : R.blocks()) {
2879 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002880 if (!R.contains(L))
2881 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002882 if (BoxedLoops && BoxedLoops->count(L))
2883 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002884 unsigned LD = L->getLoopDepth();
2885 MinLD = std::min(MinLD, LD);
2886 MaxLD = std::max(MaxLD, LD);
2887 }
2888 }
2889
2890 // Handle the case that there is no loop in the SCoP first.
2891 if (MaxLD == 0)
2892 return 1;
2893
2894 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2895 assert(MaxLD >= MinLD &&
2896 "Maximal loop depth was smaller than mininaml loop depth?");
2897 return MaxLD - MinLD + 1;
2898}
2899
Michael Kruse09eb4452016-03-03 22:10:47 +00002900Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
2901 unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002902 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002903 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002904 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
2905 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
2906 InvalidContext(nullptr), Schedule(nullptr) {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002907 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00002908 buildContext();
2909}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002910
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002911void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002912 DominatorTree &DT, LoopInfo &LI) {
2913 addUserAssumptions(AC, DT, LI);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002914 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002915
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002916 if (!buildDomains(&R, SD, DT, LI))
2917 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002918
Michael Krusecac948e2015-10-02 13:53:07 +00002919 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002920 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002921 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00002922 if (Stmts.empty())
2923 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002924
Michael Krusecac948e2015-10-02 13:53:07 +00002925 // The ScopStmts now have enough information to initialize themselves.
2926 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002927 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00002928
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002929 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002930
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002931 if (!hasFeasibleRuntimeContext())
Tobias Grosser8286b832015-11-02 11:29:32 +00002932 return;
2933
2934 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002935 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002936 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002937 addUserContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002938 addWrappingContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002939 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002940 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002941
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002942 hoistInvariantLoads(SD);
Tobias Grosser0865e7752016-02-29 07:29:42 +00002943 verifyInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002944 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002945}
2946
2947Scop::~Scop() {
2948 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002949 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002950 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002951 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002952
Johannes Doerfert96425c22015-08-30 21:13:53 +00002953 for (auto It : DomainMap)
2954 isl_set_free(It.second);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002955 for (auto It : ErrorDomainCtxMap)
2956 isl_set_free(It.second);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002957
Johannes Doerfertb164c792014-09-18 11:17:17 +00002958 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002959 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002960 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002961 isl_pw_multi_aff_free(MMA.first);
2962 isl_pw_multi_aff_free(MMA.second);
2963 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002964 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002965 isl_pw_multi_aff_free(MMA.first);
2966 isl_pw_multi_aff_free(MMA.second);
2967 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002968 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002969
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002970 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002971 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002972
2973 // Explicitly release all Scop objects and the underlying isl objects before
2974 // we relase the isl context.
2975 Stmts.clear();
2976 ScopArrayInfoMap.clear();
2977 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00002978}
2979
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002980void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00002981 // Check all array accesses for each base pointer and find a (virtual) element
2982 // size for the base pointer that divides all access functions.
2983 for (auto &Stmt : *this)
2984 for (auto *Access : Stmt) {
2985 if (!Access->isArrayKind())
2986 continue;
2987 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
2988 ScopArrayInfo::MK_Array)];
2989 if (SAI->getNumberOfDimensions() != 1)
2990 continue;
2991 unsigned DivisibleSize = SAI->getElemSizeInBytes();
2992 auto *Subscript = Access->getSubscript(0);
2993 while (!isDivisible(Subscript, DivisibleSize, *SE))
2994 DivisibleSize /= 2;
2995 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
2996 SAI->updateElementType(Ty);
2997 }
2998
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002999 for (auto &Stmt : *this)
3000 for (auto &Access : Stmt)
3001 Access->updateDimensionality();
3002}
3003
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003004void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
3005 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003006 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3007 ScopStmt &Stmt = *StmtIt;
Michael Kruse7b5caa42016-02-24 22:08:28 +00003008 RegionNode *RN = Stmt.getRegionNode();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003009
Johannes Doerferteca9e892015-11-03 16:54:49 +00003010 bool RemoveStmt = StmtIt->isEmpty();
3011 if (!RemoveStmt)
Michael Kruse375cb5f2016-02-24 22:08:24 +00003012 RemoveStmt = isl_set_is_empty(DomainMap[Stmt.getEntryBlock()]);
Johannes Doerferteca9e892015-11-03 16:54:49 +00003013 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003014 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003015
Johannes Doerferteca9e892015-11-03 16:54:49 +00003016 // Remove read only statements only after invariant loop hoisting.
3017 if (!RemoveStmt && !RemoveIgnoredStmts) {
3018 bool OnlyRead = true;
3019 for (MemoryAccess *MA : Stmt) {
3020 if (MA->isRead())
3021 continue;
3022
3023 OnlyRead = false;
3024 break;
3025 }
3026
3027 RemoveStmt = OnlyRead;
3028 }
3029
3030 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00003031 // Remove the statement because it is unnecessary.
3032 if (Stmt.isRegionStmt())
3033 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3034 StmtMap.erase(BB);
3035 else
3036 StmtMap.erase(Stmt.getBasicBlock());
3037
3038 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003039 continue;
3040 }
3041
Michael Krusecac948e2015-10-02 13:53:07 +00003042 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003043 }
3044}
3045
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003046const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
3047 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3048 if (!LInst)
3049 return nullptr;
3050
3051 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3052 LInst = cast<LoadInst>(Rep);
3053
Johannes Doerfert96e54712016-02-07 17:30:13 +00003054 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003055 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003056 for (auto &IAClass : InvariantEquivClasses) {
3057 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
3058 continue;
3059
3060 auto &MAs = std::get<1>(IAClass);
3061 for (auto *MA : MAs)
3062 if (MA->getAccessInstruction() == Val)
3063 return &IAClass;
3064 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003065
3066 return nullptr;
3067}
3068
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003069isl_set *Scop::getErrorCtxReachingStmt(ScopStmt &Stmt) {
3070 auto *BB = Stmt.getEntryBlock();
3071 return isl_set_copy(ErrorDomainCtxMap.lookup(BB));
3072}
3073
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003074void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
3075
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003076 // Get the context under which the statement is executed but remove the error
3077 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003078 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003079 if (auto *ErrorCtx = getErrorCtxReachingStmt(Stmt))
3080 DomainCtx = isl_set_subtract(DomainCtx, ErrorCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003081 DomainCtx = isl_set_remove_redundancies(DomainCtx);
3082 DomainCtx = isl_set_detect_equalities(DomainCtx);
3083 DomainCtx = isl_set_coalesce(DomainCtx);
3084
3085 // Project out all parameters that relate to loads in the statement. Otherwise
3086 // we could have cyclic dependences on the constraints under which the
3087 // hoisted loads are executed and we could not determine an order in which to
3088 // pre-load them. This happens because not only lower bounds are part of the
3089 // domain but also upper bounds.
3090 for (MemoryAccess *MA : InvMAs) {
3091 Instruction *AccInst = MA->getAccessInstruction();
3092 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003093 SetVector<Value *> Values;
3094 for (const SCEV *Parameter : Parameters) {
3095 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003096 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003097 if (!Values.count(AccInst))
3098 continue;
3099
3100 if (isl_id *ParamId = getIdForParam(Parameter)) {
3101 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3102 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3103 isl_id_free(ParamId);
3104 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003105 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003106 }
3107 }
3108
3109 for (MemoryAccess *MA : InvMAs) {
3110 // Check for another invariant access that accesses the same location as
3111 // MA and if found consolidate them. Otherwise create a new equivalence
3112 // class at the end of InvariantEquivClasses.
3113 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003114 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003115 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3116
3117 bool Consolidated = false;
3118 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003119 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003120 continue;
3121
Johannes Doerfertdf880232016-03-03 12:26:58 +00003122 // If the pointer and the type is equal check if the access function wrt.
3123 // to the domain is equal too. It can happen that the domain fixes
3124 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003125 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003126 // create a new invariant load equivalence class.
3127 auto &MAs = std::get<1>(IAClass);
3128 if (!MAs.empty()) {
3129 auto *LastMA = MAs.front();
3130
3131 auto *AR = isl_map_range(MA->getAccessRelation());
3132 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3133 bool SameAR = isl_set_is_equal(AR, LastAR);
3134 isl_set_free(AR);
3135 isl_set_free(LastAR);
3136
3137 if (!SameAR)
3138 continue;
3139 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003140
3141 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003142 MAs.push_front(MA);
3143
Johannes Doerfertdf880232016-03-03 12:26:58 +00003144 Consolidated = true;
3145
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003146 // Unify the execution context of the class and this statement.
3147 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003148 if (IAClassDomainCtx)
3149 IAClassDomainCtx = isl_set_coalesce(
3150 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
3151 else
3152 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003153 break;
3154 }
3155
3156 if (Consolidated)
3157 continue;
3158
3159 // If we did not consolidate MA, thus did not find an equivalence class
3160 // for it, we create a new one.
3161 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00003162 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003163 }
3164
3165 isl_set_free(DomainCtx);
3166}
3167
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003168bool Scop::isHoistableAccess(MemoryAccess *Access,
3169 __isl_keep isl_union_map *Writes) {
3170 // TODO: Loads that are not loop carried, hence are in a statement with
3171 // zero iterators, are by construction invariant, though we
3172 // currently "hoist" them anyway. This is necessary because we allow
3173 // them to be treated as parameters (e.g., in conditions) and our code
3174 // generation would otherwise use the old value.
3175
3176 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003177 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003178
3179 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3180 return false;
3181
3182 // Skip accesses that have an invariant base pointer which is defined but
3183 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3184 // returns a pointer that is used as a base address. However, as we want
3185 // to hoist indirect pointers, we allow the base pointer to be defined in
3186 // the region if it is also a memory access. Each ScopArrayInfo object
3187 // that has a base pointer origin has a base pointer that is loaded and
3188 // that it is invariant, thus it will be hoisted too. However, if there is
3189 // no base pointer origin we check that the base pointer is defined
3190 // outside the region.
3191 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003192 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3193 if (SAI->getBasePtrOriginSAI()) {
3194 assert(BasePtrInst && R.contains(BasePtrInst));
3195 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003196 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003197 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003198 assert(BasePtrStmt);
3199 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3200 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3201 return false;
3202 } else if (BasePtrInst && R.contains(BasePtrInst))
3203 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003204
3205 // Skip accesses in non-affine subregions as they might not be executed
3206 // under the same condition as the entry of the non-affine subregion.
3207 if (BB != Access->getAccessInstruction()->getParent())
3208 return false;
3209
3210 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003211 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003212
3213 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3214 Stmt.getNumIterators())) {
3215 isl_map_free(AccessRelation);
3216 return false;
3217 }
3218
3219 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3220 isl_set *AccessRange = isl_map_range(AccessRelation);
3221
3222 isl_union_map *Written = isl_union_map_intersect_range(
3223 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3224 bool IsWritten = !isl_union_map_is_empty(Written);
3225 isl_union_map_free(Written);
3226
3227 if (IsWritten)
3228 return false;
3229
3230 return true;
3231}
3232
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003233void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003234 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3235 for (LoadInst *LI : RIL) {
3236 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003237 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003238 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003239 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3240 return;
3241 }
3242 }
3243}
3244
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003245void Scop::hoistInvariantLoads(ScopDetection &SD) {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003246 if (!PollyInvariantLoadHoisting)
3247 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003248
Tobias Grosser0865e7752016-02-29 07:29:42 +00003249 isl_union_map *Writes = getWrites();
3250 for (ScopStmt &Stmt : *this) {
3251 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003252
Tobias Grosser0865e7752016-02-29 07:29:42 +00003253 for (MemoryAccess *Access : Stmt)
3254 if (isHoistableAccess(Access, Writes))
3255 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003256
Tobias Grosser0865e7752016-02-29 07:29:42 +00003257 // We inserted invariant accesses always in the front but need them to be
3258 // sorted in a "natural order". The statements are already sorted in
3259 // reverse post order and that suffices for the accesses too. The reason
3260 // we require an order in the first place is the dependences between
3261 // invariant loads that can be caused by indirect loads.
3262 InvariantAccesses.reverse();
3263
3264 // Transfer the memory access from the statement to the SCoP.
3265 Stmt.removeMemoryAccesses(InvariantAccesses);
3266 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003267 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003268 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003269}
3270
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003271const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003272Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003273 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003274 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003275 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003276 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003277 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003278 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003279 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003280 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003281 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003282 // In case of mismatching array sizes, we bail out by setting the run-time
3283 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003284 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003285 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003286 }
Tobias Grosserab671442015-05-23 05:58:27 +00003287 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003288}
3289
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003290const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003291 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003292 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003293 assert(SAI && "No ScopArrayInfo available for this base pointer");
3294 return SAI;
3295}
3296
Tobias Grosser74394f02013-01-14 22:40:23 +00003297std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003298
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003299std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003300 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003301 return stringFromIslObj(AssumedContext);
3302}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003303
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003304std::string Scop::getInvalidContextStr() const {
3305 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003306}
Tobias Grosser75805372011-04-29 06:27:02 +00003307
3308std::string Scop::getNameStr() const {
3309 std::string ExitName, EntryName;
3310 raw_string_ostream ExitStr(ExitName);
3311 raw_string_ostream EntryStr(EntryName);
3312
Tobias Grosserf240b482014-01-09 10:42:15 +00003313 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003314 EntryStr.str();
3315
3316 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003317 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003318 ExitStr.str();
3319 } else
3320 ExitName = "FunctionExit";
3321
3322 return EntryName + "---" + ExitName;
3323}
3324
Tobias Grosser74394f02013-01-14 22:40:23 +00003325__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003326__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003327 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003328}
3329
Tobias Grossere86109f2013-10-29 21:05:49 +00003330__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003331 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003332 return isl_set_copy(AssumedContext);
3333}
3334
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003335bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003336 auto *PositiveContext = getAssumedContext();
3337 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3338 bool IsFeasible = !isl_set_is_empty(PositiveContext);
3339 isl_set_free(PositiveContext);
3340 if (!IsFeasible)
3341 return false;
3342
3343 auto *NegativeContext = getInvalidContext();
3344 auto *DomainContext = isl_union_set_params(getDomains());
3345 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
3346 isl_set_free(NegativeContext);
3347 isl_set_free(DomainContext);
3348
Johannes Doerfert43788c52015-08-20 05:58:56 +00003349 return IsFeasible;
3350}
3351
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003352static std::string toString(AssumptionKind Kind) {
3353 switch (Kind) {
3354 case ALIASING:
3355 return "No-aliasing";
3356 case INBOUNDS:
3357 return "Inbounds";
3358 case WRAPPING:
3359 return "No-overflows";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003360 case COMPLEXITY:
3361 return "Low complexity";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003362 case ERRORBLOCK:
3363 return "No-error";
3364 case INFINITELOOP:
3365 return "Finite loop";
3366 case INVARIANTLOAD:
3367 return "Invariant load";
3368 case DELINEARIZATION:
3369 return "Delinearization";
3370 }
3371 llvm_unreachable("Unknown AssumptionKind!");
3372}
3373
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003374bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3375 DebugLoc Loc, AssumptionSign Sign) {
3376 if (Sign == AS_ASSUMPTION) {
3377 if (isl_set_is_subset(Context, Set))
3378 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003379
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003380 if (isl_set_is_subset(AssumedContext, Set))
3381 return false;
3382 } else {
3383 if (isl_set_is_disjoint(Set, Context))
3384 return false;
3385
3386 if (isl_set_is_subset(Set, InvalidContext))
3387 return false;
3388 }
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003389
3390 auto &F = *getRegion().getEntry()->getParent();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003391 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3392 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003393 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003394 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003395}
3396
3397void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003398 DebugLoc Loc, AssumptionSign Sign) {
3399 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3400 isl_set_free(Set);
3401 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003402 }
3403
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003404 if (Sign == AS_ASSUMPTION) {
3405 AssumedContext = isl_set_intersect(AssumedContext, Set);
3406 AssumedContext = isl_set_coalesce(AssumedContext);
3407 } else {
3408 InvalidContext = isl_set_union(InvalidContext, Set);
3409 InvalidContext = isl_set_coalesce(InvalidContext);
3410 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003411}
3412
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003413void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003414 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003415}
3416
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003417__isl_give isl_set *Scop::getInvalidContext() const {
3418 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003419}
3420
Tobias Grosser75805372011-04-29 06:27:02 +00003421void Scop::printContext(raw_ostream &OS) const {
3422 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003423 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003424
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003425 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003426 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003427
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003428 OS.indent(4) << "Invalid Context:\n";
3429 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003430
Tobias Grosser083d3d32014-06-28 08:59:45 +00003431 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003432 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003433 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3434 }
Tobias Grosser75805372011-04-29 06:27:02 +00003435}
3436
Johannes Doerfertb164c792014-09-18 11:17:17 +00003437void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003438 int noOfGroups = 0;
3439 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003440 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003441 noOfGroups += 1;
3442 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003443 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003444 }
3445
Tobias Grosserbb853c22015-07-25 12:31:03 +00003446 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003447 if (MinMaxAliasGroups.empty()) {
3448 OS.indent(8) << "n/a\n";
3449 return;
3450 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003451
Tobias Grosserbb853c22015-07-25 12:31:03 +00003452 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003453
3454 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003455 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003456 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003457 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003458 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3459 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003460 }
3461 OS << " ]]\n";
3462 }
3463
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003464 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003465 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003466 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003467 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003468 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3469 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003470 }
3471 OS << " ]]\n";
3472 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003473 }
3474}
3475
Tobias Grosser75805372011-04-29 06:27:02 +00003476void Scop::printStatements(raw_ostream &OS) const {
3477 OS << "Statements {\n";
3478
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003479 for (const ScopStmt &Stmt : *this)
3480 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003481
3482 OS.indent(4) << "}\n";
3483}
3484
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003485void Scop::printArrayInfo(raw_ostream &OS) const {
3486 OS << "Arrays {\n";
3487
Tobias Grosserab671442015-05-23 05:58:27 +00003488 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003489 Array.second->print(OS);
3490
3491 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003492
3493 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3494
3495 for (auto &Array : arrays())
3496 Array.second->print(OS, /* SizeAsPwAff */ true);
3497
3498 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003499}
3500
Tobias Grosser75805372011-04-29 06:27:02 +00003501void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003502 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3503 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003504 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003505 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003506 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003507 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003508 const auto &MAs = std::get<1>(IAClass);
3509 if (MAs.empty()) {
3510 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003511 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003512 MAs.front()->print(OS);
3513 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003514 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003515 }
3516 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003517 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003518 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003519 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003520 printStatements(OS.indent(4));
3521}
3522
3523void Scop::dump() const { print(dbgs()); }
3524
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003525isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003526
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003527__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003528 // First try to use the SCEVAffinator to generate a piecewise defined
3529 // affine function from @p E in the context of @p BB. If that tasks becomes to
3530 // complex the affinator might return a nullptr. In such a case we invalidate
3531 // the SCoP and return a dummy value. This way we do not need to add error
3532 // handling cdoe to all users of this function.
3533 auto *PWA = Affinator.getPwAff(E, BB);
3534 if (PWA)
3535 return PWA;
3536
3537 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3538 invalidate(COMPLEXITY, DL);
3539 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003540}
3541
Tobias Grosser808cd692015-07-14 09:33:13 +00003542__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003543 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003544
Tobias Grosser808cd692015-07-14 09:33:13 +00003545 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003546 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003547
3548 return Domain;
3549}
3550
Tobias Grossere5a35142015-11-12 14:07:09 +00003551__isl_give isl_union_map *
3552Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3553 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003554
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003555 for (ScopStmt &Stmt : *this) {
3556 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003557 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003558 continue;
3559
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003560 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003561 isl_map *AccessDomain = MA->getAccessRelation();
3562 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003563 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003564 }
3565 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003566 return isl_union_map_coalesce(Accesses);
3567}
3568
3569__isl_give isl_union_map *Scop::getMustWrites() {
3570 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003571}
3572
3573__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003574 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003575}
3576
Tobias Grosser37eb4222014-02-20 21:43:54 +00003577__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003578 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003579}
3580
3581__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003582 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003583}
3584
Tobias Grosser2ac23382015-11-12 14:07:13 +00003585__isl_give isl_union_map *Scop::getAccesses() {
3586 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3587}
3588
Tobias Grosser808cd692015-07-14 09:33:13 +00003589__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003590 auto *Tree = getScheduleTree();
3591 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003592 isl_schedule_free(Tree);
3593 return S;
3594}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003595
Tobias Grosser808cd692015-07-14 09:33:13 +00003596__isl_give isl_schedule *Scop::getScheduleTree() const {
3597 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3598 getDomains());
3599}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003600
Tobias Grosser808cd692015-07-14 09:33:13 +00003601void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3602 auto *S = isl_schedule_from_domain(getDomains());
3603 S = isl_schedule_insert_partial_schedule(
3604 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3605 isl_schedule_free(Schedule);
3606 Schedule = S;
3607}
3608
3609void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3610 isl_schedule_free(Schedule);
3611 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003612}
3613
3614bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3615 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003616 for (ScopStmt &Stmt : *this) {
3617 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003618 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3619 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3620
3621 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3622 isl_union_set_free(StmtDomain);
3623 isl_union_set_free(NewStmtDomain);
3624 continue;
3625 }
3626
3627 Changed = true;
3628
3629 isl_union_set_free(StmtDomain);
3630 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3631
3632 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003633 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003634 isl_union_set_free(NewStmtDomain);
3635 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003636 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003637 }
3638 isl_union_set_free(Domain);
3639 return Changed;
3640}
3641
Tobias Grosser75805372011-04-29 06:27:02 +00003642ScalarEvolution *Scop::getSE() const { return SE; }
3643
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003644bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003645 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse6f7721f2016-02-24 22:08:19 +00003646 ScopStmt *Stmt = getStmtFor(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003647
3648 // If there is no stmt, then it already has been removed.
3649 if (!Stmt)
3650 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003651
Johannes Doerfertf5673802015-10-01 23:48:18 +00003652 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003653 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003654 return true;
3655
3656 // Check for reachability via non-error blocks.
3657 if (!DomainMap.count(BB))
3658 return true;
3659
3660 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003661 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003662 return true;
3663
3664 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003665}
3666
Tobias Grosser808cd692015-07-14 09:33:13 +00003667struct MapToDimensionDataTy {
3668 int N;
3669 isl_union_pw_multi_aff *Res;
3670};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003671
Tobias Grosser808cd692015-07-14 09:33:13 +00003672// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003673// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003674//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003675// @param Set The input set.
3676// @param User->N The dimension to map to.
3677// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003678//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003679// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003680static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3681 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3682 int Dim;
3683 isl_space *Space;
3684 isl_pw_multi_aff *PMA;
3685
3686 Dim = isl_set_dim(Set, isl_dim_set);
3687 Space = isl_set_get_space(Set);
3688 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3689 Dim - Data->N);
3690 if (Data->N > 1)
3691 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3692 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3693
3694 isl_set_free(Set);
3695
3696 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003697}
3698
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003699// @brief Create an isl_multi_union_aff that defines an identity mapping
3700// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003701//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003702// # Example:
3703//
3704// Domain: { A[i,j]; B[i,j,k] }
3705// N: 1
3706//
3707// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3708//
3709// @param USet A union set describing the elements for which to generate a
3710// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003711// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003712// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003713static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003714mapToDimension(__isl_take isl_union_set *USet, int N) {
3715 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003716 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003717 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003718
Tobias Grosser808cd692015-07-14 09:33:13 +00003719 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003720
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003721 auto *Space = isl_union_set_get_space(USet);
3722 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003723
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003724 Data = {N, PwAff};
3725
3726 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003727 (void)Res;
3728
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003729 assert(Res == isl_stat_ok);
3730
3731 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003732 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3733}
3734
Tobias Grosser316b5b22015-11-11 19:28:14 +00003735void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003736 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003737 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003738 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003739 StmtMap[BB] = Stmt;
3740 } else {
3741 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003742 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003743 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003744 for (BasicBlock *BB : R->blocks())
3745 StmtMap[BB] = Stmt;
3746 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003747}
3748
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003749void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003750 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003751 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003752 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00003753 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3754 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003755}
3756
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003757/// To generate a schedule for the elements in a Region we traverse the Region
3758/// in reverse-post-order and add the contained RegionNodes in traversal order
3759/// to the schedule of the loop that is currently at the top of the LoopStack.
3760/// For loop-free codes, this results in a correct sequential ordering.
3761///
3762/// Example:
3763/// bb1(0)
3764/// / \.
3765/// bb2(1) bb3(2)
3766/// \ / \.
3767/// bb4(3) bb5(4)
3768/// \ /
3769/// bb6(5)
3770///
3771/// Including loops requires additional processing. Whenever a loop header is
3772/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3773/// from an empty schedule, we first process all RegionNodes that are within
3774/// this loop and complete the sequential schedule at this loop-level before
3775/// processing about any other nodes. To implement this
3776/// loop-nodes-first-processing, the reverse post-order traversal is
3777/// insufficient. Hence, we additionally check if the traversal yields
3778/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3779/// These region-nodes are then queue and only traverse after the all nodes
3780/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003781void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3782 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003783 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3784
3785 ReversePostOrderTraversal<Region *> RTraversal(R);
3786 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3787 std::deque<RegionNode *> DelayList;
3788 bool LastRNWaiting = false;
3789
3790 // Iterate over the region @p R in reverse post-order but queue
3791 // sub-regions/blocks iff they are not part of the last encountered but not
3792 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3793 // that we queued the last sub-region/block from the reverse post-order
3794 // iterator. If it is set we have to explore the next sub-region/block from
3795 // the iterator (if any) to guarantee progress. If it is not set we first try
3796 // the next queued sub-region/blocks.
3797 while (!WorkList.empty() || !DelayList.empty()) {
3798 RegionNode *RN;
3799
3800 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3801 RN = WorkList.front();
3802 WorkList.pop_front();
3803 LastRNWaiting = false;
3804 } else {
3805 RN = DelayList.front();
3806 DelayList.pop_front();
3807 }
3808
3809 Loop *L = getRegionNodeLoop(RN, LI);
3810 if (!getRegion().contains(L))
3811 L = OuterScopLoop;
3812
Tobias Grosser151ae322016-04-03 19:36:52 +00003813 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003814 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00003815 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003816 LastRNWaiting = true;
3817 DelayList.push_back(RN);
3818 continue;
3819 }
3820 LoopStack.push_back({L, nullptr, 0});
3821 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003822 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003823 }
3824
3825 return;
3826}
3827
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003828void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003829 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00003830
Tobias Grosser8362c262016-01-06 15:30:06 +00003831 if (RN->isSubRegion()) {
3832 auto *LocalRegion = RN->getNodeAs<Region>();
3833 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003834 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00003835 return;
3836 }
3837 }
Michael Kruse046dde42015-08-10 13:01:57 +00003838
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003839 auto &LoopData = LoopStack.back();
3840 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003841
Michael Kruse6f7721f2016-02-24 22:08:19 +00003842 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003843 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3844 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003845 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003846 }
3847
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003848 // Check if we just processed the last node in this loop. If we did, finalize
3849 // the loop by:
3850 //
3851 // - adding new schedule dimensions
3852 // - folding the resulting schedule into the parent loop schedule
3853 // - dropping the loop schedule from the LoopStack.
3854 //
3855 // Then continue to check surrounding loops, which might also have been
3856 // completed by this node.
3857 while (LoopData.L &&
3858 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003859 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003860 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003861
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003862 LoopStack.pop_back();
3863 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003864
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003865 if (Schedule) {
3866 auto *Domain = isl_schedule_get_domain(Schedule);
3867 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3868 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3869 NextLoopData.Schedule =
3870 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003871 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003872
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003873 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3874 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003875 }
Tobias Grosser75805372011-04-29 06:27:02 +00003876}
3877
Michael Kruse6f7721f2016-02-24 22:08:19 +00003878ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003879 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003880 if (StmtMapIt == StmtMap.end())
3881 return nullptr;
3882 return StmtMapIt->second;
3883}
3884
Michael Kruse6f7721f2016-02-24 22:08:19 +00003885ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
3886 if (RN->isSubRegion())
3887 return getStmtFor(RN->getNodeAs<Region>());
3888 return getStmtFor(RN->getNodeAs<BasicBlock>());
3889}
3890
3891ScopStmt *Scop::getStmtFor(Region *R) const {
3892 ScopStmt *Stmt = getStmtFor(R->getEntry());
3893 assert(!Stmt || Stmt->getRegion() == R);
3894 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00003895}
3896
Johannes Doerfert96425c22015-08-30 21:13:53 +00003897int Scop::getRelativeLoopDepth(const Loop *L) const {
3898 Loop *OuterLoop =
3899 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3900 if (!OuterLoop)
3901 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003902 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3903}
3904
Michael Krused868b5d2015-09-10 15:25:24 +00003905void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003906 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003907
3908 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3909 // true, are not modeled as ordinary PHI nodes as they are not part of the
3910 // region. However, we model the operands in the predecessor blocks that are
3911 // part of the region as regular scalar accesses.
3912
3913 // If we can synthesize a PHI we can skip it, however only if it is in
3914 // the region. If it is not it can only be in the exit block of the region.
3915 // In this case we model the operands but not the PHI itself.
Michael Krusec7e0d9c2016-03-01 21:44:06 +00003916 auto *Scope = LI->getLoopFor(PHI->getParent());
3917 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R, Scope))
Michael Kruse7bf39442015-09-10 12:46:52 +00003918 return;
3919
3920 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3921 // detection. Hence, the PHI is a load of a new memory location in which the
3922 // incoming value was written at the end of the incoming basic block.
3923 bool OnlyNonAffineSubRegionOperands = true;
3924 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3925 Value *Op = PHI->getIncomingValue(u);
3926 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3927
3928 // Do not build scalar dependences inside a non-affine subregion.
3929 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3930 continue;
3931
3932 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003933 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003934 }
3935
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003936 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3937 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003938 }
3939}
3940
Michael Kruse2e02d562016-02-06 09:19:40 +00003941void ScopInfo::buildScalarDependences(Instruction *Inst) {
3942 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00003943
Michael Kruse2e02d562016-02-06 09:19:40 +00003944 // Pull-in required operands.
3945 for (Use &Op : Inst->operands())
3946 ensureValueRead(Op.get(), Inst->getParent());
3947}
Michael Kruse7bf39442015-09-10 12:46:52 +00003948
Michael Kruse2e02d562016-02-06 09:19:40 +00003949void ScopInfo::buildEscapingDependences(Instruction *Inst) {
3950 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00003951
Michael Kruse2e02d562016-02-06 09:19:40 +00003952 // Check for uses of this instruction outside the scop. Because we do not
3953 // iterate over such instructions and therefore did not "ensure" the existence
3954 // of a write, we must determine such use here.
3955 for (Use &U : Inst->uses()) {
3956 Instruction *UI = dyn_cast<Instruction>(U.getUser());
3957 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00003958 continue;
3959
Michael Kruse2e02d562016-02-06 09:19:40 +00003960 BasicBlock *UseParent = getUseBlock(U);
3961 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00003962
Michael Kruse2e02d562016-02-06 09:19:40 +00003963 // An escaping value is either used by an instruction not within the scop,
3964 // or (when the scop region's exit needs to be simplified) by a PHI in the
3965 // scop's exit block. This is because region simplification before code
3966 // generation inserts new basic blocks before the PHI such that its incoming
3967 // blocks are not in the scop anymore.
3968 if (!R->contains(UseParent) ||
3969 (isa<PHINode>(UI) && UserParent == R->getExit() &&
3970 R->getExitingBlock())) {
3971 // At least one escaping use found.
3972 ensureValueWrite(Inst);
3973 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00003974 }
3975 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003976}
3977
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003978bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00003979 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003980 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3981 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00003982 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003983 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003984 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003985 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003986 const SCEVUnknown *BasePointer =
3987 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00003988 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00003989 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003990
Michael Kruse37d136e2016-02-26 16:08:24 +00003991 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
3992 auto *Src = BitCast->getOperand(0);
3993 auto *SrcTy = Src->getType();
3994 auto *DstTy = BitCast->getType();
3995 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3996 Address = Src;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003997 }
Michael Kruse37d136e2016-02-26 16:08:24 +00003998
3999 auto *GEP = dyn_cast<GetElementPtrInst>(Address);
4000 if (!GEP)
4001 return false;
4002
4003 std::vector<const SCEV *> Subscripts;
4004 std::vector<int> Sizes;
4005 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
4006 auto *BasePtr = GEP->getOperand(0);
4007
Tobias Grosser535afd82016-04-05 06:23:45 +00004008 if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
4009 BasePtr = BasePtrCast->getOperand(0);
4010
4011 // Check for identical base pointers to ensure that we do not miss index
4012 // offsets that have been added before this GEP is applied.
4013 if (BasePtr != BasePointer->getValue())
4014 return false;
4015
Michael Kruse37d136e2016-02-26 16:08:24 +00004016 std::vector<const SCEV *> SizesSCEV;
4017
4018 for (auto *Subscript : Subscripts) {
4019 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004020 if (!isAffineExpr(R, L, Subscript, *SE, nullptr, &AccessILS))
Michael Kruse37d136e2016-02-26 16:08:24 +00004021 return false;
4022
4023 for (LoadInst *LInst : AccessILS)
4024 if (!ScopRIL.count(LInst))
4025 return false;
4026 }
4027
4028 if (Sizes.empty())
4029 return false;
4030
4031 for (auto V : Sizes)
4032 SizesSCEV.push_back(SE->getSCEV(
4033 ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
4034
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004035 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004036 Subscripts, SizesSCEV, Val);
4037 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004038}
4039
4040bool ScopInfo::buildAccessMultiDimParam(
4041 MemAccInst Inst, Loop *L, Region *R,
4042 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004043 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse37d136e2016-02-26 16:08:24 +00004044 if (!PollyDelinearize)
4045 return false;
4046
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004047 Value *Address = Inst.getPointerOperand();
4048 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004049 Type *ElementType = Val->getType();
4050 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004051 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004052 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004053
4054 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4055 const SCEVUnknown *BasePointer =
4056 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4057
4058 assert(BasePointer && "Could not find base pointer");
4059 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00004060
Michael Kruse7bf39442015-09-10 12:46:52 +00004061 auto AccItr = InsnToMemAcc.find(Inst);
Michael Kruse37d136e2016-02-26 16:08:24 +00004062 if (AccItr == InsnToMemAcc.end())
4063 return false;
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004064
Michael Kruse37d136e2016-02-26 16:08:24 +00004065 std::vector<const SCEV *> Sizes(
4066 AccItr->second.Shape->DelinearizedSizes.begin(),
4067 AccItr->second.Shape->DelinearizedSizes.end());
4068 // Remove the element size. This information is already provided by the
4069 // ElementSize parameter. In case the element size of this access and the
4070 // element size used for delinearization differs the delinearization is
4071 // incorrect. Hence, we invalidate the scop.
4072 //
4073 // TODO: Handle delinearization with differing element sizes.
4074 auto DelinearizedSize =
4075 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
4076 Sizes.pop_back();
4077 if (ElementSize != DelinearizedSize)
4078 scop->invalidate(DELINEARIZATION, Inst->getDebugLoc());
4079
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004080 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, true,
Michael Kruse37d136e2016-02-26 16:08:24 +00004081 AccItr->second.DelinearizedSubscripts, Sizes, Val);
4082 return true;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004083}
4084
Johannes Doerfertcea61932016-02-21 19:13:19 +00004085bool ScopInfo::buildAccessMemIntrinsic(
4086 MemAccInst Inst, Loop *L, Region *R,
4087 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4088 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004089 auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
4090
4091 if (MemIntr == nullptr)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004092 return false;
4093
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004094 auto *LengthVal = SE->getSCEVAtScope(MemIntr->getLength(), L);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004095 assert(LengthVal);
4096
Johannes Doerferta7920982016-02-25 14:08:48 +00004097 // Check if the length val is actually affine or if we overapproximate it
4098 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004099 bool LengthIsAffine = isAffineExpr(R, L, LengthVal, *SE, nullptr, &AccessILS);
Johannes Doerferta7920982016-02-25 14:08:48 +00004100 for (LoadInst *LInst : AccessILS)
4101 if (!ScopRIL.count(LInst))
4102 LengthIsAffine = false;
4103 if (!LengthIsAffine)
4104 LengthVal = nullptr;
4105
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004106 auto *DestPtrVal = MemIntr->getDest();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004107 assert(DestPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004108
Johannes Doerfertcea61932016-02-21 19:13:19 +00004109 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
4110 assert(DestAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004111 // Ignore accesses to "NULL".
4112 // TODO: We could use this to optimize the region further, e.g., intersect
4113 // the context with
4114 // isl_set_complement(isl_set_params(getDomain()))
4115 // as we know it would be undefined to execute this instruction anyway.
4116 if (DestAccFunc->isZero())
4117 return true;
4118
Johannes Doerfertcea61932016-02-21 19:13:19 +00004119 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
4120 assert(DestPtrSCEV);
4121 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
4122 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
4123 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
4124 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
4125
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004126 auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
4127 if (!MemTrans)
Johannes Doerfertcea61932016-02-21 19:13:19 +00004128 return true;
4129
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004130 auto *SrcPtrVal = MemTrans->getSource();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004131 assert(SrcPtrVal);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004132
Johannes Doerfertcea61932016-02-21 19:13:19 +00004133 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
4134 assert(SrcAccFunc);
Johannes Doerfert733ea342016-03-24 13:50:04 +00004135 // Ignore accesses to "NULL".
4136 // TODO: See above TODO
4137 if (SrcAccFunc->isZero())
4138 return true;
4139
Johannes Doerfertcea61932016-02-21 19:13:19 +00004140 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
4141 assert(SrcPtrSCEV);
4142 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
4143 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
4144 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
4145 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
4146
4147 return true;
4148}
4149
Johannes Doerferta7920982016-02-25 14:08:48 +00004150bool ScopInfo::buildAccessCallInst(
4151 MemAccInst Inst, Loop *L, Region *R,
4152 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4153 const InvariantLoadsSetTy &ScopRIL) {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004154 auto *CI = dyn_cast_or_null<CallInst>(Inst);
4155
4156 if (CI == nullptr)
Johannes Doerferta7920982016-02-25 14:08:48 +00004157 return false;
4158
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004159 if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
Johannes Doerferta7920982016-02-25 14:08:48 +00004160 return true;
4161
4162 bool ReadOnly = false;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004163 auto *AF = SE->getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
4164 auto *CalledFunction = CI->getCalledFunction();
Johannes Doerferta7920982016-02-25 14:08:48 +00004165 switch (AA->getModRefBehavior(CalledFunction)) {
4166 case llvm::FMRB_UnknownModRefBehavior:
4167 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
4168 case llvm::FMRB_DoesNotAccessMemory:
4169 return true;
4170 case llvm::FMRB_OnlyReadsMemory:
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004171 GlobalReads.push_back(CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004172 return true;
4173 case llvm::FMRB_OnlyReadsArgumentPointees:
4174 ReadOnly = true;
4175 // Fall through
4176 case llvm::FMRB_OnlyAccessesArgumentPointees:
4177 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004178 for (const auto &Arg : CI->arg_operands()) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004179 if (!Arg->getType()->isPointerTy())
4180 continue;
4181
4182 auto *ArgSCEV = SE->getSCEVAtScope(Arg, L);
4183 if (ArgSCEV->isZero())
4184 continue;
4185
4186 auto *ArgBasePtr = cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
4187 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004188 ArgBasePtr->getType(), false, {AF}, {}, CI);
Johannes Doerferta7920982016-02-25 14:08:48 +00004189 }
4190 return true;
4191 }
4192
4193 return true;
4194}
4195
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004196void ScopInfo::buildAccessSingleDim(
4197 MemAccInst Inst, Loop *L, Region *R,
4198 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4199 const InvariantLoadsSetTy &ScopRIL) {
4200 Value *Address = Inst.getPointerOperand();
4201 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004202 Type *ElementType = Val->getType();
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004203 enum MemoryAccess::AccessType AccType =
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00004204 isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004205
4206 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4207 const SCEVUnknown *BasePointer =
4208 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4209
4210 assert(BasePointer && "Could not find base pointer");
4211 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004212
4213 // Check if the access depends on a loop contained in a non-affine subregion.
4214 bool isVariantInNonAffineLoop = false;
4215 if (BoxedLoops) {
4216 SetVector<const Loop *> Loops;
4217 findLoops(AccessFunction, Loops);
4218 for (const Loop *L : Loops)
4219 if (BoxedLoops->count(L))
4220 isVariantInNonAffineLoop = true;
4221 }
4222
Johannes Doerfert09e36972015-10-07 20:17:36 +00004223 InvariantLoadsSetTy AccessILS;
Michael Kruse09eb4452016-03-03 22:10:47 +00004224 bool IsAffine = !isVariantInNonAffineLoop &&
4225 isAffineExpr(R, L, AccessFunction, *SE,
4226 BasePointer->getValue(), &AccessILS);
Johannes Doerfert09e36972015-10-07 20:17:36 +00004227
4228 for (LoadInst *LInst : AccessILS)
4229 if (!ScopRIL.count(LInst))
4230 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004231
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004232 if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
4233 AccType = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004234
Michael Kruse1fdc2ff2016-04-08 14:35:59 +00004235 addArrayAccess(Inst, AccType, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004236 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004237}
4238
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004239void ScopInfo::buildMemoryAccess(
4240 MemAccInst Inst, Loop *L, Region *R,
4241 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004242 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004243
Johannes Doerfertcea61932016-02-21 19:13:19 +00004244 if (buildAccessMemIntrinsic(Inst, L, R, BoxedLoops, ScopRIL))
4245 return;
4246
Johannes Doerferta7920982016-02-25 14:08:48 +00004247 if (buildAccessCallInst(Inst, L, R, BoxedLoops, ScopRIL))
4248 return;
4249
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004250 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
4251 return;
4252
Hongbin Zheng22623202016-02-15 00:20:58 +00004253 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004254 return;
4255
4256 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
4257}
4258
Hongbin Zheng22623202016-02-15 00:20:58 +00004259void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
4260 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004261
4262 if (SD->isNonAffineSubRegion(&SR, &R)) {
4263 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00004264 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004265 return;
4266 }
4267
4268 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4269 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00004270 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004271 else
Hongbin Zheng22623202016-02-15 00:20:58 +00004272 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004273}
4274
Johannes Doerferta8781032016-02-02 14:14:40 +00004275void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004276
Johannes Doerferta8781032016-02-02 14:14:40 +00004277 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004278 scop->addScopStmt(nullptr, &SR);
4279 return;
4280 }
4281
4282 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4283 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004284 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004285 else
4286 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4287}
4288
Michael Krused868b5d2015-09-10 15:25:24 +00004289void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00004290 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00004291 Region *NonAffineSubRegion,
4292 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004293 // We do not build access functions for error blocks, as they may contain
4294 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004295 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004296 return;
4297
Michael Kruse7bf39442015-09-10 12:46:52 +00004298 Loop *L = LI->getLoopFor(&BB);
4299
4300 // The set of loops contained in non-affine subregions that are part of R.
4301 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
4302
Johannes Doerfert09e36972015-10-07 20:17:36 +00004303 // The set of loads that are required to be invariant.
4304 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
4305
Michael Kruse2e02d562016-02-06 09:19:40 +00004306 for (Instruction &Inst : BB) {
4307 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004308 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004309 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004310
4311 // For the exit block we stop modeling after the last PHI node.
4312 if (!PHI && IsExitBlock)
4313 break;
4314
Johannes Doerfert09e36972015-10-07 20:17:36 +00004315 // TODO: At this point we only know that elements of ScopRIL have to be
4316 // invariant and will be hoisted for the SCoP to be processed. Though,
4317 // there might be other invariant accesses that will be hoisted and
4318 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00004319 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00004320 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004321
Michael Kruse2e02d562016-02-06 09:19:40 +00004322 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004323 continue;
4324
Tobias Grosser0904c692016-03-16 23:33:54 +00004325 // PHI nodes have already been modeled above and TerminatorInsts that are
4326 // not part of a non-affine subregion are fully modeled and regenerated
4327 // from the polyhedral domains. Hence, they do not need to be modeled as
4328 // explicit data dependences.
4329 if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion))
Michael Kruse2e02d562016-02-06 09:19:40 +00004330 buildScalarDependences(&Inst);
Tobias Grosser0904c692016-03-16 23:33:54 +00004331
Michael Kruse2e02d562016-02-06 09:19:40 +00004332 if (!IsExitBlock)
4333 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004334 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004335}
Michael Kruse7bf39442015-09-10 12:46:52 +00004336
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004337MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004338 MemoryAccess::AccessType AccType,
4339 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004340 bool Affine, Value *AccessValue,
4341 ArrayRef<const SCEV *> Subscripts,
4342 ArrayRef<const SCEV *> Sizes,
4343 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004344 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004345
4346 // Do not create a memory access for anything not in the SCoP. It would be
4347 // ignored anyway.
4348 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004349 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004350
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004351 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004352 Value *BaseAddr = BaseAddress;
4353 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4354
Tobias Grosserf4f68702015-12-14 15:05:37 +00004355 bool isKnownMustAccess = false;
4356
4357 // Accesses in single-basic block statements are always excuted.
4358 if (Stmt->isBlockStmt())
4359 isKnownMustAccess = true;
4360
4361 if (Stmt->isRegionStmt()) {
4362 // Accesses that dominate the exit block of a non-affine region are always
4363 // executed. In non-affine regions there may exist MK_Values that do not
4364 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4365 // only if there is at most one PHI_WRITE in the non-affine region.
4366 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4367 isKnownMustAccess = true;
4368 }
4369
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004370 // Non-affine PHI writes do not "happen" at a particular instruction, but
4371 // after exiting the statement. Therefore they are guaranteed execute and
4372 // overwrite the old value.
4373 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4374 isKnownMustAccess = true;
4375
Johannes Doerfertcea61932016-02-21 19:13:19 +00004376 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4377 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004378
Johannes Doerfertcea61932016-02-21 19:13:19 +00004379 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004380 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004381 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004382 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004383}
4384
Michael Kruse70131d32016-01-27 17:09:17 +00004385void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004386 MemoryAccess::AccessType AccType,
4387 Value *BaseAddress, Type *ElementType,
4388 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004389 ArrayRef<const SCEV *> Sizes,
4390 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004391 ArrayBasePointers.insert(BaseAddress);
Hongbin Zhengf3d66122016-02-26 09:47:11 +00004392 addMemoryAccess(MemAccInst->getParent(), MemAccInst, AccType, BaseAddress,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004393 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004394 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004395}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004396
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004397void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004398 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004399
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004400 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004401 if (!Stmt)
4402 return;
4403
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004404 // Do not process further if the instruction is already written.
4405 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004406 return;
4407
Johannes Doerfertcea61932016-02-21 19:13:19 +00004408 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4409 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004410 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004411}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004412
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004413void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004414
Michael Kruse2e02d562016-02-06 09:19:40 +00004415 // There cannot be an "access" for literal constants. BasicBlock references
4416 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004417 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004418 return;
4419
Michael Krusefd463082016-01-27 22:51:56 +00004420 // If the instruction can be synthesized and the user is in the region we do
4421 // not need to add a value dependences.
4422 Region &ScopRegion = scop->getRegion();
Michael Krusec7e0d9c2016-03-01 21:44:06 +00004423 auto *Scope = LI->getLoopFor(UserBB);
4424 if (canSynthesize(V, LI, SE, &ScopRegion, Scope))
Michael Krusefd463082016-01-27 22:51:56 +00004425 return;
4426
Michael Kruse2e02d562016-02-06 09:19:40 +00004427 // Do not build scalar dependences for required invariant loads as we will
4428 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerferta90943d2016-02-21 16:37:25 +00004429 auto *ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004430 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004431 return;
4432
4433 // Determine the ScopStmt containing the value's definition and use. There is
4434 // no defining ScopStmt if the value is a function argument, a global value,
4435 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004436 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004437 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004438
Michael Kruse6f7721f2016-02-24 22:08:19 +00004439 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004440
4441 // We do not model uses outside the scop.
4442 if (!UserStmt)
4443 return;
4444
Michael Kruse2e02d562016-02-06 09:19:40 +00004445 // Add MemoryAccess for invariant values only if requested.
4446 if (!ModelReadOnlyScalars && !ValueStmt)
4447 return;
4448
4449 // Ignore use-def chains within the same ScopStmt.
4450 if (ValueStmt == UserStmt)
4451 return;
4452
Michael Krusead28e5a2016-01-26 13:33:15 +00004453 // Do not create another MemoryAccess for reloading the value if one already
4454 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004455 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004456 return;
4457
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004458 // For exit PHIs use the MK_ExitPHI MemoryKind not MK_Value.
4459 ScopArrayInfo::MemoryKind Kind = ScopArrayInfo::MK_Value;
4460 if (!ValueStmt && isa<PHINode>(V))
4461 Kind = ScopArrayInfo::MK_ExitPHI;
4462
Johannes Doerfertcea61932016-02-21 19:13:19 +00004463 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Johannes Doerfert2075b5d2016-04-03 11:16:00 +00004464 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(), Kind);
Michael Kruse2e02d562016-02-06 09:19:40 +00004465 if (ValueInst)
4466 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004467}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004468
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004469void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4470 Value *IncomingValue, bool IsExitBlock) {
Johannes Doerfert57c5f0b2016-04-05 13:44:21 +00004471 // As the incoming block might turn out to be an error statement ensure we
4472 // will create an exit PHI SAI object. It is needed during code generation
4473 // and would be created later anyway.
4474 if (IsExitBlock)
4475 scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
4476 ScopArrayInfo::MK_ExitPHI);
4477
Michael Kruse6f7721f2016-02-24 22:08:19 +00004478 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004479 if (!IncomingStmt)
4480 return;
4481
4482 // Take care for the incoming value being available in the incoming block.
4483 // This must be done before the check for multiple PHI writes because multiple
4484 // exiting edges from subregion each can be the effective written value of the
4485 // subregion. As such, all of them must be made available in the subregion
4486 // statement.
4487 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004488
4489 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4490 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4491 assert(Acc->getAccessInstruction() == PHI);
4492 Acc->addIncoming(IncomingBlock, IncomingValue);
4493 return;
4494 }
4495
4496 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004497 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4498 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4499 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004500 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4501 assert(Acc);
4502 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004503}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004504
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004505void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004506 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4507 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4508 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004509}
4510
Michael Krusedaf66942015-12-13 22:10:37 +00004511void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004512 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Michael Kruse09eb4452016-03-03 22:10:47 +00004513 scop.reset(new Scop(R, *SE, *LI, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004514
Johannes Doerferta8781032016-02-02 14:14:40 +00004515 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004516 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004517
4518 // In case the region does not have an exiting block we will later (during
4519 // code generation) split the exit block. This will move potential PHI nodes
4520 // from the current exit block into the new region exiting block. Hence, PHI
4521 // nodes that are at this point not part of the region will be.
4522 // To handle these PHI nodes later we will now model their operands as scalar
4523 // accesses. Note that we do not model anything in the exit block if we have
4524 // an exiting block in the region, as there will not be any splitting later.
4525 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004526 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4527 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004528
Johannes Doerferta7920982016-02-25 14:08:48 +00004529 // Create memory accesses for global reads since all arrays are now known.
4530 auto *AF = SE->getConstant(IntegerType::getInt64Ty(SE->getContext()), 0);
4531 for (auto *GlobalRead : GlobalReads)
4532 for (auto *BP : ArrayBasePointers)
4533 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4534 BP->getType(), false, {AF}, {}, GlobalRead);
4535
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004536 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004537}
4538
Michael Krused868b5d2015-09-10 15:25:24 +00004539void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004540 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004541 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004542 return;
4543 }
4544
Michael Kruse9d080092015-09-11 21:41:48 +00004545 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004546}
4547
Hongbin Zhengfec32802016-02-13 15:13:02 +00004548void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004549
4550//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004551ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004552
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004553ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004554
Tobias Grosser75805372011-04-29 06:27:02 +00004555void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004556 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004557 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004558 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004559 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4560 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004561 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004562 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004563 AU.setPreservesAll();
4564}
4565
4566bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004567 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004568
Michael Krused868b5d2015-09-10 15:25:24 +00004569 if (!SD->isMaxRegionInScop(*R))
4570 return false;
4571
4572 Function *F = R->getEntry()->getParent();
4573 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4574 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4575 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004576 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004577 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004578 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004579
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004580 DebugLoc Beg, End;
4581 getDebugLocations(R, Beg, End);
4582 std::string Msg = "SCoP begins here.";
4583 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4584
Michael Krusedaf66942015-12-13 22:10:37 +00004585 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004586
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004587 DEBUG(scop->print(dbgs()));
4588
Michael Kruseafe06702015-10-02 16:33:27 +00004589 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004590 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004591 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004592 } else {
4593 Msg = "SCoP ends here.";
4594 ++ScopFound;
4595 if (scop->getMaxLoopDepth() > 0)
4596 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004597 }
4598
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004599 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4600
Tobias Grosser75805372011-04-29 06:27:02 +00004601 return false;
4602}
4603
4604char ScopInfo::ID = 0;
4605
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004606Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4607
Tobias Grosser73600b82011-10-08 00:30:40 +00004608INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4609 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004610 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004611INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004612INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004613INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004614INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004615INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004616INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004617INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004618INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4619 "Polly - Create polyhedral description of Scops", false,
4620 false)