blob: 187ab25475476de933e40258795df31be7f27be9 [file] [log] [blame]
Michael Kruse2133cb92016-06-28 01:37:20 +00001//===--------- ScopInfo.cpp ----------------------------------------------===//
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"
Michael Kruse73fa33b2016-06-28 01:37:28 +000023#include "polly/ScopBuilder.h"
Tobias Grosser75805372011-04-29 06:27:02 +000024#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000025#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000026#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000027#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000028#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000029#include "llvm/ADT/PostOrderIterator.h"
30#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000031#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000032#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000033#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000034#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000035#include "llvm/Analysis/AssumptionCache.h"
Johannes Doerfert1dc12af2016-04-23 12:59:18 +000036#include "llvm/Analysis/Loads.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000037#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000038#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000039#include "llvm/Analysis/RegionIterator.h"
40#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000041#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000043#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000045#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000047#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000048#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000049#include "isl/schedule.h"
50#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000051#include "isl/set.h"
52#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000053#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000054#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <sstream>
56#include <string>
57#include <vector>
58
59using namespace llvm;
60using namespace polly;
61
Chandler Carruth95fef942014-04-22 03:30:19 +000062#define DEBUG_TYPE "polly-scops"
63
Tobias Grosser75dc40c2015-12-20 13:31:48 +000064// The maximal number of basic sets we allow during domain construction to
65// be created. More complex scops will result in very high compile time and
66// are also unlikely to result in good code
Michael Krusebc150122016-05-02 12:25:18 +000067static int const MaxDisjunctionsInDomain = 20;
Tobias Grosser75dc40c2015-12-20 13:31:48 +000068
Johannes Doerfert2f705842016-04-12 16:09:44 +000069static cl::opt<bool> PollyRemarksMinimal(
70 "polly-remarks-minimal",
71 cl::desc("Do not emit remarks about assumptions that are known"),
72 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
73
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000074// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000075// operations can overflow easily. Additive reductions and bit operations
76// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000077static cl::opt<bool> DisableMultiplicativeReductions(
78 "polly-disable-multiplicative-reductions",
79 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
80 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000081
Johannes Doerfert9143d672014-09-27 11:02:39 +000082static cl::opt<unsigned> RunTimeChecksMaxParameters(
83 "polly-rtc-max-parameters",
84 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
85 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
86
Tobias Grosser71500722015-03-28 15:11:14 +000087static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
88 "polly-rtc-max-arrays-per-group",
89 cl::desc("The maximal number of arrays to compare in each alias group."),
90 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Johannes Doerfert5210da52016-06-02 11:06:54 +000091
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 Grosser2937b592016-04-29 11:43:20 +0000102static cl::opt<bool>
103 IslOnErrorAbort("polly-on-isl-error-abort",
104 cl::desc("Abort if an isl error is encountered"),
105 cl::init(true), cl::cat(PollyCategory));
106
Michael Kruse7bf39442015-09-10 12:46:52 +0000107//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000108
Michael Kruse046dde42015-08-10 13:01:57 +0000109// Create a sequence of two schedules. Either argument may be null and is
110// interpreted as the empty schedule. Can also return null if both schedules are
111// empty.
112static __isl_give isl_schedule *
113combineInSequence(__isl_take isl_schedule *Prev,
114 __isl_take isl_schedule *Succ) {
115 if (!Prev)
116 return Succ;
117 if (!Succ)
118 return Prev;
119
120 return isl_schedule_sequence(Prev, Succ);
121}
122
Johannes Doerferte7044942015-02-24 11:58:30 +0000123static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
124 const ConstantRange &Range,
125 int dim,
126 enum isl_dim_type type) {
127 isl_val *V;
128 isl_ctx *ctx = isl_set_get_ctx(S);
129
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000130 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
131 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000132 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000133 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
134
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000135 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000136 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000138 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000139 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
140
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000141 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000142 return isl_set_union(SLB, SUB);
143 else
144 return isl_set_intersect(SLB, SUB);
145}
146
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000147static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
148 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
149 if (!BasePtrLI)
150 return nullptr;
151
Johannes Doerfert952b5302016-05-23 12:40:48 +0000152 if (!S->contains(BasePtrLI))
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000153 return nullptr;
154
155 ScalarEvolution &SE = *S->getSE();
156
157 auto *OriginBaseSCEV =
158 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
159 if (!OriginBaseSCEV)
160 return nullptr;
161
162 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
163 if (!OriginBaseSCEVUnknown)
164 return nullptr;
165
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000166 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000167 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000168}
169
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000170ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000171 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000172 const DataLayout &DL, Scop *S)
173 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000174 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000175 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000176 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000177
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000178 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000179 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
180 if (BasePtrOriginSAI)
181 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000182}
183
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000184__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000185 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000186 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
187 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
188 return Space;
189}
190
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000191void ScopArrayInfo::updateElementType(Type *NewElementType) {
192 if (NewElementType == ElementType)
193 return;
194
Tobias Grosserd840fc72016-02-04 13:18:42 +0000195 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
196 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
197
Johannes Doerferta7920982016-02-25 14:08:48 +0000198 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000199 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000200
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000201 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
202 ElementType = NewElementType;
203 } else {
204 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
205 ElementType = IntegerType::get(ElementType->getContext(), GCD);
206 }
207}
208
209bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000210 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
211 int ExtraDimsNew = NewSizes.size() - SharedDims;
212 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000213 for (int i = 0; i < SharedDims; i++)
214 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
215 return false;
216
217 if (DimensionSizes.size() >= NewSizes.size())
218 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000219
220 DimensionSizes.clear();
221 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
222 NewSizes.end());
223 for (isl_pw_aff *Size : DimensionSizesPw)
224 isl_pw_aff_free(Size);
225 DimensionSizesPw.clear();
226 for (const SCEV *Expr : DimensionSizes) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000227 isl_pw_aff *Size = S.getPwAffOnly(Expr);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000228 DimensionSizesPw.push_back(Size);
229 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000230 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000231}
232
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000233ScopArrayInfo::~ScopArrayInfo() {
234 isl_id_free(Id);
235 for (isl_pw_aff *Size : DimensionSizesPw)
236 isl_pw_aff_free(Size);
237}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000238
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000239std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
240
241int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000242 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000243}
244
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000245__isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
246 return isl_id_copy(Id);
247}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000248
249void ScopArrayInfo::dump() const { print(errs()); }
250
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000251void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000252 OS.indent(8) << *getElementType() << " " << getName();
253 if (getNumberOfDimensions() > 0)
254 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000255 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000256 OS << "[";
257
Tobias Grosser26253842015-11-10 14:24:21 +0000258 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000259 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000260 OS << " " << Size << " ";
261 isl_pw_aff_free(Size);
262 } else {
263 OS << *getDimensionSize(u);
264 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000265
266 OS << "]";
267 }
268
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000269 OS << ";";
270
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000271 if (BasePtrOriginSAI)
272 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
273
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000274 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000275}
276
277const ScopArrayInfo *
278ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
279 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
280 assert(Id && "Output dimension didn't have an ID");
281 return getFromId(Id);
282}
283
284const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
285 void *User = isl_id_get_user(Id);
286 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
287 isl_id_free(Id);
288 return SAI;
289}
290
Michael Kruse3b425ff2016-04-11 14:34:08 +0000291void MemoryAccess::wrapConstantDimensions() {
292 auto *SAI = getScopArrayInfo();
293 auto *ArraySpace = SAI->getSpace();
294 auto *Ctx = isl_space_get_ctx(ArraySpace);
295 unsigned DimsArray = SAI->getNumberOfDimensions();
296
297 auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
298 isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
299 auto *LArraySpace = isl_local_space_from_space(ArraySpace);
300
301 // Begin with last dimension, to iteratively carry into higher dimensions.
302 for (int i = DimsArray - 1; i > 0; i--) {
303 auto *DimSize = SAI->getDimensionSize(i);
304 auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
305
306 // This transformation is not applicable to dimensions with dynamic size.
307 if (!DimSizeCst)
308 continue;
309
310 auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
311 auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
312 isl_dim_set, i);
313 auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
314 isl_dim_set, i - 1);
315
316 // Compute: index % size
317 // Modulo must apply in the divide of the previous iteration, if any.
318 auto *Modulo = isl_aff_copy(Var);
319 Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
320 Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
321
322 // Compute: floor(index / size)
323 auto *Divide = Var;
324 Divide = isl_aff_div(
325 Divide,
326 isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
327 Divide = isl_aff_floor(Divide);
328 Divide = isl_aff_add(Divide, PrevVar);
329 Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
330
331 // Apply Modulo and Divide.
332 DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
333 DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
334 }
335
336 // Apply all modulo/divides on the accesses.
337 AccessRelation =
338 isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
339 AccessRelation = isl_map_detect_equalities(AccessRelation);
340 isl_local_space_free(LArraySpace);
341}
342
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000343void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000344 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000345 auto *ArraySpace = SAI->getSpace();
346 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000347 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000348
349 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
350 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
351 auto DimsMissing = DimsArray - DimsAccess;
352
Michael Kruse375cb5f2016-02-24 22:08:24 +0000353 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000354 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000355 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000356 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000357
Johannes Doerferta90943d2016-02-21 16:37:25 +0000358 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000359 isl_set_universe(AccessSpace),
360 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000361
362 for (unsigned i = 0; i < DimsMissing; i++)
363 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
364
365 for (unsigned i = DimsMissing; i < DimsArray; i++)
366 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
367
368 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000369
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000370 // For the non delinearized arrays, divide the access function of the last
371 // subscript by the size of the elements in the array.
372 //
373 // A stride one array access in C expressed as A[i] is expressed in
374 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
375 // two subsequent values of 'i' index two values that are stored next to
376 // each other in memory. By this division we make this characteristic
377 // obvious again. If the base pointer was accessed with offsets not divisible
378 // by the accesses element size, we will have choosen a smaller ArrayElemSize
379 // that divides the offsets of all accesses to this base pointer.
380 if (DimsAccess == 1) {
381 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
382 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
383 }
384
Michael Kruse3b425ff2016-04-11 14:34:08 +0000385 // We currently do this only if we added at least one dimension, which means
386 // some dimension's indices have not been specified, an indicator that some
387 // index values have been added together.
388 // TODO: Investigate general usefulness; Effect on unit tests is to make index
389 // expressions more complicated.
390 if (DimsMissing)
391 wrapConstantDimensions();
392
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000393 if (!isAffine())
394 computeBoundsOnAccessRelation(ArrayElemSize);
395
Tobias Grosserd840fc72016-02-04 13:18:42 +0000396 // Introduce multi-element accesses in case the type loaded by this memory
397 // access is larger than the canonical element type of the array.
398 //
399 // An access ((float *)A)[i] to an array char *A is modeled as
400 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000401 if (ElemBytes > ArrayElemSize) {
402 assert(ElemBytes % ArrayElemSize == 0 &&
403 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000404 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000405 isl_set_universe(isl_space_copy(ArraySpace)),
406 isl_set_universe(isl_space_copy(ArraySpace)));
407 for (unsigned i = 0; i < DimsArray - 1; i++)
408 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
409
Tobias Grosserd840fc72016-02-04 13:18:42 +0000410 isl_constraint *C;
411 isl_local_space *LS;
412
413 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000414 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
415
416 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
417 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000418 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000419 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
420 Map = isl_map_add_constraint(Map, C);
421
422 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000423 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000424 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
425 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
426 Map = isl_map_add_constraint(Map, C);
427 AccessRelation = isl_map_apply_range(AccessRelation, Map);
428 }
429
430 isl_space_free(ArraySpace);
431
Roman Gareev10595a12016-01-08 14:01:59 +0000432 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000433}
434
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000435const std::string
436MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
437 switch (RT) {
438 case MemoryAccess::RT_NONE:
439 llvm_unreachable("Requested a reduction operator string for a memory "
440 "access which isn't a reduction");
441 case MemoryAccess::RT_ADD:
442 return "+";
443 case MemoryAccess::RT_MUL:
444 return "*";
445 case MemoryAccess::RT_BOR:
446 return "|";
447 case MemoryAccess::RT_BXOR:
448 return "^";
449 case MemoryAccess::RT_BAND:
450 return "&";
451 }
452 llvm_unreachable("Unknown reduction type");
453 return "";
454}
455
Johannes Doerfertf6183392014-07-01 20:52:51 +0000456/// @brief Return the reduction type for a given binary operator
457static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
458 const Instruction *Load) {
459 if (!BinOp)
460 return MemoryAccess::RT_NONE;
461 switch (BinOp->getOpcode()) {
462 case Instruction::FAdd:
463 if (!BinOp->hasUnsafeAlgebra())
464 return MemoryAccess::RT_NONE;
465 // Fall through
466 case Instruction::Add:
467 return MemoryAccess::RT_ADD;
468 case Instruction::Or:
469 return MemoryAccess::RT_BOR;
470 case Instruction::Xor:
471 return MemoryAccess::RT_BXOR;
472 case Instruction::And:
473 return MemoryAccess::RT_BAND;
474 case Instruction::FMul:
475 if (!BinOp->hasUnsafeAlgebra())
476 return MemoryAccess::RT_NONE;
477 // Fall through
478 case Instruction::Mul:
479 if (DisableMultiplicativeReductions)
480 return MemoryAccess::RT_NONE;
481 return MemoryAccess::RT_MUL;
482 default:
483 return MemoryAccess::RT_NONE;
484 }
485}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000486
Tobias Grosser75805372011-04-29 06:27:02 +0000487MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000488 isl_id_free(Id);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000489 isl_set_free(InvalidDomain);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000490 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000491 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000492}
493
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000494const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
495 isl_id *ArrayId = getArrayId();
496 void *User = isl_id_get_user(ArrayId);
497 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
498 isl_id_free(ArrayId);
499 return SAI;
500}
501
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000502__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000503 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
504}
505
Tobias Grosserd840fc72016-02-04 13:18:42 +0000506__isl_give isl_map *MemoryAccess::getAddressFunction() const {
507 return isl_map_lexmin(getAccessRelation());
508}
509
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000510__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
511 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000512 isl_map *Schedule, *ScheduledAccRel;
513 isl_union_set *UDomain;
514
515 UDomain = isl_union_set_from_set(getStatement()->getDomain());
516 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
517 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000518 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000519 return isl_pw_multi_aff_from_map(ScheduledAccRel);
520}
521
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000522__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000523 return isl_map_copy(AccessRelation);
524}
525
Johannes Doerferta99130f2014-10-13 12:58:03 +0000526std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000527 return stringFromIslObj(AccessRelation);
528}
529
Johannes Doerferta99130f2014-10-13 12:58:03 +0000530__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000531 return isl_map_get_space(AccessRelation);
532}
533
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000534__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000535 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000536}
537
Tobias Grosser6f730082015-09-05 07:46:47 +0000538std::string MemoryAccess::getNewAccessRelationStr() const {
539 return stringFromIslObj(NewAccessRelation);
540}
541
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000542__isl_give isl_basic_map *
543MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000544 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000545 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000546
Tobias Grosser084d8f72012-05-29 09:29:44 +0000547 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000548 isl_basic_set_universe(Statement->getDomainSpace()),
549 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000550}
551
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000552// Formalize no out-of-bound access assumption
553//
554// When delinearizing array accesses we optimistically assume that the
555// delinearized accesses do not access out of bound locations (the subscript
556// expression of each array evaluates for each statement instance that is
557// executed to a value that is larger than zero and strictly smaller than the
558// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000559// dimension for which we do not need to assume any upper bound. At this point
560// we formalize this assumption to ensure that at code generation time the
561// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000562//
563// To find the set of constraints necessary to avoid out of bound accesses, we
564// first build the set of data locations that are not within array bounds. We
565// then apply the reverse access relation to obtain the set of iterations that
566// may contain invalid accesses and reduce this set of iterations to the ones
567// that are actually executed by intersecting them with the domain of the
568// statement. If we now project out all loop dimensions, we obtain a set of
569// parameters that may cause statement instances to be executed that may
570// possibly yield out of bound memory accesses. The complement of these
571// constraints is the set of constraints that needs to be assumed to ensure such
572// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000573void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000574 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000575 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000576 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000577 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000578 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
579 isl_pw_aff *Var =
580 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
581 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
582
583 isl_set *DimOutside;
584
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000585 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000586 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000587 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
588 isl_space_dim(Space, isl_dim_set));
589 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
590 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000591
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000592 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000593
594 Outside = isl_set_union(Outside, DimOutside);
595 }
596
597 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
598 Outside = isl_set_intersect(Outside, Statement->getDomain());
599 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000600
601 // Remove divs to avoid the construction of overly complicated assumptions.
602 // Doing so increases the set of parameter combinations that are assumed to
603 // not appear. This is always save, but may make the resulting run-time check
604 // bail out more often than strictly necessary.
605 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000606 Outside = isl_set_complement(Outside);
Michael Kruse7071e8b2016-04-11 13:24:29 +0000607 const auto &Loc = getAccessInstruction()
608 ? getAccessInstruction()->getDebugLoc()
609 : DebugLoc();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +0000610 Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
611 AS_ASSUMPTION);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000612 isl_space_free(Space);
613}
614
Johannes Doerfertcea61932016-02-21 19:13:19 +0000615void MemoryAccess::buildMemIntrinsicAccessRelation() {
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000616 assert(isa<MemIntrinsic>(getAccessInstruction()));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000617 assert(Subscripts.size() == 2 && Sizes.size() == 0);
618
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000619 auto *SubscriptPWA = getPwAff(Subscripts[0]);
Johannes Doerfertcea61932016-02-21 19:13:19 +0000620 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000621
622 isl_map *LengthMap;
623 if (Subscripts[1] == nullptr) {
624 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
625 } else {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000626 auto *LengthPWA = getPwAff(Subscripts[1]);
Johannes Doerferta7920982016-02-25 14:08:48 +0000627 LengthMap = isl_map_from_pw_aff(LengthPWA);
628 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
629 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
630 }
631 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
632 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000633 SubscriptMap =
634 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000635 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
636 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
637 getStatement()->getDomainId());
638}
639
Johannes Doerferte7044942015-02-24 11:58:30 +0000640void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
641 ScalarEvolution *SE = Statement->getParent()->getSE();
642
Johannes Doerfertcea61932016-02-21 19:13:19 +0000643 auto MAI = MemAccInst(getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +0000644 if (isa<MemIntrinsic>(MAI))
Johannes Doerfertcea61932016-02-21 19:13:19 +0000645 return;
646
647 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000648 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
649 return;
650
651 auto *PtrSCEV = SE->getSCEV(Ptr);
652 if (isa<SCEVCouldNotCompute>(PtrSCEV))
653 return;
654
655 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
656 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
657 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
658
659 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
660 if (Range.isFullSet())
661 return;
662
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000663 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000664 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000665 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000666 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000667 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000668
669 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000670 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000671
672 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
673 AccessRange =
674 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
675 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
676}
677
Michael Krusee2bccbb2015-09-18 19:59:43 +0000678__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000679 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000680 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000681
682 for (int i = Size - 2; i >= 0; --i) {
683 isl_space *Space;
684 isl_map *MapOne, *MapTwo;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000685 isl_pw_aff *DimSize = getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000686
687 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
688 isl_pw_aff_free(DimSize);
689 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
690
691 Space = isl_map_get_space(AccessRelation);
692 Space = isl_space_map_from_set(isl_space_range(Space));
693 Space = isl_space_align_params(Space, SpaceSize);
694
695 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
696 isl_id_free(ParamId);
697
698 MapOne = isl_map_universe(isl_space_copy(Space));
699 for (int j = 0; j < Size; ++j)
700 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
701 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
702
703 MapTwo = isl_map_universe(isl_space_copy(Space));
704 for (int j = 0; j < Size; ++j)
705 if (j < i || j > i + 1)
706 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
707
708 isl_local_space *LS = isl_local_space_from_space(Space);
709 isl_constraint *C;
710 C = isl_equality_alloc(isl_local_space_copy(LS));
711 C = isl_constraint_set_constant_si(C, -1);
712 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
713 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
714 MapTwo = isl_map_add_constraint(MapTwo, C);
715 C = isl_equality_alloc(LS);
716 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
717 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
718 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
719 MapTwo = isl_map_add_constraint(MapTwo, C);
720 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
721
722 MapOne = isl_map_union(MapOne, MapTwo);
723 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
724 }
725 return AccessRelation;
726}
727
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000728/// @brief Check if @p Expr is divisible by @p Size.
729static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000730 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000731 if (Size == 1)
732 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000733
734 // Only one factor needs to be divisible.
735 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
736 for (auto *FactorExpr : MulExpr->operands())
737 if (isDivisible(FactorExpr, Size, SE))
738 return true;
739 return false;
740 }
741
742 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
743 // to be divisble.
744 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
745 for (auto *OpExpr : NAryExpr->operands())
746 if (!isDivisible(OpExpr, Size, SE))
747 return false;
748 return true;
749 }
750
751 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
752 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
753 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
754 return MulSCEV == Expr;
755}
756
Michael Krusee2bccbb2015-09-18 19:59:43 +0000757void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
758 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000759
Johannes Doerfert85676e32016-04-23 14:32:34 +0000760 // Initialize the invalid domain which describes all iterations for which the
761 // access relation is not modeled correctly.
Johannes Doerferta4dd8ef2016-04-25 13:36:23 +0000762 auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
763 InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
764 isl_set_free(StmtInvalidDomain);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000765
Michael Krusee2bccbb2015-09-18 19:59:43 +0000766 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000767 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000768
Michael Krusee2bccbb2015-09-18 19:59:43 +0000769 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000770 if (isa<MemIntrinsic>(getAccessInstruction()))
771 buildMemIntrinsicAccessRelation();
772
Tobias Grosser4f967492013-06-23 05:21:18 +0000773 // We overapproximate non-affine accesses with a possible access to the
774 // whole array. For read accesses it does not make a difference, if an
775 // access must or may happen. However, for write accesses it is important to
776 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000777 if (!AccessRelation)
778 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
779
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000780 AccessRelation =
781 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000782 return;
783 }
784
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000785 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000786 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000787
Michael Krusee2bccbb2015-09-18 19:59:43 +0000788 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000789 isl_pw_aff *Affine = getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000790 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000791 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000792 }
793
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000794 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000795 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000796
Tobias Grosser79baa212014-04-10 08:38:02 +0000797 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000798 AccessRelation = isl_map_set_tuple_id(
799 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000800 AccessRelation =
801 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
802
Tobias Grosseraa660a92015-03-30 00:07:50 +0000803 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000804 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000805}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000806
Michael Krusecac948e2015-10-02 13:53:07 +0000807MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000808 AccessType AccType, Value *BaseAddress,
809 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000810 ArrayRef<const SCEV *> Subscripts,
811 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000812 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000813 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
Johannes Doerfert85676e32016-04-23 14:32:34 +0000814 InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
815 ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
816 AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000817 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000818 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000819 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000820 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000821
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000822 std::string IdName =
823 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000824 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
825}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000826
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000827void MemoryAccess::realignParams() {
Johannes Doerferta60ad842016-05-10 12:18:22 +0000828 auto *Ctx = Statement->getParent()->getContext();
829 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
830 AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
Tobias Grosser75805372011-04-29 06:27:02 +0000831}
832
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000833const std::string MemoryAccess::getReductionOperatorStr() const {
834 return MemoryAccess::getReductionOperatorStr(getReductionType());
835}
836
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000837__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
838
Johannes Doerfertf6183392014-07-01 20:52:51 +0000839raw_ostream &polly::operator<<(raw_ostream &OS,
840 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000841 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000842 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000843 else
844 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000845 return OS;
846}
847
Tobias Grosser75805372011-04-29 06:27:02 +0000848void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000849 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000850 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000851 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000852 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000853 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000854 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000855 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000856 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000857 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000858 break;
859 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000860 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000861 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000862 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000863 if (hasNewAccessRelation())
864 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000865}
866
Tobias Grosser74394f02013-01-14 22:40:23 +0000867void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000868
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000869__isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
870 auto *Stmt = getStatement();
Johannes Doerfert85676e32016-04-23 14:32:34 +0000871 PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
Tobias Grosser53292772016-07-11 12:01:26 +0000872 isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
873 isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
874 InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
Johannes Doerfert85676e32016-04-23 14:32:34 +0000875 return PWAC.first;
Johannes Doerfert97f0dcd2016-04-12 13:26:45 +0000876}
877
Tobias Grosser75805372011-04-29 06:27:02 +0000878// Create a map in the size of the provided set domain, that maps from the
879// one element of the provided set domain to another element of the provided
880// set domain.
881// The mapping is limited to all points that are equal in all but the last
882// dimension and for which the last dimension of the input is strict smaller
883// than the last dimension of the output.
884//
885// getEqualAndLarger(set[i0, i1, ..., iX]):
886//
887// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
888// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
889//
Tobias Grosserf5338802011-10-06 00:03:35 +0000890static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000891 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000892 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000893 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000894
895 // Set all but the last dimension to be equal for the input and output
896 //
897 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
898 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000899 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000900 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000901
902 // Set the last dimension of the input to be strict smaller than the
903 // last dimension of the output.
904 //
905 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000906 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
907 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000908 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000909}
910
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000911__isl_give isl_set *
912MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000913 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000914 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000915 isl_space *Space = isl_space_range(isl_map_get_space(S));
916 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000917
Sebastian Popa00a0292012-12-18 07:46:06 +0000918 S = isl_map_reverse(S);
919 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000920
Sebastian Popa00a0292012-12-18 07:46:06 +0000921 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
922 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
923 NextScatt = isl_map_apply_domain(NextScatt, S);
924 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000925
Sebastian Popa00a0292012-12-18 07:46:06 +0000926 isl_set *Deltas = isl_map_deltas(NextScatt);
927 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000928}
929
Sebastian Popa00a0292012-12-18 07:46:06 +0000930bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000931 int StrideWidth) const {
932 isl_set *Stride, *StrideX;
933 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000934
Sebastian Popa00a0292012-12-18 07:46:06 +0000935 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000936 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000937 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
938 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
939 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
940 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000941 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000942
Tobias Grosser28dd4862012-01-24 16:42:16 +0000943 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000944 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000945
Tobias Grosser28dd4862012-01-24 16:42:16 +0000946 return IsStrideX;
947}
948
Sebastian Popa00a0292012-12-18 07:46:06 +0000949bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
950 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000951}
952
Sebastian Popa00a0292012-12-18 07:46:06 +0000953bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
954 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000955}
956
Tobias Grosser166c4222015-09-05 07:46:40 +0000957void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
958 isl_map_free(NewAccessRelation);
959 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000960}
Tobias Grosser75805372011-04-29 06:27:02 +0000961
962//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000963
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +0000964__isl_give isl_map *ScopStmt::getSchedule() const {
Tobias Grosser808cd692015-07-14 09:33:13 +0000965 isl_set *Domain = getDomain();
966 if (isl_set_is_empty(Domain)) {
967 isl_set_free(Domain);
968 return isl_map_from_aff(
969 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
970 }
971 auto *Schedule = getParent()->getSchedule();
972 Schedule = isl_union_map_intersect_domain(
973 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
974 if (isl_union_map_is_empty(Schedule)) {
975 isl_set_free(Domain);
976 isl_union_map_free(Schedule);
977 return isl_map_from_aff(
978 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
979 }
980 auto *M = isl_map_from_union_map(Schedule);
981 M = isl_map_coalesce(M);
982 M = isl_map_gist_domain(M, Domain);
983 M = isl_map_coalesce(M);
984 return M;
985}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000986
Johannes Doerfert3e48ee22016-04-29 10:44:41 +0000987__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
988 PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +0000989 InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
990 return PWAC.first;
Johannes Doerfert574182d2015-08-12 10:19:50 +0000991}
992
Tobias Grosser37eb4222014-02-20 21:43:54 +0000993void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
994 assert(isl_set_is_subset(NewDomain, Domain) &&
995 "New domain is not a subset of old domain!");
996 isl_set_free(Domain);
997 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000998}
999
Michael Krusecac948e2015-10-02 13:53:07 +00001000void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +00001001 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +00001002 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00001003 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00001004
Tobias Grossera535dff2015-12-13 19:59:01 +00001005 ScopArrayInfo::MemoryKind Ty;
1006 if (Access->isPHIKind())
1007 Ty = ScopArrayInfo::MK_PHI;
1008 else if (Access->isExitPHIKind())
1009 Ty = ScopArrayInfo::MK_ExitPHI;
1010 else if (Access->isValueKind())
1011 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001012 else
Tobias Grossera535dff2015-12-13 19:59:01 +00001013 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001014
Johannes Doerfertadeab372016-02-07 13:57:32 +00001015 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1016 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001017 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001018 }
1019}
1020
Michael Krusecac948e2015-10-02 13:53:07 +00001021void ScopStmt::addAccess(MemoryAccess *Access) {
1022 Instruction *AccessInst = Access->getAccessInstruction();
1023
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001024 if (Access->isArrayKind()) {
1025 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1026 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001027 } else if (Access->isValueKind() && Access->isWrite()) {
1028 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001029 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001030 assert(!ValueWrites.lookup(AccessVal));
1031
1032 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001033 } else if (Access->isValueKind() && Access->isRead()) {
1034 Value *AccessVal = Access->getAccessValue();
1035 assert(!ValueReads.lookup(AccessVal));
1036
1037 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001038 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1039 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1040 assert(!PHIWrites.lookup(PHI));
1041
1042 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001043 }
1044
1045 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001046}
1047
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001048void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001049 for (MemoryAccess *MA : *this)
1050 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001051
Johannes Doerferta60ad842016-05-10 12:18:22 +00001052 auto *Ctx = Parent.getContext();
1053 InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1054 Domain = isl_set_gist_params(Domain, Ctx);
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001055}
1056
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001057/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1058static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1059 void *User) {
1060 isl_set **BoundedParts = static_cast<isl_set **>(User);
1061 if (isl_basic_set_is_bounded(BSet))
1062 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1063 else
1064 isl_basic_set_free(BSet);
1065 return isl_stat_ok;
1066}
1067
1068/// @brief Return the bounded parts of @p S.
1069static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1070 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1071 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1072 isl_set_free(S);
1073 return BoundedParts;
1074}
1075
1076/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1077///
1078/// @returns A separation of @p S into first an unbounded then a bounded subset,
1079/// both with regards to the dimension @p Dim.
1080static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1081partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1082
1083 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001084 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001085
1086 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001087 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001088
1089 // Remove dimensions that are greater than Dim as they are not interesting.
1090 assert(NumDimsS >= Dim + 1);
1091 OnlyDimS =
1092 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1093
1094 // Create artificial parametric upper bounds for dimensions smaller than Dim
1095 // as we are not interested in them.
1096 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1097 for (unsigned u = 0; u < Dim; u++) {
1098 isl_constraint *C = isl_inequality_alloc(
1099 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1100 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1101 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1102 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1103 }
1104
1105 // Collect all bounded parts of OnlyDimS.
1106 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1107
1108 // Create the dimensions greater than Dim again.
1109 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1110 NumDimsS - Dim - 1);
1111
1112 // Remove the artificial upper bound parameters again.
1113 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1114
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001115 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001116 return std::make_pair(UnboundedParts, BoundedParts);
1117}
1118
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001119/// @brief Set the dimension Ids from @p From in @p To.
1120static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1121 __isl_take isl_set *To) {
1122 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1123 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1124 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1125 }
1126 return To;
1127}
1128
1129/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001130static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001131 __isl_take isl_pw_aff *L,
1132 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001133 switch (Pred) {
1134 case ICmpInst::ICMP_EQ:
1135 return isl_pw_aff_eq_set(L, R);
1136 case ICmpInst::ICMP_NE:
1137 return isl_pw_aff_ne_set(L, R);
1138 case ICmpInst::ICMP_SLT:
1139 return isl_pw_aff_lt_set(L, R);
1140 case ICmpInst::ICMP_SLE:
1141 return isl_pw_aff_le_set(L, R);
1142 case ICmpInst::ICMP_SGT:
1143 return isl_pw_aff_gt_set(L, R);
1144 case ICmpInst::ICMP_SGE:
1145 return isl_pw_aff_ge_set(L, R);
1146 case ICmpInst::ICMP_ULT:
1147 return isl_pw_aff_lt_set(L, R);
1148 case ICmpInst::ICMP_UGT:
1149 return isl_pw_aff_gt_set(L, R);
1150 case ICmpInst::ICMP_ULE:
1151 return isl_pw_aff_le_set(L, R);
1152 case ICmpInst::ICMP_UGE:
1153 return isl_pw_aff_ge_set(L, R);
1154 default:
1155 llvm_unreachable("Non integer predicate not supported");
1156 }
1157}
1158
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001159/// @brief Create the conditions under which @p L @p Pred @p R is true.
1160///
1161/// Helper function that will make sure the dimensions of the result have the
1162/// same isl_id's as the @p Domain.
1163static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1164 __isl_take isl_pw_aff *L,
1165 __isl_take isl_pw_aff *R,
1166 __isl_keep isl_set *Domain) {
1167 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1168 return setDimensionIds(Domain, ConsequenceCondSet);
1169}
1170
1171/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001172///
1173/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001174/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1175/// have as many elements as @p SI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001176static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001177buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1178 __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001179 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1180
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001181 Value *Condition = getConditionFromTerminator(SI);
1182 assert(Condition && "No condition for switch");
1183
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001184 Scop &S = *Stmt.getParent();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001185 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001186 isl_pw_aff *LHS, *RHS;
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001187 LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001188
1189 unsigned NumSuccessors = SI->getNumSuccessors();
1190 ConditionSets.resize(NumSuccessors);
1191 for (auto &Case : SI->cases()) {
1192 unsigned Idx = Case.getSuccessorIndex();
1193 ConstantInt *CaseValue = Case.getCaseValue();
1194
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001195 RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001196 isl_set *CaseConditionSet =
1197 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1198 ConditionSets[Idx] = isl_set_coalesce(
1199 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1200 }
1201
1202 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1203 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1204 for (unsigned u = 2; u < NumSuccessors; u++)
1205 ConditionSetUnion =
1206 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1207 ConditionSets[0] = setDimensionIds(
1208 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1209
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001210 isl_pw_aff_free(LHS);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001211
1212 return true;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001213}
1214
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001215/// @brief Build the conditions sets for the branch condition @p Condition in
1216/// the @p Domain.
1217///
1218/// This will fill @p ConditionSets with the conditions under which control
1219/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001220/// have as many elements as @p TI has successors. If @p TI is nullptr the
1221/// context under which @p Condition is true/false will be returned as the
1222/// new elements of @p ConditionSets.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001223static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001224buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1225 Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001226 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1227
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001228 Scop &S = *Stmt.getParent();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001229 isl_set *ConsequenceCondSet = nullptr;
1230 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1231 if (CCond->isZero())
1232 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1233 else
1234 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1235 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1236 auto Opcode = BinOp->getOpcode();
1237 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1238
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001239 bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1240 ConditionSets) &&
1241 buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1242 ConditionSets);
1243 if (!Valid) {
1244 while (!ConditionSets.empty())
1245 isl_set_free(ConditionSets.pop_back_val());
Johannes Doerfert297c7202016-05-10 13:06:42 +00001246 return false;
Johannes Doerfertede4eca2016-05-10 14:01:21 +00001247 }
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001248
1249 isl_set_free(ConditionSets.pop_back_val());
1250 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1251 isl_set_free(ConditionSets.pop_back_val());
1252 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1253
1254 if (Opcode == Instruction::And)
1255 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1256 else
1257 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1258 } else {
1259 auto *ICond = dyn_cast<ICmpInst>(Condition);
1260 assert(ICond &&
1261 "Condition of exiting branch was neither constant nor ICmp!");
1262
1263 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001264 isl_pw_aff *LHS, *RHS;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00001265 // For unsigned comparisons we assumed the signed bit of neither operand
1266 // to be set. The comparison is equal to a signed comparison under this
1267 // assumption.
1268 bool NonNeg = ICond->isUnsigned();
1269 LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1270 RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001271 ConsequenceCondSet =
1272 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1273 }
1274
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001275 // If no terminator was given we are only looking for parameter constraints
1276 // under which @p Condition is true/false.
1277 if (!TI)
1278 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001279 assert(ConsequenceCondSet);
Johannes Doerfert15194912016-04-04 07:59:41 +00001280 ConsequenceCondSet = isl_set_coalesce(
1281 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001282
Johannes Doerfertb2885792016-04-26 09:20:41 +00001283 isl_set *AlternativeCondSet = nullptr;
Michael Krusef7a4a942016-05-02 12:25:36 +00001284 bool TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001285 isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001286
Michael Krusef7a4a942016-05-02 12:25:36 +00001287 if (!TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001288 AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1289 isl_set_copy(ConsequenceCondSet));
Michael Krusef7a4a942016-05-02 12:25:36 +00001290 TooComplex =
Michael Krusebc150122016-05-02 12:25:18 +00001291 isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctionsInDomain;
Johannes Doerfertb2885792016-04-26 09:20:41 +00001292 }
1293
Michael Krusef7a4a942016-05-02 12:25:36 +00001294 if (TooComplex) {
Johannes Doerfert15194912016-04-04 07:59:41 +00001295 S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
Johannes Doerfertb2885792016-04-26 09:20:41 +00001296 isl_set_free(AlternativeCondSet);
Johannes Doerfertb2885792016-04-26 09:20:41 +00001297 isl_set_free(ConsequenceCondSet);
Johannes Doerfert297c7202016-05-10 13:06:42 +00001298 return false;
Johannes Doerfert15194912016-04-04 07:59:41 +00001299 }
1300
1301 ConditionSets.push_back(ConsequenceCondSet);
1302 ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001303
1304 return true;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001305}
1306
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001307/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1308///
1309/// This will fill @p ConditionSets with the conditions under which control
1310/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1311/// have as many elements as @p TI has successors.
Johannes Doerfert297c7202016-05-10 13:06:42 +00001312static bool
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001313buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001314 __isl_keep isl_set *Domain,
1315 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1316
1317 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001318 return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001319
1320 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1321
1322 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001323 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00001324 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00001325 }
1326
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001327 Value *Condition = getConditionFromTerminator(TI);
1328 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001329
Johannes Doerfert171b92f2016-04-19 14:53:13 +00001330 return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001331}
1332
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001333void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001334 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001335
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001336 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001337 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001338}
1339
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001340void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP, LoopInfo &LI) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001341 isl_ctx *Ctx = Parent.getIslCtx();
1342 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001343 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001344
1345 // The set of loads that are required to be invariant.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001346 auto &ScopRIL = Parent.getRequiredInvariantLoads();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001347
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001348 std::vector<const SCEV *> Subscripts;
1349 std::vector<int> Sizes;
1350
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001351 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001352
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001353 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001354
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001355 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001356
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001357 auto *NotExecuted = isl_set_complement(isl_set_params(getDomain()));
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001358 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001359 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001360 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001361
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001362 auto *Scope = LI.getLoopFor(getEntryBlock());
Johannes Doerfert09e36972015-10-07 20:17:36 +00001363 InvariantLoadsSetTy AccessILS;
Johannes Doerfertec8a2172016-04-25 13:32:36 +00001364 if (!isAffineExpr(&Parent.getRegion(), Scope, Expr, SE, &AccessILS))
Johannes Doerfert09e36972015-10-07 20:17:36 +00001365 continue;
1366
1367 bool NonAffine = false;
1368 for (LoadInst *LInst : AccessILS)
1369 if (!ScopRIL.count(LInst))
1370 NonAffine = true;
1371
1372 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001373 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001374
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001375 isl_pw_aff *AccessOffset = getPwAff(Expr);
1376 AccessOffset =
1377 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001378
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001379 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1380 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001381
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001382 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1383 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1384 OutOfBound = isl_set_params(OutOfBound);
1385 isl_set *InBound = isl_set_complement(OutOfBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001386
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001387 // A => B == !A or B
1388 isl_set *InBoundIfExecuted =
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001389 isl_set_union(isl_set_copy(NotExecuted), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001390
Roman Gareev10595a12016-01-08 14:01:59 +00001391 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00001392 Parent.recordAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc(),
1393 AS_ASSUMPTION);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001394 }
1395
1396 isl_local_space_free(LSpace);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001397 isl_set_free(NotExecuted);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001398}
1399
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001400void ScopStmt::deriveAssumptions(LoopInfo &LI) {
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001401 for (auto *MA : *this) {
1402 if (!MA->isArrayKind())
1403 continue;
1404
1405 MemAccInst Acc(MA->getAccessInstruction());
1406 auto *GEP = dyn_cast_or_null<GetElementPtrInst>(Acc.getPointerOperand());
1407
1408 if (GEP)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001409 deriveAssumptionsFromGEP(GEP, LI);
Johannes Doerfertd5c369f2016-04-25 18:55:15 +00001410 }
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001411}
1412
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001413void ScopStmt::collectSurroundingLoops() {
1414 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1415 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1416 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1417 isl_id_free(DimId);
1418 }
1419}
1420
Michael Kruse9d080092015-09-11 21:41:48 +00001421ScopStmt::ScopStmt(Scop &parent, Region &R)
Johannes Doerferta3519512016-04-23 13:02:23 +00001422 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1423 R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001424
Tobias Grosser16c44032015-07-09 07:31:45 +00001425 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001426}
1427
Michael Kruse9d080092015-09-11 21:41:48 +00001428ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Johannes Doerferta3519512016-04-23 13:02:23 +00001429 : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1430 R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001431
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001432 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001433}
1434
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001435void ScopStmt::init(LoopInfo &LI) {
Michael Krusecac948e2015-10-02 13:53:07 +00001436 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001437
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001438 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001439 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001440 buildAccessRelations();
1441
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001442 deriveAssumptions(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00001443
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001444 if (DetectReductions)
1445 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001446}
1447
Johannes Doerferte58a0122014-06-27 20:31:28 +00001448/// @brief Collect loads which might form a reduction chain with @p StoreMA
1449///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001450/// Check if the stored value for @p StoreMA is a binary operator with one or
1451/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001452/// used only once (by @p StoreMA) and its load operands are also used only
1453/// once, we have found a possible reduction chain. It starts at an operand
1454/// load and includes the binary operator and @p StoreMA.
1455///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001456/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001457/// escape this block or into any other store except @p StoreMA.
1458void ScopStmt::collectCandiateReductionLoads(
1459 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1460 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1461 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001462 return;
1463
1464 // Skip if there is not one binary operator between the load and the store
1465 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001466 if (!BinOp)
1467 return;
1468
1469 // Skip if the binary operators has multiple uses
1470 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001471 return;
1472
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001473 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001474 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1475 return;
1476
Johannes Doerfert9890a052014-07-01 00:32:29 +00001477 // Skip if the binary operator is outside the current SCoP
1478 if (BinOp->getParent() != Store->getParent())
1479 return;
1480
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001481 // Skip if it is a multiplicative reduction and we disabled them
1482 if (DisableMultiplicativeReductions &&
1483 (BinOp->getOpcode() == Instruction::Mul ||
1484 BinOp->getOpcode() == Instruction::FMul))
1485 return;
1486
Johannes Doerferte58a0122014-06-27 20:31:28 +00001487 // Check the binary operator operands for a candidate load
1488 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1489 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1490 if (!PossibleLoad0 && !PossibleLoad1)
1491 return;
1492
1493 // A load is only a candidate if it cannot escape (thus has only this use)
1494 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001495 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001496 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001497 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001498 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001499 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001500}
1501
1502/// @brief Check for reductions in this ScopStmt
1503///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001504/// Iterate over all store memory accesses and check for valid binary reduction
1505/// like chains. For all candidates we check if they have the same base address
1506/// and there are no other accesses which overlap with them. The base address
1507/// check rules out impossible reductions candidates early. The overlap check,
1508/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001509/// guarantees that none of the intermediate results will escape during
1510/// execution of the loop nest. We basically check here that no other memory
1511/// access can access the same memory as the potential reduction.
1512void ScopStmt::checkForReductions() {
1513 SmallVector<MemoryAccess *, 2> Loads;
1514 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1515
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001516 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001517 // stores and collecting possible reduction loads.
1518 for (MemoryAccess *StoreMA : MemAccs) {
1519 if (StoreMA->isRead())
1520 continue;
1521
1522 Loads.clear();
1523 collectCandiateReductionLoads(StoreMA, Loads);
1524 for (MemoryAccess *LoadMA : Loads)
1525 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1526 }
1527
1528 // Then check each possible candidate pair.
1529 for (const auto &CandidatePair : Candidates) {
1530 bool Valid = true;
1531 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1532 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1533
1534 // Skip those with obviously unequal base addresses.
1535 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1536 isl_map_free(LoadAccs);
1537 isl_map_free(StoreAccs);
1538 continue;
1539 }
1540
1541 // And check if the remaining for overlap with other memory accesses.
1542 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1543 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1544 isl_set *AllAccs = isl_map_range(AllAccsRel);
1545
1546 for (MemoryAccess *MA : MemAccs) {
1547 if (MA == CandidatePair.first || MA == CandidatePair.second)
1548 continue;
1549
1550 isl_map *AccRel =
1551 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1552 isl_set *Accs = isl_map_range(AccRel);
1553
1554 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1555 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1556 Valid = Valid && isl_set_is_empty(OverlapAccs);
1557 isl_set_free(OverlapAccs);
1558 }
1559 }
1560
1561 isl_set_free(AllAccs);
1562 if (!Valid)
1563 continue;
1564
Johannes Doerfertf6183392014-07-01 20:52:51 +00001565 const LoadInst *Load =
1566 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1567 MemoryAccess::ReductionType RT =
1568 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1569
Johannes Doerferte58a0122014-06-27 20:31:28 +00001570 // If no overlapping access was found we mark the load and store as
1571 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001572 CandidatePair.first->markAsReductionLike(RT);
1573 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001574 }
Tobias Grosser75805372011-04-29 06:27:02 +00001575}
1576
Tobias Grosser74394f02013-01-14 22:40:23 +00001577std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001578
Tobias Grosser54839312015-04-21 11:37:25 +00001579std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001580 auto *S = getSchedule();
1581 auto Str = stringFromIslObj(S);
1582 isl_map_free(S);
1583 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001584}
1585
Johannes Doerferta3519512016-04-23 13:02:23 +00001586void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1587 isl_set_free(InvalidDomain);
1588 InvalidDomain = ID;
Johannes Doerfert7c013572016-04-12 09:57:34 +00001589}
1590
Michael Kruse375cb5f2016-02-24 22:08:24 +00001591BasicBlock *ScopStmt::getEntryBlock() const {
1592 if (isBlockStmt())
1593 return getBasicBlock();
1594 return getRegion()->getEntry();
1595}
1596
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001597unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001598
Tobias Grosser75805372011-04-29 06:27:02 +00001599const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1600
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001601Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001602 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001603}
1604
Tobias Grosser74394f02013-01-14 22:40:23 +00001605isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001606
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001607__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001608
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001609__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001610 return isl_set_get_space(Domain);
1611}
1612
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001613__isl_give isl_id *ScopStmt::getDomainId() const {
1614 return isl_set_get_tuple_id(Domain);
1615}
Tobias Grossercd95b772012-08-30 11:49:38 +00001616
Johannes Doerfert7c013572016-04-12 09:57:34 +00001617ScopStmt::~ScopStmt() {
1618 isl_set_free(Domain);
Johannes Doerferta3519512016-04-23 13:02:23 +00001619 isl_set_free(InvalidDomain);
Johannes Doerfert7c013572016-04-12 09:57:34 +00001620}
Tobias Grosser75805372011-04-29 06:27:02 +00001621
1622void ScopStmt::print(raw_ostream &OS) const {
1623 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001624 OS.indent(12) << "Domain :=\n";
1625
1626 if (Domain) {
1627 OS.indent(16) << getDomainStr() << ";\n";
1628 } else
1629 OS.indent(16) << "n/a\n";
1630
Tobias Grosser54839312015-04-21 11:37:25 +00001631 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001632
1633 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001634 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001635 } else
1636 OS.indent(16) << "n/a\n";
1637
Tobias Grosser083d3d32014-06-28 08:59:45 +00001638 for (MemoryAccess *Access : MemAccs)
1639 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001640}
1641
1642void ScopStmt::dump() const { print(dbgs()); }
1643
Michael Kruse10071822016-05-23 14:45:58 +00001644void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1645 // Remove the memory accesses from this statement
1646 // together with all scalar accesses that were caused by it.
Michael Krusead28e5a2016-01-26 13:33:15 +00001647 // MK_Value READs have no access instruction, hence would not be removed by
1648 // this function. However, it is only used for invariant LoadInst accesses,
1649 // its arguments are always affine, hence synthesizable, and therefore there
1650 // are no MK_Value READ accesses to be removed.
Michael Kruse10071822016-05-23 14:45:58 +00001651 auto Predicate = [&](MemoryAccess *Acc) {
1652 return Acc->getAccessInstruction() == MA->getAccessInstruction();
1653 };
1654 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1655 MemAccs.end());
1656 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001657}
1658
Tobias Grosser75805372011-04-29 06:27:02 +00001659//===----------------------------------------------------------------------===//
1660/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001661
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001662void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001663 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1664 isl_set_free(Context);
1665 Context = NewContext;
1666}
1667
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001668/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1669struct SCEVSensitiveParameterRewriter
1670 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1671 ValueToValueMap &VMap;
1672 ScalarEvolution &SE;
1673
1674public:
1675 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1676 : VMap(VMap), SE(SE) {}
1677
1678 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1679 ValueToValueMap &VMap) {
1680 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1681 return SSPR.visit(E);
1682 }
1683
1684 const SCEV *visit(const SCEV *E) {
1685 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1686 }
1687
1688 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1689
1690 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1691 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1692 }
1693
1694 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1695 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1696 }
1697
1698 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1699 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1700 }
1701
1702 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1703 SmallVector<const SCEV *, 4> Operands;
1704 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1705 Operands.push_back(visit(E->getOperand(i)));
1706 return SE.getAddExpr(Operands);
1707 }
1708
1709 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1710 SmallVector<const SCEV *, 4> Operands;
1711 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1712 Operands.push_back(visit(E->getOperand(i)));
1713 return SE.getMulExpr(Operands);
1714 }
1715
1716 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1717 SmallVector<const SCEV *, 4> Operands;
1718 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1719 Operands.push_back(visit(E->getOperand(i)));
1720 return SE.getSMaxExpr(Operands);
1721 }
1722
1723 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1724 SmallVector<const SCEV *, 4> Operands;
1725 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1726 Operands.push_back(visit(E->getOperand(i)));
1727 return SE.getUMaxExpr(Operands);
1728 }
1729
1730 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1731 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1732 }
1733
1734 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1735 auto *Start = visit(E->getStart());
1736 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1737 visit(E->getStepRecurrence(SE)),
1738 E->getLoop(), SCEV::FlagAnyWrap);
1739 return SE.getAddExpr(Start, AddRec);
1740 }
1741
1742 const SCEV *visitUnknown(const SCEVUnknown *E) {
1743 if (auto *NewValue = VMap.lookup(E->getValue()))
1744 return SE.getUnknown(NewValue);
1745 return E;
1746 }
1747};
1748
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001749const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001750 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001751}
1752
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001753void Scop::createParameterId(const SCEV *Parameter) {
1754 assert(Parameters.count(Parameter));
1755 assert(!ParameterIds.count(Parameter));
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001756
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001757 std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001758
Tobias Grosser8f99c162011-11-15 11:38:55 +00001759 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1760 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001761
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001762 // If this parameter references a specific Value and this value has a name
1763 // we use this name as it is likely to be unique and more useful than just
1764 // a number.
1765 if (Val->hasName())
1766 ParameterName = Val->getName();
1767 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001768 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001769 if (LoadOrigin->hasName()) {
1770 ParameterName += "_loaded_from_";
1771 ParameterName +=
1772 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1773 }
1774 }
1775 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001776
Tobias Grosser2ea7c6e2016-07-01 13:40:28 +00001777 ParameterName = getIslCompatibleName("", ParameterName, "");
1778
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001779 auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1780 const_cast<void *>((const void *)Parameter));
1781 ParameterIds[Parameter] = Id;
1782}
1783
1784void Scop::addParams(const ParameterSetTy &NewParameters) {
1785 for (const SCEV *Parameter : NewParameters) {
1786 // Normalize the SCEV to get the representing element for an invariant load.
1787 Parameter = extractConstantFactor(Parameter, *SE).second;
1788 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1789
1790 if (Parameters.insert(Parameter))
1791 createParameterId(Parameter);
1792 }
1793}
1794
1795__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1796 // Normalize the SCEV to get the representing element for an invariant load.
1797 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1798 return isl_id_copy(ParameterIds.lookup(Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001799}
Tobias Grosser75805372011-04-29 06:27:02 +00001800
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00001801__isl_give isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001802 isl_set *DomainContext = isl_union_set_params(getDomains());
1803 return isl_set_intersect_params(C, DomainContext);
1804}
1805
Johannes Doerferte0b08072016-05-23 12:43:44 +00001806bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1807 return DT.dominates(BB, getEntry());
1808}
1809
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001810void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1811 LoopInfo &LI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001812 auto &F = getFunction();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001813 for (auto &Assumption : AC.assumptions()) {
1814 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1815 if (!CI || CI->getNumArgOperands() != 1)
1816 continue;
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001817
Johannes Doerfert952b5302016-05-23 12:40:48 +00001818 bool InScop = contains(CI);
Johannes Doerferte0b08072016-05-23 12:43:44 +00001819 if (!InScop && !isDominatedBy(DT, CI->getParent()))
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001820 continue;
1821
Michael Kruse09eb4452016-03-03 22:10:47 +00001822 auto *L = LI.getLoopFor(CI->getParent());
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001823 auto *Val = CI->getArgOperand(0);
Johannes Doerfertf560b3d2016-04-25 13:33:07 +00001824 ParameterSetTy DetectedParams;
Johannes Doerfert3f52e352016-05-23 12:38:05 +00001825 if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001826 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1827 CI->getDebugLoc(),
1828 "Non-affine user assumption ignored.");
1829 continue;
1830 }
1831
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001832 // Collect all newly introduced parameters.
1833 ParameterSetTy NewParams;
1834 for (auto *Param : DetectedParams) {
1835 Param = extractConstantFactor(Param, *SE).second;
1836 Param = getRepresentingInvariantLoadSCEV(Param);
1837 if (Parameters.count(Param))
1838 continue;
1839 NewParams.insert(Param);
1840 }
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001841
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001842 SmallVector<isl_set *, 2> ConditionSets;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001843 auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1844 auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1845 auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001846 bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1847 isl_set_free(Dom);
1848
1849 if (!Valid)
Johannes Doerfert297c7202016-05-10 13:06:42 +00001850 continue;
1851
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001852 isl_set *AssumptionCtx = nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00001853 if (InScop) {
Johannes Doerfert2b92a0e2016-05-10 14:00:57 +00001854 AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1855 isl_set_free(ConditionSets[0]);
1856 } else {
1857 AssumptionCtx = isl_set_complement(ConditionSets[1]);
1858 AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1859 }
Johannes Doerfertc78ce7d2016-04-25 18:51:27 +00001860
1861 // Project out newly introduced parameters as they are not otherwise useful.
1862 if (!NewParams.empty()) {
1863 for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1864 auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1865 auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1866 isl_id_free(Id);
1867
1868 if (!NewParams.count(Param))
1869 continue;
1870
1871 AssumptionCtx =
1872 isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1873 }
1874 }
1875
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001876 emitOptimizationRemarkAnalysis(
1877 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1878 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1879 Context = isl_set_intersect(Context, AssumptionCtx);
1880 }
1881}
1882
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001883void Scop::addUserContext() {
1884 if (UserContextStr.empty())
1885 return;
1886
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001887 isl_set *UserContext =
1888 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001889 isl_space *Space = getParamSpace();
1890 if (isl_space_dim(Space, isl_dim_param) !=
1891 isl_set_dim(UserContext, isl_dim_param)) {
1892 auto SpaceStr = isl_space_to_str(Space);
1893 errs() << "Error: the context provided in -polly-context has not the same "
1894 << "number of dimensions than the computed context. Due to this "
1895 << "mismatch, the -polly-context option is ignored. Please provide "
1896 << "the context in the parameter space: " << SpaceStr << ".\n";
1897 free(SpaceStr);
1898 isl_set_free(UserContext);
1899 isl_space_free(Space);
1900 return;
1901 }
1902
1903 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001904 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1905 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001906
1907 if (strcmp(NameContext, NameUserContext) != 0) {
1908 auto SpaceStr = isl_space_to_str(Space);
1909 errs() << "Error: the name of dimension " << i
1910 << " provided in -polly-context "
1911 << "is '" << NameUserContext << "', but the name in the computed "
1912 << "context is '" << NameContext
1913 << "'. Due to this name mismatch, "
1914 << "the -polly-context option is ignored. Please provide "
1915 << "the context in the parameter space: " << SpaceStr << ".\n";
1916 free(SpaceStr);
1917 isl_set_free(UserContext);
1918 isl_space_free(Space);
1919 return;
1920 }
1921
1922 UserContext =
1923 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1924 isl_space_get_dim_id(Space, isl_dim_param, i));
1925 }
1926
1927 Context = isl_set_intersect(Context, UserContext);
1928 isl_space_free(Space);
1929}
1930
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001931void Scop::buildInvariantEquivalenceClasses() {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001932 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001933
Johannes Doerfertffd222f2016-05-19 12:34:57 +00001934 const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001935 for (LoadInst *LInst : RIL) {
1936 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1937
Johannes Doerfert96e54712016-02-07 17:30:13 +00001938 Type *Ty = LInst->getType();
1939 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001940 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001941 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001942 continue;
1943 }
1944
1945 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001946 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1947 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001948 }
1949}
1950
Tobias Grosser6be480c2011-11-08 15:41:13 +00001951void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001952 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001953 Context = isl_set_universe(isl_space_copy(Space));
Johannes Doerfert066dbf32016-03-01 13:06:28 +00001954 InvalidContext = isl_set_empty(isl_space_copy(Space));
Tobias Grossere86109f2013-10-29 21:05:49 +00001955 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001956}
1957
Tobias Grosser18daaca2012-05-22 10:47:27 +00001958void Scop::addParameterBounds() {
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001959 unsigned PDim = 0;
1960 for (auto *Parameter : Parameters) {
1961 ConstantRange SRange = SE->getSignedRange(Parameter);
1962 Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001963 }
1964}
1965
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001966void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001967 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001968 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001969
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001970 unsigned PDim = 0;
1971 for (const auto *Parameter : Parameters) {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001972 isl_id *id = getIdForParam(Parameter);
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00001973 Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001974 }
1975
1976 // Align the parameters of all data structures to the model.
1977 Context = isl_set_align_params(Context, Space);
1978
Johannes Doerferta60ad842016-05-10 12:18:22 +00001979 // As all parameters are known add bounds to them.
1980 addParameterBounds();
1981
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001982 for (ScopStmt &Stmt : *this)
1983 Stmt.realignParams();
Johannes Doerfert06445ded2016-06-02 15:07:41 +00001984
1985 // Simplify the schedule according to the context too.
1986 Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001987}
1988
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001989static __isl_give isl_set *
1990simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1991 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001992 // If we modelt all blocks in the SCoP that have side effects we can simplify
1993 // the context with the constraints that are needed for anything to be
1994 // executed at all. However, if we have error blocks in the SCoP we already
1995 // assumed some parameter combinations cannot occure and removed them from the
1996 // domains, thus we cannot use the remaining domain to simplify the
1997 // assumptions.
1998 if (!S.hasErrorBlock()) {
1999 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2000 AssumptionContext =
2001 isl_set_gist_params(AssumptionContext, DomainParameters);
2002 }
2003
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002004 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2005 return AssumptionContext;
2006}
2007
2008void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002009 // The parameter constraints of the iteration domains give us a set of
2010 // constraints that need to hold for all cases where at least a single
2011 // statement iteration is executed in the whole scop. We now simplify the
2012 // assumed context under the assumption that such constraints hold and at
2013 // least a single statement iteration is executed. For cases where no
2014 // statement instances are executed, the assumptions we have taken about
2015 // the executed code do not matter and can be changed.
2016 //
2017 // WARNING: This only holds if the assumptions we have taken do not reduce
2018 // the set of statement instances that are executed. Otherwise we
2019 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002020 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002021 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002022 // performed. In such a case, modifying the run-time conditions and
2023 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002024 // to not be executed.
2025 //
2026 // Example:
2027 //
2028 // When delinearizing the following code:
2029 //
2030 // for (long i = 0; i < 100; i++)
2031 // for (long j = 0; j < m; j++)
2032 // A[i+p][j] = 1.0;
2033 //
2034 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002035 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002036 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002037 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00002038 InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +00002039}
2040
Johannes Doerfertb164c792014-09-18 11:17:17 +00002041/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00002042static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002043 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2044 isl_pw_multi_aff *MinPMA, *MaxPMA;
2045 isl_pw_aff *LastDimAff;
2046 isl_aff *OneAff;
2047 unsigned Pos;
2048
Johannes Doerfert6296d952016-04-22 11:38:19 +00002049 Set = isl_set_remove_divs(Set);
2050
Michael Krusebc150122016-05-02 12:25:18 +00002051 if (isl_set_n_basic_set(Set) >= MaxDisjunctionsInDomain) {
Johannes Doerfert6296d952016-04-22 11:38:19 +00002052 isl_set_free(Set);
2053 return isl_stat_error;
2054 }
2055
Johannes Doerfert9143d672014-09-27 11:02:39 +00002056 // Restrict the number of parameters involved in the access as the lexmin/
2057 // lexmax computation will take too long if this number is high.
2058 //
2059 // Experiments with a simple test case using an i7 4800MQ:
2060 //
2061 // #Parameters involved | Time (in sec)
2062 // 6 | 0.01
2063 // 7 | 0.04
2064 // 8 | 0.12
2065 // 9 | 0.40
2066 // 10 | 1.54
2067 // 11 | 6.78
2068 // 12 | 30.38
2069 //
2070 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2071 unsigned InvolvedParams = 0;
2072 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2073 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2074 InvolvedParams++;
2075
2076 if (InvolvedParams > RunTimeChecksMaxParameters) {
2077 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002078 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002079 }
2080 }
2081
Johannes Doerfertb164c792014-09-18 11:17:17 +00002082 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2083 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2084
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002085 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2086 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2087
Johannes Doerfertb164c792014-09-18 11:17:17 +00002088 // Adjust the last dimension of the maximal access by one as we want to
2089 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2090 // we test during code generation might now point after the end of the
2091 // allocated array but we will never dereference it anyway.
2092 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2093 "Assumed at least one output dimension");
2094 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2095 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2096 OneAff = isl_aff_zero_on_domain(
2097 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2098 OneAff = isl_aff_add_constant_si(OneAff, 1);
2099 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2100 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2101
2102 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2103
2104 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002105 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002106}
2107
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002108static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2109 isl_set *Domain = MA->getStatement()->getDomain();
2110 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2111 return isl_set_reset_tuple_id(Domain);
2112}
2113
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002114/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2115static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002116 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002117 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002118
2119 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2120 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002121 Locations = isl_union_set_coalesce(Locations);
2122 Locations = isl_union_set_detect_equalities(Locations);
2123 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002124 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002125 isl_union_set_free(Locations);
2126 return Valid;
2127}
2128
Johannes Doerfert96425c22015-08-30 21:13:53 +00002129/// @brief Helper to treat non-affine regions and basic blocks the same.
2130///
2131///{
2132
2133/// @brief Return the block that is the representing block for @p RN.
2134static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2135 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2136 : RN->getNodeAs<BasicBlock>();
2137}
2138
2139/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002140static inline BasicBlock *
2141getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002142 if (RN->isSubRegion()) {
2143 assert(idx == 0);
2144 return RN->getNodeAs<Region>()->getExit();
2145 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002146 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002147}
2148
2149/// @brief Return the smallest loop surrounding @p RN.
2150static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2151 if (!RN->isSubRegion())
2152 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2153
2154 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2155 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2156 while (L && NonAffineSubRegion->contains(L))
2157 L = L->getParentLoop();
2158 return L;
2159}
2160
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002161static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2162 if (!RN->isSubRegion())
2163 return 1;
2164
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002165 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002166 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002167}
2168
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002169static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2170 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002171 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002172 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002173 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002174 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002175 return true;
2176 return false;
2177}
2178
Johannes Doerfert96425c22015-08-30 21:13:53 +00002179///}
2180
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002181static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2182 unsigned Dim, Loop *L) {
Michael Kruse88a22562016-03-29 07:50:52 +00002183 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002184 isl_id *DimId =
2185 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2186 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2187}
2188
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002189__isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002190 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002191}
2192
Johannes Doerfertfff283d2016-04-19 14:48:22 +00002193__isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
Johannes Doerfert41cda152016-04-08 10:32:26 +00002194 auto DIt = DomainMap.find(BB);
2195 if (DIt != DomainMap.end())
2196 return isl_set_copy(DIt->getSecond());
2197
2198 auto &RI = *R.getRegionInfo();
2199 auto *BBR = RI.getRegionFor(BB);
2200 while (BBR->getEntry() == BB)
2201 BBR = BBR->getParent();
2202 return getDomainConditions(BBR->getEntry());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002203}
2204
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002205bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002206
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002207 bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002208 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002209 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2210 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002211 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002212
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002213 while (LD-- >= 0) {
2214 S = addDomainDimId(S, LD + 1, L);
2215 L = L->getParentLoop();
2216 }
2217
Johannes Doerferta3519512016-04-23 13:02:23 +00002218 // Initialize the invalid domain.
2219 auto *EntryStmt = getStmtFor(EntryBB);
2220 EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2221
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002222 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002223
Johannes Doerfert432658d2016-01-26 11:01:41 +00002224 if (IsOnlyNonAffineRegion)
Johannes Doerfert26404542016-05-10 12:19:47 +00002225 return !containsErrorBlock(R->getNode(), *R, LI, DT);
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002226
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002227 if (!buildDomainsWithBranchConstraints(R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002228 return false;
2229
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002230 if (!propagateDomainConstraints(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002231 return false;
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002232
2233 // Error blocks and blocks dominated by them have been assumed to never be
2234 // executed. Representing them in the Scop does not add any value. In fact,
2235 // it is likely to cause issues during construction of the ScopStmts. The
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002236 // contents of error blocks have not been verified to be expressible and
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002237 // will cause problems when building up a ScopStmt for them.
2238 // Furthermore, basic blocks dominated by error blocks may reference
2239 // instructions in the error block which, if the error block is not modeled,
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002240 // can themselves not be constructed properly. To this end we will replace
2241 // the domains of error blocks and those only reachable via error blocks
2242 // with an empty set. Additionally, we will record for each block under which
Johannes Doerfert7c013572016-04-12 09:57:34 +00002243 // parameter combination it would be reached via an error block in its
Johannes Doerferta3519512016-04-23 13:02:23 +00002244 // InvalidDomain. This information is needed during load hoisting.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002245 if (!propagateInvalidStmtDomains(R, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002246 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002247
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002248 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002249}
2250
Michael Kruse586e5792016-07-08 12:38:28 +00002251// If the loop is nonaffine/boxed, return the first non-boxed surrounding loop
2252// for Polly. If the loop is affine, return the loop itself. Do not call
2253// `getSCEVAtScope()` on the result of `getFirstNonBoxedLoopFor()`, as we need
2254// to analyze the memory accesses of the nonaffine/boxed loops.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002255static Loop *getFirstNonBoxedLoopFor(BasicBlock *BB, LoopInfo &LI,
2256 const BoxedLoopsSetTy &BoxedLoops) {
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002257 auto *L = LI.getLoopFor(BB);
2258 while (BoxedLoops.count(L))
2259 L = L->getParentLoop();
2260 return L;
2261}
2262
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002263/// @brief Adjust the dimensions of @p Dom that was constructed for @p OldL
2264/// to be compatible to domains constructed for loop @p NewL.
2265///
2266/// This function assumes @p NewL and @p OldL are equal or there is a CFG
2267/// edge from @p OldL to @p NewL.
2268static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2269 __isl_take isl_set *Dom,
2270 Loop *OldL, Loop *NewL) {
2271
2272 // If the loops are the same there is nothing to do.
2273 if (NewL == OldL)
2274 return Dom;
2275
2276 int OldDepth = S.getRelativeLoopDepth(OldL);
2277 int NewDepth = S.getRelativeLoopDepth(NewL);
2278 // If both loops are non-affine loops there is nothing to do.
2279 if (OldDepth == -1 && NewDepth == -1)
2280 return Dom;
2281
2282 // Distinguish three cases:
2283 // 1) The depth is the same but the loops are not.
2284 // => One loop was left one was entered.
2285 // 2) The depth increased from OldL to NewL.
2286 // => One loop was entered, none was left.
2287 // 3) The depth decreased from OldL to NewL.
2288 // => Loops were left were difference of the depths defines how many.
2289 if (OldDepth == NewDepth) {
2290 assert(OldL->getParentLoop() == NewL->getParentLoop());
2291 Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2292 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2293 Dom = addDomainDimId(Dom, NewDepth, NewL);
2294 } else if (OldDepth < NewDepth) {
2295 assert(OldDepth + 1 == NewDepth);
2296 auto &R = S.getRegion();
2297 (void)R;
2298 assert(NewL->getParentLoop() == OldL ||
2299 ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2300 Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2301 Dom = addDomainDimId(Dom, NewDepth, NewL);
2302 } else {
2303 assert(OldDepth > NewDepth);
2304 int Diff = OldDepth - NewDepth;
2305 int NumDim = isl_set_n_dim(Dom);
2306 assert(NumDim >= Diff);
2307 Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2308 }
2309
2310 return Dom;
2311}
Johannes Doerfert642594a2016-04-04 07:57:39 +00002312
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002313bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2314 LoopInfo &LI) {
2315 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002316
2317 ReversePostOrderTraversal<Region *> RTraversal(R);
2318 for (auto *RN : RTraversal) {
2319
2320 // Recurse for affine subregions but go on for basic blocks and non-affine
2321 // subregions.
2322 if (RN->isSubRegion()) {
2323 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002324 if (!isNonAffineSubRegion(SubRegion)) {
2325 propagateInvalidStmtDomains(SubRegion, DT, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002326 continue;
2327 }
2328 }
2329
2330 bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2331 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002332 ScopStmt *Stmt = getStmtFor(BB);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002333 isl_set *&Domain = DomainMap[BB];
2334 assert(Domain && "Cannot propagate a nullptr");
2335
Johannes Doerferta3519512016-04-23 13:02:23 +00002336 auto *InvalidDomain = Stmt->getInvalidDomain();
Johannes Doerfert7c013572016-04-12 09:57:34 +00002337 bool IsInvalidBlock =
Johannes Doerferta3519512016-04-23 13:02:23 +00002338 ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002339
Johannes Doerferta3519512016-04-23 13:02:23 +00002340 if (!IsInvalidBlock) {
2341 InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002342 } else {
Johannes Doerferta3519512016-04-23 13:02:23 +00002343 isl_set_free(InvalidDomain);
2344 InvalidDomain = Domain;
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00002345 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2346 recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2347 AS_RESTRICTION);
2348 Domain = nullptr;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002349 }
2350
Johannes Doerferta3519512016-04-23 13:02:23 +00002351 if (isl_set_is_empty(InvalidDomain)) {
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00002352 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002353 continue;
Johannes Doerfert7c013572016-04-12 09:57:34 +00002354 }
2355
Johannes Doerferta3519512016-04-23 13:02:23 +00002356 auto *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002357 auto *TI = BB->getTerminator();
2358 unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2359 for (unsigned u = 0; u < NumSuccs; u++) {
2360 auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert7c013572016-04-12 09:57:34 +00002361 auto *SuccStmt = getStmtFor(SuccBB);
2362
2363 // Skip successors outside the SCoP.
2364 if (!SuccStmt)
2365 continue;
2366
Johannes Doerferte4459a22016-04-25 13:34:50 +00002367 // Skip backedges.
2368 if (DT.dominates(SuccBB, BB))
2369 continue;
2370
Johannes Doerferta3519512016-04-23 13:02:23 +00002371 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2372 auto *AdjustedInvalidDomain = adjustDomainDimensions(
2373 *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2374 auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2375 SuccInvalidDomain =
2376 isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2377 SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2378 unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2379 SuccStmt->setInvalidDomain(SuccInvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002380
Michael Krusebc150122016-05-02 12:25:18 +00002381 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002382 // In case this happens we will bail.
Michael Krusebc150122016-05-02 12:25:18 +00002383 if (NumConjucts < MaxDisjunctionsInDomain)
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002384 continue;
2385
Johannes Doerferta3519512016-04-23 13:02:23 +00002386 isl_set_free(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002387 invalidate(COMPLEXITY, TI->getDebugLoc());
Johannes Doerfert297c7202016-05-10 13:06:42 +00002388 return false;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002389 }
Johannes Doerferta3519512016-04-23 13:02:23 +00002390
2391 Stmt->setInvalidDomain(InvalidDomain);
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002392 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002393
2394 return true;
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00002395}
2396
Johannes Doerfert642594a2016-04-04 07:57:39 +00002397void Scop::propagateDomainConstraintsToRegionExit(
2398 BasicBlock *BB, Loop *BBLoop,
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002399 SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002400
2401 // Check if the block @p BB is the entry of a region. If so we propagate it's
2402 // domain to the exit block of the region. Otherwise we are done.
2403 auto *RI = R.getRegionInfo();
2404 auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2405 auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002406 if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
Johannes Doerfert642594a2016-04-04 07:57:39 +00002407 return;
2408
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002409 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002410 // Do not propagate the domain if there is a loop backedge inside the region
2411 // that would prevent the exit block from beeing executed.
2412 auto *L = BBLoop;
Johannes Doerfert952b5302016-05-23 12:40:48 +00002413 while (L && contains(L)) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002414 SmallVector<BasicBlock *, 4> LatchBBs;
2415 BBLoop->getLoopLatches(LatchBBs);
2416 for (auto *LatchBB : LatchBBs)
2417 if (BB != LatchBB && BBReg->contains(LatchBB))
2418 return;
2419 L = L->getParentLoop();
2420 }
2421
2422 auto *Domain = DomainMap[BB];
2423 assert(Domain && "Cannot propagate a nullptr");
2424
2425 auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2426
2427 // Since the dimensions of @p BB and @p ExitBB might be different we have to
2428 // adjust the domain before we can propagate it.
2429 auto *AdjustedDomain =
2430 adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2431 auto *&ExitDomain = DomainMap[ExitBB];
2432
2433 // If the exit domain is not yet created we set it otherwise we "add" the
2434 // current domain.
2435 ExitDomain =
2436 ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2437
Johannes Doerferta3519512016-04-23 13:02:23 +00002438 // Initialize the invalid domain.
2439 auto *ExitStmt = getStmtFor(ExitBB);
2440 ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2441
Johannes Doerfert642594a2016-04-04 07:57:39 +00002442 FinishedExitBlocks.insert(ExitBB);
2443}
2444
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002445bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2446 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002447 // To create the domain for each block in R we iterate over all blocks and
2448 // subregions in R and propagate the conditions under which the current region
2449 // element is executed. To this end we iterate in reverse post order over R as
2450 // it ensures that we first visit all predecessors of a region node (either a
2451 // basic block or a subregion) before we visit the region node itself.
2452 // Initially, only the domain for the SCoP region entry block is set and from
2453 // there we propagate the current domain to all successors, however we add the
2454 // condition that the successor is actually executed next.
2455 // As we are only interested in non-loop carried constraints here we can
2456 // simply skip loop back edges.
2457
Johannes Doerfert642594a2016-04-04 07:57:39 +00002458 SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002459 ReversePostOrderTraversal<Region *> RTraversal(R);
2460 for (auto *RN : RTraversal) {
2461
2462 // Recurse for affine subregions but go on for basic blocks and non-affine
2463 // subregions.
2464 if (RN->isSubRegion()) {
2465 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002466 if (!isNonAffineSubRegion(SubRegion)) {
2467 if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002468 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002469 continue;
2470 }
2471 }
2472
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002473 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002474 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002475
Johannes Doerfert96425c22015-08-30 21:13:53 +00002476 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002477 TerminatorInst *TI = BB->getTerminator();
2478
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002479 if (isa<UnreachableInst>(TI))
2480 continue;
2481
Johannes Doerfertf5673802015-10-01 23:48:18 +00002482 isl_set *Domain = DomainMap.lookup(BB);
Tobias Grosser4fb9e512016-02-27 06:59:30 +00002483 if (!Domain)
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002484 continue;
Johannes Doerfert60dd9e12016-05-19 12:33:14 +00002485 MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
Johannes Doerfert96425c22015-08-30 21:13:53 +00002486
Johannes Doerfert642594a2016-04-04 07:57:39 +00002487 auto *BBLoop = getRegionNodeLoop(RN, LI);
2488 // Propagate the domain from BB directly to blocks that have a superset
2489 // domain, at the moment only region exit nodes of regions that start in BB.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002490 propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002491
2492 // If all successors of BB have been set a domain through the propagation
2493 // above we do not need to build condition sets but can just skip this
2494 // block. However, it is important to note that this is a local property
2495 // with regards to the region @p R. To this end FinishedExitBlocks is a
2496 // local variable.
2497 auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2498 return FinishedExitBlocks.count(SuccBB);
2499 };
2500 if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2501 continue;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002502
2503 // Build the condition sets for the successor nodes of the current region
2504 // node. If it is a non-affine subregion we will always execute the single
2505 // exit node, hence the single entry node domain is the condition set. For
2506 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002507 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002508 if (RN->isSubRegion())
2509 ConditionSets.push_back(isl_set_copy(Domain));
Johannes Doerfert297c7202016-05-10 13:06:42 +00002510 else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2511 ConditionSets))
2512 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002513
2514 // Now iterate over the successors and set their initial domain based on
2515 // their condition set. We skip back edges here and have to be careful when
2516 // we leave a loop not to keep constraints over a dimension that doesn't
2517 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002518 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002519 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002520 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002521 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002522
Johannes Doerfert535de032016-04-19 14:49:05 +00002523 auto *SuccStmt = getStmtFor(SuccBB);
2524 // Skip blocks outside the region.
2525 if (!SuccStmt) {
2526 isl_set_free(CondSet);
2527 continue;
2528 }
2529
Johannes Doerfert642594a2016-04-04 07:57:39 +00002530 // If we propagate the domain of some block to "SuccBB" we do not have to
2531 // adjust the domain.
2532 if (FinishedExitBlocks.count(SuccBB)) {
2533 isl_set_free(CondSet);
2534 continue;
2535 }
2536
Johannes Doerfert96425c22015-08-30 21:13:53 +00002537 // Skip back edges.
2538 if (DT.dominates(SuccBB, BB)) {
2539 isl_set_free(CondSet);
2540 continue;
2541 }
2542
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002543 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert29cb0672016-03-29 20:32:43 +00002544 auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
Johannes Doerferta07f0ac2016-04-04 07:50:40 +00002545 CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002546
2547 // Set the domain for the successor or merge it with an existing domain in
2548 // case there are multiple paths (without loop back edges) to the
2549 // successor block.
2550 isl_set *&SuccDomain = DomainMap[SuccBB];
Tobias Grosser5a8c0522016-03-22 22:05:32 +00002551
Johannes Doerferta3519512016-04-23 13:02:23 +00002552 if (SuccDomain) {
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002553 SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
Johannes Doerferta3519512016-04-23 13:02:23 +00002554 } else {
2555 // Initialize the invalid domain.
2556 SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2557 SuccDomain = CondSet;
2558 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002559
Michael Krusebc150122016-05-02 12:25:18 +00002560 // Check if the maximal number of domain disjunctions was reached.
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002561 // In case this happens we will clean up and bail.
Michael Krusebc150122016-05-02 12:25:18 +00002562 if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctionsInDomain)
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002563 continue;
2564
2565 invalidate(COMPLEXITY, DebugLoc());
2566 while (++u < ConditionSets.size())
2567 isl_set_free(ConditionSets[u]);
2568 return false;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002569 }
2570 }
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00002571
2572 return true;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002573}
2574
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002575__isl_give isl_set *Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2576 isl_set *Domain,
Johannes Doerfert3c6a99b2016-04-09 21:55:23 +00002577 DominatorTree &DT,
2578 LoopInfo &LI) {
Johannes Doerfert642594a2016-04-04 07:57:39 +00002579 // If @p BB is the ScopEntry we are done
2580 if (R.getEntry() == BB)
2581 return isl_set_universe(isl_set_get_space(Domain));
2582
2583 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002584 auto &BoxedLoops = getBoxedLoops();
Johannes Doerfert642594a2016-04-04 07:57:39 +00002585
2586 // The region info of this function.
2587 auto &RI = *R.getRegionInfo();
2588
2589 auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2590
2591 // A domain to collect all predecessor domains, thus all conditions under
2592 // which the block is executed. To this end we start with the empty domain.
2593 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2594
2595 // Set of regions of which the entry block domain has been propagated to BB.
2596 // all predecessors inside any of the regions can be skipped.
2597 SmallSet<Region *, 8> PropagatedRegions;
2598
2599 for (auto *PredBB : predecessors(BB)) {
2600 // Skip backedges.
2601 if (DT.dominates(BB, PredBB))
2602 continue;
2603
2604 // If the predecessor is in a region we used for propagation we can skip it.
2605 auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2606 if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2607 PredBBInRegion)) {
2608 continue;
2609 }
2610
2611 // Check if there is a valid region we can use for propagation, thus look
2612 // for a region that contains the predecessor and has @p BB as exit block.
2613 auto *PredR = RI.getRegionFor(PredBB);
2614 while (PredR->getExit() != BB && !PredR->contains(BB))
2615 PredR->getParent();
2616
2617 // If a valid region for propagation was found use the entry of that region
2618 // for propagation, otherwise the PredBB directly.
2619 if (PredR->getExit() == BB) {
2620 PredBB = PredR->getEntry();
2621 PropagatedRegions.insert(PredR);
2622 }
2623
Johannes Doerfert41cda152016-04-08 10:32:26 +00002624 auto *PredBBDom = getDomainConditions(PredBB);
Johannes Doerfert642594a2016-04-04 07:57:39 +00002625 auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2626 PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2627
2628 PredDom = isl_set_union(PredDom, PredBBDom);
2629 }
2630
2631 return PredDom;
2632}
2633
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002634bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2635 LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002636 // Iterate over the region R and propagate the domain constrains from the
2637 // predecessors to the current node. In contrast to the
2638 // buildDomainsWithBranchConstraints function, this one will pull the domain
2639 // information from the predecessors instead of pushing it to the successors.
2640 // Additionally, we assume the domains to be already present in the domain
2641 // map here. However, we iterate again in reverse post order so we know all
2642 // predecessors have been visited before a block or non-affine subregion is
2643 // visited.
2644
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002645 ReversePostOrderTraversal<Region *> RTraversal(R);
2646 for (auto *RN : RTraversal) {
2647
2648 // Recurse for affine subregions but go on for basic blocks and non-affine
2649 // subregions.
2650 if (RN->isSubRegion()) {
2651 Region *SubRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002652 if (!isNonAffineSubRegion(SubRegion)) {
2653 if (!propagateDomainConstraints(SubRegion, DT, LI))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002654 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002655 continue;
2656 }
2657 }
2658
2659 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002660 isl_set *&Domain = DomainMap[BB];
Johannes Doerferta49c5572016-04-05 16:18:53 +00002661 assert(Domain);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002662
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002663 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00002664 auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002665 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert642594a2016-04-04 07:57:39 +00002666 Domain = isl_set_align_params(Domain, getParamSpace());
Tobias Grosser6deba4e2016-03-30 18:18:31 +00002667
Johannes Doerfert642594a2016-04-04 07:57:39 +00002668 Loop *BBLoop = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00002669 if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
Johannes Doerfert297c7202016-05-10 13:06:42 +00002670 if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2671 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002672 }
Johannes Doerfert297c7202016-05-10 13:06:42 +00002673
2674 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002675}
2676
2677/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2678/// is incremented by one and all other dimensions are equal, e.g.,
2679/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2680/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2681static __isl_give isl_map *
2682createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2683 auto *MapSpace = isl_space_map_from_set(SetSpace);
2684 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2685 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2686 if (u != Dim)
2687 NextIterationMap =
2688 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2689 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2690 C = isl_constraint_set_constant_si(C, 1);
2691 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2692 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2693 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2694 return NextIterationMap;
2695}
2696
Johannes Doerfert297c7202016-05-10 13:06:42 +00002697bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002698 int LoopDepth = getRelativeLoopDepth(L);
2699 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002700
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002701 BasicBlock *HeaderBB = L->getHeader();
2702 assert(DomainMap.count(HeaderBB));
2703 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002704
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002705 isl_map *NextIterationMap =
2706 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002707
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002708 isl_set *UnionBackedgeCondition =
2709 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002710
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002711 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2712 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002713
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002714 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002715
2716 // If the latch is only reachable via error statements we skip it.
2717 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2718 if (!LatchBBDom)
2719 continue;
2720
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002721 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002722
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002723 TerminatorInst *TI = LatchBB->getTerminator();
2724 BranchInst *BI = dyn_cast<BranchInst>(TI);
2725 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002726 BackedgeCondition = isl_set_copy(LatchBBDom);
2727 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002728 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002729 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert297c7202016-05-10 13:06:42 +00002730 if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2731 ConditionSets))
2732 return false;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002733
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002734 // Free the non back edge condition set as we do not need it.
2735 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002736
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002737 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002738 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002739
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002740 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2741 assert(LatchLoopDepth >= LoopDepth);
2742 BackedgeCondition =
2743 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2744 LatchLoopDepth - LoopDepth);
2745 UnionBackedgeCondition =
2746 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002747 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002748
2749 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2750 for (int i = 0; i < LoopDepth; i++)
2751 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2752
2753 isl_set *UnionBackedgeConditionComplement =
2754 isl_set_complement(UnionBackedgeCondition);
2755 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2756 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2757 UnionBackedgeConditionComplement =
2758 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2759 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2760 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2761
2762 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2763 HeaderBBDom = Parts.second;
2764
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002765 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2766 // the bounded assumptions to the context as they are already implied by the
2767 // <nsw> tag.
2768 if (Affinator.hasNSWAddRecForLoop(L)) {
2769 isl_set_free(Parts.first);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002770 return true;
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002771 }
2772
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002773 isl_set *UnboundedCtx = isl_set_params(Parts.first);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00002774 recordAssumption(INFINITELOOP, UnboundedCtx,
2775 HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
Johannes Doerfert297c7202016-05-10 13:06:42 +00002776 return true;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002777}
2778
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002779MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2780 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2781 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2782 if (!PointerBase)
2783 return nullptr;
2784
2785 auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase->getValue());
2786 if (!PointerBaseInst)
2787 return nullptr;
2788
2789 auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2790 if (!BasePtrStmt)
2791 return nullptr;
2792
2793 return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2794}
2795
2796bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2797 __isl_keep isl_union_map *Writes) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00002798 if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2799 auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2800 bool Hoistable = NHCtx != nullptr;
2801 isl_set_free(NHCtx);
2802 return !Hoistable;
2803 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002804
2805 auto *BaseAddr = SE->getSCEV(MA->getBaseAddr());
2806 auto *PointerBase = dyn_cast<SCEVUnknown>(SE->getPointerBase(BaseAddr));
2807 if (auto *BasePtrInst = dyn_cast<Instruction>(PointerBase->getValue()))
2808 if (!isa<LoadInst>(BasePtrInst))
Johannes Doerfert952b5302016-05-23 12:40:48 +00002809 return contains(BasePtrInst);
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002810
2811 return false;
2812}
2813
Johannes Doerfert5210da52016-06-02 11:06:54 +00002814bool Scop::buildAliasChecks(AliasAnalysis &AA) {
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002815 if (!PollyUseRuntimeAliasChecks)
Johannes Doerfert5210da52016-06-02 11:06:54 +00002816 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002817
2818 if (buildAliasGroups(AA))
Johannes Doerfert5210da52016-06-02 11:06:54 +00002819 return true;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002820
2821 // If a problem occurs while building the alias groups we need to delete
2822 // this SCoP and pretend it wasn't valid in the first place. To this end
2823 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002824 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002825
2826 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2827 << " could not be created as the number of parameters involved "
2828 "is too high. The SCoP will be "
2829 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2830 "the maximal number of parameters but be advised that the "
2831 "compile time might increase exponentially.\n\n");
Johannes Doerfert5210da52016-06-02 11:06:54 +00002832 return false;
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002833}
2834
Johannes Doerfert9143d672014-09-27 11:02:39 +00002835bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002836 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002837 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002838 // for all memory accesses inside the SCoP.
2839 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002840 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002841 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002842 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002843 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002844 // if their access domains intersect, otherwise they are in different
2845 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002846 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002847 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002848 // and maximal accesses to each array of a group in read only and non
2849 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002850 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2851
2852 AliasSetTracker AST(AA);
2853
2854 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002855 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002856 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002857
2858 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002859 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002860 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2861 isl_set_free(StmtDomain);
2862 if (StmtDomainEmpty)
2863 continue;
2864
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002865 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002866 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002867 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002868 if (!MA->isRead())
2869 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002870 MemAccInst Acc(MA->getAccessInstruction());
Hongbin Zheng8efb22e2016-02-27 01:49:58 +00002871 if (MA->isRead() && isa<MemTransferInst>(Acc))
2872 PtrToAcc[cast<MemTransferInst>(Acc)->getSource()] = MA;
Johannes Doerfertcea61932016-02-21 19:13:19 +00002873 else
2874 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002875 AST.add(Acc);
2876 }
2877 }
2878
2879 SmallVector<AliasGroupTy, 4> AliasGroups;
2880 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002881 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002882 continue;
2883 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002884 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002885 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002886 if (AG.size() < 2)
2887 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002888 AliasGroups.push_back(std::move(AG));
2889 }
2890
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002891 // Split the alias groups based on their domain.
2892 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2893 AliasGroupTy NewAG;
2894 AliasGroupTy &AG = AliasGroups[u];
2895 AliasGroupTy::iterator AGI = AG.begin();
2896 isl_set *AGDomain = getAccessDomain(*AGI);
2897 while (AGI != AG.end()) {
2898 MemoryAccess *MA = *AGI;
2899 isl_set *MADomain = getAccessDomain(MA);
2900 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2901 NewAG.push_back(MA);
2902 AGI = AG.erase(AGI);
2903 isl_set_free(MADomain);
2904 } else {
2905 AGDomain = isl_set_union(AGDomain, MADomain);
2906 AGI++;
2907 }
2908 }
2909 if (NewAG.size() > 1)
2910 AliasGroups.push_back(std::move(NewAG));
2911 isl_set_free(AGDomain);
2912 }
2913
Johannes Doerfert3f52e352016-05-23 12:38:05 +00002914 auto &F = getFunction();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002915 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002916 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2917 for (AliasGroupTy &AG : AliasGroups) {
2918 NonReadOnlyBaseValues.clear();
2919 ReadOnlyPairs.clear();
2920
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002921 if (AG.size() < 2) {
2922 AG.clear();
2923 continue;
2924 }
2925
Johannes Doerfert13771732014-10-01 12:40:46 +00002926 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002927 emitOptimizationRemarkAnalysis(
2928 F.getContext(), DEBUG_TYPE, F,
2929 (*II)->getAccessInstruction()->getDebugLoc(),
2930 "Possibly aliasing pointer, use restrict keyword.");
2931
Johannes Doerfert13771732014-10-01 12:40:46 +00002932 Value *BaseAddr = (*II)->getBaseAddr();
2933 if (HasWriteAccess.count(BaseAddr)) {
2934 NonReadOnlyBaseValues.insert(BaseAddr);
2935 II++;
2936 } else {
2937 ReadOnlyPairs[BaseAddr].insert(*II);
2938 II = AG.erase(II);
2939 }
2940 }
2941
2942 // If we don't have read only pointers check if there are at least two
2943 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002944 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002945 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002946 continue;
2947 }
2948
2949 // If we don't have non read only pointers clear the alias group.
2950 if (NonReadOnlyBaseValues.empty()) {
2951 AG.clear();
2952 continue;
2953 }
2954
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002955 // Check if we have non-affine accesses left, if so bail out as we cannot
2956 // generate a good access range yet.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002957 for (auto *MA : AG) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002958 if (!MA->isAffine()) {
2959 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2960 return false;
2961 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002962 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
2963 addRequiredInvariantLoad(
2964 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
2965 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002966 for (auto &ReadOnlyPair : ReadOnlyPairs)
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002967 for (auto *MA : ReadOnlyPair.second) {
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002968 if (!MA->isAffine()) {
2969 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2970 return false;
2971 }
Johannes Doerfert764b7e62016-05-23 09:26:46 +00002972 if (auto *BasePtrMA = lookupBasePtrAccess(MA))
2973 addRequiredInvariantLoad(
2974 cast<LoadInst>(BasePtrMA->getAccessInstruction()));
2975 }
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002976
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002977 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002978 MinMaxAliasGroups.emplace_back();
2979 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2980 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2981 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2982 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002983
2984 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002985
2986 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002987 for (MemoryAccess *MA : AG)
2988 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002989
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002990 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2991 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002992
2993 // Bail out if the number of values we need to compare is too large.
2994 // This is important as the number of comparisions grows quadratically with
2995 // the number of values we need to compare.
Johannes Doerfert5210da52016-06-02 11:06:54 +00002996 if (!Valid || (MinMaxAccessesNonReadOnly.size() + ReadOnlyPairs.size() >
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002997 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002998 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002999
3000 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003001 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003002 Accesses = isl_union_map_empty(getParamSpace());
3003
3004 for (const auto &ReadOnlyPair : ReadOnlyPairs)
3005 for (MemoryAccess *MA : ReadOnlyPair.second)
3006 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
3007
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00003008 Valid =
3009 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00003010
3011 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003012 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003013 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00003014
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00003015 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00003016}
3017
Johannes Doerfertef744432016-05-23 12:42:38 +00003018/// @brief Get the smallest loop that contains @p S but is not in @p S.
3019static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003020 // Start with the smallest loop containing the entry and expand that
3021 // loop until it contains all blocks in the region. If there is a loop
3022 // containing all blocks in the region check if it is itself contained
3023 // and if so take the parent loop as it will be the smallest containing
3024 // the region but not contained by it.
Johannes Doerfertef744432016-05-23 12:42:38 +00003025 Loop *L = LI.getLoopFor(S.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003026 while (L) {
3027 bool AllContained = true;
Johannes Doerfertef744432016-05-23 12:42:38 +00003028 for (auto *BB : S.blocks())
Johannes Doerfertdec27df2015-11-21 16:56:13 +00003029 AllContained &= L->contains(BB);
3030 if (AllContained)
3031 break;
3032 L = L->getParentLoop();
3033 }
3034
Johannes Doerfertef744432016-05-23 12:42:38 +00003035 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003036}
3037
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003038Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
Johannes Doerfert1dafea42016-05-23 09:07:08 +00003039 ScopDetection::DetectionContext &DC)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00003040 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003041 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003042 MaxLoopDepth(0), DC(DC), IslCtx(isl_ctx_alloc(), isl_ctx_free),
3043 Context(nullptr), Affinator(this, LI), AssumedContext(nullptr),
3044 InvalidContext(nullptr), Schedule(nullptr) {
Tobias Grosser2937b592016-04-29 11:43:20 +00003045 if (IslOnErrorAbort)
3046 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00003047 buildContext();
3048}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003049
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003050void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, DominatorTree &DT,
3051 LoopInfo &LI) {
3052 buildInvariantEquivalenceClasses();
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003053
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003054 if (!buildDomains(&R, DT, LI))
Johannes Doerfert5fb9b212016-03-29 20:02:05 +00003055 return;
Johannes Doerfert96425c22015-08-30 21:13:53 +00003056
Johannes Doerfertff68f462016-04-19 14:49:42 +00003057 addUserAssumptions(AC, DT, LI);
3058
Johannes Doerfert26404542016-05-10 12:19:47 +00003059 // Remove empty statements.
Michael Kruseafe06702015-10-02 16:33:27 +00003060 // Exit early in case there are no executable statements left in this scop.
Johannes Doerfert26404542016-05-10 12:19:47 +00003061 simplifySCoP(false, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00003062 if (Stmts.empty())
3063 return;
Tobias Grosser75805372011-04-29 06:27:02 +00003064
Michael Krusecac948e2015-10-02 13:53:07 +00003065 // The ScopStmts now have enough information to initialize themselves.
3066 for (ScopStmt &Stmt : Stmts)
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003067 Stmt.init(LI);
Michael Krusecac948e2015-10-02 13:53:07 +00003068
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003069 // Check early for profitability. Afterwards it cannot change anymore,
3070 // only the runtime context could become infeasible.
3071 if (!isProfitable()) {
3072 invalidate(PROFITABLE, DebugLoc());
Tobias Grosser8286b832015-11-02 11:29:32 +00003073 return;
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003074 }
3075
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003076 buildSchedule(LI);
Tobias Grosser8286b832015-11-02 11:29:32 +00003077
3078 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00003079 realignParams();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00003080 addUserContext();
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003081
3082 // After the context was fully constructed, thus all our knowledge about
3083 // the parameters is in there, we add all recorded assumptions to the
3084 // assumed/invalid context.
3085 addRecordedAssumptions();
3086
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003087 simplifyContexts();
Johannes Doerfert5210da52016-06-02 11:06:54 +00003088 if (!buildAliasChecks(AA))
3089 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003090
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003091 hoistInvariantLoads();
3092 verifyInvariantLoads();
Johannes Doerfert26404542016-05-10 12:19:47 +00003093 simplifySCoP(true, DT, LI);
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003094
3095 // Check late for a feasible runtime context because profitability did not
3096 // change.
3097 if (!hasFeasibleRuntimeContext()) {
3098 invalidate(PROFITABLE, DebugLoc());
3099 return;
3100 }
Tobias Grosser75805372011-04-29 06:27:02 +00003101}
3102
3103Scop::~Scop() {
3104 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00003105 isl_set_free(AssumedContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003106 isl_set_free(InvalidContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00003107 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003108
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003109 for (auto &It : ParameterIds)
3110 isl_id_free(It.second);
3111
Johannes Doerfert96425c22015-08-30 21:13:53 +00003112 for (auto It : DomainMap)
3113 isl_set_free(It.second);
3114
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003115 for (auto &AS : RecordedAssumptions)
3116 isl_set_free(AS.Set);
3117
Johannes Doerfertb164c792014-09-18 11:17:17 +00003118 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003119 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003120 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00003121 isl_pw_multi_aff_free(MMA.first);
3122 isl_pw_multi_aff_free(MMA.second);
3123 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003124 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003125 isl_pw_multi_aff_free(MMA.first);
3126 isl_pw_multi_aff_free(MMA.second);
3127 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003128 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003129
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003130 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003131 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003132
3133 // Explicitly release all Scop objects and the underlying isl objects before
3134 // we relase the isl context.
3135 Stmts.clear();
3136 ScopArrayInfoMap.clear();
3137 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00003138}
3139
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003140void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00003141 // Check all array accesses for each base pointer and find a (virtual) element
3142 // size for the base pointer that divides all access functions.
3143 for (auto &Stmt : *this)
3144 for (auto *Access : Stmt) {
3145 if (!Access->isArrayKind())
3146 continue;
3147 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
3148 ScopArrayInfo::MK_Array)];
3149 if (SAI->getNumberOfDimensions() != 1)
3150 continue;
3151 unsigned DivisibleSize = SAI->getElemSizeInBytes();
3152 auto *Subscript = Access->getSubscript(0);
3153 while (!isDivisible(Subscript, DivisibleSize, *SE))
3154 DivisibleSize /= 2;
3155 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3156 SAI->updateElementType(Ty);
3157 }
3158
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003159 for (auto &Stmt : *this)
3160 for (auto &Access : Stmt)
3161 Access->updateDimensionality();
3162}
3163
Johannes Doerfert26404542016-05-10 12:19:47 +00003164void Scop::simplifySCoP(bool AfterHoisting, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003165 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3166 ScopStmt &Stmt = *StmtIt;
3167
Johannes Doerfert26404542016-05-10 12:19:47 +00003168 bool RemoveStmt = Stmt.isEmpty();
Johannes Doerferteca9e892015-11-03 16:54:49 +00003169 if (!RemoveStmt)
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003170 RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00003171
Johannes Doerferteca9e892015-11-03 16:54:49 +00003172 // Remove read only statements only after invariant loop hoisting.
Johannes Doerfert26404542016-05-10 12:19:47 +00003173 if (!RemoveStmt && AfterHoisting) {
Johannes Doerferteca9e892015-11-03 16:54:49 +00003174 bool OnlyRead = true;
3175 for (MemoryAccess *MA : Stmt) {
3176 if (MA->isRead())
3177 continue;
3178
3179 OnlyRead = false;
3180 break;
3181 }
3182
3183 RemoveStmt = OnlyRead;
3184 }
3185
Johannes Doerfert26404542016-05-10 12:19:47 +00003186 if (!RemoveStmt) {
3187 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003188 continue;
3189 }
3190
Johannes Doerfert26404542016-05-10 12:19:47 +00003191 // Remove the statement because it is unnecessary.
3192 if (Stmt.isRegionStmt())
3193 for (BasicBlock *BB : Stmt.getRegion()->blocks())
3194 StmtMap.erase(BB);
3195 else
3196 StmtMap.erase(Stmt.getBasicBlock());
3197
3198 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003199 }
3200}
3201
Johannes Doerfert8ab28032016-04-27 12:49:11 +00003202InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003203 LoadInst *LInst = dyn_cast<LoadInst>(Val);
3204 if (!LInst)
3205 return nullptr;
3206
3207 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3208 LInst = cast<LoadInst>(Rep);
3209
Johannes Doerfert96e54712016-02-07 17:30:13 +00003210 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003211 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
Johannes Doerfert549768c2016-03-24 13:22:16 +00003212 for (auto &IAClass : InvariantEquivClasses) {
3213 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
3214 continue;
3215
3216 auto &MAs = std::get<1>(IAClass);
3217 for (auto *MA : MAs)
3218 if (MA->getAccessInstruction() == Val)
3219 return &IAClass;
3220 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003221
3222 return nullptr;
3223}
3224
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003225/// @brief Check if @p MA can always be hoisted without execution context.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003226static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003227 bool MAInvalidCtxIsEmpty,
3228 bool NonHoistableCtxIsEmpty) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003229 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3230 const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3231 // TODO: We can provide more information for better but more expensive
3232 // results.
3233 if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3234 LInst->getAlignment(), DL))
3235 return false;
3236
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003237 // If the location might be overwritten we do not hoist it unconditionally.
3238 //
3239 // TODO: This is probably to conservative.
3240 if (!NonHoistableCtxIsEmpty)
3241 return false;
3242
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003243 // If a dereferencable load is in a statement that is modeled precisely we can
3244 // hoist it.
Johannes Doerfert85676e32016-04-23 14:32:34 +00003245 if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003246 return true;
3247
3248 // Even if the statement is not modeled precisely we can hoist the load if it
3249 // does not involve any parameters that might have been specilized by the
3250 // statement domain.
3251 for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3252 if (!isa<SCEVConstant>(MA->getSubscript(u)))
3253 return false;
3254 return true;
3255}
3256
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003257void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003258
Johannes Doerfert5d03f842016-04-22 11:38:44 +00003259 if (InvMAs.empty())
3260 return;
3261
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003262 auto *StmtInvalidCtx = Stmt.getInvalidContext();
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003263 bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003264
Johannes Doerfert3ef78d62016-04-08 10:30:09 +00003265 // Get the context under which the statement is executed but remove the error
3266 // context under which this statement is reached.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003267 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003268 DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003269
Michael Krusebc150122016-05-02 12:25:18 +00003270 if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctionsInDomain) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003271 auto *AccInst = InvMAs.front().MA->getAccessInstruction();
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003272 invalidate(COMPLEXITY, AccInst->getDebugLoc());
3273 isl_set_free(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003274 for (auto &InvMA : InvMAs)
3275 isl_set_free(InvMA.NonHoistableCtx);
Johannes Doerfertd77089e2016-04-22 11:41:14 +00003276 return;
3277 }
3278
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003279 // Project out all parameters that relate to loads in the statement. Otherwise
3280 // we could have cyclic dependences on the constraints under which the
3281 // hoisted loads are executed and we could not determine an order in which to
3282 // pre-load them. This happens because not only lower bounds are part of the
3283 // domain but also upper bounds.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003284 for (auto &InvMA : InvMAs) {
3285 auto *MA = InvMA.MA;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003286 Instruction *AccInst = MA->getAccessInstruction();
3287 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00003288 SetVector<Value *> Values;
3289 for (const SCEV *Parameter : Parameters) {
3290 Values.clear();
Johannes Doerfert7b811032016-04-08 10:25:58 +00003291 findValues(Parameter, *SE, Values);
Johannes Doerfert44483c52015-11-07 19:45:27 +00003292 if (!Values.count(AccInst))
3293 continue;
3294
3295 if (isl_id *ParamId = getIdForParam(Parameter)) {
3296 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3297 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3298 isl_id_free(ParamId);
3299 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003300 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003301 }
3302 }
3303
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003304 for (auto &InvMA : InvMAs) {
3305 auto *MA = InvMA.MA;
3306 auto *NHCtx = InvMA.NonHoistableCtx;
3307
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003308 // Check for another invariant access that accesses the same location as
3309 // MA and if found consolidate them. Otherwise create a new equivalence
3310 // class at the end of InvariantEquivClasses.
3311 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00003312 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003313 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3314
Johannes Doerfert85676e32016-04-23 14:32:34 +00003315 auto *MAInvalidCtx = MA->getInvalidContext();
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003316 bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
Johannes Doerfert85676e32016-04-23 14:32:34 +00003317 bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3318
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003319 isl_set *MACtx;
3320 // Check if we know that this pointer can be speculatively accessed.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003321 if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3322 NonHoistableCtxIsEmpty)) {
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003323 MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
Johannes Doerfert85676e32016-04-23 14:32:34 +00003324 isl_set_free(MAInvalidCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003325 isl_set_free(NHCtx);
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003326 } else {
3327 MACtx = isl_set_copy(DomainCtx);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003328 MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003329 MACtx = isl_set_gist_params(MACtx, getContext());
3330 }
3331
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003332 bool Consolidated = false;
3333 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003334 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003335 continue;
3336
Johannes Doerfertdf880232016-03-03 12:26:58 +00003337 // If the pointer and the type is equal check if the access function wrt.
3338 // to the domain is equal too. It can happen that the domain fixes
3339 // parameter values and these can be different for distinct part of the
Johannes Doerfertac37c562016-03-03 12:30:19 +00003340 // SCoP. If this happens we cannot consolidate the loads but need to
Johannes Doerfertdf880232016-03-03 12:26:58 +00003341 // create a new invariant load equivalence class.
3342 auto &MAs = std::get<1>(IAClass);
3343 if (!MAs.empty()) {
3344 auto *LastMA = MAs.front();
3345
3346 auto *AR = isl_map_range(MA->getAccessRelation());
3347 auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3348 bool SameAR = isl_set_is_equal(AR, LastAR);
3349 isl_set_free(AR);
3350 isl_set_free(LastAR);
3351
3352 if (!SameAR)
3353 continue;
3354 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003355
3356 // Add MA to the list of accesses that are in this class.
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003357 MAs.push_front(MA);
3358
Johannes Doerfertdf880232016-03-03 12:26:58 +00003359 Consolidated = true;
3360
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003361 // Unify the execution context of the class and this statement.
3362 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003363 if (IAClassDomainCtx)
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003364 IAClassDomainCtx =
3365 isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003366 else
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003367 IAClassDomainCtx = MACtx;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003368 break;
3369 }
3370
3371 if (Consolidated)
3372 continue;
3373
3374 // If we did not consolidate MA, thus did not find an equivalence class
3375 // for it, we create a new one.
Johannes Doerfert1dc12af2016-04-23 12:59:18 +00003376 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA}, MACtx,
3377 Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003378 }
3379
3380 isl_set_free(DomainCtx);
3381}
3382
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003383__isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3384 __isl_keep isl_union_map *Writes) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003385 // TODO: Loads that are not loop carried, hence are in a statement with
3386 // zero iterators, are by construction invariant, though we
3387 // currently "hoist" them anyway. This is necessary because we allow
3388 // them to be treated as parameters (e.g., in conditions) and our code
3389 // generation would otherwise use the old value.
3390
3391 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003392 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003393
3394 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003395 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003396
3397 // Skip accesses that have an invariant base pointer which is defined but
3398 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3399 // returns a pointer that is used as a base address. However, as we want
3400 // to hoist indirect pointers, we allow the base pointer to be defined in
3401 // the region if it is also a memory access. Each ScopArrayInfo object
3402 // that has a base pointer origin has a base pointer that is loaded and
3403 // that it is invariant, thus it will be hoisted too. However, if there is
3404 // no base pointer origin we check that the base pointer is defined
3405 // outside the region.
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003406 auto *LI = cast<LoadInst>(Access->getAccessInstruction());
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003407 if (hasNonHoistableBasePtrInScop(Access, Writes))
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003408 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003409
3410 // Skip accesses in non-affine subregions as they might not be executed
3411 // under the same condition as the entry of the non-affine subregion.
Johannes Doerfert764b7e62016-05-23 09:26:46 +00003412 if (BB != LI->getParent())
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003413 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003414
3415 isl_map *AccessRelation = Access->getAccessRelation();
Johannes Doerfert2b470e82016-03-24 13:19:16 +00003416 assert(!isl_map_is_empty(AccessRelation));
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003417
3418 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3419 Stmt.getNumIterators())) {
3420 isl_map_free(AccessRelation);
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003421 return nullptr;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003422 }
3423
3424 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3425 isl_set *AccessRange = isl_map_range(AccessRelation);
3426
3427 isl_union_map *Written = isl_union_map_intersect_range(
3428 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003429 auto *WrittenCtx = isl_union_map_params(Written);
3430 bool IsWritten = !isl_set_is_empty(WrittenCtx);
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003431
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003432 if (!IsWritten)
3433 return WrittenCtx;
3434
3435 WrittenCtx = isl_set_remove_divs(WrittenCtx);
3436 bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctionsInDomain;
3437 if (TooComplex || !isRequiredInvariantLoad(LI)) {
3438 isl_set_free(WrittenCtx);
3439 return nullptr;
3440 }
3441
3442 addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3443 AS_RESTRICTION);
3444 return WrittenCtx;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003445}
3446
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003447void Scop::verifyInvariantLoads() {
3448 auto &RIL = getRequiredInvariantLoads();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003449 for (LoadInst *LI : RIL) {
Johannes Doerfert952b5302016-05-23 12:40:48 +00003450 assert(LI && contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003451 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003452 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003453 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3454 return;
3455 }
3456 }
3457}
3458
Johannes Doerfertffd222f2016-05-19 12:34:57 +00003459void Scop::hoistInvariantLoads() {
Tobias Grosser0865e7752016-02-29 07:29:42 +00003460 if (!PollyInvariantLoadHoisting)
3461 return;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003462
Tobias Grosser0865e7752016-02-29 07:29:42 +00003463 isl_union_map *Writes = getWrites();
3464 for (ScopStmt &Stmt : *this) {
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003465 InvariantAccessesTy InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003466
Tobias Grosser0865e7752016-02-29 07:29:42 +00003467 for (MemoryAccess *Access : Stmt)
Johannes Doerfert25227fe2016-05-23 10:40:54 +00003468 if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3469 InvariantAccesses.push_back({Access, NHCtx});
Tobias Grosser0865e7752016-02-29 07:29:42 +00003470
3471 // Transfer the memory access from the statement to the SCoP.
Michael Kruse10071822016-05-23 14:45:58 +00003472 for (auto InvMA : InvariantAccesses)
3473 Stmt.removeMemoryAccess(InvMA.MA);
Tobias Grosser0865e7752016-02-29 07:29:42 +00003474 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003475 }
Tobias Grosser0865e7752016-02-29 07:29:42 +00003476 isl_union_map_free(Writes);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003477}
3478
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003479const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003480Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003481 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003482 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003483 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003484 if (!SAI) {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003485 auto &DL = getFunction().getParent()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003486 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003487 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003488 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003489 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003490 // In case of mismatching array sizes, we bail out by setting the run-time
3491 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003492 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003493 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003494 }
Tobias Grosserab671442015-05-23 05:58:27 +00003495 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003496}
3497
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003498const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003499 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003500 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003501 assert(SAI && "No ScopArrayInfo available for this base pointer");
3502 return SAI;
3503}
3504
Tobias Grosser74394f02013-01-14 22:40:23 +00003505std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003506
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003507std::string Scop::getAssumedContextStr() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003508 assert(AssumedContext && "Assumed context not yet built");
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003509 return stringFromIslObj(AssumedContext);
3510}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003511
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003512std::string Scop::getInvalidContextStr() const {
3513 return stringFromIslObj(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003514}
Tobias Grosser75805372011-04-29 06:27:02 +00003515
3516std::string Scop::getNameStr() const {
3517 std::string ExitName, EntryName;
3518 raw_string_ostream ExitStr(ExitName);
3519 raw_string_ostream EntryStr(EntryName);
3520
Tobias Grosserf240b482014-01-09 10:42:15 +00003521 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003522 EntryStr.str();
3523
3524 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003525 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003526 ExitStr.str();
3527 } else
3528 ExitName = "FunctionExit";
3529
3530 return EntryName + "---" + ExitName;
3531}
3532
Tobias Grosser74394f02013-01-14 22:40:23 +00003533__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003534__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003535 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003536}
3537
Tobias Grossere86109f2013-10-29 21:05:49 +00003538__isl_give isl_set *Scop::getAssumedContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003539 assert(AssumedContext && "Assumed context not yet built");
Tobias Grossere86109f2013-10-29 21:05:49 +00003540 return isl_set_copy(AssumedContext);
3541}
3542
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003543bool Scop::isProfitable() const {
3544 if (PollyProcessUnprofitable)
3545 return true;
3546
3547 if (!hasFeasibleRuntimeContext())
3548 return false;
3549
3550 if (isEmpty())
3551 return false;
3552
3553 unsigned OptimizableStmtsOrLoops = 0;
3554 for (auto &Stmt : *this) {
3555 if (Stmt.getNumIterators() == 0)
3556 continue;
3557
3558 bool ContainsArrayAccs = false;
3559 bool ContainsScalarAccs = false;
3560 for (auto *MA : Stmt) {
3561 if (MA->isRead())
3562 continue;
3563 ContainsArrayAccs |= MA->isArrayKind();
3564 ContainsScalarAccs |= MA->isScalarKind();
3565 }
3566
3567 if (ContainsArrayAccs && !ContainsScalarAccs)
3568 OptimizableStmtsOrLoops += Stmt.getNumIterators();
3569 }
3570
3571 return OptimizableStmtsOrLoops > 1;
3572}
3573
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003574bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003575 auto *PositiveContext = getAssumedContext();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003576 auto *NegativeContext = getInvalidContext();
Johannes Doerfert94341c92016-04-23 13:00:27 +00003577 PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3578 bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3579 isl_set_is_subset(PositiveContext, NegativeContext));
3580 isl_set_free(PositiveContext);
3581 if (!IsFeasible) {
3582 isl_set_free(NegativeContext);
3583 return false;
3584 }
3585
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003586 auto *DomainContext = isl_union_set_params(getDomains());
3587 IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
Johannes Doerfertfb721872016-04-12 17:54:29 +00003588 IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003589 isl_set_free(NegativeContext);
3590 isl_set_free(DomainContext);
3591
Johannes Doerfert43788c52015-08-20 05:58:56 +00003592 return IsFeasible;
3593}
3594
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003595static std::string toString(AssumptionKind Kind) {
3596 switch (Kind) {
3597 case ALIASING:
3598 return "No-aliasing";
3599 case INBOUNDS:
3600 return "Inbounds";
3601 case WRAPPING:
3602 return "No-overflows";
Johannes Doerfertc3596282016-04-25 14:01:36 +00003603 case UNSIGNED:
3604 return "Signed-unsigned";
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003605 case COMPLEXITY:
3606 return "Low complexity";
Johannes Doerfert27d12d32016-05-10 16:38:09 +00003607 case PROFITABLE:
3608 return "Profitable";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003609 case ERRORBLOCK:
3610 return "No-error";
3611 case INFINITELOOP:
3612 return "Finite loop";
3613 case INVARIANTLOAD:
3614 return "Invariant load";
3615 case DELINEARIZATION:
3616 return "Delinearization";
3617 }
3618 llvm_unreachable("Unknown AssumptionKind!");
3619}
3620
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003621bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3622 if (Sign == AS_ASSUMPTION) {
3623 if (isl_set_is_subset(Context, Set))
3624 return false;
3625
3626 if (isl_set_is_subset(AssumedContext, Set))
3627 return false;
3628 } else {
3629 if (isl_set_is_disjoint(Set, Context))
3630 return false;
3631
3632 if (isl_set_is_subset(Set, InvalidContext))
3633 return false;
3634 }
3635 return true;
3636}
3637
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003638bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3639 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert1a6b0f72016-06-06 12:16:10 +00003640 if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3641 return false;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003642
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003643 auto &F = getFunction();
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003644 auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3645 std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003646 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003647 return true;
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003648}
3649
3650void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003651 DebugLoc Loc, AssumptionSign Sign) {
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003652 // Simplify the assumptions/restrictions first.
3653 Set = isl_set_gist_params(Set, getContext());
3654
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003655 if (!trackAssumption(Kind, Set, Loc, Sign)) {
3656 isl_set_free(Set);
3657 return;
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003658 }
3659
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003660 if (Sign == AS_ASSUMPTION) {
3661 AssumedContext = isl_set_intersect(AssumedContext, Set);
3662 AssumedContext = isl_set_coalesce(AssumedContext);
3663 } else {
3664 InvalidContext = isl_set_union(InvalidContext, Set);
3665 InvalidContext = isl_set_coalesce(InvalidContext);
3666 }
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003667}
3668
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003669void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003670 DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3671 RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003672}
3673
3674void Scop::addRecordedAssumptions() {
3675 while (!RecordedAssumptions.empty()) {
3676 const Assumption &AS = RecordedAssumptions.pop_back_val();
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003677
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003678 if (!AS.BB) {
3679 addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3680 continue;
3681 }
Johannes Doerfert615e0b82016-04-12 13:28:39 +00003682
Johannes Doerfert14b1cf32016-05-10 12:42:26 +00003683 // If the domain was deleted the assumptions are void.
3684 isl_set *Dom = getDomainConditions(AS.BB);
3685 if (!Dom) {
3686 isl_set_free(AS.Set);
3687 continue;
3688 }
3689
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003690 // If a basic block was given use its domain to simplify the assumption.
3691 // In case of restrictions we know they only have to hold on the domain,
3692 // thus we can intersect them with the domain of the block. However, for
3693 // assumptions the domain has to imply them, thus:
3694 // _ _____
3695 // Dom => S <==> A v B <==> A - B
3696 //
3697 // To avoid the complement we will register A - B as a restricton not an
3698 // assumption.
3699 isl_set *S = AS.Set;
Johannes Doerfert8475d1c2016-04-28 14:32:58 +00003700 if (AS.Sign == AS_RESTRICTION)
3701 S = isl_set_params(isl_set_intersect(S, Dom));
3702 else /* (AS.Sign == AS_ASSUMPTION) */
3703 S = isl_set_params(isl_set_subtract(Dom, S));
3704
3705 addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
Johannes Doerfert3bf6e4122016-04-12 13:27:35 +00003706 }
3707}
3708
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003709void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003710 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003711}
3712
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003713__isl_give isl_set *Scop::getInvalidContext() const {
3714 return isl_set_copy(InvalidContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003715}
3716
Tobias Grosser75805372011-04-29 06:27:02 +00003717void Scop::printContext(raw_ostream &OS) const {
3718 OS << "Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003719 OS.indent(4) << Context << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003720
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003721 OS.indent(4) << "Assumed Context:\n";
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003722 OS.indent(4) << AssumedContext << "\n";
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003723
Johannes Doerfert066dbf32016-03-01 13:06:28 +00003724 OS.indent(4) << "Invalid Context:\n";
3725 OS.indent(4) << InvalidContext << "\n";
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003726
Johannes Doerfert4e3bb7b2016-04-25 16:15:13 +00003727 unsigned Dim = 0;
3728 for (const SCEV *Parameter : Parameters)
3729 OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003730}
3731
Johannes Doerfertb164c792014-09-18 11:17:17 +00003732void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003733 int noOfGroups = 0;
3734 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003735 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003736 noOfGroups += 1;
3737 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003738 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003739 }
3740
Tobias Grosserbb853c22015-07-25 12:31:03 +00003741 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003742 if (MinMaxAliasGroups.empty()) {
3743 OS.indent(8) << "n/a\n";
3744 return;
3745 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003746
Tobias Grosserbb853c22015-07-25 12:31:03 +00003747 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003748
3749 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003750 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003751 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003752 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003753 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3754 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003755 }
3756 OS << " ]]\n";
3757 }
3758
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003759 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003760 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003761 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003762 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003763 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3764 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003765 }
3766 OS << " ]]\n";
3767 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003768 }
3769}
3770
Tobias Grosser75805372011-04-29 06:27:02 +00003771void Scop::printStatements(raw_ostream &OS) const {
3772 OS << "Statements {\n";
3773
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003774 for (const ScopStmt &Stmt : *this)
3775 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003776
3777 OS.indent(4) << "}\n";
3778}
3779
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003780void Scop::printArrayInfo(raw_ostream &OS) const {
3781 OS << "Arrays {\n";
3782
Tobias Grosserab671442015-05-23 05:58:27 +00003783 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003784 Array.second->print(OS);
3785
3786 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003787
3788 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3789
3790 for (auto &Array : arrays())
3791 Array.second->print(OS, /* SizeAsPwAff */ true);
3792
3793 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003794}
3795
Tobias Grosser75805372011-04-29 06:27:02 +00003796void Scop::print(raw_ostream &OS) const {
Johannes Doerfert3f52e352016-05-23 12:38:05 +00003797 OS.indent(4) << "Function: " << getFunction().getName() << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003798 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003799 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003800 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003801 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003802 const auto &MAs = std::get<1>(IAClass);
3803 if (MAs.empty()) {
3804 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003805 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003806 MAs.front()->print(OS);
3807 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003808 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003809 }
3810 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003811 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003812 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003813 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003814 printStatements(OS.indent(4));
3815}
3816
3817void Scop::dump() const { print(dbgs()); }
3818
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003819isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003820
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003821__isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
3822 bool NonNegative) {
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003823 // First try to use the SCEVAffinator to generate a piecewise defined
3824 // affine function from @p E in the context of @p BB. If that tasks becomes to
3825 // complex the affinator might return a nullptr. In such a case we invalidate
3826 // the SCoP and return a dummy value. This way we do not need to add error
3827 // handling cdoe to all users of this function.
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003828 auto PWAC = Affinator.getPwAff(E, BB);
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003829 if (PWAC.first) {
Johannes Doerfert56b37762016-05-10 11:45:46 +00003830 // TODO: We could use a heuristic and either use:
3831 // SCEVAffinator::takeNonNegativeAssumption
3832 // or
3833 // SCEVAffinator::interpretAsUnsigned
3834 // to deal with unsigned or "NonNegative" SCEVs.
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003835 if (NonNegative)
3836 Affinator.takeNonNegativeAssumption(PWAC);
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003837 return PWAC;
Johannes Doerfert3e48ee22016-04-29 10:44:41 +00003838 }
Johannes Doerfert6462d8c2016-03-26 16:17:00 +00003839
3840 auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
3841 invalidate(COMPLEXITY, DL);
3842 return Affinator.getPwAff(SE->getZero(E->getType()), BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003843}
3844
Tobias Grosser808cd692015-07-14 09:33:13 +00003845__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003846 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003847
Tobias Grosser808cd692015-07-14 09:33:13 +00003848 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003849 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003850
3851 return Domain;
3852}
3853
Johannes Doerfertac9c32e2016-04-23 14:31:17 +00003854__isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
3855 PWACtx PWAC = getPwAff(E, BB);
3856 isl_set_free(PWAC.second);
3857 return PWAC.first;
3858}
3859
Tobias Grossere5a35142015-11-12 14:07:09 +00003860__isl_give isl_union_map *
3861Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3862 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003863
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003864 for (ScopStmt &Stmt : *this) {
3865 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003866 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003867 continue;
3868
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003869 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003870 isl_map *AccessDomain = MA->getAccessRelation();
3871 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003872 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003873 }
3874 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003875 return isl_union_map_coalesce(Accesses);
3876}
3877
3878__isl_give isl_union_map *Scop::getMustWrites() {
3879 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003880}
3881
3882__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003883 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003884}
3885
Tobias Grosser37eb4222014-02-20 21:43:54 +00003886__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003887 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003888}
3889
3890__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003891 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003892}
3893
Tobias Grosser2ac23382015-11-12 14:07:13 +00003894__isl_give isl_union_map *Scop::getAccesses() {
3895 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3896}
3897
Tobias Grosser808cd692015-07-14 09:33:13 +00003898__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003899 auto *Tree = getScheduleTree();
3900 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003901 isl_schedule_free(Tree);
3902 return S;
3903}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003904
Tobias Grosser808cd692015-07-14 09:33:13 +00003905__isl_give isl_schedule *Scop::getScheduleTree() const {
3906 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3907 getDomains());
3908}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003909
Tobias Grosser808cd692015-07-14 09:33:13 +00003910void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3911 auto *S = isl_schedule_from_domain(getDomains());
3912 S = isl_schedule_insert_partial_schedule(
3913 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3914 isl_schedule_free(Schedule);
3915 Schedule = S;
3916}
3917
3918void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3919 isl_schedule_free(Schedule);
3920 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003921}
3922
3923bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3924 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003925 for (ScopStmt &Stmt : *this) {
3926 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003927 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3928 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3929
3930 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3931 isl_union_set_free(StmtDomain);
3932 isl_union_set_free(NewStmtDomain);
3933 continue;
3934 }
3935
3936 Changed = true;
3937
3938 isl_union_set_free(StmtDomain);
3939 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3940
3941 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003942 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003943 isl_union_set_free(NewStmtDomain);
3944 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003945 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003946 }
3947 isl_union_set_free(Domain);
3948 return Changed;
3949}
3950
Tobias Grosser75805372011-04-29 06:27:02 +00003951ScalarEvolution *Scop::getSE() const { return SE; }
3952
Tobias Grosser808cd692015-07-14 09:33:13 +00003953struct MapToDimensionDataTy {
3954 int N;
3955 isl_union_pw_multi_aff *Res;
3956};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003957
Tobias Grosser808cd692015-07-14 09:33:13 +00003958// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003959// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003960//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003961// @param Set The input set.
3962// @param User->N The dimension to map to.
3963// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003964//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003965// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003966static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3967 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3968 int Dim;
3969 isl_space *Space;
3970 isl_pw_multi_aff *PMA;
3971
3972 Dim = isl_set_dim(Set, isl_dim_set);
3973 Space = isl_set_get_space(Set);
3974 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3975 Dim - Data->N);
3976 if (Data->N > 1)
3977 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3978 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3979
3980 isl_set_free(Set);
3981
3982 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003983}
3984
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003985// @brief Create an isl_multi_union_aff that defines an identity mapping
3986// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003987//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003988// # Example:
3989//
3990// Domain: { A[i,j]; B[i,j,k] }
3991// N: 1
3992//
3993// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3994//
3995// @param USet A union set describing the elements for which to generate a
3996// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003997// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003998// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003999static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004000mapToDimension(__isl_take isl_union_set *USet, int N) {
4001 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00004002 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004003 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004004
Tobias Grosser808cd692015-07-14 09:33:13 +00004005 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00004006
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004007 auto *Space = isl_union_set_get_space(USet);
4008 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00004009
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004010 Data = {N, PwAff};
4011
4012 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00004013 (void)Res;
4014
Tobias Grossercbf7ae82015-12-21 22:45:53 +00004015 assert(Res == isl_stat_ok);
4016
4017 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00004018 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4019}
4020
Tobias Grosser316b5b22015-11-11 19:28:14 +00004021void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00004022 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00004023 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004024 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004025 StmtMap[BB] = Stmt;
4026 } else {
4027 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00004028 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00004029 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00004030 for (BasicBlock *BB : R->blocks())
4031 StmtMap[BB] = Stmt;
4032 }
Tobias Grosser808cd692015-07-14 09:33:13 +00004033}
4034
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004035void Scop::buildSchedule(LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004036 Loop *L = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004037 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004038 buildSchedule(getRegion().getNode(), LoopStack, LI);
Tobias Grosser151ae322016-04-03 19:36:52 +00004039 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4040 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00004041}
4042
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004043/// To generate a schedule for the elements in a Region we traverse the Region
4044/// in reverse-post-order and add the contained RegionNodes in traversal order
4045/// to the schedule of the loop that is currently at the top of the LoopStack.
4046/// For loop-free codes, this results in a correct sequential ordering.
4047///
4048/// Example:
4049/// bb1(0)
4050/// / \.
4051/// bb2(1) bb3(2)
4052/// \ / \.
4053/// bb4(3) bb5(4)
4054/// \ /
4055/// bb6(5)
4056///
4057/// Including loops requires additional processing. Whenever a loop header is
4058/// encountered, the corresponding loop is added to the @p LoopStack. Starting
4059/// from an empty schedule, we first process all RegionNodes that are within
4060/// this loop and complete the sequential schedule at this loop-level before
4061/// processing about any other nodes. To implement this
4062/// loop-nodes-first-processing, the reverse post-order traversal is
4063/// insufficient. Hence, we additionally check if the traversal yields
4064/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4065/// These region-nodes are then queue and only traverse after the all nodes
4066/// within the current loop have been processed.
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004067void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
Johannes Doerfertef744432016-05-23 12:42:38 +00004068 Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004069
4070 ReversePostOrderTraversal<Region *> RTraversal(R);
4071 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4072 std::deque<RegionNode *> DelayList;
4073 bool LastRNWaiting = false;
4074
4075 // Iterate over the region @p R in reverse post-order but queue
4076 // sub-regions/blocks iff they are not part of the last encountered but not
4077 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4078 // that we queued the last sub-region/block from the reverse post-order
4079 // iterator. If it is set we have to explore the next sub-region/block from
4080 // the iterator (if any) to guarantee progress. If it is not set we first try
4081 // the next queued sub-region/blocks.
4082 while (!WorkList.empty() || !DelayList.empty()) {
4083 RegionNode *RN;
4084
4085 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4086 RN = WorkList.front();
4087 WorkList.pop_front();
4088 LastRNWaiting = false;
4089 } else {
4090 RN = DelayList.front();
4091 DelayList.pop_front();
4092 }
4093
4094 Loop *L = getRegionNodeLoop(RN, LI);
Johannes Doerfert952b5302016-05-23 12:40:48 +00004095 if (!contains(L))
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004096 L = OuterScopLoop;
4097
Tobias Grosser151ae322016-04-03 19:36:52 +00004098 Loop *LastLoop = LoopStack.back().L;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004099 if (LastLoop != L) {
Johannes Doerfertd5edbd62016-04-03 23:09:06 +00004100 if (LastLoop && !LastLoop->contains(L)) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004101 LastRNWaiting = true;
4102 DelayList.push_back(RN);
4103 continue;
4104 }
4105 LoopStack.push_back({L, nullptr, 0});
4106 }
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004107 buildSchedule(RN, LoopStack, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004108 }
4109
4110 return;
4111}
4112
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004113void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00004114
Tobias Grosser8362c262016-01-06 15:30:06 +00004115 if (RN->isSubRegion()) {
4116 auto *LocalRegion = RN->getNodeAs<Region>();
Johannes Doerfertffd222f2016-05-19 12:34:57 +00004117 if (!isNonAffineSubRegion(LocalRegion)) {
4118 buildSchedule(LocalRegion, LoopStack, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00004119 return;
4120 }
4121 }
Michael Kruse046dde42015-08-10 13:01:57 +00004122
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004123 auto &LoopData = LoopStack.back();
4124 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00004125
Michael Kruse6f7721f2016-02-24 22:08:19 +00004126 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00004127 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4128 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004129 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00004130 }
4131
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004132 // Check if we just processed the last node in this loop. If we did, finalize
4133 // the loop by:
4134 //
4135 // - adding new schedule dimensions
4136 // - folding the resulting schedule into the parent loop schedule
4137 // - dropping the loop schedule from the LoopStack.
4138 //
4139 // Then continue to check surrounding loops, which might also have been
4140 // completed by this node.
4141 while (LoopData.L &&
4142 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00004143 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004144 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00004145
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004146 LoopStack.pop_back();
4147 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00004148
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004149 if (Schedule) {
4150 auto *Domain = isl_schedule_get_domain(Schedule);
4151 auto *MUPA = mapToDimension(Domain, LoopStack.size());
4152 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4153 NextLoopData.Schedule =
4154 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00004155 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00004156
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00004157 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4158 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00004159 }
Tobias Grosser75805372011-04-29 06:27:02 +00004160}
4161
Michael Kruse6f7721f2016-02-24 22:08:19 +00004162ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00004163 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00004164 if (StmtMapIt == StmtMap.end())
4165 return nullptr;
4166 return StmtMapIt->second;
4167}
4168
Michael Kruse6f7721f2016-02-24 22:08:19 +00004169ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4170 if (RN->isSubRegion())
4171 return getStmtFor(RN->getNodeAs<Region>());
4172 return getStmtFor(RN->getNodeAs<BasicBlock>());
4173}
4174
4175ScopStmt *Scop::getStmtFor(Region *R) const {
4176 ScopStmt *Stmt = getStmtFor(R->getEntry());
4177 assert(!Stmt || Stmt->getRegion() == R);
4178 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00004179}
4180
Johannes Doerfert96425c22015-08-30 21:13:53 +00004181int Scop::getRelativeLoopDepth(const Loop *L) const {
4182 Loop *OuterLoop =
4183 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4184 if (!OuterLoop)
4185 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00004186 return L->getLoopDepth() - OuterLoop->getLoopDepth();
4187}
4188
Johannes Doerfert99191c72016-05-31 09:41:04 +00004189//===----------------------------------------------------------------------===//
4190void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4191 AU.addRequired<LoopInfoWrapperPass>();
4192 AU.addRequired<RegionInfoPass>();
4193 AU.addRequired<DominatorTreeWrapperPass>();
4194 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4195 AU.addRequiredTransitive<ScopDetection>();
4196 AU.addRequired<AAResultsWrapperPass>();
4197 AU.addRequired<AssumptionCacheTracker>();
4198 AU.setPreservesAll();
4199}
4200
4201bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4202 auto &SD = getAnalysis<ScopDetection>();
4203
4204 if (!SD.isMaxRegionInScop(*R))
4205 return false;
4206
4207 Function *F = R->getEntry()->getParent();
4208 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4209 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4210 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4211 auto const &DL = F->getParent()->getDataLayout();
4212 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4213 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
4214
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004215 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4216 S = SB.getScop(); // take ownership of scop object
Tobias Grosser75805372011-04-29 06:27:02 +00004217 return false;
4218}
4219
Johannes Doerfert99191c72016-05-31 09:41:04 +00004220void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
Johannes Doerfertb7e97132016-06-27 09:25:40 +00004221 if (S)
4222 S->print(OS);
4223 else
4224 OS << "Invalid Scop!\n";
Johannes Doerfert99191c72016-05-31 09:41:04 +00004225}
Tobias Grosser75805372011-04-29 06:27:02 +00004226
Johannes Doerfert99191c72016-05-31 09:41:04 +00004227char ScopInfoRegionPass::ID = 0;
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004228
Johannes Doerfert99191c72016-05-31 09:41:04 +00004229Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4230
4231INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004232 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004233 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004234INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004235INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004236INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004237INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004238INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004239INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004240INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Johannes Doerfert99191c72016-05-31 09:41:04 +00004241INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
Tobias Grosser73600b82011-10-08 00:30:40 +00004242 "Polly - Create polyhedral description of Scops", false,
4243 false)
Johannes Doerfert4ba65a52016-06-27 09:32:30 +00004244
4245//===----------------------------------------------------------------------===//
4246void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4247 AU.addRequired<LoopInfoWrapperPass>();
4248 AU.addRequired<RegionInfoPass>();
4249 AU.addRequired<DominatorTreeWrapperPass>();
4250 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4251 AU.addRequiredTransitive<ScopDetection>();
4252 AU.addRequired<AAResultsWrapperPass>();
4253 AU.addRequired<AssumptionCacheTracker>();
4254 AU.setPreservesAll();
4255}
4256
4257bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4258 auto &SD = getAnalysis<ScopDetection>();
4259
4260 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4261 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4262 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4263 auto const &DL = F.getParent()->getDataLayout();
4264 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4265 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4266
4267 /// Create polyhedral descripton of scops for all the valid regions of a
4268 /// function.
4269 for (auto &It : SD) {
4270 Region *R = const_cast<Region *>(It);
4271 if (!SD.isMaxRegionInScop(*R))
4272 continue;
4273
4274 ScopBuilder SB(R, AC, AA, DL, DT, LI, SD, SE);
4275 bool Inserted =
4276 RegionToScopMap.insert(std::make_pair(R, SB.getScop())).second;
4277 assert(Inserted && "Building Scop for the same region twice!");
4278 (void)Inserted;
4279 }
4280 return false;
4281}
4282
4283void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4284 for (auto &It : RegionToScopMap) {
4285 if (It.second)
4286 It.second->print(OS);
4287 else
4288 OS << "Invalid Scop!\n";
4289 }
4290}
4291
4292char ScopInfoWrapperPass::ID = 0;
4293
4294Pass *polly::createScopInfoWrapperPassPass() {
4295 return new ScopInfoWrapperPass();
4296}
4297
4298INITIALIZE_PASS_BEGIN(
4299 ScopInfoWrapperPass, "polly-function-scops",
4300 "Polly - Create polyhedral description of all Scops of a function", false,
4301 false);
4302INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4303INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
4304INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4305INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4306INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4307INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4308INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4309INITIALIZE_PASS_END(
4310 ScopInfoWrapperPass, "polly-function-scops",
4311 "Polly - Create polyhedral description of all Scops of a function", false,
4312 false)