blob: 95fc0211205d3b0e9c51a0bb5f242c4377b80446 [file] [log] [blame]
Johannes Doerfert58a7c752015-09-28 09:48:53 +00001//===--------- ScopInfo.cpp - Create Scops from LLVM IR ------------------===//
Tobias Grosser75805372011-04-29 06:27:02 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Create a polyhedral description for a static control flow region.
11//
12// The pass creates a polyhedral description of the Scops detected by the Scop
13// detection derived from their LLVM-IR code.
14//
Tobias Grossera5605d32014-10-29 19:58:28 +000015// This representation is shared among several tools in the polyhedral
Tobias Grosser75805372011-04-29 06:27:02 +000016// community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17//
18//===----------------------------------------------------------------------===//
19
Tobias Grosser5624d3c2015-12-21 12:38:56 +000020#include "polly/ScopInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000021#include "polly/LinkAllPasses.h"
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000022#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000023#include "polly/Support/GICHelper.h"
Tobias Grosser60b54f12011-11-08 15:41:28 +000024#include "polly/Support/SCEVValidator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000025#include "polly/Support/ScopHelper.h"
Tobias Grosser9737c7b2015-11-22 11:06:51 +000026#include "llvm/ADT/DepthFirstIterator.h"
Tobias Grosserf4c24b22015-04-05 13:11:54 +000027#include "llvm/ADT/MapVector.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000028#include "llvm/ADT/PostOrderIterator.h"
29#include "llvm/ADT/STLExtras.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000030#include "llvm/ADT/SetVector.h"
Tobias Grosser83628182013-05-07 08:11:54 +000031#include "llvm/ADT/Statistic.h"
Hongbin Zheng86a37742012-04-25 08:01:38 +000032#include "llvm/ADT/StringExtras.h"
Johannes Doerfertb164c792014-09-18 11:17:17 +000033#include "llvm/Analysis/AliasAnalysis.h"
Johannes Doerfert2af10e22015-11-12 03:25:01 +000034#include "llvm/Analysis/AssumptionCache.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "llvm/Analysis/LoopInfo.h"
Tobias Grosserc2bb0cb2015-09-25 09:49:19 +000036#include "llvm/Analysis/LoopIterator.h"
Tobias Grosser83628182013-05-07 08:11:54 +000037#include "llvm/Analysis/RegionIterator.h"
38#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Johannes Doerfert48fe86f2015-11-12 02:32:32 +000039#include "llvm/IR/DiagnosticInfo.h"
Tobias Grosser75805372011-04-29 06:27:02 +000040#include "llvm/Support/Debug.h"
Tobias Grosser33ba62ad2011-08-18 06:31:50 +000041#include "isl/aff.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000042#include "isl/constraint.h"
Tobias Grosserf5338802011-10-06 00:03:35 +000043#include "isl/local_space.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000044#include "isl/map.h"
Tobias Grosser4a8e3562011-12-07 07:42:51 +000045#include "isl/options.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000046#include "isl/printer.h"
Tobias Grosser808cd692015-07-14 09:33:13 +000047#include "isl/schedule.h"
48#include "isl/schedule_node.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000049#include "isl/set.h"
50#include "isl/union_map.h"
Tobias Grossercd524dc2015-05-09 09:36:38 +000051#include "isl/union_set.h"
Tobias Grosseredab1352013-06-21 06:41:31 +000052#include "isl/val.h"
Tobias Grosser75805372011-04-29 06:27:02 +000053#include <sstream>
54#include <string>
55#include <vector>
56
57using namespace llvm;
58using namespace polly;
59
Chandler Carruth95fef942014-04-22 03:30:19 +000060#define DEBUG_TYPE "polly-scops"
61
Tobias Grosser74394f02013-01-14 22:40:23 +000062STATISTIC(ScopFound, "Number of valid Scops");
63STATISTIC(RichScopFound, "Number of Scops containing a loop");
Tobias Grosser75805372011-04-29 06:27:02 +000064
Tobias Grosser75dc40c2015-12-20 13:31:48 +000065// The maximal number of basic sets we allow during domain construction to
66// be created. More complex scops will result in very high compile time and
67// are also unlikely to result in good code
68static int const MaxConjunctsInDomain = 20;
69
Michael Kruse7bf39442015-09-10 12:46:52 +000070static cl::opt<bool> ModelReadOnlyScalars(
71 "polly-analyze-read-only-scalars",
72 cl::desc("Model read-only scalar values in the scop description"),
73 cl::Hidden, cl::ZeroOrMore, cl::init(true), cl::cat(PollyCategory));
74
Johannes Doerfert9e7b17b2014-08-18 00:40:13 +000075// Multiplicative reductions can be disabled separately as these kind of
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000076// operations can overflow easily. Additive reductions and bit operations
77// are in contrast pretty stable.
Tobias Grosser483a90d2014-07-09 10:50:10 +000078static cl::opt<bool> DisableMultiplicativeReductions(
79 "polly-disable-multiplicative-reductions",
80 cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
81 cl::init(false), cl::cat(PollyCategory));
Johannes Doerfert0ee1f212014-06-17 17:31:36 +000082
Johannes Doerfert9143d672014-09-27 11:02:39 +000083static cl::opt<unsigned> RunTimeChecksMaxParameters(
84 "polly-rtc-max-parameters",
85 cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
86 cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
87
Tobias Grosser71500722015-03-28 15:11:14 +000088static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
89 "polly-rtc-max-arrays-per-group",
90 cl::desc("The maximal number of arrays to compare in each alias group."),
91 cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
Tobias Grosser8a9c2352015-08-16 10:19:29 +000092static cl::opt<std::string> UserContextStr(
93 "polly-context", cl::value_desc("isl parameter set"),
94 cl::desc("Provide additional constraints on the context parameters"),
95 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser71500722015-03-28 15:11:14 +000096
Tobias Grosserd83b8a82015-08-20 19:08:11 +000097static cl::opt<bool> DetectReductions("polly-detect-reductions",
98 cl::desc("Detect and exploit reductions"),
99 cl::Hidden, cl::ZeroOrMore,
100 cl::init(true), cl::cat(PollyCategory));
101
Tobias Grosser20a4c0c2015-11-11 16:22:36 +0000102static cl::opt<int> MaxDisjunctsAssumed(
103 "polly-max-disjuncts-assumed",
104 cl::desc("The maximal number of disjuncts we allow in the assumption "
105 "context (this bounds compile time)"),
106 cl::Hidden, cl::ZeroOrMore, cl::init(150), cl::cat(PollyCategory));
107
Tobias Grosser4927c8e2015-11-24 12:50:02 +0000108static cl::opt<bool> IgnoreIntegerWrapping(
109 "polly-ignore-integer-wrapping",
110 cl::desc("Do not build run-time checks to proof absence of integer "
111 "wrapping"),
112 cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
113
Michael Kruse7bf39442015-09-10 12:46:52 +0000114//===----------------------------------------------------------------------===//
Michael Kruse7bf39442015-09-10 12:46:52 +0000115
Michael Kruse046dde42015-08-10 13:01:57 +0000116// Create a sequence of two schedules. Either argument may be null and is
117// interpreted as the empty schedule. Can also return null if both schedules are
118// empty.
119static __isl_give isl_schedule *
120combineInSequence(__isl_take isl_schedule *Prev,
121 __isl_take isl_schedule *Succ) {
122 if (!Prev)
123 return Succ;
124 if (!Succ)
125 return Prev;
126
127 return isl_schedule_sequence(Prev, Succ);
128}
129
Johannes Doerferte7044942015-02-24 11:58:30 +0000130static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
131 const ConstantRange &Range,
132 int dim,
133 enum isl_dim_type type) {
134 isl_val *V;
135 isl_ctx *ctx = isl_set_get_ctx(S);
136
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000137 bool useLowerUpperBound = Range.isSignWrappedSet() && !Range.isFullSet();
138 const auto LB = useLowerUpperBound ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000139 V = isl_valFromAPInt(ctx, LB, true);
Johannes Doerferte7044942015-02-24 11:58:30 +0000140 isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
141
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000142 const auto UB = useLowerUpperBound ? Range.getUpper() : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000143 V = isl_valFromAPInt(ctx, UB, true);
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000144 if (useLowerUpperBound)
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000145 V = isl_val_sub_ui(V, 1);
Johannes Doerferte7044942015-02-24 11:58:30 +0000146 isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
147
Johannes Doerfert8f8af432015-04-26 20:07:21 +0000148 if (useLowerUpperBound)
Johannes Doerferte7044942015-02-24 11:58:30 +0000149 return isl_set_union(SLB, SUB);
150 else
151 return isl_set_intersect(SLB, SUB);
152}
153
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000154static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
155 LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
156 if (!BasePtrLI)
157 return nullptr;
158
159 if (!S->getRegion().contains(BasePtrLI))
160 return nullptr;
161
162 ScalarEvolution &SE = *S->getSE();
163
164 auto *OriginBaseSCEV =
165 SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
166 if (!OriginBaseSCEV)
167 return nullptr;
168
169 auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
170 if (!OriginBaseSCEVUnknown)
171 return nullptr;
172
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000173 return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
Tobias Grossera535dff2015-12-13 19:59:01 +0000174 ScopArrayInfo::MK_Array);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000175}
176
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000177ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
Tobias Grossera535dff2015-12-13 19:59:01 +0000178 ArrayRef<const SCEV *> Sizes, enum MemoryKind Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000179 const DataLayout &DL, Scop *S)
180 : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
Tobias Grosser92245222015-07-28 14:53:44 +0000181 std::string BasePtrName =
Tobias Grossera535dff2015-12-13 19:59:01 +0000182 getIslCompatibleName("MemRef_", BasePtr, Kind == MK_PHI ? "__phi" : "");
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000183 Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000184
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000185 updateSizes(Sizes);
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000186 BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
187 if (BasePtrOriginSAI)
188 const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000189}
190
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000191__isl_give isl_space *ScopArrayInfo::getSpace() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000192 auto *Space =
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000193 isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
194 Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
195 return Space;
196}
197
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000198void ScopArrayInfo::updateElementType(Type *NewElementType) {
199 if (NewElementType == ElementType)
200 return;
201
Tobias Grosserd840fc72016-02-04 13:18:42 +0000202 auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
203 auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
204
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000205 if (NewElementSize == OldElementSize)
206 return;
Tobias Grosserd840fc72016-02-04 13:18:42 +0000207
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000208 if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
209 ElementType = NewElementType;
210 } else {
211 auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
212 ElementType = IntegerType::get(ElementType->getContext(), GCD);
213 }
214}
215
216bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes) {
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000217 int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
218 int ExtraDimsNew = NewSizes.size() - SharedDims;
219 int ExtraDimsOld = DimensionSizes.size() - SharedDims;
Tobias Grosser8286b832015-11-02 11:29:32 +0000220 for (int i = 0; i < SharedDims; i++)
221 if (NewSizes[i + ExtraDimsNew] != DimensionSizes[i + ExtraDimsOld])
222 return false;
223
224 if (DimensionSizes.size() >= NewSizes.size())
225 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000226
227 DimensionSizes.clear();
228 DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
229 NewSizes.end());
230 for (isl_pw_aff *Size : DimensionSizesPw)
231 isl_pw_aff_free(Size);
232 DimensionSizesPw.clear();
233 for (const SCEV *Expr : DimensionSizes) {
234 isl_pw_aff *Size = S.getPwAff(Expr);
235 DimensionSizesPw.push_back(Size);
236 }
Tobias Grosser8286b832015-11-02 11:29:32 +0000237 return true;
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000238}
239
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000240ScopArrayInfo::~ScopArrayInfo() {
241 isl_id_free(Id);
242 for (isl_pw_aff *Size : DimensionSizesPw)
243 isl_pw_aff_free(Size);
244}
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000245
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000246std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
247
248int ScopArrayInfo::getElemSizeInBytes() const {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +0000249 return DL.getTypeAllocSize(ElementType);
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000250}
251
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000252isl_id *ScopArrayInfo::getBasePtrId() const { return isl_id_copy(Id); }
253
254void ScopArrayInfo::dump() const { print(errs()); }
255
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000256void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000257 OS.indent(8) << *getElementType() << " " << getName();
258 if (getNumberOfDimensions() > 0)
259 OS << "[*]";
Tobias Grosser26253842015-11-10 14:24:21 +0000260 for (unsigned u = 1; u < getNumberOfDimensions(); u++) {
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000261 OS << "[";
262
Tobias Grosser26253842015-11-10 14:24:21 +0000263 if (SizeAsPwAff) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000264 auto *Size = getDimensionSizePw(u);
Tobias Grosser26253842015-11-10 14:24:21 +0000265 OS << " " << Size << " ";
266 isl_pw_aff_free(Size);
267 } else {
268 OS << *getDimensionSize(u);
269 }
Tobias Grosserd46fd5e2015-08-12 15:27:16 +0000270
271 OS << "]";
272 }
273
Tobias Grosser4ea2e072015-11-10 14:02:54 +0000274 OS << ";";
275
Johannes Doerfert4eed5be2015-08-20 18:04:22 +0000276 if (BasePtrOriginSAI)
277 OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
278
Tobias Grosser49ad36c2015-05-20 08:05:31 +0000279 OS << " // Element size " << getElemSizeInBytes() << "\n";
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000280}
281
282const ScopArrayInfo *
283ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
284 isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
285 assert(Id && "Output dimension didn't have an ID");
286 return getFromId(Id);
287}
288
289const ScopArrayInfo *ScopArrayInfo::getFromId(isl_id *Id) {
290 void *User = isl_id_get_user(Id);
291 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
292 isl_id_free(Id);
293 return SAI;
294}
295
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000296void MemoryAccess::updateDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000297 auto *SAI = getScopArrayInfo();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000298 auto *ArraySpace = SAI->getSpace();
299 auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000300 auto *Ctx = isl_space_get_ctx(AccessSpace);
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000301
302 auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
303 auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
304 auto DimsMissing = DimsArray - DimsAccess;
305
Michael Kruse375cb5f2016-02-24 22:08:24 +0000306 auto *BB = getStatement()->getEntryBlock();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000307 auto &DL = BB->getModule()->getDataLayout();
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000308 unsigned ArrayElemSize = SAI->getElemSizeInBytes();
Johannes Doerfertcea61932016-02-21 19:13:19 +0000309 unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000310
Johannes Doerferta90943d2016-02-21 16:37:25 +0000311 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000312 isl_set_universe(AccessSpace),
313 isl_set_universe(isl_space_copy(ArraySpace)));
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000314
315 for (unsigned i = 0; i < DimsMissing; i++)
316 Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
317
318 for (unsigned i = DimsMissing; i < DimsArray; i++)
319 Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
320
321 AccessRelation = isl_map_apply_range(AccessRelation, Map);
Roman Gareev10595a12016-01-08 14:01:59 +0000322
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000323 // For the non delinearized arrays, divide the access function of the last
324 // subscript by the size of the elements in the array.
325 //
326 // A stride one array access in C expressed as A[i] is expressed in
327 // LLVM-IR as something like A[i * elementsize]. This hides the fact that
328 // two subsequent values of 'i' index two values that are stored next to
329 // each other in memory. By this division we make this characteristic
330 // obvious again. If the base pointer was accessed with offsets not divisible
331 // by the accesses element size, we will have choosen a smaller ArrayElemSize
332 // that divides the offsets of all accesses to this base pointer.
333 if (DimsAccess == 1) {
334 isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
335 AccessRelation = isl_map_floordiv_val(AccessRelation, V);
336 }
337
338 if (!isAffine())
339 computeBoundsOnAccessRelation(ArrayElemSize);
340
Tobias Grosserd840fc72016-02-04 13:18:42 +0000341 // Introduce multi-element accesses in case the type loaded by this memory
342 // access is larger than the canonical element type of the array.
343 //
344 // An access ((float *)A)[i] to an array char *A is modeled as
345 // {[i] -> A[o] : 4 i <= o <= 4 i + 3
Tobias Grosserd840fc72016-02-04 13:18:42 +0000346 if (ElemBytes > ArrayElemSize) {
347 assert(ElemBytes % ArrayElemSize == 0 &&
348 "Loaded element size should be multiple of canonical element size");
Johannes Doerferta90943d2016-02-21 16:37:25 +0000349 auto *Map = isl_map_from_domain_and_range(
Tobias Grosserd840fc72016-02-04 13:18:42 +0000350 isl_set_universe(isl_space_copy(ArraySpace)),
351 isl_set_universe(isl_space_copy(ArraySpace)));
352 for (unsigned i = 0; i < DimsArray - 1; i++)
353 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
354
Tobias Grosserd840fc72016-02-04 13:18:42 +0000355 isl_constraint *C;
356 isl_local_space *LS;
357
358 LS = isl_local_space_from_space(isl_map_get_space(Map));
Tobias Grosserd840fc72016-02-04 13:18:42 +0000359 int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
360
361 C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
362 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000363 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000364 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
365 Map = isl_map_add_constraint(Map, C);
366
367 C = isl_constraint_alloc_inequality(LS);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000368 C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000369 C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
370 C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
371 Map = isl_map_add_constraint(Map, C);
372 AccessRelation = isl_map_apply_range(AccessRelation, Map);
373 }
374
375 isl_space_free(ArraySpace);
376
Roman Gareev10595a12016-01-08 14:01:59 +0000377 assumeNoOutOfBound();
Tobias Grosser99c70dd2015-09-26 08:55:54 +0000378}
379
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000380const std::string
381MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
382 switch (RT) {
383 case MemoryAccess::RT_NONE:
384 llvm_unreachable("Requested a reduction operator string for a memory "
385 "access which isn't a reduction");
386 case MemoryAccess::RT_ADD:
387 return "+";
388 case MemoryAccess::RT_MUL:
389 return "*";
390 case MemoryAccess::RT_BOR:
391 return "|";
392 case MemoryAccess::RT_BXOR:
393 return "^";
394 case MemoryAccess::RT_BAND:
395 return "&";
396 }
397 llvm_unreachable("Unknown reduction type");
398 return "";
399}
400
Johannes Doerfertf6183392014-07-01 20:52:51 +0000401/// @brief Return the reduction type for a given binary operator
402static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
403 const Instruction *Load) {
404 if (!BinOp)
405 return MemoryAccess::RT_NONE;
406 switch (BinOp->getOpcode()) {
407 case Instruction::FAdd:
408 if (!BinOp->hasUnsafeAlgebra())
409 return MemoryAccess::RT_NONE;
410 // Fall through
411 case Instruction::Add:
412 return MemoryAccess::RT_ADD;
413 case Instruction::Or:
414 return MemoryAccess::RT_BOR;
415 case Instruction::Xor:
416 return MemoryAccess::RT_BXOR;
417 case Instruction::And:
418 return MemoryAccess::RT_BAND;
419 case Instruction::FMul:
420 if (!BinOp->hasUnsafeAlgebra())
421 return MemoryAccess::RT_NONE;
422 // Fall through
423 case Instruction::Mul:
424 if (DisableMultiplicativeReductions)
425 return MemoryAccess::RT_NONE;
426 return MemoryAccess::RT_MUL;
427 default:
428 return MemoryAccess::RT_NONE;
429 }
430}
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000431
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000432/// @brief Derive the individual index expressions from a GEP instruction
433///
434/// This function optimistically assumes the GEP references into a fixed size
435/// array. If this is actually true, this function returns a list of array
436/// subscript expressions as SCEV as well as a list of integers describing
437/// the size of the individual array dimensions. Both lists have either equal
438/// length of the size list is one element shorter in case there is no known
439/// size available for the outermost array dimension.
440///
441/// @param GEP The GetElementPtr instruction to analyze.
442///
443/// @return A tuple with the subscript expressions and the dimension sizes.
444static std::tuple<std::vector<const SCEV *>, std::vector<int>>
445getIndexExpressionsFromGEP(GetElementPtrInst *GEP, ScalarEvolution &SE) {
446 std::vector<const SCEV *> Subscripts;
447 std::vector<int> Sizes;
448
449 Type *Ty = GEP->getPointerOperandType();
450
451 bool DroppedFirstDim = false;
452
Michael Kruse26ed65e2015-09-24 17:32:49 +0000453 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000454
455 const SCEV *Expr = SE.getSCEV(GEP->getOperand(i));
456
457 if (i == 1) {
Johannes Doerferta90943d2016-02-21 16:37:25 +0000458 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000459 Ty = PtrTy->getElementType();
Johannes Doerferta90943d2016-02-21 16:37:25 +0000460 } else if (auto *ArrayTy = dyn_cast<ArrayType>(Ty)) {
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000461 Ty = ArrayTy->getElementType();
462 } else {
463 Subscripts.clear();
464 Sizes.clear();
465 break;
466 }
Johannes Doerferta90943d2016-02-21 16:37:25 +0000467 if (auto *Const = dyn_cast<SCEVConstant>(Expr))
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000468 if (Const->getValue()->isZero()) {
469 DroppedFirstDim = true;
470 continue;
471 }
472 Subscripts.push_back(Expr);
473 continue;
474 }
475
Johannes Doerferta90943d2016-02-21 16:37:25 +0000476 auto *ArrayTy = dyn_cast<ArrayType>(Ty);
Tobias Grosser5fd8c092015-09-17 17:28:15 +0000477 if (!ArrayTy) {
478 Subscripts.clear();
479 Sizes.clear();
480 break;
481 }
482
483 Subscripts.push_back(Expr);
484 if (!(DroppedFirstDim && i == 2))
485 Sizes.push_back(ArrayTy->getNumElements());
486
487 Ty = ArrayTy->getElementType();
488 }
489
490 return std::make_tuple(Subscripts, Sizes);
491}
492
Tobias Grosser75805372011-04-29 06:27:02 +0000493MemoryAccess::~MemoryAccess() {
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000494 isl_id_free(Id);
Tobias Grosser54a86e62011-08-18 06:31:46 +0000495 isl_map_free(AccessRelation);
Tobias Grosser166c4222015-09-05 07:46:40 +0000496 isl_map_free(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000497}
498
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000499const ScopArrayInfo *MemoryAccess::getScopArrayInfo() const {
500 isl_id *ArrayId = getArrayId();
501 void *User = isl_id_get_user(ArrayId);
502 const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
503 isl_id_free(ArrayId);
504 return SAI;
505}
506
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000507__isl_give isl_id *MemoryAccess::getArrayId() const {
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000508 return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
509}
510
Tobias Grosserd840fc72016-02-04 13:18:42 +0000511__isl_give isl_map *MemoryAccess::getAddressFunction() const {
512 return isl_map_lexmin(getAccessRelation());
513}
514
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000515__isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
516 __isl_take isl_union_map *USchedule) const {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000517 isl_map *Schedule, *ScheduledAccRel;
518 isl_union_set *UDomain;
519
520 UDomain = isl_union_set_from_set(getStatement()->getDomain());
521 USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
522 Schedule = isl_map_from_union_map(USchedule);
Tobias Grosserd840fc72016-02-04 13:18:42 +0000523 ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000524 return isl_pw_multi_aff_from_map(ScheduledAccRel);
525}
526
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000527__isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000528 return isl_map_copy(AccessRelation);
529}
530
Johannes Doerferta99130f2014-10-13 12:58:03 +0000531std::string MemoryAccess::getOriginalAccessRelationStr() const {
Tobias Grosser5d453812011-10-06 00:04:11 +0000532 return stringFromIslObj(AccessRelation);
533}
534
Johannes Doerferta99130f2014-10-13 12:58:03 +0000535__isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000536 return isl_map_get_space(AccessRelation);
537}
538
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000539__isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
Tobias Grosser166c4222015-09-05 07:46:40 +0000540 return isl_map_copy(NewAccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000541}
542
Tobias Grosser6f730082015-09-05 07:46:47 +0000543std::string MemoryAccess::getNewAccessRelationStr() const {
544 return stringFromIslObj(NewAccessRelation);
545}
546
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000547__isl_give isl_basic_map *
548MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
Tobias Grosser084d8f72012-05-29 09:29:44 +0000549 isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
Tobias Grossered295662012-09-11 13:50:21 +0000550 Space = isl_space_align_params(Space, Statement->getDomainSpace());
Tobias Grosser75805372011-04-29 06:27:02 +0000551
Tobias Grosser084d8f72012-05-29 09:29:44 +0000552 return isl_basic_map_from_domain_and_range(
Tobias Grosserabfbe632013-02-05 12:09:06 +0000553 isl_basic_set_universe(Statement->getDomainSpace()),
554 isl_basic_set_universe(Space));
Tobias Grosser75805372011-04-29 06:27:02 +0000555}
556
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000557// Formalize no out-of-bound access assumption
558//
559// When delinearizing array accesses we optimistically assume that the
560// delinearized accesses do not access out of bound locations (the subscript
561// expression of each array evaluates for each statement instance that is
562// executed to a value that is larger than zero and strictly smaller than the
563// size of the corresponding dimension). The only exception is the outermost
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000564// dimension for which we do not need to assume any upper bound. At this point
565// we formalize this assumption to ensure that at code generation time the
566// relevant run-time checks can be generated.
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000567//
568// To find the set of constraints necessary to avoid out of bound accesses, we
569// first build the set of data locations that are not within array bounds. We
570// then apply the reverse access relation to obtain the set of iterations that
571// may contain invalid accesses and reduce this set of iterations to the ones
572// that are actually executed by intersecting them with the domain of the
573// statement. If we now project out all loop dimensions, we obtain a set of
574// parameters that may cause statement instances to be executed that may
575// possibly yield out of bound memory accesses. The complement of these
576// constraints is the set of constraints that needs to be assumed to ensure such
577// statement instances are never executed.
Michael Krusee2bccbb2015-09-18 19:59:43 +0000578void MemoryAccess::assumeNoOutOfBound() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000579 auto *SAI = getScopArrayInfo();
Johannes Doerferta99130f2014-10-13 12:58:03 +0000580 isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000581 isl_set *Outside = isl_set_empty(isl_space_copy(Space));
Roman Gareev10595a12016-01-08 14:01:59 +0000582 for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000583 isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
584 isl_pw_aff *Var =
585 isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
586 isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
587
588 isl_set *DimOutside;
589
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000590 DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
Johannes Doerfertadeab372016-02-07 13:57:32 +0000591 isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000592 SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
593 isl_space_dim(Space, isl_dim_set));
594 SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
595 isl_space_get_tuple_id(Space, isl_dim_set));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000596
Tobias Grosserf57d63f2014-08-03 21:07:30 +0000597 DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000598
599 Outside = isl_set_union(Outside, DimOutside);
600 }
601
602 Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
603 Outside = isl_set_intersect(Outside, Statement->getDomain());
604 Outside = isl_set_params(Outside);
Tobias Grosserf54bb772015-06-26 12:09:28 +0000605
606 // Remove divs to avoid the construction of overly complicated assumptions.
607 // Doing so increases the set of parameter combinations that are assumed to
608 // not appear. This is always save, but may make the resulting run-time check
609 // bail out more often than strictly necessary.
610 Outside = isl_set_remove_divs(Outside);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000611 Outside = isl_set_complement(Outside);
Michael Krusead28e5a2016-01-26 13:33:15 +0000612 Statement->getParent()->addAssumption(
613 INBOUNDS, Outside,
614 getAccessInstruction() ? getAccessInstruction()->getDebugLoc() : nullptr);
Tobias Grosser5e6813d2014-07-02 17:47:48 +0000615 isl_space_free(Space);
616}
617
Johannes Doerfertcea61932016-02-21 19:13:19 +0000618void MemoryAccess::buildMemIntrinsicAccessRelation() {
619 auto MAI = MemAccInst(getAccessInstruction());
620 assert(MAI.isMemIntrinsic());
621 assert(Subscripts.size() == 2 && Sizes.size() == 0);
622
623 auto *LengthPWA = Statement->getPwAff(Subscripts[1]);
624 auto *LengthMap = isl_map_from_pw_aff(LengthPWA);
625 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
626 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
627 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
628 auto *SubscriptPWA = Statement->getPwAff(Subscripts[0]);
629 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
630 SubscriptMap =
631 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
632 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
633 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
634 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
635 getStatement()->getDomainId());
636}
637
Johannes Doerferte7044942015-02-24 11:58:30 +0000638void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
639 ScalarEvolution *SE = Statement->getParent()->getSE();
640
Johannes Doerfertcea61932016-02-21 19:13:19 +0000641 auto MAI = MemAccInst(getAccessInstruction());
642 if (MAI.isMemIntrinsic())
643 return;
644
645 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000646 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
647 return;
648
649 auto *PtrSCEV = SE->getSCEV(Ptr);
650 if (isa<SCEVCouldNotCompute>(PtrSCEV))
651 return;
652
653 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
654 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
655 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
656
657 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
658 if (Range.isFullSet())
659 return;
660
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000661 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000662 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000663 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000664 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000665 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000666
667 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000668 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000669
670 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
671 AccessRange =
672 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
673 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
674}
675
Michael Krusee2bccbb2015-09-18 19:59:43 +0000676__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000677 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000678 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000679
680 for (int i = Size - 2; i >= 0; --i) {
681 isl_space *Space;
682 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000683 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000684
685 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
686 isl_pw_aff_free(DimSize);
687 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
688
689 Space = isl_map_get_space(AccessRelation);
690 Space = isl_space_map_from_set(isl_space_range(Space));
691 Space = isl_space_align_params(Space, SpaceSize);
692
693 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
694 isl_id_free(ParamId);
695
696 MapOne = isl_map_universe(isl_space_copy(Space));
697 for (int j = 0; j < Size; ++j)
698 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
699 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
700
701 MapTwo = isl_map_universe(isl_space_copy(Space));
702 for (int j = 0; j < Size; ++j)
703 if (j < i || j > i + 1)
704 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
705
706 isl_local_space *LS = isl_local_space_from_space(Space);
707 isl_constraint *C;
708 C = isl_equality_alloc(isl_local_space_copy(LS));
709 C = isl_constraint_set_constant_si(C, -1);
710 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
711 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
712 MapTwo = isl_map_add_constraint(MapTwo, C);
713 C = isl_equality_alloc(LS);
714 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
715 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
716 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
717 MapTwo = isl_map_add_constraint(MapTwo, C);
718 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
719
720 MapOne = isl_map_union(MapOne, MapTwo);
721 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
722 }
723 return AccessRelation;
724}
725
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000726/// @brief Check if @p Expr is divisible by @p Size.
727static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000728 if (Size == 1)
729 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000730
731 // Only one factor needs to be divisible.
732 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
733 for (auto *FactorExpr : MulExpr->operands())
734 if (isDivisible(FactorExpr, Size, SE))
735 return true;
736 return false;
737 }
738
739 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
740 // to be divisble.
741 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
742 for (auto *OpExpr : NAryExpr->operands())
743 if (!isDivisible(OpExpr, Size, SE))
744 return false;
745 return true;
746 }
747
748 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
749 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
750 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
751 return MulSCEV == Expr;
752}
753
Michael Krusee2bccbb2015-09-18 19:59:43 +0000754void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
755 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000756
Michael Krusee2bccbb2015-09-18 19:59:43 +0000757 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000758 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000759
Michael Krusee2bccbb2015-09-18 19:59:43 +0000760 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000761 if (isa<MemIntrinsic>(getAccessInstruction()))
762 buildMemIntrinsicAccessRelation();
763
Tobias Grosser4f967492013-06-23 05:21:18 +0000764 // We overapproximate non-affine accesses with a possible access to the
765 // whole array. For read accesses it does not make a difference, if an
766 // access must or may happen. However, for write accesses it is important to
767 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000768 if (!AccessRelation)
769 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
770
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000771 AccessRelation =
772 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000773 return;
774 }
775
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000776 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000777 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000778
Michael Krusee2bccbb2015-09-18 19:59:43 +0000779 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
780 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000781 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000782 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000783 }
784
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000785 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000786 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000787
Tobias Grosser79baa212014-04-10 08:38:02 +0000788 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000789 AccessRelation = isl_map_set_tuple_id(
790 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000791 AccessRelation =
792 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
793
Tobias Grosseraa660a92015-03-30 00:07:50 +0000794 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000795 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000796}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000797
Michael Krusecac948e2015-10-02 13:53:07 +0000798MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000799 AccessType AccType, Value *BaseAddress,
800 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000801 ArrayRef<const SCEV *> Subscripts,
802 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000803 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000804 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
805 BaseAddr(BaseAddress), BaseName(BaseName), ElementType(ElementType),
Michael Krusecac948e2015-10-02 13:53:07 +0000806 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
807 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000808 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000809 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000810 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000811 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000812
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000813 std::string IdName =
814 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000815 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
816}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000817
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000818void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000819 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000820 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000821}
822
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000823const std::string MemoryAccess::getReductionOperatorStr() const {
824 return MemoryAccess::getReductionOperatorStr(getReductionType());
825}
826
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000827__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
828
Johannes Doerfertf6183392014-07-01 20:52:51 +0000829raw_ostream &polly::operator<<(raw_ostream &OS,
830 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000831 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000832 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000833 else
834 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000835 return OS;
836}
837
Tobias Grosser75805372011-04-29 06:27:02 +0000838void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000839 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000840 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000841 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000842 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000843 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000844 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000845 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000846 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000847 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000848 break;
849 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000850 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000851 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000852 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000853 if (hasNewAccessRelation())
854 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000855}
856
Tobias Grosser74394f02013-01-14 22:40:23 +0000857void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000858
859// Create a map in the size of the provided set domain, that maps from the
860// one element of the provided set domain to another element of the provided
861// set domain.
862// The mapping is limited to all points that are equal in all but the last
863// dimension and for which the last dimension of the input is strict smaller
864// than the last dimension of the output.
865//
866// getEqualAndLarger(set[i0, i1, ..., iX]):
867//
868// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
869// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
870//
Tobias Grosserf5338802011-10-06 00:03:35 +0000871static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000872 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000873 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000874 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000875
876 // Set all but the last dimension to be equal for the input and output
877 //
878 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
879 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000880 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000881 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000882
883 // Set the last dimension of the input to be strict smaller than the
884 // last dimension of the output.
885 //
886 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000887 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
888 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000889 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000890}
891
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000892__isl_give isl_set *
893MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000894 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000895 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000896 isl_space *Space = isl_space_range(isl_map_get_space(S));
897 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000898
Sebastian Popa00a0292012-12-18 07:46:06 +0000899 S = isl_map_reverse(S);
900 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000901
Sebastian Popa00a0292012-12-18 07:46:06 +0000902 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
903 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
904 NextScatt = isl_map_apply_domain(NextScatt, S);
905 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000906
Sebastian Popa00a0292012-12-18 07:46:06 +0000907 isl_set *Deltas = isl_map_deltas(NextScatt);
908 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000909}
910
Sebastian Popa00a0292012-12-18 07:46:06 +0000911bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000912 int StrideWidth) const {
913 isl_set *Stride, *StrideX;
914 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000915
Sebastian Popa00a0292012-12-18 07:46:06 +0000916 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000917 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000918 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
919 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
920 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
921 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000922 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000923
Tobias Grosser28dd4862012-01-24 16:42:16 +0000924 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000925 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000926
Tobias Grosser28dd4862012-01-24 16:42:16 +0000927 return IsStrideX;
928}
929
Sebastian Popa00a0292012-12-18 07:46:06 +0000930bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
931 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000932}
933
Sebastian Popa00a0292012-12-18 07:46:06 +0000934bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
935 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000936}
937
Tobias Grosser166c4222015-09-05 07:46:40 +0000938void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
939 isl_map_free(NewAccessRelation);
940 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000941}
Tobias Grosser75805372011-04-29 06:27:02 +0000942
943//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000944
Tobias Grosser808cd692015-07-14 09:33:13 +0000945isl_map *ScopStmt::getSchedule() const {
946 isl_set *Domain = getDomain();
947 if (isl_set_is_empty(Domain)) {
948 isl_set_free(Domain);
949 return isl_map_from_aff(
950 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
951 }
952 auto *Schedule = getParent()->getSchedule();
953 Schedule = isl_union_map_intersect_domain(
954 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
955 if (isl_union_map_is_empty(Schedule)) {
956 isl_set_free(Domain);
957 isl_union_map_free(Schedule);
958 return isl_map_from_aff(
959 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
960 }
961 auto *M = isl_map_from_union_map(Schedule);
962 M = isl_map_coalesce(M);
963 M = isl_map_gist_domain(M, Domain);
964 M = isl_map_coalesce(M);
965 return M;
966}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000967
Johannes Doerfert574182d2015-08-12 10:19:50 +0000968__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Michael Kruse375cb5f2016-02-24 22:08:24 +0000969 return getParent()->getPwAff(E, getEntryBlock());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000970}
971
Tobias Grosser37eb4222014-02-20 21:43:54 +0000972void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
973 assert(isl_set_is_subset(NewDomain, Domain) &&
974 "New domain is not a subset of old domain!");
975 isl_set_free(Domain);
976 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000977}
978
Michael Krusecac948e2015-10-02 13:53:07 +0000979void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000980 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000981 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000982 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000983
Tobias Grossera535dff2015-12-13 19:59:01 +0000984 ScopArrayInfo::MemoryKind Ty;
985 if (Access->isPHIKind())
986 Ty = ScopArrayInfo::MK_PHI;
987 else if (Access->isExitPHIKind())
988 Ty = ScopArrayInfo::MK_ExitPHI;
989 else if (Access->isValueKind())
990 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000991 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000992 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000993
Johannes Doerfertadeab372016-02-07 13:57:32 +0000994 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
995 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +0000996 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +0000997 }
998}
999
Michael Krusecac948e2015-10-02 13:53:07 +00001000void ScopStmt::addAccess(MemoryAccess *Access) {
1001 Instruction *AccessInst = Access->getAccessInstruction();
1002
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001003 if (Access->isArrayKind()) {
1004 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1005 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001006 } else if (Access->isValueKind() && Access->isWrite()) {
1007 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001008 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001009 assert(!ValueWrites.lookup(AccessVal));
1010
1011 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001012 } else if (Access->isValueKind() && Access->isRead()) {
1013 Value *AccessVal = Access->getAccessValue();
1014 assert(!ValueReads.lookup(AccessVal));
1015
1016 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001017 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1018 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1019 assert(!PHIWrites.lookup(PHI));
1020
1021 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001022 }
1023
1024 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001025}
1026
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001027void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001028 for (MemoryAccess *MA : *this)
1029 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001030
1031 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001032}
1033
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001034/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1035static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1036 void *User) {
1037 isl_set **BoundedParts = static_cast<isl_set **>(User);
1038 if (isl_basic_set_is_bounded(BSet))
1039 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1040 else
1041 isl_basic_set_free(BSet);
1042 return isl_stat_ok;
1043}
1044
1045/// @brief Return the bounded parts of @p S.
1046static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1047 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1048 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1049 isl_set_free(S);
1050 return BoundedParts;
1051}
1052
1053/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1054///
1055/// @returns A separation of @p S into first an unbounded then a bounded subset,
1056/// both with regards to the dimension @p Dim.
1057static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1058partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1059
1060 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001061 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001062
1063 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001064 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001065
1066 // Remove dimensions that are greater than Dim as they are not interesting.
1067 assert(NumDimsS >= Dim + 1);
1068 OnlyDimS =
1069 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1070
1071 // Create artificial parametric upper bounds for dimensions smaller than Dim
1072 // as we are not interested in them.
1073 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1074 for (unsigned u = 0; u < Dim; u++) {
1075 isl_constraint *C = isl_inequality_alloc(
1076 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1077 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1078 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1079 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1080 }
1081
1082 // Collect all bounded parts of OnlyDimS.
1083 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1084
1085 // Create the dimensions greater than Dim again.
1086 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1087 NumDimsS - Dim - 1);
1088
1089 // Remove the artificial upper bound parameters again.
1090 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1091
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001092 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001093 return std::make_pair(UnboundedParts, BoundedParts);
1094}
1095
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001096/// @brief Set the dimension Ids from @p From in @p To.
1097static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1098 __isl_take isl_set *To) {
1099 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1100 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1101 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1102 }
1103 return To;
1104}
1105
1106/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001107static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001108 __isl_take isl_pw_aff *L,
1109 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001110 switch (Pred) {
1111 case ICmpInst::ICMP_EQ:
1112 return isl_pw_aff_eq_set(L, R);
1113 case ICmpInst::ICMP_NE:
1114 return isl_pw_aff_ne_set(L, R);
1115 case ICmpInst::ICMP_SLT:
1116 return isl_pw_aff_lt_set(L, R);
1117 case ICmpInst::ICMP_SLE:
1118 return isl_pw_aff_le_set(L, R);
1119 case ICmpInst::ICMP_SGT:
1120 return isl_pw_aff_gt_set(L, R);
1121 case ICmpInst::ICMP_SGE:
1122 return isl_pw_aff_ge_set(L, R);
1123 case ICmpInst::ICMP_ULT:
1124 return isl_pw_aff_lt_set(L, R);
1125 case ICmpInst::ICMP_UGT:
1126 return isl_pw_aff_gt_set(L, R);
1127 case ICmpInst::ICMP_ULE:
1128 return isl_pw_aff_le_set(L, R);
1129 case ICmpInst::ICMP_UGE:
1130 return isl_pw_aff_ge_set(L, R);
1131 default:
1132 llvm_unreachable("Non integer predicate not supported");
1133 }
1134}
1135
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001136/// @brief Create the conditions under which @p L @p Pred @p R is true.
1137///
1138/// Helper function that will make sure the dimensions of the result have the
1139/// same isl_id's as the @p Domain.
1140static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1141 __isl_take isl_pw_aff *L,
1142 __isl_take isl_pw_aff *R,
1143 __isl_keep isl_set *Domain) {
1144 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1145 return setDimensionIds(Domain, ConsequenceCondSet);
1146}
1147
1148/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001149///
1150/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001151/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1152/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001153static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001154buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001155 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1156
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001157 Value *Condition = getConditionFromTerminator(SI);
1158 assert(Condition && "No condition for switch");
1159
1160 ScalarEvolution &SE = *S.getSE();
1161 BasicBlock *BB = SI->getParent();
1162 isl_pw_aff *LHS, *RHS;
1163 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1164
1165 unsigned NumSuccessors = SI->getNumSuccessors();
1166 ConditionSets.resize(NumSuccessors);
1167 for (auto &Case : SI->cases()) {
1168 unsigned Idx = Case.getSuccessorIndex();
1169 ConstantInt *CaseValue = Case.getCaseValue();
1170
1171 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1172 isl_set *CaseConditionSet =
1173 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1174 ConditionSets[Idx] = isl_set_coalesce(
1175 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1176 }
1177
1178 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1179 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1180 for (unsigned u = 2; u < NumSuccessors; u++)
1181 ConditionSetUnion =
1182 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1183 ConditionSets[0] = setDimensionIds(
1184 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1185
1186 S.markAsOptimized();
1187 isl_pw_aff_free(LHS);
1188}
1189
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001190/// @brief Build the conditions sets for the branch condition @p Condition in
1191/// the @p Domain.
1192///
1193/// This will fill @p ConditionSets with the conditions under which control
1194/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001195/// have as many elements as @p TI has successors. If @p TI is nullptr the
1196/// context under which @p Condition is true/false will be returned as the
1197/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001198static void
1199buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1200 __isl_keep isl_set *Domain,
1201 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1202
1203 isl_set *ConsequenceCondSet = nullptr;
1204 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1205 if (CCond->isZero())
1206 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1207 else
1208 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1209 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1210 auto Opcode = BinOp->getOpcode();
1211 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1212
1213 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1214 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1215
1216 isl_set_free(ConditionSets.pop_back_val());
1217 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1218 isl_set_free(ConditionSets.pop_back_val());
1219 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1220
1221 if (Opcode == Instruction::And)
1222 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1223 else
1224 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1225 } else {
1226 auto *ICond = dyn_cast<ICmpInst>(Condition);
1227 assert(ICond &&
1228 "Condition of exiting branch was neither constant nor ICmp!");
1229
1230 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001231 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001232 isl_pw_aff *LHS, *RHS;
1233 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1234 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1235 ConsequenceCondSet =
1236 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1237 }
1238
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001239 // If no terminator was given we are only looking for parameter constraints
1240 // under which @p Condition is true/false.
1241 if (!TI)
1242 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1243
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001244 assert(ConsequenceCondSet);
1245 isl_set *AlternativeCondSet =
1246 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1247
1248 ConditionSets.push_back(isl_set_coalesce(
1249 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1250 ConditionSets.push_back(isl_set_coalesce(
1251 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1252}
1253
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001254/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1255///
1256/// This will fill @p ConditionSets with the conditions under which control
1257/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1258/// have as many elements as @p TI has successors.
1259static void
1260buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1261 __isl_keep isl_set *Domain,
1262 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1263
1264 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1265 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1266
1267 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1268
1269 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001270 ConditionSets.push_back(isl_set_copy(Domain));
1271 return;
1272 }
1273
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001274 Value *Condition = getConditionFromTerminator(TI);
1275 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001276
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001277 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001278}
1279
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001280void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001281 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001282
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001283 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001284 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001285}
1286
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001287void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1288 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001289 isl_ctx *Ctx = Parent.getIslCtx();
1290 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1291 Type *Ty = GEP->getPointerOperandType();
1292 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001293
1294 // The set of loads that are required to be invariant.
1295 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001296
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001297 std::vector<const SCEV *> Subscripts;
1298 std::vector<int> Sizes;
1299
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001300 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001301
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001302 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001303 Ty = PtrTy->getElementType();
1304 }
1305
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001306 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001307
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001308 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001309
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001310 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001311 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001312 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001313
Johannes Doerfert09e36972015-10-07 20:17:36 +00001314 InvariantLoadsSetTy AccessILS;
1315 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1316 continue;
1317
1318 bool NonAffine = false;
1319 for (LoadInst *LInst : AccessILS)
1320 if (!ScopRIL.count(LInst))
1321 NonAffine = true;
1322
1323 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001324 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001325
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001326 isl_pw_aff *AccessOffset = getPwAff(Expr);
1327 AccessOffset =
1328 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001329
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001330 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1331 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001332
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001333 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1334 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1335 OutOfBound = isl_set_params(OutOfBound);
1336 isl_set *InBound = isl_set_complement(OutOfBound);
1337 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001338
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001339 // A => B == !A or B
1340 isl_set *InBoundIfExecuted =
1341 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001342
Roman Gareev10595a12016-01-08 14:01:59 +00001343 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001344 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001345 }
1346
1347 isl_local_space_free(LSpace);
1348}
1349
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001350void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001351 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001352 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001353 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001354}
1355
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001356void ScopStmt::collectSurroundingLoops() {
1357 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1358 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1359 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1360 isl_id_free(DimId);
1361 }
1362}
1363
Michael Kruse9d080092015-09-11 21:41:48 +00001364ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001365 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001366
Tobias Grosser16c44032015-07-09 07:31:45 +00001367 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001368}
1369
Michael Kruse9d080092015-09-11 21:41:48 +00001370ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001371 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001372
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001373 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001374}
1375
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001376void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001377 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001378
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001379 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001380 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001381 buildAccessRelations();
1382
1383 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001384 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001385 } else {
1386 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001387 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001388 }
1389 }
1390
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001391 if (DetectReductions)
1392 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001393}
1394
Johannes Doerferte58a0122014-06-27 20:31:28 +00001395/// @brief Collect loads which might form a reduction chain with @p StoreMA
1396///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001397/// Check if the stored value for @p StoreMA is a binary operator with one or
1398/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001399/// used only once (by @p StoreMA) and its load operands are also used only
1400/// once, we have found a possible reduction chain. It starts at an operand
1401/// load and includes the binary operator and @p StoreMA.
1402///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001403/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001404/// escape this block or into any other store except @p StoreMA.
1405void ScopStmt::collectCandiateReductionLoads(
1406 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1407 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1408 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001409 return;
1410
1411 // Skip if there is not one binary operator between the load and the store
1412 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001413 if (!BinOp)
1414 return;
1415
1416 // Skip if the binary operators has multiple uses
1417 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001418 return;
1419
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001420 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001421 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1422 return;
1423
Johannes Doerfert9890a052014-07-01 00:32:29 +00001424 // Skip if the binary operator is outside the current SCoP
1425 if (BinOp->getParent() != Store->getParent())
1426 return;
1427
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001428 // Skip if it is a multiplicative reduction and we disabled them
1429 if (DisableMultiplicativeReductions &&
1430 (BinOp->getOpcode() == Instruction::Mul ||
1431 BinOp->getOpcode() == Instruction::FMul))
1432 return;
1433
Johannes Doerferte58a0122014-06-27 20:31:28 +00001434 // Check the binary operator operands for a candidate load
1435 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1436 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1437 if (!PossibleLoad0 && !PossibleLoad1)
1438 return;
1439
1440 // A load is only a candidate if it cannot escape (thus has only this use)
1441 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001442 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001443 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001444 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001445 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001446 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001447}
1448
1449/// @brief Check for reductions in this ScopStmt
1450///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001451/// Iterate over all store memory accesses and check for valid binary reduction
1452/// like chains. For all candidates we check if they have the same base address
1453/// and there are no other accesses which overlap with them. The base address
1454/// check rules out impossible reductions candidates early. The overlap check,
1455/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001456/// guarantees that none of the intermediate results will escape during
1457/// execution of the loop nest. We basically check here that no other memory
1458/// access can access the same memory as the potential reduction.
1459void ScopStmt::checkForReductions() {
1460 SmallVector<MemoryAccess *, 2> Loads;
1461 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1462
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001463 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001464 // stores and collecting possible reduction loads.
1465 for (MemoryAccess *StoreMA : MemAccs) {
1466 if (StoreMA->isRead())
1467 continue;
1468
1469 Loads.clear();
1470 collectCandiateReductionLoads(StoreMA, Loads);
1471 for (MemoryAccess *LoadMA : Loads)
1472 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1473 }
1474
1475 // Then check each possible candidate pair.
1476 for (const auto &CandidatePair : Candidates) {
1477 bool Valid = true;
1478 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1479 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1480
1481 // Skip those with obviously unequal base addresses.
1482 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1483 isl_map_free(LoadAccs);
1484 isl_map_free(StoreAccs);
1485 continue;
1486 }
1487
1488 // And check if the remaining for overlap with other memory accesses.
1489 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1490 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1491 isl_set *AllAccs = isl_map_range(AllAccsRel);
1492
1493 for (MemoryAccess *MA : MemAccs) {
1494 if (MA == CandidatePair.first || MA == CandidatePair.second)
1495 continue;
1496
1497 isl_map *AccRel =
1498 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1499 isl_set *Accs = isl_map_range(AccRel);
1500
1501 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1502 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1503 Valid = Valid && isl_set_is_empty(OverlapAccs);
1504 isl_set_free(OverlapAccs);
1505 }
1506 }
1507
1508 isl_set_free(AllAccs);
1509 if (!Valid)
1510 continue;
1511
Johannes Doerfertf6183392014-07-01 20:52:51 +00001512 const LoadInst *Load =
1513 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1514 MemoryAccess::ReductionType RT =
1515 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1516
Johannes Doerferte58a0122014-06-27 20:31:28 +00001517 // If no overlapping access was found we mark the load and store as
1518 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001519 CandidatePair.first->markAsReductionLike(RT);
1520 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001521 }
Tobias Grosser75805372011-04-29 06:27:02 +00001522}
1523
Tobias Grosser74394f02013-01-14 22:40:23 +00001524std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001525
Tobias Grosser54839312015-04-21 11:37:25 +00001526std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001527 auto *S = getSchedule();
1528 auto Str = stringFromIslObj(S);
1529 isl_map_free(S);
1530 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001531}
1532
Michael Kruse375cb5f2016-02-24 22:08:24 +00001533BasicBlock *ScopStmt::getEntryBlock() const {
1534 if (isBlockStmt())
1535 return getBasicBlock();
1536 return getRegion()->getEntry();
1537}
1538
Tobias Grosser74394f02013-01-14 22:40:23 +00001539unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001540
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001541unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001542
Tobias Grosser75805372011-04-29 06:27:02 +00001543const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1544
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001545const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001546 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001547}
1548
Tobias Grosser74394f02013-01-14 22:40:23 +00001549isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001550
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001551__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001552
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001553__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001554 return isl_set_get_space(Domain);
1555}
1556
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001557__isl_give isl_id *ScopStmt::getDomainId() const {
1558 return isl_set_get_tuple_id(Domain);
1559}
Tobias Grossercd95b772012-08-30 11:49:38 +00001560
Tobias Grosser10120182015-12-16 16:14:03 +00001561ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001562
1563void ScopStmt::print(raw_ostream &OS) const {
1564 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001565 OS.indent(12) << "Domain :=\n";
1566
1567 if (Domain) {
1568 OS.indent(16) << getDomainStr() << ";\n";
1569 } else
1570 OS.indent(16) << "n/a\n";
1571
Tobias Grosser54839312015-04-21 11:37:25 +00001572 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001573
1574 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001575 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001576 } else
1577 OS.indent(16) << "n/a\n";
1578
Tobias Grosser083d3d32014-06-28 08:59:45 +00001579 for (MemoryAccess *Access : MemAccs)
1580 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001581}
1582
1583void ScopStmt::dump() const { print(dbgs()); }
1584
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001585void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001586 // Remove all memory accesses in @p InvMAs from this statement
1587 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001588 // MK_Value READs have no access instruction, hence would not be removed by
1589 // this function. However, it is only used for invariant LoadInst accesses,
1590 // its arguments are always affine, hence synthesizable, and therefore there
1591 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001592 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001593 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001594 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001595 };
1596 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1597 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001598 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001599 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001600}
1601
Tobias Grosser75805372011-04-29 06:27:02 +00001602//===----------------------------------------------------------------------===//
1603/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001604
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001605void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001606 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1607 isl_set_free(Context);
1608 Context = NewContext;
1609}
1610
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001611/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1612struct SCEVSensitiveParameterRewriter
1613 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1614 ValueToValueMap &VMap;
1615 ScalarEvolution &SE;
1616
1617public:
1618 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1619 : VMap(VMap), SE(SE) {}
1620
1621 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1622 ValueToValueMap &VMap) {
1623 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1624 return SSPR.visit(E);
1625 }
1626
1627 const SCEV *visit(const SCEV *E) {
1628 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1629 }
1630
1631 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1632
1633 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1634 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1635 }
1636
1637 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1638 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1639 }
1640
1641 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1642 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1643 }
1644
1645 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1646 SmallVector<const SCEV *, 4> Operands;
1647 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1648 Operands.push_back(visit(E->getOperand(i)));
1649 return SE.getAddExpr(Operands);
1650 }
1651
1652 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1653 SmallVector<const SCEV *, 4> Operands;
1654 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1655 Operands.push_back(visit(E->getOperand(i)));
1656 return SE.getMulExpr(Operands);
1657 }
1658
1659 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1660 SmallVector<const SCEV *, 4> Operands;
1661 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1662 Operands.push_back(visit(E->getOperand(i)));
1663 return SE.getSMaxExpr(Operands);
1664 }
1665
1666 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1667 SmallVector<const SCEV *, 4> Operands;
1668 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1669 Operands.push_back(visit(E->getOperand(i)));
1670 return SE.getUMaxExpr(Operands);
1671 }
1672
1673 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1674 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1675 }
1676
1677 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1678 auto *Start = visit(E->getStart());
1679 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1680 visit(E->getStepRecurrence(SE)),
1681 E->getLoop(), SCEV::FlagAnyWrap);
1682 return SE.getAddExpr(Start, AddRec);
1683 }
1684
1685 const SCEV *visitUnknown(const SCEVUnknown *E) {
1686 if (auto *NewValue = VMap.lookup(E->getValue()))
1687 return SE.getUnknown(NewValue);
1688 return E;
1689 }
1690};
1691
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001692const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001693 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001694}
1695
Tobias Grosserabfbe632013-02-05 12:09:06 +00001696void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001697 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001698 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001699
1700 // Normalize the SCEV to get the representing element for an invariant load.
1701 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1702
Tobias Grosser60b54f12011-11-08 15:41:28 +00001703 if (ParameterIds.find(Parameter) != ParameterIds.end())
1704 continue;
1705
1706 int dimension = Parameters.size();
1707
1708 Parameters.push_back(Parameter);
1709 ParameterIds[Parameter] = dimension;
1710 }
1711}
1712
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001713__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001714 // Normalize the SCEV to get the representing element for an invariant load.
1715 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1716
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001717 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001718
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001719 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001720 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001721
Tobias Grosser8f99c162011-11-15 11:38:55 +00001722 std::string ParameterName;
1723
Craig Topper7fb6e472016-01-31 20:36:20 +00001724 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001725
Tobias Grosser8f99c162011-11-15 11:38:55 +00001726 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1727 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001728
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001729 // If this parameter references a specific Value and this value has a name
1730 // we use this name as it is likely to be unique and more useful than just
1731 // a number.
1732 if (Val->hasName())
1733 ParameterName = Val->getName();
1734 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001735 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001736 if (LoadOrigin->hasName()) {
1737 ParameterName += "_loaded_from_";
1738 ParameterName +=
1739 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1740 }
1741 }
1742 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001743
Tobias Grosser20532b82014-04-11 17:56:49 +00001744 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1745 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001746}
Tobias Grosser75805372011-04-29 06:27:02 +00001747
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001748isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1749 isl_set *DomainContext = isl_union_set_params(getDomains());
1750 return isl_set_intersect_params(C, DomainContext);
1751}
1752
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001753void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001754 if (IgnoreIntegerWrapping) {
1755 BoundaryContext = isl_set_universe(getParamSpace());
1756 return;
1757 }
1758
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001759 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001760
1761 // The isl_set_complement operation used to create the boundary context
1762 // can possibly become very expensive. We bound the compile time of
1763 // this operation by setting a compute out.
1764 //
1765 // TODO: We can probably get around using isl_set_complement and directly
1766 // AST generate BoundaryContext.
1767 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001768 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001769 isl_ctx_set_max_operations(getIslCtx(), 300000);
1770 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1771
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001772 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001773
Tobias Grossera52b4da2015-11-11 17:59:53 +00001774 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1775 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001776 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001777 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001778
1779 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1780 isl_ctx_reset_operations(getIslCtx());
1781 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001782 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001783 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001784}
1785
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001786void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1787 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001788 auto *R = &getRegion();
1789 auto &F = *R->getEntry()->getParent();
1790 for (auto &Assumption : AC.assumptions()) {
1791 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1792 if (!CI || CI->getNumArgOperands() != 1)
1793 continue;
1794 if (!DT.dominates(CI->getParent(), R->getEntry()))
1795 continue;
1796
1797 auto *Val = CI->getArgOperand(0);
1798 std::vector<const SCEV *> Params;
1799 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1800 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1801 CI->getDebugLoc(),
1802 "Non-affine user assumption ignored.");
1803 continue;
1804 }
1805
1806 addParams(Params);
1807
1808 auto *L = LI.getLoopFor(CI->getParent());
1809 SmallVector<isl_set *, 2> ConditionSets;
1810 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1811 assert(ConditionSets.size() == 2);
1812 isl_set_free(ConditionSets[1]);
1813
1814 auto *AssumptionCtx = ConditionSets[0];
1815 emitOptimizationRemarkAnalysis(
1816 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1817 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1818 Context = isl_set_intersect(Context, AssumptionCtx);
1819 }
1820}
1821
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001822void Scop::addUserContext() {
1823 if (UserContextStr.empty())
1824 return;
1825
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001826 isl_set *UserContext =
1827 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001828 isl_space *Space = getParamSpace();
1829 if (isl_space_dim(Space, isl_dim_param) !=
1830 isl_set_dim(UserContext, isl_dim_param)) {
1831 auto SpaceStr = isl_space_to_str(Space);
1832 errs() << "Error: the context provided in -polly-context has not the same "
1833 << "number of dimensions than the computed context. Due to this "
1834 << "mismatch, the -polly-context option is ignored. Please provide "
1835 << "the context in the parameter space: " << SpaceStr << ".\n";
1836 free(SpaceStr);
1837 isl_set_free(UserContext);
1838 isl_space_free(Space);
1839 return;
1840 }
1841
1842 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001843 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1844 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001845
1846 if (strcmp(NameContext, NameUserContext) != 0) {
1847 auto SpaceStr = isl_space_to_str(Space);
1848 errs() << "Error: the name of dimension " << i
1849 << " provided in -polly-context "
1850 << "is '" << NameUserContext << "', but the name in the computed "
1851 << "context is '" << NameContext
1852 << "'. Due to this name mismatch, "
1853 << "the -polly-context option is ignored. Please provide "
1854 << "the context in the parameter space: " << SpaceStr << ".\n";
1855 free(SpaceStr);
1856 isl_set_free(UserContext);
1857 isl_space_free(Space);
1858 return;
1859 }
1860
1861 UserContext =
1862 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1863 isl_space_get_dim_id(Space, isl_dim_param, i));
1864 }
1865
1866 Context = isl_set_intersect(Context, UserContext);
1867 isl_space_free(Space);
1868}
1869
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001870void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001871 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001872
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001873 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001874 for (LoadInst *LInst : RIL) {
1875 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1876
Johannes Doerfert96e54712016-02-07 17:30:13 +00001877 Type *Ty = LInst->getType();
1878 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001879 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001880 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001881 continue;
1882 }
1883
1884 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001885 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1886 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001887 }
1888}
1889
Tobias Grosser6be480c2011-11-08 15:41:13 +00001890void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001891 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001892 Context = isl_set_universe(isl_space_copy(Space));
1893 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001894}
1895
Tobias Grosser18daaca2012-05-22 10:47:27 +00001896void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001897 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001898 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001899
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001900 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001901
Johannes Doerferte7044942015-02-24 11:58:30 +00001902 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001903 }
1904}
1905
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001906void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001907 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001908 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001909
Tobias Grosser083d3d32014-06-28 08:59:45 +00001910 for (const auto &ParamID : ParameterIds) {
1911 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001912 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001913 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001914 }
1915
1916 // Align the parameters of all data structures to the model.
1917 Context = isl_set_align_params(Context, Space);
1918
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001919 for (ScopStmt &Stmt : *this)
1920 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001921}
1922
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001923static __isl_give isl_set *
1924simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1925 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001926 // If we modelt all blocks in the SCoP that have side effects we can simplify
1927 // the context with the constraints that are needed for anything to be
1928 // executed at all. However, if we have error blocks in the SCoP we already
1929 // assumed some parameter combinations cannot occure and removed them from the
1930 // domains, thus we cannot use the remaining domain to simplify the
1931 // assumptions.
1932 if (!S.hasErrorBlock()) {
1933 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1934 AssumptionContext =
1935 isl_set_gist_params(AssumptionContext, DomainParameters);
1936 }
1937
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001938 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1939 return AssumptionContext;
1940}
1941
1942void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001943 // The parameter constraints of the iteration domains give us a set of
1944 // constraints that need to hold for all cases where at least a single
1945 // statement iteration is executed in the whole scop. We now simplify the
1946 // assumed context under the assumption that such constraints hold and at
1947 // least a single statement iteration is executed. For cases where no
1948 // statement instances are executed, the assumptions we have taken about
1949 // the executed code do not matter and can be changed.
1950 //
1951 // WARNING: This only holds if the assumptions we have taken do not reduce
1952 // the set of statement instances that are executed. Otherwise we
1953 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001954 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001955 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001956 // performed. In such a case, modifying the run-time conditions and
1957 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001958 // to not be executed.
1959 //
1960 // Example:
1961 //
1962 // When delinearizing the following code:
1963 //
1964 // for (long i = 0; i < 100; i++)
1965 // for (long j = 0; j < m; j++)
1966 // A[i+p][j] = 1.0;
1967 //
1968 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001969 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001970 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001971 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1972 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001973}
1974
Johannes Doerfertb164c792014-09-18 11:17:17 +00001975/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001976static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001977 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1978 isl_pw_multi_aff *MinPMA, *MaxPMA;
1979 isl_pw_aff *LastDimAff;
1980 isl_aff *OneAff;
1981 unsigned Pos;
1982
Johannes Doerfert9143d672014-09-27 11:02:39 +00001983 // Restrict the number of parameters involved in the access as the lexmin/
1984 // lexmax computation will take too long if this number is high.
1985 //
1986 // Experiments with a simple test case using an i7 4800MQ:
1987 //
1988 // #Parameters involved | Time (in sec)
1989 // 6 | 0.01
1990 // 7 | 0.04
1991 // 8 | 0.12
1992 // 9 | 0.40
1993 // 10 | 1.54
1994 // 11 | 6.78
1995 // 12 | 30.38
1996 //
1997 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
1998 unsigned InvolvedParams = 0;
1999 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2000 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2001 InvolvedParams++;
2002
2003 if (InvolvedParams > RunTimeChecksMaxParameters) {
2004 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002005 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002006 }
2007 }
2008
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00002009 Set = isl_set_remove_divs(Set);
2010
Johannes Doerfertb164c792014-09-18 11:17:17 +00002011 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2012 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2013
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002014 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2015 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2016
Johannes Doerfertb164c792014-09-18 11:17:17 +00002017 // Adjust the last dimension of the maximal access by one as we want to
2018 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2019 // we test during code generation might now point after the end of the
2020 // allocated array but we will never dereference it anyway.
2021 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2022 "Assumed at least one output dimension");
2023 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2024 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2025 OneAff = isl_aff_zero_on_domain(
2026 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2027 OneAff = isl_aff_add_constant_si(OneAff, 1);
2028 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2029 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2030
2031 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2032
2033 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002034 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002035}
2036
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002037static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2038 isl_set *Domain = MA->getStatement()->getDomain();
2039 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2040 return isl_set_reset_tuple_id(Domain);
2041}
2042
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002043/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2044static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002045 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002046 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002047
2048 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2049 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002050 Locations = isl_union_set_coalesce(Locations);
2051 Locations = isl_union_set_detect_equalities(Locations);
2052 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002053 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002054 isl_union_set_free(Locations);
2055 return Valid;
2056}
2057
Johannes Doerfert96425c22015-08-30 21:13:53 +00002058/// @brief Helper to treat non-affine regions and basic blocks the same.
2059///
2060///{
2061
2062/// @brief Return the block that is the representing block for @p RN.
2063static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2064 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2065 : RN->getNodeAs<BasicBlock>();
2066}
2067
2068/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002069static inline BasicBlock *
2070getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002071 if (RN->isSubRegion()) {
2072 assert(idx == 0);
2073 return RN->getNodeAs<Region>()->getExit();
2074 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002075 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002076}
2077
2078/// @brief Return the smallest loop surrounding @p RN.
2079static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2080 if (!RN->isSubRegion())
2081 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2082
2083 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2084 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2085 while (L && NonAffineSubRegion->contains(L))
2086 L = L->getParentLoop();
2087 return L;
2088}
2089
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002090static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2091 if (!RN->isSubRegion())
2092 return 1;
2093
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002094 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002095 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002096}
2097
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002098static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2099 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002100 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002101 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002102 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002103 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002104 return true;
2105 return false;
2106}
2107
Johannes Doerfert96425c22015-08-30 21:13:53 +00002108///}
2109
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002110static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2111 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002112 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002113 isl_id *DimId =
2114 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2115 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2116}
2117
Johannes Doerfert96425c22015-08-30 21:13:53 +00002118isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002119 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002120}
2121
2122isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2123 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002124 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002125}
2126
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002127void Scop::removeErrorBlockDomains(ScopDetection &SD, DominatorTree &DT,
2128 LoopInfo &LI) {
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002129 auto removeDomains = [this, &DT](BasicBlock *Start) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002130 auto *BBNode = DT.getNode(Start);
2131 for (auto *ErrorChild : depth_first(BBNode)) {
2132 auto *ErrorChildBlock = ErrorChild->getBlock();
2133 auto *CurrentDomain = DomainMap[ErrorChildBlock];
2134 auto *Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002135 DomainMap[ErrorChildBlock] = Empty;
2136 isl_set_free(CurrentDomain);
2137 }
2138 };
2139
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002140 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002141
2142 while (!Todo.empty()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002143 auto *SubRegion = Todo.back();
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002144 Todo.pop_back();
2145
2146 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2147 for (auto &Child : *SubRegion)
2148 Todo.push_back(Child.get());
2149 continue;
2150 }
2151 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2152 removeDomains(SubRegion->getEntry());
2153 }
2154
Johannes Doerferta90943d2016-02-21 16:37:25 +00002155 for (auto *BB : R.blocks())
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002156 if (isErrorBlock(*BB, R, LI, DT))
2157 removeDomains(BB);
2158}
2159
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002160void Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
2161 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002162
Johannes Doerfert432658d2016-01-26 11:01:41 +00002163 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002164 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002165 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2166 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002167 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002168
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002169 while (LD-- >= 0) {
2170 S = addDomainDimId(S, LD + 1, L);
2171 L = L->getParentLoop();
2172 }
2173
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002174 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002175
Johannes Doerfert432658d2016-01-26 11:01:41 +00002176 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002177 return;
2178
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002179 buildDomainsWithBranchConstraints(R, SD, DT, LI);
2180 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002181
2182 // Error blocks and blocks dominated by them have been assumed to never be
2183 // executed. Representing them in the Scop does not add any value. In fact,
2184 // it is likely to cause issues during construction of the ScopStmts. The
2185 // contents of error blocks have not been verfied to be expressible and
2186 // will cause problems when building up a ScopStmt for them.
2187 // Furthermore, basic blocks dominated by error blocks may reference
2188 // instructions in the error block which, if the error block is not modeled,
2189 // can themselves not be constructed properly.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002190 removeErrorBlockDomains(SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002191}
2192
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002193void Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002194 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002195 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002196
2197 // To create the domain for each block in R we iterate over all blocks and
2198 // subregions in R and propagate the conditions under which the current region
2199 // element is executed. To this end we iterate in reverse post order over R as
2200 // it ensures that we first visit all predecessors of a region node (either a
2201 // basic block or a subregion) before we visit the region node itself.
2202 // Initially, only the domain for the SCoP region entry block is set and from
2203 // there we propagate the current domain to all successors, however we add the
2204 // condition that the successor is actually executed next.
2205 // As we are only interested in non-loop carried constraints here we can
2206 // simply skip loop back edges.
2207
2208 ReversePostOrderTraversal<Region *> RTraversal(R);
2209 for (auto *RN : RTraversal) {
2210
2211 // Recurse for affine subregions but go on for basic blocks and non-affine
2212 // subregions.
2213 if (RN->isSubRegion()) {
2214 Region *SubRegion = RN->getNodeAs<Region>();
2215 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002216 buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002217 continue;
2218 }
2219 }
2220
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002221 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002222 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002223
Johannes Doerfert96425c22015-08-30 21:13:53 +00002224 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002225 TerminatorInst *TI = BB->getTerminator();
2226
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002227 if (isa<UnreachableInst>(TI))
2228 continue;
2229
Johannes Doerfertf5673802015-10-01 23:48:18 +00002230 isl_set *Domain = DomainMap.lookup(BB);
2231 if (!Domain) {
2232 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2233 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002234 continue;
2235 }
2236
Johannes Doerfert96425c22015-08-30 21:13:53 +00002237 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002238
2239 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2240 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2241
2242 // Build the condition sets for the successor nodes of the current region
2243 // node. If it is a non-affine subregion we will always execute the single
2244 // exit node, hence the single entry node domain is the condition set. For
2245 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002246 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002247 if (RN->isSubRegion())
2248 ConditionSets.push_back(isl_set_copy(Domain));
2249 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002250 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002251
2252 // Now iterate over the successors and set their initial domain based on
2253 // their condition set. We skip back edges here and have to be careful when
2254 // we leave a loop not to keep constraints over a dimension that doesn't
2255 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002256 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002257 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002258 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002259 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002260
2261 // Skip back edges.
2262 if (DT.dominates(SuccBB, BB)) {
2263 isl_set_free(CondSet);
2264 continue;
2265 }
2266
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002267 // Do not adjust the number of dimensions if we enter a boxed loop or are
2268 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002269 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002270 while (BoxedLoops.count(SuccBBLoop))
2271 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002272
2273 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002274
2275 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2276 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2277 // and enter a new one we need to drop the old constraints.
2278 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002279 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002280 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002281 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2282 isl_set_n_dim(CondSet) - LoopDepthDiff,
2283 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002284 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002285 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002286 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002287 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002288 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002289 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002290 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2291 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002292 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002293 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002294 }
2295
2296 // Set the domain for the successor or merge it with an existing domain in
2297 // case there are multiple paths (without loop back edges) to the
2298 // successor block.
2299 isl_set *&SuccDomain = DomainMap[SuccBB];
2300 if (!SuccDomain)
2301 SuccDomain = CondSet;
2302 else
2303 SuccDomain = isl_set_union(SuccDomain, CondSet);
2304
2305 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002306 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2307 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2308 isl_set_free(SuccDomain);
2309 SuccDomain = Empty;
2310 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2311 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002312 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2313 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002314 }
2315 }
2316}
2317
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002318/// @brief Return the domain for @p BB wrt @p DomainMap.
2319///
2320/// This helper function will lookup @p BB in @p DomainMap but also handle the
2321/// case where @p BB is contained in a non-affine subregion using the region
2322/// tree obtained by @p RI.
2323static __isl_give isl_set *
2324getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2325 RegionInfo &RI) {
2326 auto DIt = DomainMap.find(BB);
2327 if (DIt != DomainMap.end())
2328 return isl_set_copy(DIt->getSecond());
2329
2330 Region *R = RI.getRegionFor(BB);
2331 while (R->getEntry() == BB)
2332 R = R->getParent();
2333 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2334}
2335
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002336void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002337 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002338 // Iterate over the region R and propagate the domain constrains from the
2339 // predecessors to the current node. In contrast to the
2340 // buildDomainsWithBranchConstraints function, this one will pull the domain
2341 // information from the predecessors instead of pushing it to the successors.
2342 // Additionally, we assume the domains to be already present in the domain
2343 // map here. However, we iterate again in reverse post order so we know all
2344 // predecessors have been visited before a block or non-affine subregion is
2345 // visited.
2346
2347 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2348 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2349
2350 ReversePostOrderTraversal<Region *> RTraversal(R);
2351 for (auto *RN : RTraversal) {
2352
2353 // Recurse for affine subregions but go on for basic blocks and non-affine
2354 // subregions.
2355 if (RN->isSubRegion()) {
2356 Region *SubRegion = RN->getNodeAs<Region>();
2357 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002358 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002359 continue;
2360 }
2361 }
2362
Johannes Doerfertf5673802015-10-01 23:48:18 +00002363 // Get the domain for the current block and check if it was initialized or
2364 // not. The only way it was not is if this block is only reachable via error
2365 // blocks, thus will not be executed under the assumptions we make. Such
2366 // blocks have to be skipped as their predecessors might not have domains
2367 // either. It would not benefit us to compute the domain anyway, only the
2368 // domains of the error blocks that are reachable from non-error blocks
2369 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002370 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002371 isl_set *&Domain = DomainMap[BB];
2372 if (!Domain) {
2373 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2374 << ", it is only reachable from error blocks.\n");
2375 DomainMap.erase(BB);
2376 continue;
2377 }
2378 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2379
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002380 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2381 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2382
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002383 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2384 for (auto *PredBB : predecessors(BB)) {
2385
2386 // Skip backedges
2387 if (DT.dominates(BB, PredBB))
2388 continue;
2389
2390 isl_set *PredBBDom = nullptr;
2391
2392 // Handle the SCoP entry block with its outside predecessors.
2393 if (!getRegion().contains(PredBB))
2394 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2395
2396 if (!PredBBDom) {
2397 // Determine the loop depth of the predecessor and adjust its domain to
2398 // the domain of the current block. This can mean we have to:
2399 // o) Drop a dimension if this block is the exit of a loop, not the
2400 // header of a new loop and the predecessor was part of the loop.
2401 // o) Add an unconstrainted new dimension if this block is the header
2402 // of a loop and the predecessor is not part of it.
2403 // o) Drop the information about the innermost loop dimension when the
2404 // predecessor and the current block are surrounded by different
2405 // loops in the same depth.
2406 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2407 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2408 while (BoxedLoops.count(PredBBLoop))
2409 PredBBLoop = PredBBLoop->getParentLoop();
2410
2411 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002412 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002413 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002414 PredBBDom = isl_set_project_out(
2415 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2416 LoopDepthDiff);
2417 else if (PredBBLoopDepth < BBLoopDepth) {
2418 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002419 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002420 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2421 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002422 PredBBDom = isl_set_drop_constraints_involving_dims(
2423 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002424 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002425 }
2426
2427 PredDom = isl_set_union(PredDom, PredBBDom);
2428 }
2429
2430 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002431 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002432
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002433 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002434 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002435
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002436 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002437 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002438 IsOptimized = true;
2439 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002440 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2441 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002442 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002443 }
2444}
2445
2446/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2447/// is incremented by one and all other dimensions are equal, e.g.,
2448/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2449/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2450static __isl_give isl_map *
2451createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2452 auto *MapSpace = isl_space_map_from_set(SetSpace);
2453 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2454 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2455 if (u != Dim)
2456 NextIterationMap =
2457 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2458 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2459 C = isl_constraint_set_constant_si(C, 1);
2460 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2461 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2462 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2463 return NextIterationMap;
2464}
2465
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002466void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002467 int LoopDepth = getRelativeLoopDepth(L);
2468 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002469
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002470 BasicBlock *HeaderBB = L->getHeader();
2471 assert(DomainMap.count(HeaderBB));
2472 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002473
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002474 isl_map *NextIterationMap =
2475 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002476
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002477 isl_set *UnionBackedgeCondition =
2478 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002479
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002480 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2481 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002482
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002483 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002484
2485 // If the latch is only reachable via error statements we skip it.
2486 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2487 if (!LatchBBDom)
2488 continue;
2489
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002490 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002491
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002492 TerminatorInst *TI = LatchBB->getTerminator();
2493 BranchInst *BI = dyn_cast<BranchInst>(TI);
2494 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002495 BackedgeCondition = isl_set_copy(LatchBBDom);
2496 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002497 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002498 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002499 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002500
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002501 // Free the non back edge condition set as we do not need it.
2502 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002503
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002504 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002505 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002506
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002507 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2508 assert(LatchLoopDepth >= LoopDepth);
2509 BackedgeCondition =
2510 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2511 LatchLoopDepth - LoopDepth);
2512 UnionBackedgeCondition =
2513 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002514 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002515
2516 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2517 for (int i = 0; i < LoopDepth; i++)
2518 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2519
2520 isl_set *UnionBackedgeConditionComplement =
2521 isl_set_complement(UnionBackedgeCondition);
2522 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2523 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2524 UnionBackedgeConditionComplement =
2525 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2526 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2527 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2528
2529 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2530 HeaderBBDom = Parts.second;
2531
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002532 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2533 // the bounded assumptions to the context as they are already implied by the
2534 // <nsw> tag.
2535 if (Affinator.hasNSWAddRecForLoop(L)) {
2536 isl_set_free(Parts.first);
2537 return;
2538 }
2539
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002540 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2541 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002542 addAssumption(INFINITELOOP, BoundedCtx,
2543 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002544}
2545
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002546void Scop::buildAliasChecks(AliasAnalysis &AA) {
2547 if (!PollyUseRuntimeAliasChecks)
2548 return;
2549
2550 if (buildAliasGroups(AA))
2551 return;
2552
2553 // If a problem occurs while building the alias groups we need to delete
2554 // this SCoP and pretend it wasn't valid in the first place. To this end
2555 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002556 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002557
2558 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2559 << " could not be created as the number of parameters involved "
2560 "is too high. The SCoP will be "
2561 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2562 "the maximal number of parameters but be advised that the "
2563 "compile time might increase exponentially.\n\n");
2564}
2565
Johannes Doerfert9143d672014-09-27 11:02:39 +00002566bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002567 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002568 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002569 // for all memory accesses inside the SCoP.
2570 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002571 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002572 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002573 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002574 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002575 // if their access domains intersect, otherwise they are in different
2576 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002577 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002578 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002579 // and maximal accesses to each array of a group in read only and non
2580 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002581 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2582
2583 AliasSetTracker AST(AA);
2584
2585 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002586 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002587 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002588
2589 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002590 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002591 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2592 isl_set_free(StmtDomain);
2593 if (StmtDomainEmpty)
2594 continue;
2595
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002596 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002597 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002598 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002599 if (!MA->isRead())
2600 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002601 MemAccInst Acc(MA->getAccessInstruction());
Johannes Doerfertcea61932016-02-21 19:13:19 +00002602 if (MA->isRead() && Acc.isMemTransferInst())
2603 PtrToAcc[Acc.asMemTransferInst()->getSource()] = MA;
2604 else
2605 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002606 AST.add(Acc);
2607 }
2608 }
2609
2610 SmallVector<AliasGroupTy, 4> AliasGroups;
2611 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002612 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002613 continue;
2614 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002615 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002616 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002617 if (AG.size() < 2)
2618 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002619 AliasGroups.push_back(std::move(AG));
2620 }
2621
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002622 // Split the alias groups based on their domain.
2623 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2624 AliasGroupTy NewAG;
2625 AliasGroupTy &AG = AliasGroups[u];
2626 AliasGroupTy::iterator AGI = AG.begin();
2627 isl_set *AGDomain = getAccessDomain(*AGI);
2628 while (AGI != AG.end()) {
2629 MemoryAccess *MA = *AGI;
2630 isl_set *MADomain = getAccessDomain(MA);
2631 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2632 NewAG.push_back(MA);
2633 AGI = AG.erase(AGI);
2634 isl_set_free(MADomain);
2635 } else {
2636 AGDomain = isl_set_union(AGDomain, MADomain);
2637 AGI++;
2638 }
2639 }
2640 if (NewAG.size() > 1)
2641 AliasGroups.push_back(std::move(NewAG));
2642 isl_set_free(AGDomain);
2643 }
2644
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002645 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002646 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002647 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2648 for (AliasGroupTy &AG : AliasGroups) {
2649 NonReadOnlyBaseValues.clear();
2650 ReadOnlyPairs.clear();
2651
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002652 if (AG.size() < 2) {
2653 AG.clear();
2654 continue;
2655 }
2656
Johannes Doerfert13771732014-10-01 12:40:46 +00002657 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002658 emitOptimizationRemarkAnalysis(
2659 F.getContext(), DEBUG_TYPE, F,
2660 (*II)->getAccessInstruction()->getDebugLoc(),
2661 "Possibly aliasing pointer, use restrict keyword.");
2662
Johannes Doerfert13771732014-10-01 12:40:46 +00002663 Value *BaseAddr = (*II)->getBaseAddr();
2664 if (HasWriteAccess.count(BaseAddr)) {
2665 NonReadOnlyBaseValues.insert(BaseAddr);
2666 II++;
2667 } else {
2668 ReadOnlyPairs[BaseAddr].insert(*II);
2669 II = AG.erase(II);
2670 }
2671 }
2672
2673 // If we don't have read only pointers check if there are at least two
2674 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002675 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002676 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002677 continue;
2678 }
2679
2680 // If we don't have non read only pointers clear the alias group.
2681 if (NonReadOnlyBaseValues.empty()) {
2682 AG.clear();
2683 continue;
2684 }
2685
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002686 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002687 MinMaxAliasGroups.emplace_back();
2688 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2689 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2690 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2691 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002692
2693 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002694
2695 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002696 for (MemoryAccess *MA : AG)
2697 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002698
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002699 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2700 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002701
2702 // Bail out if the number of values we need to compare is too large.
2703 // This is important as the number of comparisions grows quadratically with
2704 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002705 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2706 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002707 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002708
2709 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002710 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002711 Accesses = isl_union_map_empty(getParamSpace());
2712
2713 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2714 for (MemoryAccess *MA : ReadOnlyPair.second)
2715 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2716
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002717 Valid =
2718 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002719
2720 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002721 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002722 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002723
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002724 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002725}
2726
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002727/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002728static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002729 // Start with the smallest loop containing the entry and expand that
2730 // loop until it contains all blocks in the region. If there is a loop
2731 // containing all blocks in the region check if it is itself contained
2732 // and if so take the parent loop as it will be the smallest containing
2733 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002734 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002735 while (L) {
2736 bool AllContained = true;
2737 for (auto *BB : R.blocks())
2738 AllContained &= L->contains(BB);
2739 if (AllContained)
2740 break;
2741 L = L->getParentLoop();
2742 }
2743
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002744 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2745}
2746
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002747static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2748 ScopDetection &SD) {
2749
2750 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2751
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002752 unsigned MinLD = INT_MAX, MaxLD = 0;
2753 for (BasicBlock *BB : R.blocks()) {
2754 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002755 if (!R.contains(L))
2756 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002757 if (BoxedLoops && BoxedLoops->count(L))
2758 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002759 unsigned LD = L->getLoopDepth();
2760 MinLD = std::min(MinLD, LD);
2761 MaxLD = std::max(MaxLD, LD);
2762 }
2763 }
2764
2765 // Handle the case that there is no loop in the SCoP first.
2766 if (MaxLD == 0)
2767 return 1;
2768
2769 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2770 assert(MaxLD >= MinLD &&
2771 "Maximal loop depth was smaller than mininaml loop depth?");
2772 return MaxLD - MinLD + 1;
2773}
2774
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002775Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002776 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002777 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002778 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
2779 Context(nullptr), Affinator(this), AssumedContext(nullptr),
2780 BoundaryContext(nullptr), Schedule(nullptr) {
2781 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00002782 buildContext();
2783}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002784
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002785void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002786 DominatorTree &DT, LoopInfo &LI) {
2787 addUserAssumptions(AC, DT, LI);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002788 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002789
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002790 buildDomains(&R, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002791
Michael Krusecac948e2015-10-02 13:53:07 +00002792 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002793 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002794 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00002795 if (Stmts.empty())
2796 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002797
Michael Krusecac948e2015-10-02 13:53:07 +00002798 // The ScopStmts now have enough information to initialize themselves.
2799 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002800 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00002801
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002802 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002803
Tobias Grosser8286b832015-11-02 11:29:32 +00002804 if (isl_set_is_empty(AssumedContext))
2805 return;
2806
2807 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002808 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002809 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002810 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002811 buildBoundaryContext();
2812 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002813 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002814
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002815 hoistInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002816 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002817}
2818
2819Scop::~Scop() {
2820 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002821 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002822 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002823 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002824
Johannes Doerfert96425c22015-08-30 21:13:53 +00002825 for (auto It : DomainMap)
2826 isl_set_free(It.second);
2827
Johannes Doerfertb164c792014-09-18 11:17:17 +00002828 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002829 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002830 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002831 isl_pw_multi_aff_free(MMA.first);
2832 isl_pw_multi_aff_free(MMA.second);
2833 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002834 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002835 isl_pw_multi_aff_free(MMA.first);
2836 isl_pw_multi_aff_free(MMA.second);
2837 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002838 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002839
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002840 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002841 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002842
2843 // Explicitly release all Scop objects and the underlying isl objects before
2844 // we relase the isl context.
2845 Stmts.clear();
2846 ScopArrayInfoMap.clear();
2847 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00002848}
2849
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002850void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00002851 // Check all array accesses for each base pointer and find a (virtual) element
2852 // size for the base pointer that divides all access functions.
2853 for (auto &Stmt : *this)
2854 for (auto *Access : Stmt) {
2855 if (!Access->isArrayKind())
2856 continue;
2857 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
2858 ScopArrayInfo::MK_Array)];
2859 if (SAI->getNumberOfDimensions() != 1)
2860 continue;
2861 unsigned DivisibleSize = SAI->getElemSizeInBytes();
2862 auto *Subscript = Access->getSubscript(0);
2863 while (!isDivisible(Subscript, DivisibleSize, *SE))
2864 DivisibleSize /= 2;
2865 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
2866 SAI->updateElementType(Ty);
2867 }
2868
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002869 for (auto &Stmt : *this)
2870 for (auto &Access : Stmt)
2871 Access->updateDimensionality();
2872}
2873
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002874void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
2875 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002876 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2877 ScopStmt &Stmt = *StmtIt;
Michael Krusecac948e2015-10-02 13:53:07 +00002878 RegionNode *RN = Stmt.isRegionStmt()
2879 ? Stmt.getRegion()->getNode()
2880 : getRegion().getBBNode(Stmt.getBasicBlock());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002881
Johannes Doerferteca9e892015-11-03 16:54:49 +00002882 bool RemoveStmt = StmtIt->isEmpty();
2883 if (!RemoveStmt)
Michael Kruse375cb5f2016-02-24 22:08:24 +00002884 RemoveStmt = isl_set_is_empty(DomainMap[Stmt.getEntryBlock()]);
Johannes Doerferteca9e892015-11-03 16:54:49 +00002885 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002886 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002887
Johannes Doerferteca9e892015-11-03 16:54:49 +00002888 // Remove read only statements only after invariant loop hoisting.
2889 if (!RemoveStmt && !RemoveIgnoredStmts) {
2890 bool OnlyRead = true;
2891 for (MemoryAccess *MA : Stmt) {
2892 if (MA->isRead())
2893 continue;
2894
2895 OnlyRead = false;
2896 break;
2897 }
2898
2899 RemoveStmt = OnlyRead;
2900 }
2901
2902 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002903 // Remove the statement because it is unnecessary.
2904 if (Stmt.isRegionStmt())
2905 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2906 StmtMap.erase(BB);
2907 else
2908 StmtMap.erase(Stmt.getBasicBlock());
2909
2910 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002911 continue;
2912 }
2913
Michael Krusecac948e2015-10-02 13:53:07 +00002914 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002915 }
2916}
2917
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002918const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2919 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2920 if (!LInst)
2921 return nullptr;
2922
2923 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2924 LInst = cast<LoadInst>(Rep);
2925
Johannes Doerfert96e54712016-02-07 17:30:13 +00002926 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002927 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2928 for (auto &IAClass : InvariantEquivClasses)
Johannes Doerfert96e54712016-02-07 17:30:13 +00002929 if (PointerSCEV == std::get<0>(IAClass) && Ty == std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002930 return &IAClass;
2931
2932 return nullptr;
2933}
2934
2935void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2936
2937 // Get the context under which the statement is executed.
2938 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2939 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2940 DomainCtx = isl_set_detect_equalities(DomainCtx);
2941 DomainCtx = isl_set_coalesce(DomainCtx);
2942
2943 // Project out all parameters that relate to loads in the statement. Otherwise
2944 // we could have cyclic dependences on the constraints under which the
2945 // hoisted loads are executed and we could not determine an order in which to
2946 // pre-load them. This happens because not only lower bounds are part of the
2947 // domain but also upper bounds.
2948 for (MemoryAccess *MA : InvMAs) {
2949 Instruction *AccInst = MA->getAccessInstruction();
2950 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002951 SetVector<Value *> Values;
2952 for (const SCEV *Parameter : Parameters) {
2953 Values.clear();
2954 findValues(Parameter, Values);
2955 if (!Values.count(AccInst))
2956 continue;
2957
2958 if (isl_id *ParamId = getIdForParam(Parameter)) {
2959 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2960 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2961 isl_id_free(ParamId);
2962 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002963 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002964 }
2965 }
2966
2967 for (MemoryAccess *MA : InvMAs) {
2968 // Check for another invariant access that accesses the same location as
2969 // MA and if found consolidate them. Otherwise create a new equivalence
2970 // class at the end of InvariantEquivClasses.
2971 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00002972 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002973 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2974
2975 bool Consolidated = false;
2976 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00002977 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002978 continue;
2979
2980 Consolidated = true;
2981
2982 // Add MA to the list of accesses that are in this class.
2983 auto &MAs = std::get<1>(IAClass);
2984 MAs.push_front(MA);
2985
2986 // Unify the execution context of the class and this statement.
2987 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00002988 if (IAClassDomainCtx)
2989 IAClassDomainCtx = isl_set_coalesce(
2990 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
2991 else
2992 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002993 break;
2994 }
2995
2996 if (Consolidated)
2997 continue;
2998
2999 // If we did not consolidate MA, thus did not find an equivalence class
3000 // for it, we create a new one.
3001 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00003002 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003003 }
3004
3005 isl_set_free(DomainCtx);
3006}
3007
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003008bool Scop::isHoistableAccess(MemoryAccess *Access,
3009 __isl_keep isl_union_map *Writes) {
3010 // TODO: Loads that are not loop carried, hence are in a statement with
3011 // zero iterators, are by construction invariant, though we
3012 // currently "hoist" them anyway. This is necessary because we allow
3013 // them to be treated as parameters (e.g., in conditions) and our code
3014 // generation would otherwise use the old value.
3015
3016 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003017 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003018
3019 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3020 return false;
3021
3022 // Skip accesses that have an invariant base pointer which is defined but
3023 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3024 // returns a pointer that is used as a base address. However, as we want
3025 // to hoist indirect pointers, we allow the base pointer to be defined in
3026 // the region if it is also a memory access. Each ScopArrayInfo object
3027 // that has a base pointer origin has a base pointer that is loaded and
3028 // that it is invariant, thus it will be hoisted too. However, if there is
3029 // no base pointer origin we check that the base pointer is defined
3030 // outside the region.
3031 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003032 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3033 if (SAI->getBasePtrOriginSAI()) {
3034 assert(BasePtrInst && R.contains(BasePtrInst));
3035 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003036 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003037 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003038 assert(BasePtrStmt);
3039 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3040 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3041 return false;
3042 } else if (BasePtrInst && R.contains(BasePtrInst))
3043 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003044
3045 // Skip accesses in non-affine subregions as they might not be executed
3046 // under the same condition as the entry of the non-affine subregion.
3047 if (BB != Access->getAccessInstruction()->getParent())
3048 return false;
3049
3050 isl_map *AccessRelation = Access->getAccessRelation();
3051
3052 // Skip accesses that have an empty access relation. These can be caused
3053 // by multiple offsets with a type cast in-between that cause the overall
3054 // byte offset to be not divisible by the new types sizes.
3055 if (isl_map_is_empty(AccessRelation)) {
3056 isl_map_free(AccessRelation);
3057 return false;
3058 }
3059
3060 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3061 Stmt.getNumIterators())) {
3062 isl_map_free(AccessRelation);
3063 return false;
3064 }
3065
3066 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3067 isl_set *AccessRange = isl_map_range(AccessRelation);
3068
3069 isl_union_map *Written = isl_union_map_intersect_range(
3070 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3071 bool IsWritten = !isl_union_map_is_empty(Written);
3072 isl_union_map_free(Written);
3073
3074 if (IsWritten)
3075 return false;
3076
3077 return true;
3078}
3079
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003080void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003081 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3082 for (LoadInst *LI : RIL) {
3083 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003084 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003085 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003086 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3087 return;
3088 }
3089 }
3090}
3091
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003092void Scop::hoistInvariantLoads(ScopDetection &SD) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003093 isl_union_map *Writes = getWrites();
3094 for (ScopStmt &Stmt : *this) {
3095
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003096 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003097
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003098 for (MemoryAccess *Access : Stmt)
3099 if (isHoistableAccess(Access, Writes))
3100 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003101
3102 // We inserted invariant accesses always in the front but need them to be
3103 // sorted in a "natural order". The statements are already sorted in reverse
3104 // post order and that suffices for the accesses too. The reason we require
3105 // an order in the first place is the dependences between invariant loads
3106 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003107 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003108
3109 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003110 Stmt.removeMemoryAccesses(InvariantAccesses);
3111 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003112 }
3113 isl_union_map_free(Writes);
3114
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003115 verifyInvariantLoads(SD);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003116}
3117
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003118const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003119Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003120 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003121 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003122 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003123 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003124 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003125 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003126 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003127 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003128 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003129 // In case of mismatching array sizes, we bail out by setting the run-time
3130 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003131 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003132 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003133 }
Tobias Grosserab671442015-05-23 05:58:27 +00003134 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003135}
3136
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003137const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003138 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003139 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003140 assert(SAI && "No ScopArrayInfo available for this base pointer");
3141 return SAI;
3142}
3143
Tobias Grosser74394f02013-01-14 22:40:23 +00003144std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003145
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003146std::string Scop::getAssumedContextStr() const {
3147 return stringFromIslObj(AssumedContext);
3148}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003149
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003150std::string Scop::getBoundaryContextStr() const {
3151 return stringFromIslObj(BoundaryContext);
3152}
Tobias Grosser75805372011-04-29 06:27:02 +00003153
3154std::string Scop::getNameStr() const {
3155 std::string ExitName, EntryName;
3156 raw_string_ostream ExitStr(ExitName);
3157 raw_string_ostream EntryStr(EntryName);
3158
Tobias Grosserf240b482014-01-09 10:42:15 +00003159 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003160 EntryStr.str();
3161
3162 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003163 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003164 ExitStr.str();
3165 } else
3166 ExitName = "FunctionExit";
3167
3168 return EntryName + "---" + ExitName;
3169}
3170
Tobias Grosser74394f02013-01-14 22:40:23 +00003171__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003172__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003173 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003174}
3175
Tobias Grossere86109f2013-10-29 21:05:49 +00003176__isl_give isl_set *Scop::getAssumedContext() const {
3177 return isl_set_copy(AssumedContext);
3178}
3179
Johannes Doerfert43788c52015-08-20 05:58:56 +00003180__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3181 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003182 RuntimeCheckContext =
3183 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3184 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003185 return RuntimeCheckContext;
3186}
3187
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003188bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003189 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003190 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003191 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3192 isl_set_free(RuntimeCheckContext);
3193 return IsFeasible;
3194}
3195
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003196static std::string toString(AssumptionKind Kind) {
3197 switch (Kind) {
3198 case ALIASING:
3199 return "No-aliasing";
3200 case INBOUNDS:
3201 return "Inbounds";
3202 case WRAPPING:
3203 return "No-overflows";
3204 case ERRORBLOCK:
3205 return "No-error";
3206 case INFINITELOOP:
3207 return "Finite loop";
3208 case INVARIANTLOAD:
3209 return "Invariant load";
3210 case DELINEARIZATION:
3211 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003212 case ERROR_DOMAINCONJUNCTS:
3213 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003214 }
3215 llvm_unreachable("Unknown AssumptionKind!");
3216}
3217
3218void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3219 DebugLoc Loc) {
3220 if (isl_set_is_subset(Context, Set))
3221 return;
3222
3223 if (isl_set_is_subset(AssumedContext, Set))
3224 return;
3225
3226 auto &F = *getRegion().getEntry()->getParent();
3227 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3228 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3229}
3230
3231void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3232 DebugLoc Loc) {
3233 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003234 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003235
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003236 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003237 if (NSets >= MaxDisjunctsAssumed) {
3238 isl_space *Space = isl_set_get_space(AssumedContext);
3239 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003240 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003241 }
3242
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003243 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003244}
3245
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003246void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3247 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3248}
3249
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003250__isl_give isl_set *Scop::getBoundaryContext() const {
3251 return isl_set_copy(BoundaryContext);
3252}
3253
Tobias Grosser75805372011-04-29 06:27:02 +00003254void Scop::printContext(raw_ostream &OS) const {
3255 OS << "Context:\n";
3256
3257 if (!Context) {
3258 OS.indent(4) << "n/a\n\n";
3259 return;
3260 }
3261
3262 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003263
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003264 OS.indent(4) << "Assumed Context:\n";
3265 if (!AssumedContext) {
3266 OS.indent(4) << "n/a\n\n";
3267 return;
3268 }
3269
3270 OS.indent(4) << getAssumedContextStr() << "\n";
3271
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003272 OS.indent(4) << "Boundary Context:\n";
3273 if (!BoundaryContext) {
3274 OS.indent(4) << "n/a\n\n";
3275 return;
3276 }
3277
3278 OS.indent(4) << getBoundaryContextStr() << "\n";
3279
Tobias Grosser083d3d32014-06-28 08:59:45 +00003280 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003281 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003282 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3283 }
Tobias Grosser75805372011-04-29 06:27:02 +00003284}
3285
Johannes Doerfertb164c792014-09-18 11:17:17 +00003286void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003287 int noOfGroups = 0;
3288 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003289 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003290 noOfGroups += 1;
3291 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003292 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003293 }
3294
Tobias Grosserbb853c22015-07-25 12:31:03 +00003295 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003296 if (MinMaxAliasGroups.empty()) {
3297 OS.indent(8) << "n/a\n";
3298 return;
3299 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003300
Tobias Grosserbb853c22015-07-25 12:31:03 +00003301 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003302
3303 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003304 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003305 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003306 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003307 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3308 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003309 }
3310 OS << " ]]\n";
3311 }
3312
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003313 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003314 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003315 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003316 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003317 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3318 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003319 }
3320 OS << " ]]\n";
3321 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003322 }
3323}
3324
Tobias Grosser75805372011-04-29 06:27:02 +00003325void Scop::printStatements(raw_ostream &OS) const {
3326 OS << "Statements {\n";
3327
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003328 for (const ScopStmt &Stmt : *this)
3329 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003330
3331 OS.indent(4) << "}\n";
3332}
3333
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003334void Scop::printArrayInfo(raw_ostream &OS) const {
3335 OS << "Arrays {\n";
3336
Tobias Grosserab671442015-05-23 05:58:27 +00003337 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003338 Array.second->print(OS);
3339
3340 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003341
3342 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3343
3344 for (auto &Array : arrays())
3345 Array.second->print(OS, /* SizeAsPwAff */ true);
3346
3347 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003348}
3349
Tobias Grosser75805372011-04-29 06:27:02 +00003350void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003351 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3352 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003353 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003354 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003355 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003356 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003357 const auto &MAs = std::get<1>(IAClass);
3358 if (MAs.empty()) {
3359 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003360 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003361 MAs.front()->print(OS);
3362 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003363 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003364 }
3365 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003366 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003367 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003368 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003369 printStatements(OS.indent(4));
3370}
3371
3372void Scop::dump() const { print(dbgs()); }
3373
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003374isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003375
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003376__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3377 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003378}
3379
Tobias Grosser808cd692015-07-14 09:33:13 +00003380__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003381 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003382
Tobias Grosser808cd692015-07-14 09:33:13 +00003383 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003384 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003385
3386 return Domain;
3387}
3388
Tobias Grossere5a35142015-11-12 14:07:09 +00003389__isl_give isl_union_map *
3390Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3391 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003392
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003393 for (ScopStmt &Stmt : *this) {
3394 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003395 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003396 continue;
3397
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003398 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003399 isl_map *AccessDomain = MA->getAccessRelation();
3400 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003401 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003402 }
3403 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003404 return isl_union_map_coalesce(Accesses);
3405}
3406
3407__isl_give isl_union_map *Scop::getMustWrites() {
3408 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003409}
3410
3411__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003412 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003413}
3414
Tobias Grosser37eb4222014-02-20 21:43:54 +00003415__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003416 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003417}
3418
3419__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003420 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003421}
3422
Tobias Grosser2ac23382015-11-12 14:07:13 +00003423__isl_give isl_union_map *Scop::getAccesses() {
3424 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3425}
3426
Tobias Grosser808cd692015-07-14 09:33:13 +00003427__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003428 auto *Tree = getScheduleTree();
3429 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003430 isl_schedule_free(Tree);
3431 return S;
3432}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003433
Tobias Grosser808cd692015-07-14 09:33:13 +00003434__isl_give isl_schedule *Scop::getScheduleTree() const {
3435 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3436 getDomains());
3437}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003438
Tobias Grosser808cd692015-07-14 09:33:13 +00003439void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3440 auto *S = isl_schedule_from_domain(getDomains());
3441 S = isl_schedule_insert_partial_schedule(
3442 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3443 isl_schedule_free(Schedule);
3444 Schedule = S;
3445}
3446
3447void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3448 isl_schedule_free(Schedule);
3449 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003450}
3451
3452bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3453 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003454 for (ScopStmt &Stmt : *this) {
3455 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003456 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3457 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3458
3459 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3460 isl_union_set_free(StmtDomain);
3461 isl_union_set_free(NewStmtDomain);
3462 continue;
3463 }
3464
3465 Changed = true;
3466
3467 isl_union_set_free(StmtDomain);
3468 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3469
3470 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003471 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003472 isl_union_set_free(NewStmtDomain);
3473 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003474 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003475 }
3476 isl_union_set_free(Domain);
3477 return Changed;
3478}
3479
Tobias Grosser75805372011-04-29 06:27:02 +00003480ScalarEvolution *Scop::getSE() const { return SE; }
3481
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003482bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003483 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse6f7721f2016-02-24 22:08:19 +00003484 ScopStmt *Stmt = getStmtFor(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003485
3486 // If there is no stmt, then it already has been removed.
3487 if (!Stmt)
3488 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003489
Johannes Doerfertf5673802015-10-01 23:48:18 +00003490 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003491 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003492 return true;
3493
3494 // Check for reachability via non-error blocks.
3495 if (!DomainMap.count(BB))
3496 return true;
3497
3498 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003499 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003500 return true;
3501
3502 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003503}
3504
Tobias Grosser808cd692015-07-14 09:33:13 +00003505struct MapToDimensionDataTy {
3506 int N;
3507 isl_union_pw_multi_aff *Res;
3508};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003509
Tobias Grosser808cd692015-07-14 09:33:13 +00003510// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003511// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003512//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003513// @param Set The input set.
3514// @param User->N The dimension to map to.
3515// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003516//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003517// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003518static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3519 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3520 int Dim;
3521 isl_space *Space;
3522 isl_pw_multi_aff *PMA;
3523
3524 Dim = isl_set_dim(Set, isl_dim_set);
3525 Space = isl_set_get_space(Set);
3526 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3527 Dim - Data->N);
3528 if (Data->N > 1)
3529 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3530 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3531
3532 isl_set_free(Set);
3533
3534 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003535}
3536
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003537// @brief Create an isl_multi_union_aff that defines an identity mapping
3538// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003539//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003540// # Example:
3541//
3542// Domain: { A[i,j]; B[i,j,k] }
3543// N: 1
3544//
3545// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3546//
3547// @param USet A union set describing the elements for which to generate a
3548// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003549// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003550// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003551static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003552mapToDimension(__isl_take isl_union_set *USet, int N) {
3553 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003554 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003555 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003556
Tobias Grosser808cd692015-07-14 09:33:13 +00003557 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003558
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003559 auto *Space = isl_union_set_get_space(USet);
3560 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003561
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003562 Data = {N, PwAff};
3563
3564 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003565 (void)Res;
3566
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003567 assert(Res == isl_stat_ok);
3568
3569 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003570 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3571}
3572
Tobias Grosser316b5b22015-11-11 19:28:14 +00003573void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003574 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003575 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003576 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003577 StmtMap[BB] = Stmt;
3578 } else {
3579 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003580 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003581 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003582 for (BasicBlock *BB : R->blocks())
3583 StmtMap[BB] = Stmt;
3584 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003585}
3586
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003587void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003588 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003589 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003590 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003591 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3592 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003593}
3594
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003595/// To generate a schedule for the elements in a Region we traverse the Region
3596/// in reverse-post-order and add the contained RegionNodes in traversal order
3597/// to the schedule of the loop that is currently at the top of the LoopStack.
3598/// For loop-free codes, this results in a correct sequential ordering.
3599///
3600/// Example:
3601/// bb1(0)
3602/// / \.
3603/// bb2(1) bb3(2)
3604/// \ / \.
3605/// bb4(3) bb5(4)
3606/// \ /
3607/// bb6(5)
3608///
3609/// Including loops requires additional processing. Whenever a loop header is
3610/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3611/// from an empty schedule, we first process all RegionNodes that are within
3612/// this loop and complete the sequential schedule at this loop-level before
3613/// processing about any other nodes. To implement this
3614/// loop-nodes-first-processing, the reverse post-order traversal is
3615/// insufficient. Hence, we additionally check if the traversal yields
3616/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3617/// These region-nodes are then queue and only traverse after the all nodes
3618/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003619void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3620 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003621 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3622
3623 ReversePostOrderTraversal<Region *> RTraversal(R);
3624 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3625 std::deque<RegionNode *> DelayList;
3626 bool LastRNWaiting = false;
3627
3628 // Iterate over the region @p R in reverse post-order but queue
3629 // sub-regions/blocks iff they are not part of the last encountered but not
3630 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3631 // that we queued the last sub-region/block from the reverse post-order
3632 // iterator. If it is set we have to explore the next sub-region/block from
3633 // the iterator (if any) to guarantee progress. If it is not set we first try
3634 // the next queued sub-region/blocks.
3635 while (!WorkList.empty() || !DelayList.empty()) {
3636 RegionNode *RN;
3637
3638 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3639 RN = WorkList.front();
3640 WorkList.pop_front();
3641 LastRNWaiting = false;
3642 } else {
3643 RN = DelayList.front();
3644 DelayList.pop_front();
3645 }
3646
3647 Loop *L = getRegionNodeLoop(RN, LI);
3648 if (!getRegion().contains(L))
3649 L = OuterScopLoop;
3650
3651 Loop *LastLoop = LoopStack.back().L;
3652 if (LastLoop != L) {
3653 if (!LastLoop->contains(L)) {
3654 LastRNWaiting = true;
3655 DelayList.push_back(RN);
3656 continue;
3657 }
3658 LoopStack.push_back({L, nullptr, 0});
3659 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003660 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003661 }
3662
3663 return;
3664}
3665
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003666void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003667 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00003668
Tobias Grosser8362c262016-01-06 15:30:06 +00003669 if (RN->isSubRegion()) {
3670 auto *LocalRegion = RN->getNodeAs<Region>();
3671 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003672 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00003673 return;
3674 }
3675 }
Michael Kruse046dde42015-08-10 13:01:57 +00003676
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003677 auto &LoopData = LoopStack.back();
3678 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003679
Michael Kruse6f7721f2016-02-24 22:08:19 +00003680 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003681 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3682 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003683 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003684 }
3685
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003686 // Check if we just processed the last node in this loop. If we did, finalize
3687 // the loop by:
3688 //
3689 // - adding new schedule dimensions
3690 // - folding the resulting schedule into the parent loop schedule
3691 // - dropping the loop schedule from the LoopStack.
3692 //
3693 // Then continue to check surrounding loops, which might also have been
3694 // completed by this node.
3695 while (LoopData.L &&
3696 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003697 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003698 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003699
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003700 LoopStack.pop_back();
3701 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003702
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003703 if (Schedule) {
3704 auto *Domain = isl_schedule_get_domain(Schedule);
3705 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3706 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3707 NextLoopData.Schedule =
3708 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003709 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003710
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003711 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3712 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003713 }
Tobias Grosser75805372011-04-29 06:27:02 +00003714}
3715
Michael Kruse6f7721f2016-02-24 22:08:19 +00003716ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003717 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003718 if (StmtMapIt == StmtMap.end())
3719 return nullptr;
3720 return StmtMapIt->second;
3721}
3722
Michael Kruse6f7721f2016-02-24 22:08:19 +00003723ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
3724 if (RN->isSubRegion())
3725 return getStmtFor(RN->getNodeAs<Region>());
3726 return getStmtFor(RN->getNodeAs<BasicBlock>());
3727}
3728
3729ScopStmt *Scop::getStmtFor(Region *R) const {
3730 ScopStmt *Stmt = getStmtFor(R->getEntry());
3731 assert(!Stmt || Stmt->getRegion() == R);
3732 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00003733}
3734
Johannes Doerfert96425c22015-08-30 21:13:53 +00003735int Scop::getRelativeLoopDepth(const Loop *L) const {
3736 Loop *OuterLoop =
3737 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3738 if (!OuterLoop)
3739 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003740 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3741}
3742
Michael Krused868b5d2015-09-10 15:25:24 +00003743void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003744 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003745
3746 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3747 // true, are not modeled as ordinary PHI nodes as they are not part of the
3748 // region. However, we model the operands in the predecessor blocks that are
3749 // part of the region as regular scalar accesses.
3750
3751 // If we can synthesize a PHI we can skip it, however only if it is in
3752 // the region. If it is not it can only be in the exit block of the region.
3753 // In this case we model the operands but not the PHI itself.
3754 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3755 return;
3756
3757 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3758 // detection. Hence, the PHI is a load of a new memory location in which the
3759 // incoming value was written at the end of the incoming basic block.
3760 bool OnlyNonAffineSubRegionOperands = true;
3761 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3762 Value *Op = PHI->getIncomingValue(u);
3763 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3764
3765 // Do not build scalar dependences inside a non-affine subregion.
3766 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3767 continue;
3768
3769 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003770 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003771 }
3772
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003773 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3774 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003775 }
3776}
3777
Michael Kruse2e02d562016-02-06 09:19:40 +00003778void ScopInfo::buildScalarDependences(Instruction *Inst) {
3779 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00003780
Michael Kruse2e02d562016-02-06 09:19:40 +00003781 // Pull-in required operands.
3782 for (Use &Op : Inst->operands())
3783 ensureValueRead(Op.get(), Inst->getParent());
3784}
Michael Kruse7bf39442015-09-10 12:46:52 +00003785
Michael Kruse2e02d562016-02-06 09:19:40 +00003786void ScopInfo::buildEscapingDependences(Instruction *Inst) {
3787 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00003788
Michael Kruse2e02d562016-02-06 09:19:40 +00003789 // Check for uses of this instruction outside the scop. Because we do not
3790 // iterate over such instructions and therefore did not "ensure" the existence
3791 // of a write, we must determine such use here.
3792 for (Use &U : Inst->uses()) {
3793 Instruction *UI = dyn_cast<Instruction>(U.getUser());
3794 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00003795 continue;
3796
Michael Kruse2e02d562016-02-06 09:19:40 +00003797 BasicBlock *UseParent = getUseBlock(U);
3798 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00003799
Michael Kruse2e02d562016-02-06 09:19:40 +00003800 // An escaping value is either used by an instruction not within the scop,
3801 // or (when the scop region's exit needs to be simplified) by a PHI in the
3802 // scop's exit block. This is because region simplification before code
3803 // generation inserts new basic blocks before the PHI such that its incoming
3804 // blocks are not in the scop anymore.
3805 if (!R->contains(UseParent) ||
3806 (isa<PHINode>(UI) && UserParent == R->getExit() &&
3807 R->getExitingBlock())) {
3808 // At least one escaping use found.
3809 ensureValueWrite(Inst);
3810 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00003811 }
3812 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003813}
3814
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003815bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00003816 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003817 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3818 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00003819 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003820 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003821 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003822 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003823 const SCEVUnknown *BasePointer =
3824 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003825 enum MemoryAccess::AccessType Type =
3826 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003827
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003828 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003829 auto *NewAddress = Address;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003830 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003831 auto *Src = BitCast->getOperand(0);
3832 auto *SrcTy = Src->getType();
3833 auto *DstTy = BitCast->getType();
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003834 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3835 NewAddress = Src;
3836 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003837
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003838 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3839 std::vector<const SCEV *> Subscripts;
3840 std::vector<int> Sizes;
3841 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003842 auto *BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003843
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003844 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003845
Johannes Doerferta90943d2016-02-21 16:37:25 +00003846 for (auto *Subscript : Subscripts) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00003847 InvariantLoadsSetTy AccessILS;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003848 if (!isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS))
3849 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003850
3851 for (LoadInst *LInst : AccessILS)
3852 if (!ScopRIL.count(LInst))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003853 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003854 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003855
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003856 if (Sizes.size() > 0) {
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003857 for (auto V : Sizes)
3858 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3859 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003860
Johannes Doerfertcea61932016-02-21 19:13:19 +00003861 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, true,
Tobias Grossera535dff2015-12-13 19:59:01 +00003862 Subscripts, SizesSCEV, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003863 return true;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003864 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003865 }
3866 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003867 return false;
3868}
3869
3870bool ScopInfo::buildAccessMultiDimParam(
3871 MemAccInst Inst, Loop *L, Region *R,
3872 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003873 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003874 Value *Address = Inst.getPointerOperand();
3875 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003876 Type *ElementType = Val->getType();
3877 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003878 enum MemoryAccess::AccessType Type =
3879 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3880
3881 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3882 const SCEVUnknown *BasePointer =
3883 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3884
3885 assert(BasePointer && "Could not find base pointer");
3886 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003887
Michael Kruse7bf39442015-09-10 12:46:52 +00003888 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003889 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003890 std::vector<const SCEV *> Sizes(
3891 AccItr->second.Shape->DelinearizedSizes.begin(),
3892 AccItr->second.Shape->DelinearizedSizes.end());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003893 // Remove the element size. This information is already provided by the
Tobias Grosserd840fc72016-02-04 13:18:42 +00003894 // ElementSize parameter. In case the element size of this access and the
3895 // element size used for delinearization differs the delinearization is
3896 // incorrect. Hence, we invalidate the scop.
3897 //
3898 // TODO: Handle delinearization with differing element sizes.
3899 auto DelinearizedSize =
3900 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003901 Sizes.pop_back();
Tobias Grosserd840fc72016-02-04 13:18:42 +00003902 if (ElementSize != DelinearizedSize)
3903 scop->invalidate(DELINEARIZATION, Inst.getDebugLoc());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003904
Johannes Doerfertcea61932016-02-21 19:13:19 +00003905 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, true,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003906 AccItr->second.DelinearizedSubscripts, Sizes, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003907 return true;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003908 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003909 return false;
3910}
3911
Johannes Doerfertcea61932016-02-21 19:13:19 +00003912bool ScopInfo::buildAccessMemIntrinsic(
3913 MemAccInst Inst, Loop *L, Region *R,
3914 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3915 const InvariantLoadsSetTy &ScopRIL) {
3916 if (!Inst.isMemIntrinsic())
3917 return false;
3918
3919 auto *LengthVal = SE->getSCEVAtScope(Inst.asMemIntrinsic()->getLength(), L);
3920 assert(LengthVal);
3921
3922 auto *DestPtrVal = Inst.asMemIntrinsic()->getDest();
3923 assert(DestPtrVal);
3924 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
3925 assert(DestAccFunc);
3926 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
3927 assert(DestPtrSCEV);
3928 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
3929 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
3930 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
3931 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
3932
3933 if (!Inst.isMemTransferInst())
3934 return true;
3935
3936 auto *SrcPtrVal = Inst.asMemTransferInst()->getSource();
3937 assert(SrcPtrVal);
3938 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
3939 assert(SrcAccFunc);
3940 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
3941 assert(SrcPtrSCEV);
3942 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
3943 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
3944 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
3945 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
3946
3947 return true;
3948}
3949
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003950void ScopInfo::buildAccessSingleDim(
3951 MemAccInst Inst, Loop *L, Region *R,
3952 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3953 const InvariantLoadsSetTy &ScopRIL) {
3954 Value *Address = Inst.getPointerOperand();
3955 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003956 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003957 enum MemoryAccess::AccessType Type =
3958 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3959
3960 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3961 const SCEVUnknown *BasePointer =
3962 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3963
3964 assert(BasePointer && "Could not find base pointer");
3965 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00003966
3967 // Check if the access depends on a loop contained in a non-affine subregion.
3968 bool isVariantInNonAffineLoop = false;
3969 if (BoxedLoops) {
3970 SetVector<const Loop *> Loops;
3971 findLoops(AccessFunction, Loops);
3972 for (const Loop *L : Loops)
3973 if (BoxedLoops->count(L))
3974 isVariantInNonAffineLoop = true;
3975 }
3976
Johannes Doerfert09e36972015-10-07 20:17:36 +00003977 InvariantLoadsSetTy AccessILS;
3978 bool IsAffine =
3979 !isVariantInNonAffineLoop &&
3980 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
3981
3982 for (LoadInst *LInst : AccessILS)
3983 if (!ScopRIL.count(LInst))
3984 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00003985
Michael Krusee2bccbb2015-09-18 19:59:43 +00003986 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
3987 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003988
Johannes Doerfertcea61932016-02-21 19:13:19 +00003989 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003990 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00003991}
3992
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003993void ScopInfo::buildMemoryAccess(
3994 MemAccInst Inst, Loop *L, Region *R,
3995 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003996 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003997
Johannes Doerfertcea61932016-02-21 19:13:19 +00003998 if (buildAccessMemIntrinsic(Inst, L, R, BoxedLoops, ScopRIL))
3999 return;
4000
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004001 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
4002 return;
4003
Hongbin Zheng22623202016-02-15 00:20:58 +00004004 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004005 return;
4006
4007 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
4008}
4009
Hongbin Zheng22623202016-02-15 00:20:58 +00004010void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
4011 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004012
4013 if (SD->isNonAffineSubRegion(&SR, &R)) {
4014 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00004015 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004016 return;
4017 }
4018
4019 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4020 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00004021 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004022 else
Hongbin Zheng22623202016-02-15 00:20:58 +00004023 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004024}
4025
Johannes Doerferta8781032016-02-02 14:14:40 +00004026void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004027
Johannes Doerferta8781032016-02-02 14:14:40 +00004028 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004029 scop->addScopStmt(nullptr, &SR);
4030 return;
4031 }
4032
4033 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4034 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004035 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004036 else
4037 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4038}
4039
Michael Krused868b5d2015-09-10 15:25:24 +00004040void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00004041 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00004042 Region *NonAffineSubRegion,
4043 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004044 // We do not build access functions for error blocks, as they may contain
4045 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004046 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004047 return;
4048
Michael Kruse7bf39442015-09-10 12:46:52 +00004049 Loop *L = LI->getLoopFor(&BB);
4050
4051 // The set of loops contained in non-affine subregions that are part of R.
4052 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
4053
Johannes Doerfert09e36972015-10-07 20:17:36 +00004054 // The set of loads that are required to be invariant.
4055 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
4056
Michael Kruse2e02d562016-02-06 09:19:40 +00004057 for (Instruction &Inst : BB) {
4058 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004059 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004060 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004061
4062 // For the exit block we stop modeling after the last PHI node.
4063 if (!PHI && IsExitBlock)
4064 break;
4065
Johannes Doerfert09e36972015-10-07 20:17:36 +00004066 // TODO: At this point we only know that elements of ScopRIL have to be
4067 // invariant and will be hoisted for the SCoP to be processed. Though,
4068 // there might be other invariant accesses that will be hoisted and
4069 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00004070 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00004071 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004072
Michael Kruse2e02d562016-02-06 09:19:40 +00004073 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004074 continue;
4075
Michael Kruse2e02d562016-02-06 09:19:40 +00004076 if (!PHI)
4077 buildScalarDependences(&Inst);
4078 if (!IsExitBlock)
4079 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004080 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004081}
Michael Kruse7bf39442015-09-10 12:46:52 +00004082
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004083MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004084 MemoryAccess::AccessType AccType,
4085 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004086 bool Affine, Value *AccessValue,
4087 ArrayRef<const SCEV *> Subscripts,
4088 ArrayRef<const SCEV *> Sizes,
4089 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004090 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004091
4092 // Do not create a memory access for anything not in the SCoP. It would be
4093 // ignored anyway.
4094 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004095 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004096
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004097 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004098 Value *BaseAddr = BaseAddress;
4099 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4100
Tobias Grosserf4f68702015-12-14 15:05:37 +00004101 bool isKnownMustAccess = false;
4102
4103 // Accesses in single-basic block statements are always excuted.
4104 if (Stmt->isBlockStmt())
4105 isKnownMustAccess = true;
4106
4107 if (Stmt->isRegionStmt()) {
4108 // Accesses that dominate the exit block of a non-affine region are always
4109 // executed. In non-affine regions there may exist MK_Values that do not
4110 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4111 // only if there is at most one PHI_WRITE in the non-affine region.
4112 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4113 isKnownMustAccess = true;
4114 }
4115
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004116 // Non-affine PHI writes do not "happen" at a particular instruction, but
4117 // after exiting the statement. Therefore they are guaranteed execute and
4118 // overwrite the old value.
4119 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4120 isKnownMustAccess = true;
4121
Johannes Doerfertcea61932016-02-21 19:13:19 +00004122 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4123 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004124
Johannes Doerfertcea61932016-02-21 19:13:19 +00004125 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004126 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004127 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004128 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004129}
4130
Michael Kruse70131d32016-01-27 17:09:17 +00004131void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004132 MemoryAccess::AccessType AccType,
4133 Value *BaseAddress, Type *ElementType,
4134 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004135 ArrayRef<const SCEV *> Sizes,
4136 Value *AccessValue) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004137 addMemoryAccess(MemAccInst.getParent(), MemAccInst, AccType, BaseAddress,
4138 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004139 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004140}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004141
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004142void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004143 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004144
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004145 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004146 if (!Stmt)
4147 return;
4148
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004149 // Do not process further if the instruction is already written.
4150 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004151 return;
4152
Johannes Doerfertcea61932016-02-21 19:13:19 +00004153 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4154 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004155 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004156}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004157
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004158void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004159
Michael Kruse2e02d562016-02-06 09:19:40 +00004160 // There cannot be an "access" for literal constants. BasicBlock references
4161 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004162 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004163 return;
4164
Michael Krusefd463082016-01-27 22:51:56 +00004165 // If the instruction can be synthesized and the user is in the region we do
4166 // not need to add a value dependences.
4167 Region &ScopRegion = scop->getRegion();
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004168 if (canSynthesize(V, LI, SE, &ScopRegion))
Michael Krusefd463082016-01-27 22:51:56 +00004169 return;
4170
Michael Kruse2e02d562016-02-06 09:19:40 +00004171 // Do not build scalar dependences for required invariant loads as we will
4172 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerferta90943d2016-02-21 16:37:25 +00004173 auto *ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004174 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004175 return;
4176
4177 // Determine the ScopStmt containing the value's definition and use. There is
4178 // no defining ScopStmt if the value is a function argument, a global value,
4179 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004180 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004181 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004182
Michael Kruse6f7721f2016-02-24 22:08:19 +00004183 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004184
4185 // We do not model uses outside the scop.
4186 if (!UserStmt)
4187 return;
4188
Michael Kruse2e02d562016-02-06 09:19:40 +00004189 // Add MemoryAccess for invariant values only if requested.
4190 if (!ModelReadOnlyScalars && !ValueStmt)
4191 return;
4192
4193 // Ignore use-def chains within the same ScopStmt.
4194 if (ValueStmt == UserStmt)
4195 return;
4196
Michael Krusead28e5a2016-01-26 13:33:15 +00004197 // Do not create another MemoryAccess for reloading the value if one already
4198 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004199 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004200 return;
4201
Johannes Doerfertcea61932016-02-21 19:13:19 +00004202 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004203 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004204 ScopArrayInfo::MK_Value);
Michael Kruse2e02d562016-02-06 09:19:40 +00004205 if (ValueInst)
4206 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004207}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004208
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004209void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4210 Value *IncomingValue, bool IsExitBlock) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004211 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004212 if (!IncomingStmt)
4213 return;
4214
4215 // Take care for the incoming value being available in the incoming block.
4216 // This must be done before the check for multiple PHI writes because multiple
4217 // exiting edges from subregion each can be the effective written value of the
4218 // subregion. As such, all of them must be made available in the subregion
4219 // statement.
4220 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004221
4222 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4223 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4224 assert(Acc->getAccessInstruction() == PHI);
4225 Acc->addIncoming(IncomingBlock, IncomingValue);
4226 return;
4227 }
4228
4229 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004230 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4231 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4232 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004233 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4234 assert(Acc);
4235 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004236}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004237
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004238void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004239 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4240 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4241 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004242}
4243
Michael Krusedaf66942015-12-13 22:10:37 +00004244void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004245 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004246 scop.reset(new Scop(R, *SE, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004247
Johannes Doerferta8781032016-02-02 14:14:40 +00004248 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004249 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004250
4251 // In case the region does not have an exiting block we will later (during
4252 // code generation) split the exit block. This will move potential PHI nodes
4253 // from the current exit block into the new region exiting block. Hence, PHI
4254 // nodes that are at this point not part of the region will be.
4255 // To handle these PHI nodes later we will now model their operands as scalar
4256 // accesses. Note that we do not model anything in the exit block if we have
4257 // an exiting block in the region, as there will not be any splitting later.
4258 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004259 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4260 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004261
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004262 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004263}
4264
Michael Krused868b5d2015-09-10 15:25:24 +00004265void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004266 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004267 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004268 return;
4269 }
4270
Michael Kruse9d080092015-09-11 21:41:48 +00004271 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004272}
4273
Hongbin Zhengfec32802016-02-13 15:13:02 +00004274void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004275
4276//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004277ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004278
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004279ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004280
Tobias Grosser75805372011-04-29 06:27:02 +00004281void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004282 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004283 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004284 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004285 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4286 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004287 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004288 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004289 AU.setPreservesAll();
4290}
4291
4292bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004293 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004294
Michael Krused868b5d2015-09-10 15:25:24 +00004295 if (!SD->isMaxRegionInScop(*R))
4296 return false;
4297
4298 Function *F = R->getEntry()->getParent();
4299 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4300 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4301 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004302 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004303 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004304 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004305
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004306 DebugLoc Beg, End;
4307 getDebugLocations(R, Beg, End);
4308 std::string Msg = "SCoP begins here.";
4309 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4310
Michael Krusedaf66942015-12-13 22:10:37 +00004311 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004312
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004313 DEBUG(scop->print(dbgs()));
4314
Michael Kruseafe06702015-10-02 16:33:27 +00004315 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004316 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004317 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004318 } else {
4319 Msg = "SCoP ends here.";
4320 ++ScopFound;
4321 if (scop->getMaxLoopDepth() > 0)
4322 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004323 }
4324
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004325 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4326
Tobias Grosser75805372011-04-29 06:27:02 +00004327 return false;
4328}
4329
4330char ScopInfo::ID = 0;
4331
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004332Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4333
Tobias Grosser73600b82011-10-08 00:30:40 +00004334INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4335 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004336 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004337INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004338INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004339INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004340INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004341INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004342INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004343INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004344INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4345 "Polly - Create polyhedral description of Scops", false,
4346 false)