blob: 680efcb3701e4051662edd24a9fa3524a6ce4aa9 [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 Doerferta7920982016-02-25 14:08:48 +0000205 if (NewElementSize == OldElementSize || NewElementSize == 0)
Johannes Doerfert3ff22212016-02-14 22:31:39 +0000206 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
Johannes Doerfertcea61932016-02-21 19:13:19 +0000623 auto *SubscriptPWA = Statement->getPwAff(Subscripts[0]);
624 auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
Johannes Doerferta7920982016-02-25 14:08:48 +0000625
626 isl_map *LengthMap;
627 if (Subscripts[1] == nullptr) {
628 LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
629 } else {
630 auto *LengthPWA = Statement->getPwAff(Subscripts[1]);
631 LengthMap = isl_map_from_pw_aff(LengthPWA);
632 auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
633 LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
634 }
635 LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
636 LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000637 SubscriptMap =
638 isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
Johannes Doerfertcea61932016-02-21 19:13:19 +0000639 LengthMap = isl_map_sum(LengthMap, SubscriptMap);
640 AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
641 getStatement()->getDomainId());
642}
643
Johannes Doerferte7044942015-02-24 11:58:30 +0000644void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
645 ScalarEvolution *SE = Statement->getParent()->getSE();
646
Johannes Doerfertcea61932016-02-21 19:13:19 +0000647 auto MAI = MemAccInst(getAccessInstruction());
648 if (MAI.isMemIntrinsic())
649 return;
650
651 Value *Ptr = MAI.getPointerOperand();
Johannes Doerferte7044942015-02-24 11:58:30 +0000652 if (!Ptr || !SE->isSCEVable(Ptr->getType()))
653 return;
654
655 auto *PtrSCEV = SE->getSCEV(Ptr);
656 if (isa<SCEVCouldNotCompute>(PtrSCEV))
657 return;
658
659 auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
660 if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
661 PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
662
663 const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
664 if (Range.isFullSet())
665 return;
666
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000667 bool isWrapping = Range.isSignWrappedSet();
Johannes Doerferte7044942015-02-24 11:58:30 +0000668 unsigned BW = Range.getBitWidth();
Johannes Doerferte7087902016-02-07 13:59:03 +0000669 const auto One = APInt(BW, 1);
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000670 const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
Johannes Doerferte7087902016-02-07 13:59:03 +0000671 const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
Johannes Doerferte4bd53b2015-03-08 19:49:50 +0000672
673 auto Min = LB.sdiv(APInt(BW, ElementSize));
Johannes Doerferte7087902016-02-07 13:59:03 +0000674 auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
Johannes Doerferte7044942015-02-24 11:58:30 +0000675
676 isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
677 AccessRange =
678 addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
679 AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
680}
681
Michael Krusee2bccbb2015-09-18 19:59:43 +0000682__isl_give isl_map *MemoryAccess::foldAccess(__isl_take isl_map *AccessRelation,
Tobias Grosser619190d2015-03-30 17:22:28 +0000683 ScopStmt *Statement) {
Michael Krusee2bccbb2015-09-18 19:59:43 +0000684 int Size = Subscripts.size();
Tobias Grosser619190d2015-03-30 17:22:28 +0000685
686 for (int i = Size - 2; i >= 0; --i) {
687 isl_space *Space;
688 isl_map *MapOne, *MapTwo;
Michael Krusee2bccbb2015-09-18 19:59:43 +0000689 isl_pw_aff *DimSize = Statement->getPwAff(Sizes[i]);
Tobias Grosser619190d2015-03-30 17:22:28 +0000690
691 isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
692 isl_pw_aff_free(DimSize);
693 isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
694
695 Space = isl_map_get_space(AccessRelation);
696 Space = isl_space_map_from_set(isl_space_range(Space));
697 Space = isl_space_align_params(Space, SpaceSize);
698
699 int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
700 isl_id_free(ParamId);
701
702 MapOne = isl_map_universe(isl_space_copy(Space));
703 for (int j = 0; j < Size; ++j)
704 MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
705 MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
706
707 MapTwo = isl_map_universe(isl_space_copy(Space));
708 for (int j = 0; j < Size; ++j)
709 if (j < i || j > i + 1)
710 MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
711
712 isl_local_space *LS = isl_local_space_from_space(Space);
713 isl_constraint *C;
714 C = isl_equality_alloc(isl_local_space_copy(LS));
715 C = isl_constraint_set_constant_si(C, -1);
716 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
717 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
718 MapTwo = isl_map_add_constraint(MapTwo, C);
719 C = isl_equality_alloc(LS);
720 C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
721 C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
722 C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
723 MapTwo = isl_map_add_constraint(MapTwo, C);
724 MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
725
726 MapOne = isl_map_union(MapOne, MapTwo);
727 AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
728 }
729 return AccessRelation;
730}
731
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000732/// @brief Check if @p Expr is divisible by @p Size.
733static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
Johannes Doerferta7920982016-02-25 14:08:48 +0000734 assert(Size != 0);
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +0000735 if (Size == 1)
736 return true;
Johannes Doerferta4b77c02015-11-12 20:15:32 +0000737
738 // Only one factor needs to be divisible.
739 if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
740 for (auto *FactorExpr : MulExpr->operands())
741 if (isDivisible(FactorExpr, Size, SE))
742 return true;
743 return false;
744 }
745
746 // For other n-ary expressions (Add, AddRec, Max,...) all operands need
747 // to be divisble.
748 if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
749 for (auto *OpExpr : NAryExpr->operands())
750 if (!isDivisible(OpExpr, Size, SE))
751 return false;
752 return true;
753 }
754
755 auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
756 auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
757 auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
758 return MulSCEV == Expr;
759}
760
Michael Krusee2bccbb2015-09-18 19:59:43 +0000761void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
762 assert(!AccessRelation && "AccessReltation already built");
Tobias Grosser75805372011-04-29 06:27:02 +0000763
Michael Krusee2bccbb2015-09-18 19:59:43 +0000764 isl_ctx *Ctx = isl_id_get_ctx(Id);
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000765 isl_id *BaseAddrId = SAI->getBasePtrId();
Tobias Grosser5683df42011-11-09 22:34:34 +0000766
Michael Krusee2bccbb2015-09-18 19:59:43 +0000767 if (!isAffine()) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000768 if (isa<MemIntrinsic>(getAccessInstruction()))
769 buildMemIntrinsicAccessRelation();
770
Tobias Grosser4f967492013-06-23 05:21:18 +0000771 // We overapproximate non-affine accesses with a possible access to the
772 // whole array. For read accesses it does not make a difference, if an
773 // access must or may happen. However, for write accesses it is important to
774 // differentiate between writes that must happen and writes that may happen.
Johannes Doerfertcea61932016-02-21 19:13:19 +0000775 if (!AccessRelation)
776 AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
777
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000778 AccessRelation =
779 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
Tobias Grossera1879642011-12-20 10:43:14 +0000780 return;
781 }
782
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000783 isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
Tobias Grosser79baa212014-04-10 08:38:02 +0000784 AccessRelation = isl_map_universe(Space);
Tobias Grossera1879642011-12-20 10:43:14 +0000785
Michael Krusee2bccbb2015-09-18 19:59:43 +0000786 for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
787 isl_pw_aff *Affine = Statement->getPwAff(Subscripts[i]);
Sebastian Pop18016682014-04-08 21:20:44 +0000788 isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
Tobias Grosser79baa212014-04-10 08:38:02 +0000789 AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
Sebastian Pop18016682014-04-08 21:20:44 +0000790 }
791
Tobias Grosser5d51afe2016-02-02 16:46:45 +0000792 if (Sizes.size() >= 1 && !isa<SCEVConstant>(Sizes[0]))
Michael Krusee2bccbb2015-09-18 19:59:43 +0000793 AccessRelation = foldAccess(AccessRelation, Statement);
Tobias Grosser619190d2015-03-30 17:22:28 +0000794
Tobias Grosser79baa212014-04-10 08:38:02 +0000795 Space = Statement->getDomainSpace();
Tobias Grosserabfbe632013-02-05 12:09:06 +0000796 AccessRelation = isl_map_set_tuple_id(
797 AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000798 AccessRelation =
799 isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
800
Tobias Grosseraa660a92015-03-30 00:07:50 +0000801 AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
Johannes Doerfert5d83f092014-07-29 08:37:55 +0000802 isl_space_free(Space);
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000803}
Tobias Grosser30b8a092011-08-18 07:51:37 +0000804
Michael Krusecac948e2015-10-02 13:53:07 +0000805MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +0000806 AccessType AccType, Value *BaseAddress,
807 Type *ElementType, bool Affine,
Michael Krusee2bccbb2015-09-18 19:59:43 +0000808 ArrayRef<const SCEV *> Subscripts,
809 ArrayRef<const SCEV *> Sizes, Value *AccessValue,
Tobias Grossera535dff2015-12-13 19:59:01 +0000810 ScopArrayInfo::MemoryKind Kind, StringRef BaseName)
Johannes Doerfertcea61932016-02-21 19:13:19 +0000811 : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
812 BaseAddr(BaseAddress), BaseName(BaseName), ElementType(ElementType),
Michael Krusecac948e2015-10-02 13:53:07 +0000813 Sizes(Sizes.begin(), Sizes.end()), AccessInstruction(AccessInst),
814 AccessValue(AccessValue), IsAffine(Affine),
Michael Krusee2bccbb2015-09-18 19:59:43 +0000815 Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000816 NewAccessRelation(nullptr) {
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000817 static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
Johannes Doerfertcea61932016-02-21 19:13:19 +0000818 const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000819
Hongbin Zheng86f43ea2016-02-20 03:40:15 +0000820 std::string IdName =
821 getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
Tobias Grosserf1bfd752015-11-05 20:15:37 +0000822 Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
823}
Michael Krusee2bccbb2015-09-18 19:59:43 +0000824
Tobias Grosser8cae72f2011-11-08 15:41:08 +0000825void MemoryAccess::realignParams() {
Tobias Grosser6defb5b2014-04-10 08:37:44 +0000826 isl_space *ParamSpace = Statement->getParent()->getParamSpace();
Tobias Grosser37487052011-10-06 00:03:42 +0000827 AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
Tobias Grosser75805372011-04-29 06:27:02 +0000828}
829
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000830const std::string MemoryAccess::getReductionOperatorStr() const {
831 return MemoryAccess::getReductionOperatorStr(getReductionType());
832}
833
Tobias Grosser6f48e0f2015-05-15 09:58:32 +0000834__isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
835
Johannes Doerfertf6183392014-07-01 20:52:51 +0000836raw_ostream &polly::operator<<(raw_ostream &OS,
837 MemoryAccess::ReductionType RT) {
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000838 if (RT == MemoryAccess::RT_NONE)
Johannes Doerfertf6183392014-07-01 20:52:51 +0000839 OS << "NONE";
Johannes Doerfert32868bf2014-08-01 08:13:25 +0000840 else
841 OS << MemoryAccess::getReductionOperatorStr(RT);
Johannes Doerfertf6183392014-07-01 20:52:51 +0000842 return OS;
843}
844
Tobias Grosser75805372011-04-29 06:27:02 +0000845void MemoryAccess::print(raw_ostream &OS) const {
Johannes Doerfert4c7ce472014-10-08 10:11:33 +0000846 switch (AccType) {
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000847 case READ:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000848 OS.indent(12) << "ReadAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000849 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000850 case MUST_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000851 OS.indent(12) << "MustWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000852 break;
Tobias Grosserb58f6a42013-07-13 20:41:24 +0000853 case MAY_WRITE:
Johannes Doerfert6780bc32014-06-26 18:47:03 +0000854 OS.indent(12) << "MayWriteAccess :=\t";
Tobias Grosser4f967492013-06-23 05:21:18 +0000855 break;
856 }
Johannes Doerfert0ff23ec2015-02-06 20:13:15 +0000857 OS << "[Reduction Type: " << getReductionType() << "] ";
Tobias Grossera535dff2015-12-13 19:59:01 +0000858 OS << "[Scalar: " << isScalarKind() << "]\n";
Michael Kruseb8d26442015-12-13 19:35:26 +0000859 OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
Tobias Grosser6f730082015-09-05 07:46:47 +0000860 if (hasNewAccessRelation())
861 OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +0000862}
863
Tobias Grosser74394f02013-01-14 22:40:23 +0000864void MemoryAccess::dump() const { print(errs()); }
Tobias Grosser75805372011-04-29 06:27:02 +0000865
866// Create a map in the size of the provided set domain, that maps from the
867// one element of the provided set domain to another element of the provided
868// set domain.
869// The mapping is limited to all points that are equal in all but the last
870// dimension and for which the last dimension of the input is strict smaller
871// than the last dimension of the output.
872//
873// getEqualAndLarger(set[i0, i1, ..., iX]):
874//
875// set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
876// : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
877//
Tobias Grosserf5338802011-10-06 00:03:35 +0000878static isl_map *getEqualAndLarger(isl_space *setDomain) {
Tobias Grosserc327932c2012-02-01 14:23:36 +0000879 isl_space *Space = isl_space_map_from_set(setDomain);
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000880 isl_map *Map = isl_map_universe(Space);
Sebastian Pop40408762013-10-04 17:14:53 +0000881 unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
Tobias Grosser75805372011-04-29 06:27:02 +0000882
883 // Set all but the last dimension to be equal for the input and output
884 //
885 // input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
886 // : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
Sebastian Pop40408762013-10-04 17:14:53 +0000887 for (unsigned i = 0; i < lastDimension; ++i)
Tobias Grosserc327932c2012-02-01 14:23:36 +0000888 Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
Tobias Grosser75805372011-04-29 06:27:02 +0000889
890 // Set the last dimension of the input to be strict smaller than the
891 // last dimension of the output.
892 //
893 // input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
Tobias Grosser1b6ea572015-05-21 19:02:44 +0000894 Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
895 lastDimension);
Tobias Grosserc327932c2012-02-01 14:23:36 +0000896 return Map;
Tobias Grosser75805372011-04-29 06:27:02 +0000897}
898
Tobias Grosser4f663aa2015-03-30 11:52:59 +0000899__isl_give isl_set *
900MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
Tobias Grosserabfbe632013-02-05 12:09:06 +0000901 isl_map *S = const_cast<isl_map *>(Schedule);
Johannes Doerferta99130f2014-10-13 12:58:03 +0000902 isl_map *AccessRelation = getAccessRelation();
Sebastian Popa00a0292012-12-18 07:46:06 +0000903 isl_space *Space = isl_space_range(isl_map_get_space(S));
904 isl_map *NextScatt = getEqualAndLarger(Space);
Tobias Grosser75805372011-04-29 06:27:02 +0000905
Sebastian Popa00a0292012-12-18 07:46:06 +0000906 S = isl_map_reverse(S);
907 NextScatt = isl_map_lexmin(NextScatt);
Tobias Grosser75805372011-04-29 06:27:02 +0000908
Sebastian Popa00a0292012-12-18 07:46:06 +0000909 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
910 NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
911 NextScatt = isl_map_apply_domain(NextScatt, S);
912 NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
Tobias Grosser75805372011-04-29 06:27:02 +0000913
Sebastian Popa00a0292012-12-18 07:46:06 +0000914 isl_set *Deltas = isl_map_deltas(NextScatt);
915 return Deltas;
Tobias Grosser75805372011-04-29 06:27:02 +0000916}
917
Sebastian Popa00a0292012-12-18 07:46:06 +0000918bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
Tobias Grosser28dd4862012-01-24 16:42:16 +0000919 int StrideWidth) const {
920 isl_set *Stride, *StrideX;
921 bool IsStrideX;
Tobias Grosser75805372011-04-29 06:27:02 +0000922
Sebastian Popa00a0292012-12-18 07:46:06 +0000923 Stride = getStride(Schedule);
Tobias Grosser28dd4862012-01-24 16:42:16 +0000924 StrideX = isl_set_universe(isl_set_get_space(Stride));
Tobias Grosser01c8f5f2015-08-24 22:20:46 +0000925 for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
926 StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
927 StrideX = isl_set_fix_si(StrideX, isl_dim_set,
928 isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
Roman Gareevf2bd72e2015-08-18 16:12:05 +0000929 IsStrideX = isl_set_is_subset(Stride, StrideX);
Tobias Grosser75805372011-04-29 06:27:02 +0000930
Tobias Grosser28dd4862012-01-24 16:42:16 +0000931 isl_set_free(StrideX);
Tobias Grosserdea98232012-01-17 20:34:27 +0000932 isl_set_free(Stride);
Tobias Grosserb76f38532011-08-20 11:11:25 +0000933
Tobias Grosser28dd4862012-01-24 16:42:16 +0000934 return IsStrideX;
935}
936
Sebastian Popa00a0292012-12-18 07:46:06 +0000937bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
938 return isStrideX(Schedule, 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000939}
940
Sebastian Popa00a0292012-12-18 07:46:06 +0000941bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
942 return isStrideX(Schedule, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000943}
944
Tobias Grosser166c4222015-09-05 07:46:40 +0000945void MemoryAccess::setNewAccessRelation(isl_map *NewAccess) {
946 isl_map_free(NewAccessRelation);
947 NewAccessRelation = NewAccess;
Raghesh Aloor3cb66282011-07-12 17:14:03 +0000948}
Tobias Grosser75805372011-04-29 06:27:02 +0000949
950//===----------------------------------------------------------------------===//
Tobias Grossercf3942d2011-10-06 00:04:05 +0000951
Tobias Grosser808cd692015-07-14 09:33:13 +0000952isl_map *ScopStmt::getSchedule() const {
953 isl_set *Domain = getDomain();
954 if (isl_set_is_empty(Domain)) {
955 isl_set_free(Domain);
956 return isl_map_from_aff(
957 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
958 }
959 auto *Schedule = getParent()->getSchedule();
960 Schedule = isl_union_map_intersect_domain(
961 Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
962 if (isl_union_map_is_empty(Schedule)) {
963 isl_set_free(Domain);
964 isl_union_map_free(Schedule);
965 return isl_map_from_aff(
966 isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
967 }
968 auto *M = isl_map_from_union_map(Schedule);
969 M = isl_map_coalesce(M);
970 M = isl_map_gist_domain(M, Domain);
971 M = isl_map_coalesce(M);
972 return M;
973}
Tobias Grossercf3942d2011-10-06 00:04:05 +0000974
Johannes Doerfert574182d2015-08-12 10:19:50 +0000975__isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E) {
Michael Kruse375cb5f2016-02-24 22:08:24 +0000976 return getParent()->getPwAff(E, getEntryBlock());
Johannes Doerfert574182d2015-08-12 10:19:50 +0000977}
978
Tobias Grosser37eb4222014-02-20 21:43:54 +0000979void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
980 assert(isl_set_is_subset(NewDomain, Domain) &&
981 "New domain is not a subset of old domain!");
982 isl_set_free(Domain);
983 Domain = NewDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000984}
985
Michael Krusecac948e2015-10-02 13:53:07 +0000986void ScopStmt::buildAccessRelations() {
Johannes Doerfertadeab372016-02-07 13:57:32 +0000987 Scop &S = *getParent();
Michael Krusecac948e2015-10-02 13:53:07 +0000988 for (MemoryAccess *Access : MemAccs) {
Johannes Doerfertcea61932016-02-21 19:13:19 +0000989 Type *ElementType = Access->getElementType();
Johannes Doerfert1a28a892014-10-05 11:32:18 +0000990
Tobias Grossera535dff2015-12-13 19:59:01 +0000991 ScopArrayInfo::MemoryKind Ty;
992 if (Access->isPHIKind())
993 Ty = ScopArrayInfo::MK_PHI;
994 else if (Access->isExitPHIKind())
995 Ty = ScopArrayInfo::MK_ExitPHI;
996 else if (Access->isValueKind())
997 Ty = ScopArrayInfo::MK_Value;
Tobias Grosser6abc75a2015-11-10 17:31:31 +0000998 else
Tobias Grossera535dff2015-12-13 19:59:01 +0000999 Ty = ScopArrayInfo::MK_Array;
Tobias Grosser6abc75a2015-11-10 17:31:31 +00001000
Johannes Doerfertadeab372016-02-07 13:57:32 +00001001 auto *SAI = S.getOrCreateScopArrayInfo(Access->getBaseAddr(), ElementType,
1002 Access->Sizes, Ty);
Michael Krusecac948e2015-10-02 13:53:07 +00001003 Access->buildAccessRelation(SAI);
Tobias Grosser75805372011-04-29 06:27:02 +00001004 }
1005}
1006
Michael Krusecac948e2015-10-02 13:53:07 +00001007void ScopStmt::addAccess(MemoryAccess *Access) {
1008 Instruction *AccessInst = Access->getAccessInstruction();
1009
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001010 if (Access->isArrayKind()) {
1011 MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1012 MAL.emplace_front(Access);
Michael Kruse436db622016-01-26 13:33:10 +00001013 } else if (Access->isValueKind() && Access->isWrite()) {
1014 Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
Michael Kruse6f7721f2016-02-24 22:08:19 +00001015 assert(Parent.getStmtFor(AccessVal) == this);
Michael Kruse436db622016-01-26 13:33:10 +00001016 assert(!ValueWrites.lookup(AccessVal));
1017
1018 ValueWrites[AccessVal] = Access;
Michael Krusead28e5a2016-01-26 13:33:15 +00001019 } else if (Access->isValueKind() && Access->isRead()) {
1020 Value *AccessVal = Access->getAccessValue();
1021 assert(!ValueReads.lookup(AccessVal));
1022
1023 ValueReads[AccessVal] = Access;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001024 } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1025 PHINode *PHI = cast<PHINode>(Access->getBaseAddr());
1026 assert(!PHIWrites.lookup(PHI));
1027
1028 PHIWrites[PHI] = Access;
Michael Kruse58fa3bb2015-12-22 23:25:11 +00001029 }
1030
1031 MemAccs.push_back(Access);
Michael Krusecac948e2015-10-02 13:53:07 +00001032}
1033
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001034void ScopStmt::realignParams() {
Johannes Doerfertf6752892014-06-13 18:01:45 +00001035 for (MemoryAccess *MA : *this)
1036 MA->realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001037
1038 Domain = isl_set_align_params(Domain, Parent.getParamSpace());
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001039}
1040
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001041/// @brief Add @p BSet to the set @p User if @p BSet is bounded.
1042static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1043 void *User) {
1044 isl_set **BoundedParts = static_cast<isl_set **>(User);
1045 if (isl_basic_set_is_bounded(BSet))
1046 *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1047 else
1048 isl_basic_set_free(BSet);
1049 return isl_stat_ok;
1050}
1051
1052/// @brief Return the bounded parts of @p S.
1053static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1054 isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1055 isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1056 isl_set_free(S);
1057 return BoundedParts;
1058}
1059
1060/// @brief Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1061///
1062/// @returns A separation of @p S into first an unbounded then a bounded subset,
1063/// both with regards to the dimension @p Dim.
1064static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1065partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1066
1067 for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001068 S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001069
1070 unsigned NumDimsS = isl_set_n_dim(S);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001071 isl_set *OnlyDimS = isl_set_copy(S);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001072
1073 // Remove dimensions that are greater than Dim as they are not interesting.
1074 assert(NumDimsS >= Dim + 1);
1075 OnlyDimS =
1076 isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1077
1078 // Create artificial parametric upper bounds for dimensions smaller than Dim
1079 // as we are not interested in them.
1080 OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1081 for (unsigned u = 0; u < Dim; u++) {
1082 isl_constraint *C = isl_inequality_alloc(
1083 isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1084 C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1085 C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1086 OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1087 }
1088
1089 // Collect all bounded parts of OnlyDimS.
1090 isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1091
1092 // Create the dimensions greater than Dim again.
1093 BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1094 NumDimsS - Dim - 1);
1095
1096 // Remove the artificial upper bound parameters again.
1097 BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1098
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00001099 isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001100 return std::make_pair(UnboundedParts, BoundedParts);
1101}
1102
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001103/// @brief Set the dimension Ids from @p From in @p To.
1104static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1105 __isl_take isl_set *To) {
1106 for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1107 isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1108 To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1109 }
1110 return To;
1111}
1112
1113/// @brief Create the conditions under which @p L @p Pred @p R is true.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001114static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001115 __isl_take isl_pw_aff *L,
1116 __isl_take isl_pw_aff *R) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001117 switch (Pred) {
1118 case ICmpInst::ICMP_EQ:
1119 return isl_pw_aff_eq_set(L, R);
1120 case ICmpInst::ICMP_NE:
1121 return isl_pw_aff_ne_set(L, R);
1122 case ICmpInst::ICMP_SLT:
1123 return isl_pw_aff_lt_set(L, R);
1124 case ICmpInst::ICMP_SLE:
1125 return isl_pw_aff_le_set(L, R);
1126 case ICmpInst::ICMP_SGT:
1127 return isl_pw_aff_gt_set(L, R);
1128 case ICmpInst::ICMP_SGE:
1129 return isl_pw_aff_ge_set(L, R);
1130 case ICmpInst::ICMP_ULT:
1131 return isl_pw_aff_lt_set(L, R);
1132 case ICmpInst::ICMP_UGT:
1133 return isl_pw_aff_gt_set(L, R);
1134 case ICmpInst::ICMP_ULE:
1135 return isl_pw_aff_le_set(L, R);
1136 case ICmpInst::ICMP_UGE:
1137 return isl_pw_aff_ge_set(L, R);
1138 default:
1139 llvm_unreachable("Non integer predicate not supported");
1140 }
1141}
1142
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001143/// @brief Create the conditions under which @p L @p Pred @p R is true.
1144///
1145/// Helper function that will make sure the dimensions of the result have the
1146/// same isl_id's as the @p Domain.
1147static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1148 __isl_take isl_pw_aff *L,
1149 __isl_take isl_pw_aff *R,
1150 __isl_keep isl_set *Domain) {
1151 isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1152 return setDimensionIds(Domain, ConsequenceCondSet);
1153}
1154
1155/// @brief Build the conditions sets for the switch @p SI in the @p Domain.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001156///
1157/// This will fill @p ConditionSets with the conditions under which control
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001158/// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1159/// have as many elements as @p SI has successors.
Johannes Doerfert96425c22015-08-30 21:13:53 +00001160static void
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001161buildConditionSets(Scop &S, SwitchInst *SI, Loop *L, __isl_keep isl_set *Domain,
Johannes Doerfert96425c22015-08-30 21:13:53 +00001162 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1163
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001164 Value *Condition = getConditionFromTerminator(SI);
1165 assert(Condition && "No condition for switch");
1166
1167 ScalarEvolution &SE = *S.getSE();
1168 BasicBlock *BB = SI->getParent();
1169 isl_pw_aff *LHS, *RHS;
1170 LHS = S.getPwAff(SE.getSCEVAtScope(Condition, L), BB);
1171
1172 unsigned NumSuccessors = SI->getNumSuccessors();
1173 ConditionSets.resize(NumSuccessors);
1174 for (auto &Case : SI->cases()) {
1175 unsigned Idx = Case.getSuccessorIndex();
1176 ConstantInt *CaseValue = Case.getCaseValue();
1177
1178 RHS = S.getPwAff(SE.getSCEV(CaseValue), BB);
1179 isl_set *CaseConditionSet =
1180 buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1181 ConditionSets[Idx] = isl_set_coalesce(
1182 isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1183 }
1184
1185 assert(ConditionSets[0] == nullptr && "Default condition set was set");
1186 isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1187 for (unsigned u = 2; u < NumSuccessors; u++)
1188 ConditionSetUnion =
1189 isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1190 ConditionSets[0] = setDimensionIds(
1191 Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1192
1193 S.markAsOptimized();
1194 isl_pw_aff_free(LHS);
1195}
1196
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001197/// @brief Build the conditions sets for the branch condition @p Condition in
1198/// the @p Domain.
1199///
1200/// This will fill @p ConditionSets with the conditions under which control
1201/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001202/// have as many elements as @p TI has successors. If @p TI is nullptr the
1203/// context under which @p Condition is true/false will be returned as the
1204/// new elements of @p ConditionSets.
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001205static void
1206buildConditionSets(Scop &S, Value *Condition, TerminatorInst *TI, Loop *L,
1207 __isl_keep isl_set *Domain,
1208 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1209
1210 isl_set *ConsequenceCondSet = nullptr;
1211 if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1212 if (CCond->isZero())
1213 ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1214 else
1215 ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1216 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1217 auto Opcode = BinOp->getOpcode();
1218 assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1219
1220 buildConditionSets(S, BinOp->getOperand(0), TI, L, Domain, ConditionSets);
1221 buildConditionSets(S, BinOp->getOperand(1), TI, L, Domain, ConditionSets);
1222
1223 isl_set_free(ConditionSets.pop_back_val());
1224 isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1225 isl_set_free(ConditionSets.pop_back_val());
1226 isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1227
1228 if (Opcode == Instruction::And)
1229 ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1230 else
1231 ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1232 } else {
1233 auto *ICond = dyn_cast<ICmpInst>(Condition);
1234 assert(ICond &&
1235 "Condition of exiting branch was neither constant nor ICmp!");
1236
1237 ScalarEvolution &SE = *S.getSE();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001238 BasicBlock *BB = TI ? TI->getParent() : nullptr;
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001239 isl_pw_aff *LHS, *RHS;
1240 LHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), BB);
1241 RHS = S.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), BB);
1242 ConsequenceCondSet =
1243 buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1244 }
1245
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001246 // If no terminator was given we are only looking for parameter constraints
1247 // under which @p Condition is true/false.
1248 if (!TI)
1249 ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1250
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001251 assert(ConsequenceCondSet);
1252 isl_set *AlternativeCondSet =
1253 isl_set_complement(isl_set_copy(ConsequenceCondSet));
1254
1255 ConditionSets.push_back(isl_set_coalesce(
1256 isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain))));
1257 ConditionSets.push_back(isl_set_coalesce(
1258 isl_set_intersect(AlternativeCondSet, isl_set_copy(Domain))));
1259}
1260
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001261/// @brief Build the conditions sets for the terminator @p TI in the @p Domain.
1262///
1263/// This will fill @p ConditionSets with the conditions under which control
1264/// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1265/// have as many elements as @p TI has successors.
1266static void
1267buildConditionSets(Scop &S, TerminatorInst *TI, Loop *L,
1268 __isl_keep isl_set *Domain,
1269 SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1270
1271 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1272 return buildConditionSets(S, SI, L, Domain, ConditionSets);
1273
1274 assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1275
1276 if (TI->getNumSuccessors() == 1) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00001277 ConditionSets.push_back(isl_set_copy(Domain));
1278 return;
1279 }
1280
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001281 Value *Condition = getConditionFromTerminator(TI);
1282 assert(Condition && "No condition for Terminator");
Johannes Doerfert96425c22015-08-30 21:13:53 +00001283
Johannes Doerfert9b1f9c82015-10-11 13:21:03 +00001284 return buildConditionSets(S, Condition, TI, L, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00001285}
1286
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001287void ScopStmt::buildDomain() {
Michael Kruse526fcf52016-02-24 22:08:08 +00001288 isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001289
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00001290 Domain = getParent()->getDomainConditions(this);
Tobias Grosser084d8f72012-05-29 09:29:44 +00001291 Domain = isl_set_set_tuple_id(Domain, Id);
Tobias Grosser75805372011-04-29 06:27:02 +00001292}
1293
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001294void ScopStmt::deriveAssumptionsFromGEP(GetElementPtrInst *GEP,
1295 ScopDetection &SD) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001296 isl_ctx *Ctx = Parent.getIslCtx();
1297 isl_local_space *LSpace = isl_local_space_from_space(getDomainSpace());
1298 Type *Ty = GEP->getPointerOperandType();
1299 ScalarEvolution &SE = *Parent.getSE();
Johannes Doerfert09e36972015-10-07 20:17:36 +00001300
1301 // The set of loads that are required to be invariant.
1302 auto &ScopRIL = *SD.getRequiredInvariantLoads(&Parent.getRegion());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001303
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001304 std::vector<const SCEV *> Subscripts;
1305 std::vector<int> Sizes;
1306
Tobias Grosser5fd8c092015-09-17 17:28:15 +00001307 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001308
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001309 if (auto *PtrTy = dyn_cast<PointerType>(Ty)) {
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001310 Ty = PtrTy->getElementType();
1311 }
1312
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001313 int IndexOffset = Subscripts.size() - Sizes.size();
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001314
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001315 assert(IndexOffset <= 1 && "Unexpected large index offset");
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001316
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001317 for (size_t i = 0; i < Sizes.size(); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001318 auto *Expr = Subscripts[i + IndexOffset];
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001319 auto Size = Sizes[i];
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001320
Johannes Doerfert09e36972015-10-07 20:17:36 +00001321 InvariantLoadsSetTy AccessILS;
1322 if (!isAffineExpr(&Parent.getRegion(), Expr, SE, nullptr, &AccessILS))
1323 continue;
1324
1325 bool NonAffine = false;
1326 for (LoadInst *LInst : AccessILS)
1327 if (!ScopRIL.count(LInst))
1328 NonAffine = true;
1329
1330 if (NonAffine)
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001331 continue;
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001332
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001333 isl_pw_aff *AccessOffset = getPwAff(Expr);
1334 AccessOffset =
1335 isl_pw_aff_set_tuple_id(AccessOffset, isl_dim_in, getDomainId());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001336
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001337 isl_pw_aff *DimSize = isl_pw_aff_from_aff(isl_aff_val_on_domain(
1338 isl_local_space_copy(LSpace), isl_val_int_from_si(Ctx, Size)));
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001339
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001340 isl_set *OutOfBound = isl_pw_aff_ge_set(AccessOffset, DimSize);
1341 OutOfBound = isl_set_intersect(getDomain(), OutOfBound);
1342 OutOfBound = isl_set_params(OutOfBound);
1343 isl_set *InBound = isl_set_complement(OutOfBound);
1344 isl_set *Executed = isl_set_params(getDomain());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001345
Tobias Grosserfaf8f6f2015-09-17 15:47:52 +00001346 // A => B == !A or B
1347 isl_set *InBoundIfExecuted =
1348 isl_set_union(isl_set_complement(Executed), InBound);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001349
Roman Gareev10595a12016-01-08 14:01:59 +00001350 InBoundIfExecuted = isl_set_coalesce(InBoundIfExecuted);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001351 Parent.addAssumption(INBOUNDS, InBoundIfExecuted, GEP->getDebugLoc());
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001352 }
1353
1354 isl_local_space_free(LSpace);
1355}
1356
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001357void ScopStmt::deriveAssumptions(BasicBlock *Block, ScopDetection &SD) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001358 for (Instruction &Inst : *Block)
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001359 if (auto *GEP = dyn_cast<GetElementPtrInst>(&Inst))
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001360 deriveAssumptionsFromGEP(GEP, SD);
Tobias Grosser7b50bee2014-11-25 10:51:12 +00001361}
1362
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001363void ScopStmt::collectSurroundingLoops() {
1364 for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1365 isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1366 NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1367 isl_id_free(DimId);
1368 }
1369}
1370
Michael Kruse9d080092015-09-11 21:41:48 +00001371ScopStmt::ScopStmt(Scop &parent, Region &R)
Michael Krusecac948e2015-10-02 13:53:07 +00001372 : Parent(parent), Domain(nullptr), BB(nullptr), R(&R), Build(nullptr) {
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001373
Tobias Grosser16c44032015-07-09 07:31:45 +00001374 BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
Johannes Doerfertff9d1982015-02-24 12:00:50 +00001375}
1376
Michael Kruse9d080092015-09-11 21:41:48 +00001377ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
Michael Krusecac948e2015-10-02 13:53:07 +00001378 : Parent(parent), Domain(nullptr), BB(&bb), R(nullptr), Build(nullptr) {
Tobias Grosser75805372011-04-29 06:27:02 +00001379
Johannes Doerfert79fc23f2014-07-24 23:48:02 +00001380 BaseName = getIslCompatibleName("Stmt_", &bb, "");
Michael Krusecac948e2015-10-02 13:53:07 +00001381}
1382
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001383void ScopStmt::init(ScopDetection &SD) {
Michael Krusecac948e2015-10-02 13:53:07 +00001384 assert(!Domain && "init must be called only once");
Tobias Grosser75805372011-04-29 06:27:02 +00001385
Johannes Doerfert32ae76e2015-09-10 13:12:02 +00001386 buildDomain();
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00001387 collectSurroundingLoops();
Michael Krusecac948e2015-10-02 13:53:07 +00001388 buildAccessRelations();
1389
1390 if (BB) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001391 deriveAssumptions(BB, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001392 } else {
1393 for (BasicBlock *Block : R->blocks()) {
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001394 deriveAssumptions(Block, SD);
Michael Krusecac948e2015-10-02 13:53:07 +00001395 }
1396 }
1397
Tobias Grosserd83b8a82015-08-20 19:08:11 +00001398 if (DetectReductions)
1399 checkForReductions();
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001400}
1401
Johannes Doerferte58a0122014-06-27 20:31:28 +00001402/// @brief Collect loads which might form a reduction chain with @p StoreMA
1403///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001404/// Check if the stored value for @p StoreMA is a binary operator with one or
1405/// two loads as operands. If the binary operand is commutative & associative,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001406/// used only once (by @p StoreMA) and its load operands are also used only
1407/// once, we have found a possible reduction chain. It starts at an operand
1408/// load and includes the binary operator and @p StoreMA.
1409///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001410/// Note: We allow only one use to ensure the load and binary operator cannot
Johannes Doerferte58a0122014-06-27 20:31:28 +00001411/// escape this block or into any other store except @p StoreMA.
1412void ScopStmt::collectCandiateReductionLoads(
1413 MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1414 auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1415 if (!Store)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001416 return;
1417
1418 // Skip if there is not one binary operator between the load and the store
1419 auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
Johannes Doerferte58a0122014-06-27 20:31:28 +00001420 if (!BinOp)
1421 return;
1422
1423 // Skip if the binary operators has multiple uses
1424 if (BinOp->getNumUses() != 1)
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001425 return;
1426
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001427 // Skip if the opcode of the binary operator is not commutative/associative
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001428 if (!BinOp->isCommutative() || !BinOp->isAssociative())
1429 return;
1430
Johannes Doerfert9890a052014-07-01 00:32:29 +00001431 // Skip if the binary operator is outside the current SCoP
1432 if (BinOp->getParent() != Store->getParent())
1433 return;
1434
Johannes Doerfert0ee1f212014-06-17 17:31:36 +00001435 // Skip if it is a multiplicative reduction and we disabled them
1436 if (DisableMultiplicativeReductions &&
1437 (BinOp->getOpcode() == Instruction::Mul ||
1438 BinOp->getOpcode() == Instruction::FMul))
1439 return;
1440
Johannes Doerferte58a0122014-06-27 20:31:28 +00001441 // Check the binary operator operands for a candidate load
1442 auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1443 auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1444 if (!PossibleLoad0 && !PossibleLoad1)
1445 return;
1446
1447 // A load is only a candidate if it cannot escape (thus has only this use)
1448 if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001449 if (PossibleLoad0->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001450 Loads.push_back(&getArrayAccessFor(PossibleLoad0));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001451 if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
Johannes Doerfert9890a052014-07-01 00:32:29 +00001452 if (PossibleLoad1->getParent() == Store->getParent())
Tobias Grosser35ec5fb2015-12-15 23:50:04 +00001453 Loads.push_back(&getArrayAccessFor(PossibleLoad1));
Johannes Doerferte58a0122014-06-27 20:31:28 +00001454}
1455
1456/// @brief Check for reductions in this ScopStmt
1457///
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001458/// Iterate over all store memory accesses and check for valid binary reduction
1459/// like chains. For all candidates we check if they have the same base address
1460/// and there are no other accesses which overlap with them. The base address
1461/// check rules out impossible reductions candidates early. The overlap check,
1462/// together with the "only one user" check in collectCandiateReductionLoads,
Johannes Doerferte58a0122014-06-27 20:31:28 +00001463/// guarantees that none of the intermediate results will escape during
1464/// execution of the loop nest. We basically check here that no other memory
1465/// access can access the same memory as the potential reduction.
1466void ScopStmt::checkForReductions() {
1467 SmallVector<MemoryAccess *, 2> Loads;
1468 SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1469
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001470 // First collect candidate load-store reduction chains by iterating over all
Johannes Doerferte58a0122014-06-27 20:31:28 +00001471 // stores and collecting possible reduction loads.
1472 for (MemoryAccess *StoreMA : MemAccs) {
1473 if (StoreMA->isRead())
1474 continue;
1475
1476 Loads.clear();
1477 collectCandiateReductionLoads(StoreMA, Loads);
1478 for (MemoryAccess *LoadMA : Loads)
1479 Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1480 }
1481
1482 // Then check each possible candidate pair.
1483 for (const auto &CandidatePair : Candidates) {
1484 bool Valid = true;
1485 isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1486 isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1487
1488 // Skip those with obviously unequal base addresses.
1489 if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1490 isl_map_free(LoadAccs);
1491 isl_map_free(StoreAccs);
1492 continue;
1493 }
1494
1495 // And check if the remaining for overlap with other memory accesses.
1496 isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1497 AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1498 isl_set *AllAccs = isl_map_range(AllAccsRel);
1499
1500 for (MemoryAccess *MA : MemAccs) {
1501 if (MA == CandidatePair.first || MA == CandidatePair.second)
1502 continue;
1503
1504 isl_map *AccRel =
1505 isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1506 isl_set *Accs = isl_map_range(AccRel);
1507
1508 if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
1509 isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1510 Valid = Valid && isl_set_is_empty(OverlapAccs);
1511 isl_set_free(OverlapAccs);
1512 }
1513 }
1514
1515 isl_set_free(AllAccs);
1516 if (!Valid)
1517 continue;
1518
Johannes Doerfertf6183392014-07-01 20:52:51 +00001519 const LoadInst *Load =
1520 dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1521 MemoryAccess::ReductionType RT =
1522 getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1523
Johannes Doerferte58a0122014-06-27 20:31:28 +00001524 // If no overlapping access was found we mark the load and store as
1525 // reduction like.
Johannes Doerfertf6183392014-07-01 20:52:51 +00001526 CandidatePair.first->markAsReductionLike(RT);
1527 CandidatePair.second->markAsReductionLike(RT);
Johannes Doerferte58a0122014-06-27 20:31:28 +00001528 }
Tobias Grosser75805372011-04-29 06:27:02 +00001529}
1530
Tobias Grosser74394f02013-01-14 22:40:23 +00001531std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001532
Tobias Grosser54839312015-04-21 11:37:25 +00001533std::string ScopStmt::getScheduleStr() const {
Tobias Grosser808cd692015-07-14 09:33:13 +00001534 auto *S = getSchedule();
1535 auto Str = stringFromIslObj(S);
1536 isl_map_free(S);
1537 return Str;
Tobias Grosser75805372011-04-29 06:27:02 +00001538}
1539
Michael Kruse375cb5f2016-02-24 22:08:24 +00001540BasicBlock *ScopStmt::getEntryBlock() const {
1541 if (isBlockStmt())
1542 return getBasicBlock();
1543 return getRegion()->getEntry();
1544}
1545
Michael Kruse7b5caa42016-02-24 22:08:28 +00001546RegionNode *ScopStmt::getRegionNode() const {
1547 if (isRegionStmt())
1548 return getRegion()->getNode();
1549 return getParent()->getRegion().getBBNode(getBasicBlock());
1550}
1551
Tobias Grosser74394f02013-01-14 22:40:23 +00001552unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001553
Tobias Grosserf567e1a2015-02-19 22:16:12 +00001554unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001555
Tobias Grosser75805372011-04-29 06:27:02 +00001556const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1557
Hongbin Zheng27f3afb2011-04-30 03:26:51 +00001558const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
Sebastian Pop860e0212013-02-15 21:26:44 +00001559 return NestLoops[Dimension];
Tobias Grosser75805372011-04-29 06:27:02 +00001560}
1561
Tobias Grosser74394f02013-01-14 22:40:23 +00001562isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
Tobias Grosser75805372011-04-29 06:27:02 +00001563
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001564__isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
Tobias Grosserd5a7bfc2011-05-06 19:52:19 +00001565
Tobias Grosser6e6c7e02015-03-30 12:22:39 +00001566__isl_give isl_space *ScopStmt::getDomainSpace() const {
Tobias Grosser78d8a3d2012-01-17 20:34:23 +00001567 return isl_set_get_space(Domain);
1568}
1569
Tobias Grosser4f663aa2015-03-30 11:52:59 +00001570__isl_give isl_id *ScopStmt::getDomainId() const {
1571 return isl_set_get_tuple_id(Domain);
1572}
Tobias Grossercd95b772012-08-30 11:49:38 +00001573
Tobias Grosser10120182015-12-16 16:14:03 +00001574ScopStmt::~ScopStmt() { isl_set_free(Domain); }
Tobias Grosser75805372011-04-29 06:27:02 +00001575
1576void ScopStmt::print(raw_ostream &OS) const {
1577 OS << "\t" << getBaseName() << "\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001578 OS.indent(12) << "Domain :=\n";
1579
1580 if (Domain) {
1581 OS.indent(16) << getDomainStr() << ";\n";
1582 } else
1583 OS.indent(16) << "n/a\n";
1584
Tobias Grosser54839312015-04-21 11:37:25 +00001585 OS.indent(12) << "Schedule :=\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001586
1587 if (Domain) {
Tobias Grosser54839312015-04-21 11:37:25 +00001588 OS.indent(16) << getScheduleStr() << ";\n";
Tobias Grosser75805372011-04-29 06:27:02 +00001589 } else
1590 OS.indent(16) << "n/a\n";
1591
Tobias Grosser083d3d32014-06-28 08:59:45 +00001592 for (MemoryAccess *Access : MemAccs)
1593 Access->print(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00001594}
1595
1596void ScopStmt::dump() const { print(dbgs()); }
1597
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001598void ScopStmt::removeMemoryAccesses(MemoryAccessList &InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001599 // Remove all memory accesses in @p InvMAs from this statement
1600 // together with all scalar accesses that were caused by them.
Michael Krusead28e5a2016-01-26 13:33:15 +00001601 // MK_Value READs have no access instruction, hence would not be removed by
1602 // this function. However, it is only used for invariant LoadInst accesses,
1603 // its arguments are always affine, hence synthesizable, and therefore there
1604 // are no MK_Value READ accesses to be removed.
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001605 for (MemoryAccess *MA : InvMAs) {
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001606 auto Predicate = [&](MemoryAccess *Acc) {
Tobias Grosser3a6ac9f2015-11-30 21:13:43 +00001607 return Acc->getAccessInstruction() == MA->getAccessInstruction();
Tobias Grosseref9ca5d2015-11-30 17:20:40 +00001608 };
1609 MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1610 MemAccs.end());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001611 InstructionToAccess.erase(MA->getAccessInstruction());
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001612 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00001613}
1614
Tobias Grosser75805372011-04-29 06:27:02 +00001615//===----------------------------------------------------------------------===//
1616/// Scop class implement
Tobias Grosser60b54f12011-11-08 15:41:28 +00001617
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001618void Scop::setContext(__isl_take isl_set *NewContext) {
Tobias Grosserff9b54d2011-11-15 11:38:44 +00001619 NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1620 isl_set_free(Context);
1621 Context = NewContext;
1622}
1623
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001624/// @brief Remap parameter values but keep AddRecs valid wrt. invariant loads.
1625struct SCEVSensitiveParameterRewriter
1626 : public SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *> {
1627 ValueToValueMap &VMap;
1628 ScalarEvolution &SE;
1629
1630public:
1631 SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1632 : VMap(VMap), SE(SE) {}
1633
1634 static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1635 ValueToValueMap &VMap) {
1636 SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1637 return SSPR.visit(E);
1638 }
1639
1640 const SCEV *visit(const SCEV *E) {
1641 return SCEVVisitor<SCEVSensitiveParameterRewriter, const SCEV *>::visit(E);
1642 }
1643
1644 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
1645
1646 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
1647 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
1648 }
1649
1650 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
1651 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
1652 }
1653
1654 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
1655 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
1656 }
1657
1658 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
1659 SmallVector<const SCEV *, 4> Operands;
1660 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1661 Operands.push_back(visit(E->getOperand(i)));
1662 return SE.getAddExpr(Operands);
1663 }
1664
1665 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
1666 SmallVector<const SCEV *, 4> Operands;
1667 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1668 Operands.push_back(visit(E->getOperand(i)));
1669 return SE.getMulExpr(Operands);
1670 }
1671
1672 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
1673 SmallVector<const SCEV *, 4> Operands;
1674 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1675 Operands.push_back(visit(E->getOperand(i)));
1676 return SE.getSMaxExpr(Operands);
1677 }
1678
1679 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
1680 SmallVector<const SCEV *, 4> Operands;
1681 for (int i = 0, e = E->getNumOperands(); i < e; ++i)
1682 Operands.push_back(visit(E->getOperand(i)));
1683 return SE.getUMaxExpr(Operands);
1684 }
1685
1686 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
1687 return SE.getUDivExpr(visit(E->getLHS()), visit(E->getRHS()));
1688 }
1689
1690 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1691 auto *Start = visit(E->getStart());
1692 auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1693 visit(E->getStepRecurrence(SE)),
1694 E->getLoop(), SCEV::FlagAnyWrap);
1695 return SE.getAddExpr(Start, AddRec);
1696 }
1697
1698 const SCEV *visitUnknown(const SCEVUnknown *E) {
1699 if (auto *NewValue = VMap.lookup(E->getValue()))
1700 return SE.getUnknown(NewValue);
1701 return E;
1702 }
1703};
1704
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001705const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
Johannes Doerfertd6fc0702015-11-03 16:47:58 +00001706 return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001707}
1708
Tobias Grosserabfbe632013-02-05 12:09:06 +00001709void Scop::addParams(std::vector<const SCEV *> NewParameters) {
Tobias Grosser083d3d32014-06-28 08:59:45 +00001710 for (const SCEV *Parameter : NewParameters) {
Johannes Doerfertbe409962015-03-29 20:45:09 +00001711 Parameter = extractConstantFactor(Parameter, *SE).second;
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001712
1713 // Normalize the SCEV to get the representing element for an invariant load.
1714 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1715
Tobias Grosser60b54f12011-11-08 15:41:28 +00001716 if (ParameterIds.find(Parameter) != ParameterIds.end())
1717 continue;
1718
1719 int dimension = Parameters.size();
1720
1721 Parameters.push_back(Parameter);
1722 ParameterIds[Parameter] = dimension;
1723 }
1724}
1725
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001726__isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001727 // Normalize the SCEV to get the representing element for an invariant load.
1728 Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1729
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001730 ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
Tobias Grosser76c2e322011-11-07 12:58:59 +00001731
Tobias Grosser9a38ab82011-11-08 15:41:03 +00001732 if (IdIter == ParameterIds.end())
Tobias Grosser5a56cbf2014-04-16 07:33:47 +00001733 return nullptr;
Tobias Grosser76c2e322011-11-07 12:58:59 +00001734
Tobias Grosser8f99c162011-11-15 11:38:55 +00001735 std::string ParameterName;
1736
Craig Topper7fb6e472016-01-31 20:36:20 +00001737 ParameterName = "p_" + utostr(IdIter->second);
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001738
Tobias Grosser8f99c162011-11-15 11:38:55 +00001739 if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1740 Value *Val = ValueParameter->getValue();
Tobias Grosser8f99c162011-11-15 11:38:55 +00001741
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001742 // If this parameter references a specific Value and this value has a name
1743 // we use this name as it is likely to be unique and more useful than just
1744 // a number.
1745 if (Val->hasName())
1746 ParameterName = Val->getName();
1747 else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001748 auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
Tobias Grosserb39c96a2015-11-17 11:54:51 +00001749 if (LoadOrigin->hasName()) {
1750 ParameterName += "_loaded_from_";
1751 ParameterName +=
1752 LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1753 }
1754 }
1755 }
Tobias Grosser8f99c162011-11-15 11:38:55 +00001756
Tobias Grosser20532b82014-04-11 17:56:49 +00001757 return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1758 const_cast<void *>((const void *)Parameter));
Tobias Grosser76c2e322011-11-07 12:58:59 +00001759}
Tobias Grosser75805372011-04-29 06:27:02 +00001760
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00001761isl_set *Scop::addNonEmptyDomainConstraints(isl_set *C) const {
1762 isl_set *DomainContext = isl_union_set_params(getDomains());
1763 return isl_set_intersect_params(C, DomainContext);
1764}
1765
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001766void Scop::buildBoundaryContext() {
Tobias Grosser4927c8e2015-11-24 12:50:02 +00001767 if (IgnoreIntegerWrapping) {
1768 BoundaryContext = isl_set_universe(getParamSpace());
1769 return;
1770 }
1771
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001772 BoundaryContext = Affinator.getWrappingContext();
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001773
1774 // The isl_set_complement operation used to create the boundary context
1775 // can possibly become very expensive. We bound the compile time of
1776 // this operation by setting a compute out.
1777 //
1778 // TODO: We can probably get around using isl_set_complement and directly
1779 // AST generate BoundaryContext.
1780 long MaxOpsOld = isl_ctx_get_max_operations(getIslCtx());
Tobias Grosserf920fb12015-11-13 16:56:13 +00001781 isl_ctx_reset_operations(getIslCtx());
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001782 isl_ctx_set_max_operations(getIslCtx(), 300000);
1783 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_CONTINUE);
1784
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001785 BoundaryContext = isl_set_complement(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001786
Tobias Grossera52b4da2015-11-11 17:59:53 +00001787 if (isl_ctx_last_error(getIslCtx()) == isl_error_quota) {
1788 isl_set_free(BoundaryContext);
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001789 BoundaryContext = isl_set_empty(getParamSpace());
Tobias Grossera52b4da2015-11-11 17:59:53 +00001790 }
Tobias Grosser4cd07b12015-11-11 17:34:02 +00001791
1792 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
1793 isl_ctx_reset_operations(getIslCtx());
1794 isl_ctx_set_max_operations(getIslCtx(), MaxOpsOld);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001795 BoundaryContext = isl_set_gist_params(BoundaryContext, getContext());
Johannes Doerfertd84493e2015-11-12 02:33:38 +00001796 trackAssumption(WRAPPING, BoundaryContext, DebugLoc());
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001797}
1798
Hongbin Zheng192f69a2016-02-13 15:12:54 +00001799void Scop::addUserAssumptions(AssumptionCache &AC, DominatorTree &DT,
1800 LoopInfo &LI) {
Johannes Doerfert2af10e22015-11-12 03:25:01 +00001801 auto *R = &getRegion();
1802 auto &F = *R->getEntry()->getParent();
1803 for (auto &Assumption : AC.assumptions()) {
1804 auto *CI = dyn_cast_or_null<CallInst>(Assumption);
1805 if (!CI || CI->getNumArgOperands() != 1)
1806 continue;
1807 if (!DT.dominates(CI->getParent(), R->getEntry()))
1808 continue;
1809
1810 auto *Val = CI->getArgOperand(0);
1811 std::vector<const SCEV *> Params;
1812 if (!isAffineParamConstraint(Val, R, *SE, Params)) {
1813 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1814 CI->getDebugLoc(),
1815 "Non-affine user assumption ignored.");
1816 continue;
1817 }
1818
1819 addParams(Params);
1820
1821 auto *L = LI.getLoopFor(CI->getParent());
1822 SmallVector<isl_set *, 2> ConditionSets;
1823 buildConditionSets(*this, Val, nullptr, L, Context, ConditionSets);
1824 assert(ConditionSets.size() == 2);
1825 isl_set_free(ConditionSets[1]);
1826
1827 auto *AssumptionCtx = ConditionSets[0];
1828 emitOptimizationRemarkAnalysis(
1829 F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1830 "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1831 Context = isl_set_intersect(Context, AssumptionCtx);
1832 }
1833}
1834
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001835void Scop::addUserContext() {
1836 if (UserContextStr.empty())
1837 return;
1838
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001839 isl_set *UserContext =
1840 isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001841 isl_space *Space = getParamSpace();
1842 if (isl_space_dim(Space, isl_dim_param) !=
1843 isl_set_dim(UserContext, isl_dim_param)) {
1844 auto SpaceStr = isl_space_to_str(Space);
1845 errs() << "Error: the context provided in -polly-context has not the same "
1846 << "number of dimensions than the computed context. Due to this "
1847 << "mismatch, the -polly-context option is ignored. Please provide "
1848 << "the context in the parameter space: " << SpaceStr << ".\n";
1849 free(SpaceStr);
1850 isl_set_free(UserContext);
1851 isl_space_free(Space);
1852 return;
1853 }
1854
1855 for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00001856 auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1857 auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
Tobias Grosser8a9c2352015-08-16 10:19:29 +00001858
1859 if (strcmp(NameContext, NameUserContext) != 0) {
1860 auto SpaceStr = isl_space_to_str(Space);
1861 errs() << "Error: the name of dimension " << i
1862 << " provided in -polly-context "
1863 << "is '" << NameUserContext << "', but the name in the computed "
1864 << "context is '" << NameContext
1865 << "'. Due to this name mismatch, "
1866 << "the -polly-context option is ignored. Please provide "
1867 << "the context in the parameter space: " << SpaceStr << ".\n";
1868 free(SpaceStr);
1869 isl_set_free(UserContext);
1870 isl_space_free(Space);
1871 return;
1872 }
1873
1874 UserContext =
1875 isl_set_set_dim_id(UserContext, isl_dim_param, i,
1876 isl_space_get_dim_id(Space, isl_dim_param, i));
1877 }
1878
1879 Context = isl_set_intersect(Context, UserContext);
1880 isl_space_free(Space);
1881}
1882
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00001883void Scop::buildInvariantEquivalenceClasses(ScopDetection &SD) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00001884 DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001885
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001886 const InvariantLoadsSetTy &RIL = *SD.getRequiredInvariantLoads(&getRegion());
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001887 for (LoadInst *LInst : RIL) {
1888 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
1889
Johannes Doerfert96e54712016-02-07 17:30:13 +00001890 Type *Ty = LInst->getType();
1891 LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001892 if (ClassRep) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00001893 InvEquivClassVMap[LInst] = ClassRep;
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00001894 continue;
1895 }
1896
1897 ClassRep = LInst;
Johannes Doerfert96e54712016-02-07 17:30:13 +00001898 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList(), nullptr,
1899 Ty);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00001900 }
1901}
1902
Tobias Grosser6be480c2011-11-08 15:41:13 +00001903void Scop::buildContext() {
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001904 isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
Tobias Grossere86109f2013-10-29 21:05:49 +00001905 Context = isl_set_universe(isl_space_copy(Space));
1906 AssumedContext = isl_set_universe(Space);
Tobias Grosser0e27e242011-10-06 00:03:48 +00001907}
1908
Tobias Grosser18daaca2012-05-22 10:47:27 +00001909void Scop::addParameterBounds() {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001910 for (const auto &ParamID : ParameterIds) {
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001911 int dim = ParamID.second;
Tobias Grosser18daaca2012-05-22 10:47:27 +00001912
Johannes Doerfert4f8ac3d2015-02-23 16:15:51 +00001913 ConstantRange SRange = SE->getSignedRange(ParamID.first);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001914
Johannes Doerferte7044942015-02-24 11:58:30 +00001915 Context = addRangeBoundsToSet(Context, SRange, dim, isl_dim_param);
Tobias Grosser18daaca2012-05-22 10:47:27 +00001916 }
1917}
1918
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001919void Scop::realignParams() {
Tobias Grosser6be480c2011-11-08 15:41:13 +00001920 // Add all parameters into a common model.
Hongbin Zheng8831eb72016-02-17 15:49:21 +00001921 isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
Tobias Grosser6be480c2011-11-08 15:41:13 +00001922
Tobias Grosser083d3d32014-06-28 08:59:45 +00001923 for (const auto &ParamID : ParameterIds) {
1924 const SCEV *Parameter = ParamID.first;
Tobias Grosser6be480c2011-11-08 15:41:13 +00001925 isl_id *id = getIdForParam(Parameter);
Tobias Grosser083d3d32014-06-28 08:59:45 +00001926 Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
Tobias Grosser6be480c2011-11-08 15:41:13 +00001927 }
1928
1929 // Align the parameters of all data structures to the model.
1930 Context = isl_set_align_params(Context, Space);
1931
Tobias Grosser7c3bad52015-05-27 05:16:57 +00001932 for (ScopStmt &Stmt : *this)
1933 Stmt.realignParams();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00001934}
1935
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001936static __isl_give isl_set *
1937simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
1938 const Scop &S) {
Johannes Doerfertf85ad042015-11-08 20:16:39 +00001939 // If we modelt all blocks in the SCoP that have side effects we can simplify
1940 // the context with the constraints that are needed for anything to be
1941 // executed at all. However, if we have error blocks in the SCoP we already
1942 // assumed some parameter combinations cannot occure and removed them from the
1943 // domains, thus we cannot use the remaining domain to simplify the
1944 // assumptions.
1945 if (!S.hasErrorBlock()) {
1946 isl_set *DomainParameters = isl_union_set_params(S.getDomains());
1947 AssumptionContext =
1948 isl_set_gist_params(AssumptionContext, DomainParameters);
1949 }
1950
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001951 AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
1952 return AssumptionContext;
1953}
1954
1955void Scop::simplifyContexts() {
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001956 // The parameter constraints of the iteration domains give us a set of
1957 // constraints that need to hold for all cases where at least a single
1958 // statement iteration is executed in the whole scop. We now simplify the
1959 // assumed context under the assumption that such constraints hold and at
1960 // least a single statement iteration is executed. For cases where no
1961 // statement instances are executed, the assumptions we have taken about
1962 // the executed code do not matter and can be changed.
1963 //
1964 // WARNING: This only holds if the assumptions we have taken do not reduce
1965 // the set of statement instances that are executed. Otherwise we
1966 // may run into a case where the iteration domains suggest that
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001967 // for a certain set of parameter constraints no code is executed,
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001968 // but in the original program some computation would have been
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001969 // performed. In such a case, modifying the run-time conditions and
1970 // possibly influencing the run-time check may cause certain scops
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001971 // to not be executed.
1972 //
1973 // Example:
1974 //
1975 // When delinearizing the following code:
1976 //
1977 // for (long i = 0; i < 100; i++)
1978 // for (long j = 0; j < m; j++)
1979 // A[i+p][j] = 1.0;
1980 //
1981 // we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00001982 // otherwise we would access out of bound data. Now, knowing that code is
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001983 // only executed for the case m >= 0, it is sufficient to assume p >= 0.
Johannes Doerfert883f8c12015-09-15 22:52:53 +00001984 AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
1985 BoundaryContext = simplifyAssumptionContext(BoundaryContext, *this);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00001986}
1987
Johannes Doerfertb164c792014-09-18 11:17:17 +00001988/// @brief Add the minimal/maximal access in @p Set to @p User.
Tobias Grosserb2f39922015-05-28 13:32:11 +00001989static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00001990 Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
1991 isl_pw_multi_aff *MinPMA, *MaxPMA;
1992 isl_pw_aff *LastDimAff;
1993 isl_aff *OneAff;
1994 unsigned Pos;
1995
Johannes Doerfert9143d672014-09-27 11:02:39 +00001996 // Restrict the number of parameters involved in the access as the lexmin/
1997 // lexmax computation will take too long if this number is high.
1998 //
1999 // Experiments with a simple test case using an i7 4800MQ:
2000 //
2001 // #Parameters involved | Time (in sec)
2002 // 6 | 0.01
2003 // 7 | 0.04
2004 // 8 | 0.12
2005 // 9 | 0.40
2006 // 10 | 1.54
2007 // 11 | 6.78
2008 // 12 | 30.38
2009 //
2010 if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2011 unsigned InvolvedParams = 0;
2012 for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2013 if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2014 InvolvedParams++;
2015
2016 if (InvolvedParams > RunTimeChecksMaxParameters) {
2017 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002018 return isl_stat_error;
Johannes Doerfert9143d672014-09-27 11:02:39 +00002019 }
2020 }
2021
Johannes Doerfertb6755bb2015-02-14 12:00:06 +00002022 Set = isl_set_remove_divs(Set);
2023
Johannes Doerfertb164c792014-09-18 11:17:17 +00002024 MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2025 MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2026
Johannes Doerfert219b20e2014-10-07 14:37:59 +00002027 MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2028 MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2029
Johannes Doerfertb164c792014-09-18 11:17:17 +00002030 // Adjust the last dimension of the maximal access by one as we want to
2031 // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2032 // we test during code generation might now point after the end of the
2033 // allocated array but we will never dereference it anyway.
2034 assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2035 "Assumed at least one output dimension");
2036 Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2037 LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2038 OneAff = isl_aff_zero_on_domain(
2039 isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2040 OneAff = isl_aff_add_constant_si(OneAff, 1);
2041 LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2042 MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2043
2044 MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2045
2046 isl_set_free(Set);
Tobias Grosserb2f39922015-05-28 13:32:11 +00002047 return isl_stat_ok;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002048}
2049
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002050static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2051 isl_set *Domain = MA->getStatement()->getDomain();
2052 Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2053 return isl_set_reset_tuple_id(Domain);
2054}
2055
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002056/// @brief Wrapper function to calculate minimal/maximal accesses to each array.
2057static bool calculateMinMaxAccess(__isl_take isl_union_map *Accesses,
Tobias Grosserbb853c22015-07-25 12:31:03 +00002058 __isl_take isl_union_set *Domains,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002059 Scop::MinMaxVectorTy &MinMaxAccesses) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002060
2061 Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2062 isl_union_set *Locations = isl_union_map_range(Accesses);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002063 Locations = isl_union_set_coalesce(Locations);
2064 Locations = isl_union_set_detect_equalities(Locations);
2065 bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002066 &MinMaxAccesses));
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002067 isl_union_set_free(Locations);
2068 return Valid;
2069}
2070
Johannes Doerfert96425c22015-08-30 21:13:53 +00002071/// @brief Helper to treat non-affine regions and basic blocks the same.
2072///
2073///{
2074
2075/// @brief Return the block that is the representing block for @p RN.
2076static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2077 return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2078 : RN->getNodeAs<BasicBlock>();
2079}
2080
2081/// @brief Return the @p idx'th block that is executed after @p RN.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002082static inline BasicBlock *
2083getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002084 if (RN->isSubRegion()) {
2085 assert(idx == 0);
2086 return RN->getNodeAs<Region>()->getExit();
2087 }
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002088 return TI->getSuccessor(idx);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002089}
2090
2091/// @brief Return the smallest loop surrounding @p RN.
2092static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2093 if (!RN->isSubRegion())
2094 return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2095
2096 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2097 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2098 while (L && NonAffineSubRegion->contains(L))
2099 L = L->getParentLoop();
2100 return L;
2101}
2102
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002103static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2104 if (!RN->isSubRegion())
2105 return 1;
2106
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002107 Region *R = RN->getNodeAs<Region>();
Tobias Grosser0dd4a9a2016-02-01 01:55:08 +00002108 return std::distance(R->block_begin(), R->block_end());
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002109}
2110
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002111static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2112 const DominatorTree &DT) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002113 if (!RN->isSubRegion())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002114 return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002115 for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002116 if (isErrorBlock(*BB, R, LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00002117 return true;
2118 return false;
2119}
2120
Johannes Doerfert96425c22015-08-30 21:13:53 +00002121///}
2122
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002123static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2124 unsigned Dim, Loop *L) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002125 Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002126 isl_id *DimId =
2127 isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2128 return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2129}
2130
Johannes Doerfert96425c22015-08-30 21:13:53 +00002131isl_set *Scop::getDomainConditions(ScopStmt *Stmt) {
Michael Kruse375cb5f2016-02-24 22:08:24 +00002132 return getDomainConditions(Stmt->getEntryBlock());
Johannes Doerfertcef616f2015-09-15 22:49:04 +00002133}
2134
2135isl_set *Scop::getDomainConditions(BasicBlock *BB) {
2136 assert(DomainMap.count(BB) && "Requested BB did not have a domain");
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002137 return isl_set_copy(DomainMap[BB]);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002138}
2139
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002140void Scop::removeErrorBlockDomains(ScopDetection &SD, DominatorTree &DT,
2141 LoopInfo &LI) {
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002142 auto removeDomains = [this, &DT](BasicBlock *Start) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002143 auto *BBNode = DT.getNode(Start);
2144 for (auto *ErrorChild : depth_first(BBNode)) {
2145 auto *ErrorChildBlock = ErrorChild->getBlock();
2146 auto *CurrentDomain = DomainMap[ErrorChildBlock];
2147 auto *Empty = isl_set_empty(isl_set_get_space(CurrentDomain));
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002148 DomainMap[ErrorChildBlock] = Empty;
2149 isl_set_free(CurrentDomain);
2150 }
2151 };
2152
Tobias Grosser5ef2bc32015-11-23 10:18:23 +00002153 SmallVector<Region *, 4> Todo = {&R};
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002154
2155 while (!Todo.empty()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00002156 auto *SubRegion = Todo.back();
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002157 Todo.pop_back();
2158
2159 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
2160 for (auto &Child : *SubRegion)
2161 Todo.push_back(Child.get());
2162 continue;
2163 }
2164 if (containsErrorBlock(SubRegion->getNode(), getRegion(), LI, DT))
2165 removeDomains(SubRegion->getEntry());
2166 }
2167
Johannes Doerferta90943d2016-02-21 16:37:25 +00002168 for (auto *BB : R.blocks())
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002169 if (isErrorBlock(*BB, R, LI, DT))
2170 removeDomains(BB);
2171}
2172
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002173void Scop::buildDomains(Region *R, ScopDetection &SD, DominatorTree &DT,
2174 LoopInfo &LI) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002175
Johannes Doerfert432658d2016-01-26 11:01:41 +00002176 bool IsOnlyNonAffineRegion = SD.isNonAffineSubRegion(R, R);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002177 auto *EntryBB = R->getEntry();
Johannes Doerfert432658d2016-01-26 11:01:41 +00002178 auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2179 int LD = getRelativeLoopDepth(L);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002180 auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002181
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002182 while (LD-- >= 0) {
2183 S = addDomainDimId(S, LD + 1, L);
2184 L = L->getParentLoop();
2185 }
2186
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002187 DomainMap[EntryBB] = S;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002188
Johannes Doerfert432658d2016-01-26 11:01:41 +00002189 if (IsOnlyNonAffineRegion)
Johannes Doerfert40fa56f2015-09-14 11:15:07 +00002190 return;
2191
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002192 buildDomainsWithBranchConstraints(R, SD, DT, LI);
2193 propagateDomainConstraints(R, SD, DT, LI);
Tobias Grosser9737c7b2015-11-22 11:06:51 +00002194
2195 // Error blocks and blocks dominated by them have been assumed to never be
2196 // executed. Representing them in the Scop does not add any value. In fact,
2197 // it is likely to cause issues during construction of the ScopStmts. The
2198 // contents of error blocks have not been verfied to be expressible and
2199 // will cause problems when building up a ScopStmt for them.
2200 // Furthermore, basic blocks dominated by error blocks may reference
2201 // instructions in the error block which, if the error block is not modeled,
2202 // can themselves not be constructed properly.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002203 removeErrorBlockDomains(SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002204}
2205
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002206void Scop::buildDomainsWithBranchConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002207 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002208 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002209
2210 // To create the domain for each block in R we iterate over all blocks and
2211 // subregions in R and propagate the conditions under which the current region
2212 // element is executed. To this end we iterate in reverse post order over R as
2213 // it ensures that we first visit all predecessors of a region node (either a
2214 // basic block or a subregion) before we visit the region node itself.
2215 // Initially, only the domain for the SCoP region entry block is set and from
2216 // there we propagate the current domain to all successors, however we add the
2217 // condition that the successor is actually executed next.
2218 // As we are only interested in non-loop carried constraints here we can
2219 // simply skip loop back edges.
2220
2221 ReversePostOrderTraversal<Region *> RTraversal(R);
2222 for (auto *RN : RTraversal) {
2223
2224 // Recurse for affine subregions but go on for basic blocks and non-affine
2225 // subregions.
2226 if (RN->isSubRegion()) {
2227 Region *SubRegion = RN->getNodeAs<Region>();
2228 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002229 buildDomainsWithBranchConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002230 continue;
2231 }
2232 }
2233
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002234 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf85ad042015-11-08 20:16:39 +00002235 HasErrorBlock = true;
Johannes Doerfertf5673802015-10-01 23:48:18 +00002236
Johannes Doerfert96425c22015-08-30 21:13:53 +00002237 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002238 TerminatorInst *TI = BB->getTerminator();
2239
Tobias Grosserb76cd3c2015-11-11 08:42:20 +00002240 if (isa<UnreachableInst>(TI))
2241 continue;
2242
Johannes Doerfertf5673802015-10-01 23:48:18 +00002243 isl_set *Domain = DomainMap.lookup(BB);
2244 if (!Domain) {
2245 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2246 << ", it is only reachable from error blocks.\n");
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002247 continue;
2248 }
2249
Johannes Doerfert96425c22015-08-30 21:13:53 +00002250 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002251
2252 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2253 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2254
2255 // Build the condition sets for the successor nodes of the current region
2256 // node. If it is a non-affine subregion we will always execute the single
2257 // exit node, hence the single entry node domain is the condition set. For
2258 // basic blocks we use the helper function buildConditionSets.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002259 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfert96425c22015-08-30 21:13:53 +00002260 if (RN->isSubRegion())
2261 ConditionSets.push_back(isl_set_copy(Domain));
2262 else
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002263 buildConditionSets(*this, TI, BBLoop, Domain, ConditionSets);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002264
2265 // Now iterate over the successors and set their initial domain based on
2266 // their condition set. We skip back edges here and have to be careful when
2267 // we leave a loop not to keep constraints over a dimension that doesn't
2268 // exist anymore.
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002269 assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
Johannes Doerfert96425c22015-08-30 21:13:53 +00002270 for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
Johannes Doerfert96425c22015-08-30 21:13:53 +00002271 isl_set *CondSet = ConditionSets[u];
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002272 BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002273
2274 // Skip back edges.
2275 if (DT.dominates(SuccBB, BB)) {
2276 isl_set_free(CondSet);
2277 continue;
2278 }
2279
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002280 // Do not adjust the number of dimensions if we enter a boxed loop or are
2281 // in a non-affine subregion or if the surrounding loop stays the same.
Johannes Doerfert96425c22015-08-30 21:13:53 +00002282 Loop *SuccBBLoop = LI.getLoopFor(SuccBB);
Johannes Doerfert6f50c292016-01-26 11:03:25 +00002283 while (BoxedLoops.count(SuccBBLoop))
2284 SuccBBLoop = SuccBBLoop->getParentLoop();
Johannes Doerfert634909c2015-10-04 14:57:41 +00002285
2286 if (BBLoop != SuccBBLoop) {
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002287
2288 // Check if the edge to SuccBB is a loop entry or exit edge. If so
2289 // adjust the dimensionality accordingly. Lastly, if we leave a loop
2290 // and enter a new one we need to drop the old constraints.
2291 int SuccBBLoopDepth = getRelativeLoopDepth(SuccBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002292 unsigned LoopDepthDiff = std::abs(BBLoopDepth - SuccBBLoopDepth);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002293 if (BBLoopDepth > SuccBBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002294 CondSet = isl_set_project_out(CondSet, isl_dim_set,
2295 isl_set_n_dim(CondSet) - LoopDepthDiff,
2296 LoopDepthDiff);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002297 } else if (SuccBBLoopDepth > BBLoopDepth) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002298 assert(LoopDepthDiff == 1);
Johannes Doerfertf08bd002015-08-31 13:56:32 +00002299 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002300 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002301 } else if (BBLoopDepth >= 0) {
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002302 assert(LoopDepthDiff <= 1);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002303 CondSet = isl_set_project_out(CondSet, isl_dim_set, BBLoopDepth, 1);
2304 CondSet = isl_set_add_dims(CondSet, isl_dim_set, 1);
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002305 CondSet = addDomainDimId(CondSet, SuccBBLoopDepth, SuccBBLoop);
Tobias Grosser2df884f2015-09-01 18:17:41 +00002306 }
Johannes Doerfert96425c22015-08-30 21:13:53 +00002307 }
2308
2309 // Set the domain for the successor or merge it with an existing domain in
2310 // case there are multiple paths (without loop back edges) to the
2311 // successor block.
2312 isl_set *&SuccDomain = DomainMap[SuccBB];
2313 if (!SuccDomain)
2314 SuccDomain = CondSet;
2315 else
2316 SuccDomain = isl_set_union(SuccDomain, CondSet);
2317
2318 SuccDomain = isl_set_coalesce(SuccDomain);
Tobias Grosser75dc40c2015-12-20 13:31:48 +00002319 if (isl_set_n_basic_set(SuccDomain) > MaxConjunctsInDomain) {
2320 auto *Empty = isl_set_empty(isl_set_get_space(SuccDomain));
2321 isl_set_free(SuccDomain);
2322 SuccDomain = Empty;
2323 invalidate(ERROR_DOMAINCONJUNCTS, DebugLoc());
2324 }
Johannes Doerfert634909c2015-10-04 14:57:41 +00002325 DEBUG(dbgs() << "\tSet SuccBB: " << SuccBB->getName() << " : "
2326 << SuccDomain << "\n");
Johannes Doerfert96425c22015-08-30 21:13:53 +00002327 }
2328 }
2329}
2330
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002331/// @brief Return the domain for @p BB wrt @p DomainMap.
2332///
2333/// This helper function will lookup @p BB in @p DomainMap but also handle the
2334/// case where @p BB is contained in a non-affine subregion using the region
2335/// tree obtained by @p RI.
2336static __isl_give isl_set *
2337getDomainForBlock(BasicBlock *BB, DenseMap<BasicBlock *, isl_set *> &DomainMap,
2338 RegionInfo &RI) {
2339 auto DIt = DomainMap.find(BB);
2340 if (DIt != DomainMap.end())
2341 return isl_set_copy(DIt->getSecond());
2342
2343 Region *R = RI.getRegionFor(BB);
2344 while (R->getEntry() == BB)
2345 R = R->getParent();
2346 return getDomainForBlock(R->getEntry(), DomainMap, RI);
2347}
2348
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002349void Scop::propagateDomainConstraints(Region *R, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002350 DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002351 // Iterate over the region R and propagate the domain constrains from the
2352 // predecessors to the current node. In contrast to the
2353 // buildDomainsWithBranchConstraints function, this one will pull the domain
2354 // information from the predecessors instead of pushing it to the successors.
2355 // Additionally, we assume the domains to be already present in the domain
2356 // map here. However, we iterate again in reverse post order so we know all
2357 // predecessors have been visited before a block or non-affine subregion is
2358 // visited.
2359
2360 // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2361 auto &BoxedLoops = *SD.getBoxedLoops(&getRegion());
2362
2363 ReversePostOrderTraversal<Region *> RTraversal(R);
2364 for (auto *RN : RTraversal) {
2365
2366 // Recurse for affine subregions but go on for basic blocks and non-affine
2367 // subregions.
2368 if (RN->isSubRegion()) {
2369 Region *SubRegion = RN->getNodeAs<Region>();
2370 if (!SD.isNonAffineSubRegion(SubRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002371 propagateDomainConstraints(SubRegion, SD, DT, LI);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002372 continue;
2373 }
2374 }
2375
Johannes Doerfertf5673802015-10-01 23:48:18 +00002376 // Get the domain for the current block and check if it was initialized or
2377 // not. The only way it was not is if this block is only reachable via error
2378 // blocks, thus will not be executed under the assumptions we make. Such
2379 // blocks have to be skipped as their predecessors might not have domains
2380 // either. It would not benefit us to compute the domain anyway, only the
2381 // domains of the error blocks that are reachable from non-error blocks
2382 // are needed to generate assumptions.
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002383 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Johannes Doerfertf5673802015-10-01 23:48:18 +00002384 isl_set *&Domain = DomainMap[BB];
2385 if (!Domain) {
2386 DEBUG(dbgs() << "\tSkip: " << BB->getName()
2387 << ", it is only reachable from error blocks.\n");
2388 DomainMap.erase(BB);
2389 continue;
2390 }
2391 DEBUG(dbgs() << "\tVisit: " << BB->getName() << " : " << Domain << "\n");
2392
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002393 Loop *BBLoop = getRegionNodeLoop(RN, LI);
2394 int BBLoopDepth = getRelativeLoopDepth(BBLoop);
2395
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002396 isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2397 for (auto *PredBB : predecessors(BB)) {
2398
2399 // Skip backedges
2400 if (DT.dominates(BB, PredBB))
2401 continue;
2402
2403 isl_set *PredBBDom = nullptr;
2404
2405 // Handle the SCoP entry block with its outside predecessors.
2406 if (!getRegion().contains(PredBB))
2407 PredBBDom = isl_set_universe(isl_set_get_space(PredDom));
2408
2409 if (!PredBBDom) {
2410 // Determine the loop depth of the predecessor and adjust its domain to
2411 // the domain of the current block. This can mean we have to:
2412 // o) Drop a dimension if this block is the exit of a loop, not the
2413 // header of a new loop and the predecessor was part of the loop.
2414 // o) Add an unconstrainted new dimension if this block is the header
2415 // of a loop and the predecessor is not part of it.
2416 // o) Drop the information about the innermost loop dimension when the
2417 // predecessor and the current block are surrounded by different
2418 // loops in the same depth.
2419 PredBBDom = getDomainForBlock(PredBB, DomainMap, *R->getRegionInfo());
2420 Loop *PredBBLoop = LI.getLoopFor(PredBB);
2421 while (BoxedLoops.count(PredBBLoop))
2422 PredBBLoop = PredBBLoop->getParentLoop();
2423
2424 int PredBBLoopDepth = getRelativeLoopDepth(PredBBLoop);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002425 unsigned LoopDepthDiff = std::abs(BBLoopDepth - PredBBLoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002426 if (BBLoopDepth < PredBBLoopDepth)
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002427 PredBBDom = isl_set_project_out(
2428 PredBBDom, isl_dim_set, isl_set_n_dim(PredBBDom) - LoopDepthDiff,
2429 LoopDepthDiff);
2430 else if (PredBBLoopDepth < BBLoopDepth) {
2431 assert(LoopDepthDiff == 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002432 PredBBDom = isl_set_add_dims(PredBBDom, isl_dim_set, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002433 } else if (BBLoop != PredBBLoop && BBLoopDepth >= 0) {
2434 assert(LoopDepthDiff <= 1);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002435 PredBBDom = isl_set_drop_constraints_involving_dims(
2436 PredBBDom, isl_dim_set, BBLoopDepth, 1);
Johannes Doerfertf4fa9872015-09-10 15:53:59 +00002437 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002438 }
2439
2440 PredDom = isl_set_union(PredDom, PredBBDom);
2441 }
2442
2443 // Under the union of all predecessor conditions we can reach this block.
Johannes Doerfertb20f1512015-09-15 22:11:49 +00002444 Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002445
Johannes Doerfertf32f5f22015-09-28 01:30:37 +00002446 if (BBLoop && BBLoop->getHeader() == BB && getRegion().contains(BBLoop))
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002447 addLoopBoundsToHeaderDomain(BBLoop, LI);
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002448
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002449 // Add assumptions for error blocks.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00002450 if (containsErrorBlock(RN, getRegion(), LI, DT)) {
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002451 IsOptimized = true;
2452 isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002453 addAssumption(ERRORBLOCK, isl_set_complement(DomPar),
2454 BB->getTerminator()->getDebugLoc());
Johannes Doerfert90db75e2015-09-10 17:51:27 +00002455 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002456 }
2457}
2458
2459/// @brief Create a map from SetSpace -> SetSpace where the dimensions @p Dim
2460/// is incremented by one and all other dimensions are equal, e.g.,
2461/// [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2462/// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2463static __isl_give isl_map *
2464createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2465 auto *MapSpace = isl_space_map_from_set(SetSpace);
2466 auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2467 for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2468 if (u != Dim)
2469 NextIterationMap =
2470 isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2471 auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2472 C = isl_constraint_set_constant_si(C, 1);
2473 C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2474 C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2475 NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2476 return NextIterationMap;
2477}
2478
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002479void Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002480 int LoopDepth = getRelativeLoopDepth(L);
2481 assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002482
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002483 BasicBlock *HeaderBB = L->getHeader();
2484 assert(DomainMap.count(HeaderBB));
2485 isl_set *&HeaderBBDom = DomainMap[HeaderBB];
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002486
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002487 isl_map *NextIterationMap =
2488 createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002489
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002490 isl_set *UnionBackedgeCondition =
2491 isl_set_empty(isl_set_get_space(HeaderBBDom));
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002492
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002493 SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2494 L->getLoopLatches(LatchBlocks);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002495
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002496 for (BasicBlock *LatchBB : LatchBlocks) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00002497
2498 // If the latch is only reachable via error statements we skip it.
2499 isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2500 if (!LatchBBDom)
2501 continue;
2502
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002503 isl_set *BackedgeCondition = nullptr;
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002504
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002505 TerminatorInst *TI = LatchBB->getTerminator();
2506 BranchInst *BI = dyn_cast<BranchInst>(TI);
2507 if (BI && BI->isUnconditional())
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002508 BackedgeCondition = isl_set_copy(LatchBBDom);
2509 else {
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002510 SmallVector<isl_set *, 8> ConditionSets;
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002511 int idx = BI->getSuccessor(0) != HeaderBB;
Johannes Doerfert9a132f32015-09-28 09:33:22 +00002512 buildConditionSets(*this, TI, L, LatchBBDom, ConditionSets);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002513
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002514 // Free the non back edge condition set as we do not need it.
2515 isl_set_free(ConditionSets[1 - idx]);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002516
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002517 BackedgeCondition = ConditionSets[idx];
Johannes Doerfert06c57b52015-09-20 15:00:20 +00002518 }
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002519
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002520 int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2521 assert(LatchLoopDepth >= LoopDepth);
2522 BackedgeCondition =
2523 isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2524 LatchLoopDepth - LoopDepth);
2525 UnionBackedgeCondition =
2526 isl_set_union(UnionBackedgeCondition, BackedgeCondition);
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002527 }
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002528
2529 isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2530 for (int i = 0; i < LoopDepth; i++)
2531 ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2532
2533 isl_set *UnionBackedgeConditionComplement =
2534 isl_set_complement(UnionBackedgeCondition);
2535 UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2536 UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2537 UnionBackedgeConditionComplement =
2538 isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2539 HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2540 HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2541
2542 auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2543 HeaderBBDom = Parts.second;
2544
Johannes Doerfert6a72a2a2015-09-20 16:59:23 +00002545 // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2546 // the bounded assumptions to the context as they are already implied by the
2547 // <nsw> tag.
2548 if (Affinator.hasNSWAddRecForLoop(L)) {
2549 isl_set_free(Parts.first);
2550 return;
2551 }
2552
Johannes Doerfertf2cc86e2015-09-20 16:15:32 +00002553 isl_set *UnboundedCtx = isl_set_params(Parts.first);
2554 isl_set *BoundedCtx = isl_set_complement(UnboundedCtx);
Johannes Doerfertd84493e2015-11-12 02:33:38 +00002555 addAssumption(INFINITELOOP, BoundedCtx,
2556 HeaderBB->getTerminator()->getDebugLoc());
Johannes Doerfert5b9ff8b2015-09-10 13:00:06 +00002557}
2558
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002559void Scop::buildAliasChecks(AliasAnalysis &AA) {
2560 if (!PollyUseRuntimeAliasChecks)
2561 return;
2562
2563 if (buildAliasGroups(AA))
2564 return;
2565
2566 // If a problem occurs while building the alias groups we need to delete
2567 // this SCoP and pretend it wasn't valid in the first place. To this end
2568 // we make the assumed context infeasible.
Tobias Grosser8d4f6262015-12-12 09:52:26 +00002569 invalidate(ALIASING, DebugLoc());
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002570
2571 DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2572 << " could not be created as the number of parameters involved "
2573 "is too high. The SCoP will be "
2574 "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2575 "the maximal number of parameters but be advised that the "
2576 "compile time might increase exponentially.\n\n");
2577}
2578
Johannes Doerfert9143d672014-09-27 11:02:39 +00002579bool Scop::buildAliasGroups(AliasAnalysis &AA) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002580 // To create sound alias checks we perform the following steps:
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002581 // o) Use the alias analysis and an alias set tracker to build alias sets
Johannes Doerfertb164c792014-09-18 11:17:17 +00002582 // for all memory accesses inside the SCoP.
2583 // o) For each alias set we then map the aliasing pointers back to the
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002584 // memory accesses we know, thus obtain groups of memory accesses which
Johannes Doerfertb164c792014-09-18 11:17:17 +00002585 // might alias.
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002586 // o) We divide each group based on the domains of the minimal/maximal
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002587 // accesses. That means two minimal/maximal accesses are only in a group
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002588 // if their access domains intersect, otherwise they are in different
2589 // ones.
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002590 // o) We partition each group into read only and non read only accesses.
Johannes Doerfert6cad9c42015-02-24 16:00:29 +00002591 // o) For each group with more than one base pointer we then compute minimal
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002592 // and maximal accesses to each array of a group in read only and non
2593 // read only partitions separately.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002594 using AliasGroupTy = SmallVector<MemoryAccess *, 4>;
2595
2596 AliasSetTracker AST(AA);
2597
2598 DenseMap<Value *, MemoryAccess *> PtrToAcc;
Johannes Doerfert13771732014-10-01 12:40:46 +00002599 DenseSet<Value *> HasWriteAccess;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002600 for (ScopStmt &Stmt : *this) {
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002601
2602 // Skip statements with an empty domain as they will never be executed.
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002603 isl_set *StmtDomain = Stmt.getDomain();
Johannes Doerfertf1ee2622014-10-06 17:43:00 +00002604 bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2605 isl_set_free(StmtDomain);
2606 if (StmtDomainEmpty)
2607 continue;
2608
Tobias Grosser7c3bad52015-05-27 05:16:57 +00002609 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00002610 if (MA->isScalarKind())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002611 continue;
Johannes Doerfert13771732014-10-01 12:40:46 +00002612 if (!MA->isRead())
2613 HasWriteAccess.insert(MA->getBaseAddr());
Michael Kruse70131d32016-01-27 17:09:17 +00002614 MemAccInst Acc(MA->getAccessInstruction());
Johannes Doerfertcea61932016-02-21 19:13:19 +00002615 if (MA->isRead() && Acc.isMemTransferInst())
2616 PtrToAcc[Acc.asMemTransferInst()->getSource()] = MA;
2617 else
2618 PtrToAcc[Acc.getPointerOperand()] = MA;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002619 AST.add(Acc);
2620 }
2621 }
2622
2623 SmallVector<AliasGroupTy, 4> AliasGroups;
2624 for (AliasSet &AS : AST) {
Johannes Doerfert74f68692014-10-08 02:23:48 +00002625 if (AS.isMustAlias() || AS.isForwardingAliasSet())
Johannes Doerfertb164c792014-09-18 11:17:17 +00002626 continue;
2627 AliasGroupTy AG;
Johannes Doerferta90943d2016-02-21 16:37:25 +00002628 for (auto &PR : AS)
Johannes Doerfertb164c792014-09-18 11:17:17 +00002629 AG.push_back(PtrToAcc[PR.getValue()]);
Johannes Doerfertcea61932016-02-21 19:13:19 +00002630 if (AG.size() < 2)
2631 continue;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002632 AliasGroups.push_back(std::move(AG));
2633 }
2634
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002635 // Split the alias groups based on their domain.
2636 for (unsigned u = 0; u < AliasGroups.size(); u++) {
2637 AliasGroupTy NewAG;
2638 AliasGroupTy &AG = AliasGroups[u];
2639 AliasGroupTy::iterator AGI = AG.begin();
2640 isl_set *AGDomain = getAccessDomain(*AGI);
2641 while (AGI != AG.end()) {
2642 MemoryAccess *MA = *AGI;
2643 isl_set *MADomain = getAccessDomain(MA);
2644 if (isl_set_is_disjoint(AGDomain, MADomain)) {
2645 NewAG.push_back(MA);
2646 AGI = AG.erase(AGI);
2647 isl_set_free(MADomain);
2648 } else {
2649 AGDomain = isl_set_union(AGDomain, MADomain);
2650 AGI++;
2651 }
2652 }
2653 if (NewAG.size() > 1)
2654 AliasGroups.push_back(std::move(NewAG));
2655 isl_set_free(AGDomain);
2656 }
2657
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002658 auto &F = *getRegion().getEntry()->getParent();
Tobias Grosserf4c24b22015-04-05 13:11:54 +00002659 MapVector<const Value *, SmallPtrSet<MemoryAccess *, 8>> ReadOnlyPairs;
Johannes Doerfert13771732014-10-01 12:40:46 +00002660 SmallPtrSet<const Value *, 4> NonReadOnlyBaseValues;
2661 for (AliasGroupTy &AG : AliasGroups) {
2662 NonReadOnlyBaseValues.clear();
2663 ReadOnlyPairs.clear();
2664
Johannes Doerferteeab05a2014-10-01 12:42:37 +00002665 if (AG.size() < 2) {
2666 AG.clear();
2667 continue;
2668 }
2669
Johannes Doerfert13771732014-10-01 12:40:46 +00002670 for (auto II = AG.begin(); II != AG.end();) {
Johannes Doerfert0cf4e0a2015-11-12 02:32:51 +00002671 emitOptimizationRemarkAnalysis(
2672 F.getContext(), DEBUG_TYPE, F,
2673 (*II)->getAccessInstruction()->getDebugLoc(),
2674 "Possibly aliasing pointer, use restrict keyword.");
2675
Johannes Doerfert13771732014-10-01 12:40:46 +00002676 Value *BaseAddr = (*II)->getBaseAddr();
2677 if (HasWriteAccess.count(BaseAddr)) {
2678 NonReadOnlyBaseValues.insert(BaseAddr);
2679 II++;
2680 } else {
2681 ReadOnlyPairs[BaseAddr].insert(*II);
2682 II = AG.erase(II);
2683 }
2684 }
2685
2686 // If we don't have read only pointers check if there are at least two
2687 // non read only pointers, otherwise clear the alias group.
Tobias Grosserbb853c22015-07-25 12:31:03 +00002688 if (ReadOnlyPairs.empty() && NonReadOnlyBaseValues.size() <= 1) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002689 AG.clear();
Johannes Doerfert13771732014-10-01 12:40:46 +00002690 continue;
2691 }
2692
2693 // If we don't have non read only pointers clear the alias group.
2694 if (NonReadOnlyBaseValues.empty()) {
2695 AG.clear();
2696 continue;
2697 }
2698
Johannes Doerfert9dd42ee2016-02-25 14:06:11 +00002699 // Check if we have non-affine accesses left, if so bail out as we cannot
2700 // generate a good access range yet.
2701 for (auto *MA : AG)
2702 if (!MA->isAffine()) {
2703 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2704 return false;
2705 }
2706 for (auto &ReadOnlyPair : ReadOnlyPairs)
2707 for (auto *MA : ReadOnlyPair.second)
2708 if (!MA->isAffine()) {
2709 invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
2710 return false;
2711 }
2712
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002713 // Calculate minimal and maximal accesses for non read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002714 MinMaxAliasGroups.emplace_back();
2715 MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
2716 MinMaxVectorTy &MinMaxAccessesNonReadOnly = pair.first;
2717 MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
2718 MinMaxAccessesNonReadOnly.reserve(AG.size());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002719
2720 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002721
2722 // AG contains only non read only accesses.
Johannes Doerfertb164c792014-09-18 11:17:17 +00002723 for (MemoryAccess *MA : AG)
2724 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
Johannes Doerfertb164c792014-09-18 11:17:17 +00002725
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002726 bool Valid = calculateMinMaxAccess(Accesses, getDomains(),
2727 MinMaxAccessesNonReadOnly);
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002728
2729 // Bail out if the number of values we need to compare is too large.
2730 // This is important as the number of comparisions grows quadratically with
2731 // the number of values we need to compare.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002732 if (!Valid || (MinMaxAccessesNonReadOnly.size() + !ReadOnlyPairs.empty() >
2733 RunTimeChecksMaxArraysPerGroup))
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002734 return false;
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002735
2736 // Calculate minimal and maximal accesses for read only accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002737 MinMaxAccessesReadOnly.reserve(ReadOnlyPairs.size());
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002738 Accesses = isl_union_map_empty(getParamSpace());
2739
2740 for (const auto &ReadOnlyPair : ReadOnlyPairs)
2741 for (MemoryAccess *MA : ReadOnlyPair.second)
2742 Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2743
Tobias Grosserdaaed0e2015-08-20 21:29:26 +00002744 Valid =
2745 calculateMinMaxAccess(Accesses, getDomains(), MinMaxAccessesReadOnly);
Johannes Doerfert9143d672014-09-27 11:02:39 +00002746
2747 if (!Valid)
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002748 return false;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002749 }
Johannes Doerfert9143d672014-09-27 11:02:39 +00002750
Tobias Grosser50d4e2e2015-03-28 14:50:32 +00002751 return true;
Johannes Doerfertb164c792014-09-18 11:17:17 +00002752}
2753
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002754/// @brief Get the smallest loop that contains @p R but is not in @p R.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002755static Loop *getLoopSurroundingRegion(Region &R, LoopInfo &LI) {
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002756 // Start with the smallest loop containing the entry and expand that
2757 // loop until it contains all blocks in the region. If there is a loop
2758 // containing all blocks in the region check if it is itself contained
2759 // and if so take the parent loop as it will be the smallest containing
2760 // the region but not contained by it.
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002761 Loop *L = LI.getLoopFor(R.getEntry());
Johannes Doerfertdec27df2015-11-21 16:56:13 +00002762 while (L) {
2763 bool AllContained = true;
2764 for (auto *BB : R.blocks())
2765 AllContained &= L->contains(BB);
2766 if (AllContained)
2767 break;
2768 L = L->getParentLoop();
2769 }
2770
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00002771 return L ? (R.contains(L) ? L->getParentLoop() : L) : nullptr;
2772}
2773
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002774static unsigned getMaxLoopDepthInRegion(const Region &R, LoopInfo &LI,
2775 ScopDetection &SD) {
2776
2777 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD.getBoxedLoops(&R);
2778
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002779 unsigned MinLD = INT_MAX, MaxLD = 0;
2780 for (BasicBlock *BB : R.blocks()) {
2781 if (Loop *L = LI.getLoopFor(BB)) {
David Peixottodc0a11c2015-01-13 18:31:55 +00002782 if (!R.contains(L))
2783 continue;
Johannes Doerfertf8206cf2015-04-12 22:58:40 +00002784 if (BoxedLoops && BoxedLoops->count(L))
2785 continue;
Johannes Doerferte3da05a2014-11-01 00:12:13 +00002786 unsigned LD = L->getLoopDepth();
2787 MinLD = std::min(MinLD, LD);
2788 MaxLD = std::max(MaxLD, LD);
2789 }
2790 }
2791
2792 // Handle the case that there is no loop in the SCoP first.
2793 if (MaxLD == 0)
2794 return 1;
2795
2796 assert(MinLD >= 1 && "Minimal loop depth should be at least one");
2797 assert(MaxLD >= MinLD &&
2798 "Maximal loop depth was smaller than mininaml loop depth?");
2799 return MaxLD - MinLD + 1;
2800}
2801
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002802Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, unsigned MaxLoopDepth)
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00002803 : SE(&ScalarEvolution), R(R), IsOptimized(false),
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002804 HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002805 MaxLoopDepth(MaxLoopDepth), IslCtx(isl_ctx_alloc(), isl_ctx_free),
2806 Context(nullptr), Affinator(this), AssumedContext(nullptr),
2807 BoundaryContext(nullptr), Schedule(nullptr) {
2808 isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
Tobias Grosserd840fc72016-02-04 13:18:42 +00002809 buildContext();
2810}
Johannes Doerfertff9d1982015-02-24 12:00:50 +00002811
Hongbin Zhengf53ffa62016-02-13 15:12:51 +00002812void Scop::init(AliasAnalysis &AA, AssumptionCache &AC, ScopDetection &SD,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002813 DominatorTree &DT, LoopInfo &LI) {
2814 addUserAssumptions(AC, DT, LI);
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002815 buildInvariantEquivalenceClasses(SD);
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002816
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002817 buildDomains(&R, SD, DT, LI);
Johannes Doerfert96425c22015-08-30 21:13:53 +00002818
Michael Krusecac948e2015-10-02 13:53:07 +00002819 // Remove empty and ignored statements.
Michael Kruseafe06702015-10-02 16:33:27 +00002820 // Exit early in case there are no executable statements left in this scop.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002821 simplifySCoP(true, DT, LI);
Michael Kruseafe06702015-10-02 16:33:27 +00002822 if (Stmts.empty())
2823 return;
Tobias Grosser75805372011-04-29 06:27:02 +00002824
Michael Krusecac948e2015-10-02 13:53:07 +00002825 // The ScopStmts now have enough information to initialize themselves.
2826 for (ScopStmt &Stmt : Stmts)
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002827 Stmt.init(SD);
Michael Krusecac948e2015-10-02 13:53:07 +00002828
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002829 buildSchedule(SD, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002830
Tobias Grosser8286b832015-11-02 11:29:32 +00002831 if (isl_set_is_empty(AssumedContext))
2832 return;
2833
2834 updateAccessDimensionality();
Tobias Grosser8cae72f2011-11-08 15:41:08 +00002835 realignParams();
Tobias Grosser18daaca2012-05-22 10:47:27 +00002836 addParameterBounds();
Tobias Grosser8a9c2352015-08-16 10:19:29 +00002837 addUserContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002838 buildBoundaryContext();
2839 simplifyContexts();
Johannes Doerfert120de4b2015-08-20 18:30:08 +00002840 buildAliasChecks(AA);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002841
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00002842 hoistInvariantLoads(SD);
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002843 simplifySCoP(false, DT, LI);
Tobias Grosser75805372011-04-29 06:27:02 +00002844}
2845
2846Scop::~Scop() {
2847 isl_set_free(Context);
Tobias Grossere86109f2013-10-29 21:05:49 +00002848 isl_set_free(AssumedContext);
Johannes Doerfert883f8c12015-09-15 22:52:53 +00002849 isl_set_free(BoundaryContext);
Tobias Grosser808cd692015-07-14 09:33:13 +00002850 isl_schedule_free(Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00002851
Johannes Doerfert96425c22015-08-30 21:13:53 +00002852 for (auto It : DomainMap)
2853 isl_set_free(It.second);
2854
Johannes Doerfertb164c792014-09-18 11:17:17 +00002855 // Free the alias groups
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002856 for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002857 for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
Johannes Doerfertb164c792014-09-18 11:17:17 +00002858 isl_pw_multi_aff_free(MMA.first);
2859 isl_pw_multi_aff_free(MMA.second);
2860 }
Johannes Doerfert210b09a2015-07-26 13:14:38 +00002861 for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00002862 isl_pw_multi_aff_free(MMA.first);
2863 isl_pw_multi_aff_free(MMA.second);
2864 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00002865 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002866
Johannes Doerfert697fdf82015-10-09 17:12:26 +00002867 for (const auto &IAClass : InvariantEquivClasses)
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002868 isl_set_free(std::get<2>(IAClass));
Hongbin Zheng8831eb72016-02-17 15:49:21 +00002869
2870 // Explicitly release all Scop objects and the underlying isl objects before
2871 // we relase the isl context.
2872 Stmts.clear();
2873 ScopArrayInfoMap.clear();
2874 AccFuncMap.clear();
Tobias Grosser75805372011-04-29 06:27:02 +00002875}
2876
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002877void Scop::updateAccessDimensionality() {
Johannes Doerfert4d9bb8d2016-02-18 16:50:12 +00002878 // Check all array accesses for each base pointer and find a (virtual) element
2879 // size for the base pointer that divides all access functions.
2880 for (auto &Stmt : *this)
2881 for (auto *Access : Stmt) {
2882 if (!Access->isArrayKind())
2883 continue;
2884 auto &SAI = ScopArrayInfoMap[std::make_pair(Access->getBaseAddr(),
2885 ScopArrayInfo::MK_Array)];
2886 if (SAI->getNumberOfDimensions() != 1)
2887 continue;
2888 unsigned DivisibleSize = SAI->getElemSizeInBytes();
2889 auto *Subscript = Access->getSubscript(0);
2890 while (!isDivisible(Subscript, DivisibleSize, *SE))
2891 DivisibleSize /= 2;
2892 auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
2893 SAI->updateElementType(Ty);
2894 }
2895
Tobias Grosser99c70dd2015-09-26 08:55:54 +00002896 for (auto &Stmt : *this)
2897 for (auto &Access : Stmt)
2898 Access->updateDimensionality();
2899}
2900
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002901void Scop::simplifySCoP(bool RemoveIgnoredStmts, DominatorTree &DT,
2902 LoopInfo &LI) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002903 for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
2904 ScopStmt &Stmt = *StmtIt;
Michael Kruse7b5caa42016-02-24 22:08:28 +00002905 RegionNode *RN = Stmt.getRegionNode();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002906
Johannes Doerferteca9e892015-11-03 16:54:49 +00002907 bool RemoveStmt = StmtIt->isEmpty();
2908 if (!RemoveStmt)
Michael Kruse375cb5f2016-02-24 22:08:24 +00002909 RemoveStmt = isl_set_is_empty(DomainMap[Stmt.getEntryBlock()]);
Johannes Doerferteca9e892015-11-03 16:54:49 +00002910 if (!RemoveStmt)
Hongbin Zheng192f69a2016-02-13 15:12:54 +00002911 RemoveStmt = (RemoveIgnoredStmts && isIgnored(RN, DT, LI));
Johannes Doerfertf17a78e2015-10-04 15:00:05 +00002912
Johannes Doerferteca9e892015-11-03 16:54:49 +00002913 // Remove read only statements only after invariant loop hoisting.
2914 if (!RemoveStmt && !RemoveIgnoredStmts) {
2915 bool OnlyRead = true;
2916 for (MemoryAccess *MA : Stmt) {
2917 if (MA->isRead())
2918 continue;
2919
2920 OnlyRead = false;
2921 break;
2922 }
2923
2924 RemoveStmt = OnlyRead;
2925 }
2926
2927 if (RemoveStmt) {
Michael Krusecac948e2015-10-02 13:53:07 +00002928 // Remove the statement because it is unnecessary.
2929 if (Stmt.isRegionStmt())
2930 for (BasicBlock *BB : Stmt.getRegion()->blocks())
2931 StmtMap.erase(BB);
2932 else
2933 StmtMap.erase(Stmt.getBasicBlock());
2934
2935 StmtIt = Stmts.erase(StmtIt);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002936 continue;
2937 }
2938
Michael Krusecac948e2015-10-02 13:53:07 +00002939 StmtIt++;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00002940 }
2941}
2942
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002943const InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) const {
2944 LoadInst *LInst = dyn_cast<LoadInst>(Val);
2945 if (!LInst)
2946 return nullptr;
2947
2948 if (Value *Rep = InvEquivClassVMap.lookup(LInst))
2949 LInst = cast<LoadInst>(Rep);
2950
Johannes Doerfert96e54712016-02-07 17:30:13 +00002951 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002952 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2953 for (auto &IAClass : InvariantEquivClasses)
Johannes Doerfert96e54712016-02-07 17:30:13 +00002954 if (PointerSCEV == std::get<0>(IAClass) && Ty == std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002955 return &IAClass;
2956
2957 return nullptr;
2958}
2959
2960void Scop::addInvariantLoads(ScopStmt &Stmt, MemoryAccessList &InvMAs) {
2961
2962 // Get the context under which the statement is executed.
2963 isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
2964 DomainCtx = isl_set_remove_redundancies(DomainCtx);
2965 DomainCtx = isl_set_detect_equalities(DomainCtx);
2966 DomainCtx = isl_set_coalesce(DomainCtx);
2967
2968 // Project out all parameters that relate to loads in the statement. Otherwise
2969 // we could have cyclic dependences on the constraints under which the
2970 // hoisted loads are executed and we could not determine an order in which to
2971 // pre-load them. This happens because not only lower bounds are part of the
2972 // domain but also upper bounds.
2973 for (MemoryAccess *MA : InvMAs) {
2974 Instruction *AccInst = MA->getAccessInstruction();
2975 if (SE->isSCEVable(AccInst->getType())) {
Johannes Doerfert44483c52015-11-07 19:45:27 +00002976 SetVector<Value *> Values;
2977 for (const SCEV *Parameter : Parameters) {
2978 Values.clear();
2979 findValues(Parameter, Values);
2980 if (!Values.count(AccInst))
2981 continue;
2982
2983 if (isl_id *ParamId = getIdForParam(Parameter)) {
2984 int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
2985 DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
2986 isl_id_free(ParamId);
2987 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002988 }
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002989 }
2990 }
2991
2992 for (MemoryAccess *MA : InvMAs) {
2993 // Check for another invariant access that accesses the same location as
2994 // MA and if found consolidate them. Otherwise create a new equivalence
2995 // class at the end of InvariantEquivClasses.
2996 LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
Johannes Doerfert96e54712016-02-07 17:30:13 +00002997 Type *Ty = LInst->getType();
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00002998 const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2999
3000 bool Consolidated = false;
3001 for (auto &IAClass : InvariantEquivClasses) {
Johannes Doerfert96e54712016-02-07 17:30:13 +00003002 if (PointerSCEV != std::get<0>(IAClass) || Ty != std::get<3>(IAClass))
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003003 continue;
3004
3005 Consolidated = true;
3006
3007 // Add MA to the list of accesses that are in this class.
3008 auto &MAs = std::get<1>(IAClass);
3009 MAs.push_front(MA);
3010
3011 // Unify the execution context of the class and this statement.
3012 isl_set *&IAClassDomainCtx = std::get<2>(IAClass);
Johannes Doerfertfc4bfc42015-11-11 04:30:07 +00003013 if (IAClassDomainCtx)
3014 IAClassDomainCtx = isl_set_coalesce(
3015 isl_set_union(IAClassDomainCtx, isl_set_copy(DomainCtx)));
3016 else
3017 IAClassDomainCtx = isl_set_copy(DomainCtx);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003018 break;
3019 }
3020
3021 if (Consolidated)
3022 continue;
3023
3024 // If we did not consolidate MA, thus did not find an equivalence class
3025 // for it, we create a new one.
3026 InvariantEquivClasses.emplace_back(PointerSCEV, MemoryAccessList{MA},
Johannes Doerfert96e54712016-02-07 17:30:13 +00003027 isl_set_copy(DomainCtx), Ty);
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003028 }
3029
3030 isl_set_free(DomainCtx);
3031}
3032
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003033bool Scop::isHoistableAccess(MemoryAccess *Access,
3034 __isl_keep isl_union_map *Writes) {
3035 // TODO: Loads that are not loop carried, hence are in a statement with
3036 // zero iterators, are by construction invariant, though we
3037 // currently "hoist" them anyway. This is necessary because we allow
3038 // them to be treated as parameters (e.g., in conditions) and our code
3039 // generation would otherwise use the old value.
3040
3041 auto &Stmt = *Access->getStatement();
Michael Kruse375cb5f2016-02-24 22:08:24 +00003042 BasicBlock *BB = Stmt.getEntryBlock();
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003043
3044 if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine())
3045 return false;
3046
3047 // Skip accesses that have an invariant base pointer which is defined but
3048 // not loaded inside the SCoP. This can happened e.g., if a readnone call
3049 // returns a pointer that is used as a base address. However, as we want
3050 // to hoist indirect pointers, we allow the base pointer to be defined in
3051 // the region if it is also a memory access. Each ScopArrayInfo object
3052 // that has a base pointer origin has a base pointer that is loaded and
3053 // that it is invariant, thus it will be hoisted too. However, if there is
3054 // no base pointer origin we check that the base pointer is defined
3055 // outside the region.
3056 const ScopArrayInfo *SAI = Access->getScopArrayInfo();
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003057 auto *BasePtrInst = dyn_cast<Instruction>(SAI->getBasePtr());
3058 if (SAI->getBasePtrOriginSAI()) {
3059 assert(BasePtrInst && R.contains(BasePtrInst));
3060 if (!isa<LoadInst>(BasePtrInst))
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003061 return false;
Michael Kruse6f7721f2016-02-24 22:08:19 +00003062 auto *BasePtrStmt = getStmtFor(BasePtrInst);
Johannes Doerfert4cf15802016-02-15 12:42:05 +00003063 assert(BasePtrStmt);
3064 auto *BasePtrMA = BasePtrStmt->getArrayAccessOrNULLFor(BasePtrInst);
3065 if (BasePtrMA && !isHoistableAccess(BasePtrMA, Writes))
3066 return false;
3067 } else if (BasePtrInst && R.contains(BasePtrInst))
3068 return false;
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003069
3070 // Skip accesses in non-affine subregions as they might not be executed
3071 // under the same condition as the entry of the non-affine subregion.
3072 if (BB != Access->getAccessInstruction()->getParent())
3073 return false;
3074
3075 isl_map *AccessRelation = Access->getAccessRelation();
3076
3077 // Skip accesses that have an empty access relation. These can be caused
3078 // by multiple offsets with a type cast in-between that cause the overall
3079 // byte offset to be not divisible by the new types sizes.
3080 if (isl_map_is_empty(AccessRelation)) {
3081 isl_map_free(AccessRelation);
3082 return false;
3083 }
3084
3085 if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3086 Stmt.getNumIterators())) {
3087 isl_map_free(AccessRelation);
3088 return false;
3089 }
3090
3091 AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3092 isl_set *AccessRange = isl_map_range(AccessRelation);
3093
3094 isl_union_map *Written = isl_union_map_intersect_range(
3095 isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3096 bool IsWritten = !isl_union_map_is_empty(Written);
3097 isl_union_map_free(Written);
3098
3099 if (IsWritten)
3100 return false;
3101
3102 return true;
3103}
3104
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003105void Scop::verifyInvariantLoads(ScopDetection &SD) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003106 auto &RIL = *SD.getRequiredInvariantLoads(&getRegion());
3107 for (LoadInst *LI : RIL) {
3108 assert(LI && getRegion().contains(LI));
Michael Kruse6f7721f2016-02-24 22:08:19 +00003109 ScopStmt *Stmt = getStmtFor(LI);
Tobias Grosser949e8c62015-12-21 07:10:39 +00003110 if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003111 invalidate(INVARIANTLOAD, LI->getDebugLoc());
3112 return;
3113 }
3114 }
3115}
3116
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003117void Scop::hoistInvariantLoads(ScopDetection &SD) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003118 isl_union_map *Writes = getWrites();
3119 for (ScopStmt &Stmt : *this) {
3120
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003121 MemoryAccessList InvariantAccesses;
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003122
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003123 for (MemoryAccess *Access : Stmt)
3124 if (isHoistableAccess(Access, Writes))
3125 InvariantAccesses.push_front(Access);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003126
3127 // We inserted invariant accesses always in the front but need them to be
3128 // sorted in a "natural order". The statements are already sorted in reverse
3129 // post order and that suffices for the accesses too. The reason we require
3130 // an order in the first place is the dependences between invariant loads
3131 // that can be caused by indirect loads.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003132 InvariantAccesses.reverse();
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003133
3134 // Transfer the memory access from the statement to the SCoP.
Tobias Grosser29f38ab2015-12-13 21:00:40 +00003135 Stmt.removeMemoryAccesses(InvariantAccesses);
3136 addInvariantLoads(Stmt, InvariantAccesses);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003137 }
3138 isl_union_map_free(Writes);
3139
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003140 verifyInvariantLoads(SD);
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003141}
3142
Johannes Doerfert80ef1102014-11-07 08:31:31 +00003143const ScopArrayInfo *
Tobias Grossercc779502016-02-02 13:22:54 +00003144Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003145 ArrayRef<const SCEV *> Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00003146 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003147 auto &SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)];
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003148 if (!SAI) {
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003149 auto &DL = getRegion().getEntry()->getModule()->getDataLayout();
Tobias Grossercc779502016-02-02 13:22:54 +00003150 SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
Johannes Doerfert55b3d8b2015-11-12 20:15:08 +00003151 DL, this));
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003152 } else {
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003153 SAI->updateElementType(ElementType);
Tobias Grosser8286b832015-11-02 11:29:32 +00003154 // In case of mismatching array sizes, we bail out by setting the run-time
3155 // context to false.
Johannes Doerfert3ff22212016-02-14 22:31:39 +00003156 if (!SAI->updateSizes(Sizes))
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003157 invalidate(DELINEARIZATION, DebugLoc());
Tobias Grosser99c70dd2015-09-26 08:55:54 +00003158 }
Tobias Grosserab671442015-05-23 05:58:27 +00003159 return SAI.get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003160}
3161
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003162const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr,
Tobias Grossera535dff2015-12-13 19:59:01 +00003163 ScopArrayInfo::MemoryKind Kind) {
Tobias Grosser6abc75a2015-11-10 17:31:31 +00003164 auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
Johannes Doerfert1a28a892014-10-05 11:32:18 +00003165 assert(SAI && "No ScopArrayInfo available for this base pointer");
3166 return SAI;
3167}
3168
Tobias Grosser74394f02013-01-14 22:40:23 +00003169std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003170
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003171std::string Scop::getAssumedContextStr() const {
3172 return stringFromIslObj(AssumedContext);
3173}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00003174
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003175std::string Scop::getBoundaryContextStr() const {
3176 return stringFromIslObj(BoundaryContext);
3177}
Tobias Grosser75805372011-04-29 06:27:02 +00003178
3179std::string Scop::getNameStr() const {
3180 std::string ExitName, EntryName;
3181 raw_string_ostream ExitStr(ExitName);
3182 raw_string_ostream EntryStr(EntryName);
3183
Tobias Grosserf240b482014-01-09 10:42:15 +00003184 R.getEntry()->printAsOperand(EntryStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003185 EntryStr.str();
3186
3187 if (R.getExit()) {
Tobias Grosserf240b482014-01-09 10:42:15 +00003188 R.getExit()->printAsOperand(ExitStr, false);
Tobias Grosser75805372011-04-29 06:27:02 +00003189 ExitStr.str();
3190 } else
3191 ExitName = "FunctionExit";
3192
3193 return EntryName + "---" + ExitName;
3194}
3195
Tobias Grosser74394f02013-01-14 22:40:23 +00003196__isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
Tobias Grosser37487052011-10-06 00:03:42 +00003197__isl_give isl_space *Scop::getParamSpace() const {
Tobias Grossereeb9f3c2015-05-26 21:37:31 +00003198 return isl_set_get_space(Context);
Tobias Grosser37487052011-10-06 00:03:42 +00003199}
3200
Tobias Grossere86109f2013-10-29 21:05:49 +00003201__isl_give isl_set *Scop::getAssumedContext() const {
3202 return isl_set_copy(AssumedContext);
3203}
3204
Johannes Doerfert43788c52015-08-20 05:58:56 +00003205__isl_give isl_set *Scop::getRuntimeCheckContext() const {
3206 isl_set *RuntimeCheckContext = getAssumedContext();
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003207 RuntimeCheckContext =
3208 isl_set_intersect(RuntimeCheckContext, getBoundaryContext());
3209 RuntimeCheckContext = simplifyAssumptionContext(RuntimeCheckContext, *this);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003210 return RuntimeCheckContext;
3211}
3212
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003213bool Scop::hasFeasibleRuntimeContext() const {
Johannes Doerfert43788c52015-08-20 05:58:56 +00003214 isl_set *RuntimeCheckContext = getRuntimeCheckContext();
Johannes Doerfert5d5b3062015-08-20 18:06:30 +00003215 RuntimeCheckContext = addNonEmptyDomainConstraints(RuntimeCheckContext);
Johannes Doerfert43788c52015-08-20 05:58:56 +00003216 bool IsFeasible = !isl_set_is_empty(RuntimeCheckContext);
3217 isl_set_free(RuntimeCheckContext);
3218 return IsFeasible;
3219}
3220
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003221static std::string toString(AssumptionKind Kind) {
3222 switch (Kind) {
3223 case ALIASING:
3224 return "No-aliasing";
3225 case INBOUNDS:
3226 return "Inbounds";
3227 case WRAPPING:
3228 return "No-overflows";
3229 case ERRORBLOCK:
3230 return "No-error";
3231 case INFINITELOOP:
3232 return "Finite loop";
3233 case INVARIANTLOAD:
3234 return "Invariant load";
3235 case DELINEARIZATION:
3236 return "Delinearization";
Tobias Grosser75dc40c2015-12-20 13:31:48 +00003237 case ERROR_DOMAINCONJUNCTS:
3238 return "Low number of domain conjuncts";
Johannes Doerfertd84493e2015-11-12 02:33:38 +00003239 }
3240 llvm_unreachable("Unknown AssumptionKind!");
3241}
3242
3243void Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3244 DebugLoc Loc) {
3245 if (isl_set_is_subset(Context, Set))
3246 return;
3247
3248 if (isl_set_is_subset(AssumedContext, Set))
3249 return;
3250
3251 auto &F = *getRegion().getEntry()->getParent();
3252 std::string Msg = toString(Kind) + " assumption:\t" + stringFromIslObj(Set);
3253 emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3254}
3255
3256void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3257 DebugLoc Loc) {
3258 trackAssumption(Kind, Set, Loc);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003259 AssumedContext = isl_set_intersect(AssumedContext, Set);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003260
Johannes Doerfert9d7899e2015-11-11 20:01:31 +00003261 int NSets = isl_set_n_basic_set(AssumedContext);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003262 if (NSets >= MaxDisjunctsAssumed) {
3263 isl_space *Space = isl_set_get_space(AssumedContext);
3264 isl_set_free(AssumedContext);
Tobias Grossere19fca42015-11-11 20:21:39 +00003265 AssumedContext = isl_set_empty(Space);
Tobias Grosser20a4c0c2015-11-11 16:22:36 +00003266 }
3267
Tobias Grosser7b50bee2014-11-25 10:51:12 +00003268 AssumedContext = isl_set_coalesce(AssumedContext);
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003269}
3270
Tobias Grosser8d4f6262015-12-12 09:52:26 +00003271void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
3272 addAssumption(Kind, isl_set_empty(getParamSpace()), Loc);
3273}
3274
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003275__isl_give isl_set *Scop::getBoundaryContext() const {
3276 return isl_set_copy(BoundaryContext);
3277}
3278
Tobias Grosser75805372011-04-29 06:27:02 +00003279void Scop::printContext(raw_ostream &OS) const {
3280 OS << "Context:\n";
3281
3282 if (!Context) {
3283 OS.indent(4) << "n/a\n\n";
3284 return;
3285 }
3286
3287 OS.indent(4) << getContextStr() << "\n";
Tobias Grosser60b54f12011-11-08 15:41:28 +00003288
Tobias Grosser5e6813d2014-07-02 17:47:48 +00003289 OS.indent(4) << "Assumed Context:\n";
3290 if (!AssumedContext) {
3291 OS.indent(4) << "n/a\n\n";
3292 return;
3293 }
3294
3295 OS.indent(4) << getAssumedContextStr() << "\n";
3296
Johannes Doerfert883f8c12015-09-15 22:52:53 +00003297 OS.indent(4) << "Boundary Context:\n";
3298 if (!BoundaryContext) {
3299 OS.indent(4) << "n/a\n\n";
3300 return;
3301 }
3302
3303 OS.indent(4) << getBoundaryContextStr() << "\n";
3304
Tobias Grosser083d3d32014-06-28 08:59:45 +00003305 for (const SCEV *Parameter : Parameters) {
Tobias Grosser60b54f12011-11-08 15:41:28 +00003306 int Dim = ParameterIds.find(Parameter)->second;
Tobias Grosser60b54f12011-11-08 15:41:28 +00003307 OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
3308 }
Tobias Grosser75805372011-04-29 06:27:02 +00003309}
3310
Johannes Doerfertb164c792014-09-18 11:17:17 +00003311void Scop::printAliasAssumptions(raw_ostream &OS) const {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003312 int noOfGroups = 0;
3313 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003314 if (Pair.second.size() == 0)
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003315 noOfGroups += 1;
3316 else
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003317 noOfGroups += Pair.second.size();
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003318 }
3319
Tobias Grosserbb853c22015-07-25 12:31:03 +00003320 OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
Johannes Doerfertb164c792014-09-18 11:17:17 +00003321 if (MinMaxAliasGroups.empty()) {
3322 OS.indent(8) << "n/a\n";
3323 return;
3324 }
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003325
Tobias Grosserbb853c22015-07-25 12:31:03 +00003326 for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003327
3328 // If the group has no read only accesses print the write accesses.
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003329 if (Pair.second.empty()) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003330 OS.indent(8) << "[[";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003331 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003332 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3333 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003334 }
3335 OS << " ]]\n";
3336 }
3337
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003338 for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003339 OS.indent(8) << "[[";
Tobias Grosserbb853c22015-07-25 12:31:03 +00003340 OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
Johannes Doerfert210b09a2015-07-26 13:14:38 +00003341 for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
Tobias Grosserbb853c22015-07-25 12:31:03 +00003342 OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
3343 << ">";
Johannes Doerfert338b42c2015-07-23 17:04:54 +00003344 }
3345 OS << " ]]\n";
3346 }
Johannes Doerfertb164c792014-09-18 11:17:17 +00003347 }
3348}
3349
Tobias Grosser75805372011-04-29 06:27:02 +00003350void Scop::printStatements(raw_ostream &OS) const {
3351 OS << "Statements {\n";
3352
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003353 for (const ScopStmt &Stmt : *this)
3354 OS.indent(4) << Stmt;
Tobias Grosser75805372011-04-29 06:27:02 +00003355
3356 OS.indent(4) << "}\n";
3357}
3358
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003359void Scop::printArrayInfo(raw_ostream &OS) const {
3360 OS << "Arrays {\n";
3361
Tobias Grosserab671442015-05-23 05:58:27 +00003362 for (auto &Array : arrays())
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003363 Array.second->print(OS);
3364
3365 OS.indent(4) << "}\n";
Tobias Grosserd46fd5e2015-08-12 15:27:16 +00003366
3367 OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
3368
3369 for (auto &Array : arrays())
3370 Array.second->print(OS, /* SizeAsPwAff */ true);
3371
3372 OS.indent(4) << "}\n";
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003373}
3374
Tobias Grosser75805372011-04-29 06:27:02 +00003375void Scop::print(raw_ostream &OS) const {
Tobias Grosser4eb7ddb2014-03-18 18:51:11 +00003376 OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
3377 << "\n";
Tobias Grosser483fdd42014-03-18 18:05:38 +00003378 OS.indent(4) << "Region: " << getNameStr() << "\n";
David Peixottodc0a11c2015-01-13 18:31:55 +00003379 OS.indent(4) << "Max Loop Depth: " << getMaxLoopDepth() << "\n";
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003380 OS.indent(4) << "Invariant Accesses: {\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003381 for (const auto &IAClass : InvariantEquivClasses) {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003382 const auto &MAs = std::get<1>(IAClass);
3383 if (MAs.empty()) {
3384 OS.indent(12) << "Class Pointer: " << *std::get<0>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003385 } else {
Johannes Doerfertaf3e3012015-10-18 12:39:19 +00003386 MAs.front()->print(OS);
3387 OS.indent(12) << "Execution Context: " << std::get<2>(IAClass) << "\n";
Johannes Doerfert697fdf82015-10-09 17:12:26 +00003388 }
Johannes Doerfertc1db67e2015-09-29 23:47:21 +00003389 }
3390 OS.indent(4) << "}\n";
Tobias Grosser75805372011-04-29 06:27:02 +00003391 printContext(OS.indent(4));
Tobias Grosser49ad36c2015-05-20 08:05:31 +00003392 printArrayInfo(OS.indent(4));
Johannes Doerfertb164c792014-09-18 11:17:17 +00003393 printAliasAssumptions(OS);
Tobias Grosser75805372011-04-29 06:27:02 +00003394 printStatements(OS.indent(4));
3395}
3396
3397void Scop::dump() const { print(dbgs()); }
3398
Hongbin Zheng8831eb72016-02-17 15:49:21 +00003399isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
Tobias Grosser75805372011-04-29 06:27:02 +00003400
Johannes Doerfertcef616f2015-09-15 22:49:04 +00003401__isl_give isl_pw_aff *Scop::getPwAff(const SCEV *E, BasicBlock *BB) {
3402 return Affinator.getPwAff(E, BB);
Johannes Doerfert574182d2015-08-12 10:19:50 +00003403}
3404
Tobias Grosser808cd692015-07-14 09:33:13 +00003405__isl_give isl_union_set *Scop::getDomains() const {
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003406 isl_union_set *Domain = isl_union_set_empty(getParamSpace());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003407
Tobias Grosser808cd692015-07-14 09:33:13 +00003408 for (const ScopStmt &Stmt : *this)
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003409 Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
Tobias Grosser5f9a7622012-02-14 14:02:40 +00003410
3411 return Domain;
3412}
3413
Tobias Grossere5a35142015-11-12 14:07:09 +00003414__isl_give isl_union_map *
3415Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
3416 isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003417
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003418 for (ScopStmt &Stmt : *this) {
3419 for (MemoryAccess *MA : Stmt) {
Tobias Grossere5a35142015-11-12 14:07:09 +00003420 if (!Predicate(*MA))
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003421 continue;
3422
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003423 isl_set *Domain = Stmt.getDomain();
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003424 isl_map *AccessDomain = MA->getAccessRelation();
3425 AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
Tobias Grossere5a35142015-11-12 14:07:09 +00003426 Accesses = isl_union_map_add_map(Accesses, AccessDomain);
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003427 }
3428 }
Tobias Grossere5a35142015-11-12 14:07:09 +00003429 return isl_union_map_coalesce(Accesses);
3430}
3431
3432__isl_give isl_union_map *Scop::getMustWrites() {
3433 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003434}
3435
3436__isl_give isl_union_map *Scop::getMayWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003437 return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
Tobias Grosser780ce0f2014-07-11 07:12:10 +00003438}
3439
Tobias Grosser37eb4222014-02-20 21:43:54 +00003440__isl_give isl_union_map *Scop::getWrites() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003441 return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003442}
3443
3444__isl_give isl_union_map *Scop::getReads() {
Tobias Grossere5a35142015-11-12 14:07:09 +00003445 return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
Tobias Grosser37eb4222014-02-20 21:43:54 +00003446}
3447
Tobias Grosser2ac23382015-11-12 14:07:13 +00003448__isl_give isl_union_map *Scop::getAccesses() {
3449 return getAccessesOfType([](MemoryAccess &MA) { return true; });
3450}
3451
Tobias Grosser808cd692015-07-14 09:33:13 +00003452__isl_give isl_union_map *Scop::getSchedule() const {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003453 auto *Tree = getScheduleTree();
3454 auto *S = isl_schedule_get_map(Tree);
Tobias Grosser808cd692015-07-14 09:33:13 +00003455 isl_schedule_free(Tree);
3456 return S;
3457}
Tobias Grosser37eb4222014-02-20 21:43:54 +00003458
Tobias Grosser808cd692015-07-14 09:33:13 +00003459__isl_give isl_schedule *Scop::getScheduleTree() const {
3460 return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
3461 getDomains());
3462}
Tobias Grosserbc4ef902014-06-28 08:59:38 +00003463
Tobias Grosser808cd692015-07-14 09:33:13 +00003464void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
3465 auto *S = isl_schedule_from_domain(getDomains());
3466 S = isl_schedule_insert_partial_schedule(
3467 S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
3468 isl_schedule_free(Schedule);
3469 Schedule = S;
3470}
3471
3472void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
3473 isl_schedule_free(Schedule);
3474 Schedule = NewSchedule;
Tobias Grosser37eb4222014-02-20 21:43:54 +00003475}
3476
3477bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
3478 bool Changed = false;
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003479 for (ScopStmt &Stmt : *this) {
3480 isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
Tobias Grosser37eb4222014-02-20 21:43:54 +00003481 isl_union_set *NewStmtDomain = isl_union_set_intersect(
3482 isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
3483
3484 if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
3485 isl_union_set_free(StmtDomain);
3486 isl_union_set_free(NewStmtDomain);
3487 continue;
3488 }
3489
3490 Changed = true;
3491
3492 isl_union_set_free(StmtDomain);
3493 NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
3494
3495 if (isl_union_set_is_empty(NewStmtDomain)) {
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003496 Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003497 isl_union_set_free(NewStmtDomain);
3498 } else
Tobias Grosser7c3bad52015-05-27 05:16:57 +00003499 Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
Tobias Grosser37eb4222014-02-20 21:43:54 +00003500 }
3501 isl_union_set_free(Domain);
3502 return Changed;
3503}
3504
Tobias Grosser75805372011-04-29 06:27:02 +00003505ScalarEvolution *Scop::getSE() const { return SE; }
3506
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003507bool Scop::isIgnored(RegionNode *RN, DominatorTree &DT, LoopInfo &LI) {
Johannes Doerfertf5673802015-10-01 23:48:18 +00003508 BasicBlock *BB = getRegionNodeBasicBlock(RN);
Michael Kruse6f7721f2016-02-24 22:08:19 +00003509 ScopStmt *Stmt = getStmtFor(RN);
Michael Krusea902ba62015-12-13 19:21:45 +00003510
3511 // If there is no stmt, then it already has been removed.
3512 if (!Stmt)
3513 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00003514
Johannes Doerfertf5673802015-10-01 23:48:18 +00003515 // Check if there are accesses contained.
Michael Krusea902ba62015-12-13 19:21:45 +00003516 if (Stmt->isEmpty())
Johannes Doerfertf5673802015-10-01 23:48:18 +00003517 return true;
3518
3519 // Check for reachability via non-error blocks.
3520 if (!DomainMap.count(BB))
3521 return true;
3522
3523 // Check if error blocks are contained.
Johannes Doerfert08d90a32015-10-07 20:32:43 +00003524 if (containsErrorBlock(RN, getRegion(), LI, DT))
Johannes Doerfertf5673802015-10-01 23:48:18 +00003525 return true;
3526
3527 return false;
Tobias Grosser75805372011-04-29 06:27:02 +00003528}
3529
Tobias Grosser808cd692015-07-14 09:33:13 +00003530struct MapToDimensionDataTy {
3531 int N;
3532 isl_union_pw_multi_aff *Res;
3533};
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003534
Tobias Grosser808cd692015-07-14 09:33:13 +00003535// @brief Create a function that maps the elements of 'Set' to its N-th
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003536// dimension and add it to User->Res.
Tobias Grosser808cd692015-07-14 09:33:13 +00003537//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003538// @param Set The input set.
3539// @param User->N The dimension to map to.
3540// @param User->Res The isl_union_pw_multi_aff to which to add the result.
Tobias Grosser808cd692015-07-14 09:33:13 +00003541//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003542// @returns isl_stat_ok if no error occured, othewise isl_stat_error.
Tobias Grosser808cd692015-07-14 09:33:13 +00003543static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
3544 struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
3545 int Dim;
3546 isl_space *Space;
3547 isl_pw_multi_aff *PMA;
3548
3549 Dim = isl_set_dim(Set, isl_dim_set);
3550 Space = isl_set_get_space(Set);
3551 PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
3552 Dim - Data->N);
3553 if (Data->N > 1)
3554 PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
3555 Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
3556
3557 isl_set_free(Set);
3558
3559 return isl_stat_ok;
Johannes Doerfertff9d1982015-02-24 12:00:50 +00003560}
3561
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003562// @brief Create an isl_multi_union_aff that defines an identity mapping
3563// from the elements of USet to their N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003564//
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003565// # Example:
3566//
3567// Domain: { A[i,j]; B[i,j,k] }
3568// N: 1
3569//
3570// Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
3571//
3572// @param USet A union set describing the elements for which to generate a
3573// mapping.
Tobias Grosser808cd692015-07-14 09:33:13 +00003574// @param N The dimension to map to.
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003575// @returns A mapping from USet to its N-th dimension.
Tobias Grosser808cd692015-07-14 09:33:13 +00003576static __isl_give isl_multi_union_pw_aff *
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003577mapToDimension(__isl_take isl_union_set *USet, int N) {
3578 assert(N >= 0);
Tobias Grosserc900633d2015-12-21 23:01:53 +00003579 assert(USet);
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003580 assert(!isl_union_set_is_empty(USet));
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003581
Tobias Grosser808cd692015-07-14 09:33:13 +00003582 struct MapToDimensionDataTy Data;
Tobias Grosser808cd692015-07-14 09:33:13 +00003583
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003584 auto *Space = isl_union_set_get_space(USet);
3585 auto *PwAff = isl_union_pw_multi_aff_empty(Space);
Tobias Grosser808cd692015-07-14 09:33:13 +00003586
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003587 Data = {N, PwAff};
3588
3589 auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
Sumanth Gundapaneni4b1472f2016-01-20 15:41:30 +00003590 (void)Res;
3591
Tobias Grossercbf7ae82015-12-21 22:45:53 +00003592 assert(Res == isl_stat_ok);
3593
3594 isl_union_set_free(USet);
Tobias Grosser808cd692015-07-14 09:33:13 +00003595 return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
3596}
3597
Tobias Grosser316b5b22015-11-11 19:28:14 +00003598void Scop::addScopStmt(BasicBlock *BB, Region *R) {
Tobias Grosser808cd692015-07-14 09:33:13 +00003599 if (BB) {
Michael Kruse9d080092015-09-11 21:41:48 +00003600 Stmts.emplace_back(*this, *BB);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003601 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003602 StmtMap[BB] = Stmt;
3603 } else {
3604 assert(R && "Either basic block or a region expected.");
Michael Kruse9d080092015-09-11 21:41:48 +00003605 Stmts.emplace_back(*this, *R);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003606 auto *Stmt = &Stmts.back();
Tobias Grosser808cd692015-07-14 09:33:13 +00003607 for (BasicBlock *BB : R->blocks())
3608 StmtMap[BB] = Stmt;
3609 }
Tobias Grosser808cd692015-07-14 09:33:13 +00003610}
3611
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003612void Scop::buildSchedule(ScopDetection &SD, LoopInfo &LI) {
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003613 Loop *L = getLoopSurroundingRegion(getRegion(), LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003614 LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003615 buildSchedule(getRegion().getNode(), LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003616 assert(LoopStack.size() == 1 && LoopStack.back().L == L);
3617 Schedule = LoopStack[0].Schedule;
Johannes Doerfertf9711ef2016-01-06 12:59:23 +00003618}
3619
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003620/// To generate a schedule for the elements in a Region we traverse the Region
3621/// in reverse-post-order and add the contained RegionNodes in traversal order
3622/// to the schedule of the loop that is currently at the top of the LoopStack.
3623/// For loop-free codes, this results in a correct sequential ordering.
3624///
3625/// Example:
3626/// bb1(0)
3627/// / \.
3628/// bb2(1) bb3(2)
3629/// \ / \.
3630/// bb4(3) bb5(4)
3631/// \ /
3632/// bb6(5)
3633///
3634/// Including loops requires additional processing. Whenever a loop header is
3635/// encountered, the corresponding loop is added to the @p LoopStack. Starting
3636/// from an empty schedule, we first process all RegionNodes that are within
3637/// this loop and complete the sequential schedule at this loop-level before
3638/// processing about any other nodes. To implement this
3639/// loop-nodes-first-processing, the reverse post-order traversal is
3640/// insufficient. Hence, we additionally check if the traversal yields
3641/// sub-regions or blocks that are outside the last loop on the @p LoopStack.
3642/// These region-nodes are then queue and only traverse after the all nodes
3643/// within the current loop have been processed.
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003644void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, ScopDetection &SD,
3645 LoopInfo &LI) {
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003646 Loop *OuterScopLoop = getLoopSurroundingRegion(getRegion(), LI);
3647
3648 ReversePostOrderTraversal<Region *> RTraversal(R);
3649 std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
3650 std::deque<RegionNode *> DelayList;
3651 bool LastRNWaiting = false;
3652
3653 // Iterate over the region @p R in reverse post-order but queue
3654 // sub-regions/blocks iff they are not part of the last encountered but not
3655 // completely traversed loop. The variable LastRNWaiting is a flag to indicate
3656 // that we queued the last sub-region/block from the reverse post-order
3657 // iterator. If it is set we have to explore the next sub-region/block from
3658 // the iterator (if any) to guarantee progress. If it is not set we first try
3659 // the next queued sub-region/blocks.
3660 while (!WorkList.empty() || !DelayList.empty()) {
3661 RegionNode *RN;
3662
3663 if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
3664 RN = WorkList.front();
3665 WorkList.pop_front();
3666 LastRNWaiting = false;
3667 } else {
3668 RN = DelayList.front();
3669 DelayList.pop_front();
3670 }
3671
3672 Loop *L = getRegionNodeLoop(RN, LI);
3673 if (!getRegion().contains(L))
3674 L = OuterScopLoop;
3675
3676 Loop *LastLoop = LoopStack.back().L;
3677 if (LastLoop != L) {
3678 if (!LastLoop->contains(L)) {
3679 LastRNWaiting = true;
3680 DelayList.push_back(RN);
3681 continue;
3682 }
3683 LoopStack.push_back({L, nullptr, 0});
3684 }
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003685 buildSchedule(RN, LoopStack, SD, LI);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003686 }
3687
3688 return;
3689}
3690
Hongbin Zheng7dddfba2016-02-13 15:12:47 +00003691void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack,
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003692 ScopDetection &SD, LoopInfo &LI) {
Michael Kruse046dde42015-08-10 13:01:57 +00003693
Tobias Grosser8362c262016-01-06 15:30:06 +00003694 if (RN->isSubRegion()) {
3695 auto *LocalRegion = RN->getNodeAs<Region>();
3696 if (!SD.isNonAffineSubRegion(LocalRegion, &getRegion())) {
Hongbin Zheng192f69a2016-02-13 15:12:54 +00003697 buildSchedule(LocalRegion, LoopStack, SD, LI);
Tobias Grosser8362c262016-01-06 15:30:06 +00003698 return;
3699 }
3700 }
Michael Kruse046dde42015-08-10 13:01:57 +00003701
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003702 auto &LoopData = LoopStack.back();
3703 LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
Tobias Grosser8362c262016-01-06 15:30:06 +00003704
Michael Kruse6f7721f2016-02-24 22:08:19 +00003705 if (auto *Stmt = getStmtFor(RN)) {
Tobias Grosser8362c262016-01-06 15:30:06 +00003706 auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
3707 auto *StmtSchedule = isl_schedule_from_domain(UDomain);
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003708 LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
Tobias Grosser8362c262016-01-06 15:30:06 +00003709 }
3710
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003711 // Check if we just processed the last node in this loop. If we did, finalize
3712 // the loop by:
3713 //
3714 // - adding new schedule dimensions
3715 // - folding the resulting schedule into the parent loop schedule
3716 // - dropping the loop schedule from the LoopStack.
3717 //
3718 // Then continue to check surrounding loops, which might also have been
3719 // completed by this node.
3720 while (LoopData.L &&
3721 LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003722 auto *Schedule = LoopData.Schedule;
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003723 auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
Tobias Grosser8362c262016-01-06 15:30:06 +00003724
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003725 LoopStack.pop_back();
3726 auto &NextLoopData = LoopStack.back();
Tobias Grosser8362c262016-01-06 15:30:06 +00003727
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003728 if (Schedule) {
3729 auto *Domain = isl_schedule_get_domain(Schedule);
3730 auto *MUPA = mapToDimension(Domain, LoopStack.size());
3731 Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
3732 NextLoopData.Schedule =
3733 combineInSequence(NextLoopData.Schedule, Schedule);
Tobias Grosser75805372011-04-29 06:27:02 +00003734 }
Johannes Doerfertb68cffb2015-09-10 15:27:46 +00003735
Tobias Grosserc2fd8b42016-02-01 11:54:13 +00003736 NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
3737 LoopData = NextLoopData;
Tobias Grosser808cd692015-07-14 09:33:13 +00003738 }
Tobias Grosser75805372011-04-29 06:27:02 +00003739}
3740
Michael Kruse6f7721f2016-02-24 22:08:19 +00003741ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
Tobias Grosser57411e32015-05-27 06:51:34 +00003742 auto StmtMapIt = StmtMap.find(BB);
Johannes Doerfert7c494212014-10-31 23:13:39 +00003743 if (StmtMapIt == StmtMap.end())
3744 return nullptr;
3745 return StmtMapIt->second;
3746}
3747
Michael Kruse6f7721f2016-02-24 22:08:19 +00003748ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
3749 if (RN->isSubRegion())
3750 return getStmtFor(RN->getNodeAs<Region>());
3751 return getStmtFor(RN->getNodeAs<BasicBlock>());
3752}
3753
3754ScopStmt *Scop::getStmtFor(Region *R) const {
3755 ScopStmt *Stmt = getStmtFor(R->getEntry());
3756 assert(!Stmt || Stmt->getRegion() == R);
3757 return Stmt;
Michael Krusea902ba62015-12-13 19:21:45 +00003758}
3759
Johannes Doerfert96425c22015-08-30 21:13:53 +00003760int Scop::getRelativeLoopDepth(const Loop *L) const {
3761 Loop *OuterLoop =
3762 L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
3763 if (!OuterLoop)
3764 return -1;
Johannes Doerfertd020b772015-08-27 06:53:52 +00003765 return L->getLoopDepth() - OuterLoop->getLoopDepth();
3766}
3767
Michael Krused868b5d2015-09-10 15:25:24 +00003768void ScopInfo::buildPHIAccesses(PHINode *PHI, Region &R,
Michael Krused868b5d2015-09-10 15:25:24 +00003769 Region *NonAffineSubRegion, bool IsExitBlock) {
Michael Kruse7bf39442015-09-10 12:46:52 +00003770
3771 // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
3772 // true, are not modeled as ordinary PHI nodes as they are not part of the
3773 // region. However, we model the operands in the predecessor blocks that are
3774 // part of the region as regular scalar accesses.
3775
3776 // If we can synthesize a PHI we can skip it, however only if it is in
3777 // the region. If it is not it can only be in the exit block of the region.
3778 // In this case we model the operands but not the PHI itself.
3779 if (!IsExitBlock && canSynthesize(PHI, LI, SE, &R))
3780 return;
3781
3782 // PHI nodes are modeled as if they had been demoted prior to the SCoP
3783 // detection. Hence, the PHI is a load of a new memory location in which the
3784 // incoming value was written at the end of the incoming basic block.
3785 bool OnlyNonAffineSubRegionOperands = true;
3786 for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
3787 Value *Op = PHI->getIncomingValue(u);
3788 BasicBlock *OpBB = PHI->getIncomingBlock(u);
3789
3790 // Do not build scalar dependences inside a non-affine subregion.
3791 if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB))
3792 continue;
3793
3794 OnlyNonAffineSubRegionOperands = false;
Michael Kruseee6a4fc2016-01-26 13:33:27 +00003795 ensurePHIWrite(PHI, OpBB, Op, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00003796 }
3797
Michael Kruse33d6c0b2015-09-25 18:53:27 +00003798 if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
3799 addPHIReadAccess(PHI);
Michael Kruse7bf39442015-09-10 12:46:52 +00003800 }
3801}
3802
Michael Kruse2e02d562016-02-06 09:19:40 +00003803void ScopInfo::buildScalarDependences(Instruction *Inst) {
3804 assert(!isa<PHINode>(Inst));
Michael Kruse7bf39442015-09-10 12:46:52 +00003805
Michael Kruse2e02d562016-02-06 09:19:40 +00003806 // Pull-in required operands.
3807 for (Use &Op : Inst->operands())
3808 ensureValueRead(Op.get(), Inst->getParent());
3809}
Michael Kruse7bf39442015-09-10 12:46:52 +00003810
Michael Kruse2e02d562016-02-06 09:19:40 +00003811void ScopInfo::buildEscapingDependences(Instruction *Inst) {
3812 Region *R = &scop->getRegion();
Michael Kruse7bf39442015-09-10 12:46:52 +00003813
Michael Kruse2e02d562016-02-06 09:19:40 +00003814 // Check for uses of this instruction outside the scop. Because we do not
3815 // iterate over such instructions and therefore did not "ensure" the existence
3816 // of a write, we must determine such use here.
3817 for (Use &U : Inst->uses()) {
3818 Instruction *UI = dyn_cast<Instruction>(U.getUser());
3819 if (!UI)
Michael Kruse7bf39442015-09-10 12:46:52 +00003820 continue;
3821
Michael Kruse2e02d562016-02-06 09:19:40 +00003822 BasicBlock *UseParent = getUseBlock(U);
3823 BasicBlock *UserParent = UI->getParent();
Michael Kruse7bf39442015-09-10 12:46:52 +00003824
Michael Kruse2e02d562016-02-06 09:19:40 +00003825 // An escaping value is either used by an instruction not within the scop,
3826 // or (when the scop region's exit needs to be simplified) by a PHI in the
3827 // scop's exit block. This is because region simplification before code
3828 // generation inserts new basic blocks before the PHI such that its incoming
3829 // blocks are not in the scop anymore.
3830 if (!R->contains(UseParent) ||
3831 (isa<PHINode>(UI) && UserParent == R->getExit() &&
3832 R->getExitingBlock())) {
3833 // At least one escaping use found.
3834 ensureValueWrite(Inst);
3835 break;
Michael Kruse7bf39442015-09-10 12:46:52 +00003836 }
3837 }
Michael Kruse7bf39442015-09-10 12:46:52 +00003838}
3839
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003840bool ScopInfo::buildAccessMultiDimFixed(
Michael Kruse70131d32016-01-27 17:09:17 +00003841 MemAccInst Inst, Loop *L, Region *R,
Johannes Doerfert09e36972015-10-07 20:17:36 +00003842 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3843 const InvariantLoadsSetTy &ScopRIL) {
Michael Kruse70131d32016-01-27 17:09:17 +00003844 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003845 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003846 Value *Address = Inst.getPointerOperand();
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003847 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
Michael Kruse7bf39442015-09-10 12:46:52 +00003848 const SCEVUnknown *BasePointer =
3849 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003850 enum MemoryAccess::AccessType Type =
3851 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00003852
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003853 if (isa<GetElementPtrInst>(Address) || isa<BitCastInst>(Address)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003854 auto *NewAddress = Address;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003855 if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
Johannes Doerferta90943d2016-02-21 16:37:25 +00003856 auto *Src = BitCast->getOperand(0);
3857 auto *SrcTy = Src->getType();
3858 auto *DstTy = BitCast->getType();
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003859 if (SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits())
3860 NewAddress = Src;
3861 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003862
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003863 if (auto *GEP = dyn_cast<GetElementPtrInst>(NewAddress)) {
3864 std::vector<const SCEV *> Subscripts;
3865 std::vector<int> Sizes;
3866 std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, *SE);
Johannes Doerferta90943d2016-02-21 16:37:25 +00003867 auto *BasePtr = GEP->getOperand(0);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003868
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003869 std::vector<const SCEV *> SizesSCEV;
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003870
Johannes Doerferta90943d2016-02-21 16:37:25 +00003871 for (auto *Subscript : Subscripts) {
Johannes Doerfert09e36972015-10-07 20:17:36 +00003872 InvariantLoadsSetTy AccessILS;
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003873 if (!isAffineExpr(R, Subscript, *SE, nullptr, &AccessILS))
3874 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003875
3876 for (LoadInst *LInst : AccessILS)
3877 if (!ScopRIL.count(LInst))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003878 return false;
Johannes Doerfert09e36972015-10-07 20:17:36 +00003879 }
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003880
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003881 if (Sizes.size() > 0) {
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003882 for (auto V : Sizes)
3883 SizesSCEV.push_back(SE->getSCEV(ConstantInt::get(
3884 IntegerType::getInt64Ty(BasePtr->getContext()), V)));
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003885
Johannes Doerfertcea61932016-02-21 19:13:19 +00003886 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, true,
Tobias Grossera535dff2015-12-13 19:59:01 +00003887 Subscripts, SizesSCEV, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003888 return true;
Tobias Grosser6f36d9a2015-09-17 20:16:21 +00003889 }
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003890 }
3891 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003892 return false;
3893}
3894
3895bool ScopInfo::buildAccessMultiDimParam(
3896 MemAccInst Inst, Loop *L, Region *R,
3897 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00003898 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003899 Value *Address = Inst.getPointerOperand();
3900 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00003901 Type *ElementType = Val->getType();
3902 unsigned ElementSize = DL->getTypeAllocSize(ElementType);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003903 enum MemoryAccess::AccessType Type =
3904 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
3905
3906 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
3907 const SCEVUnknown *BasePointer =
3908 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
3909
3910 assert(BasePointer && "Could not find base pointer");
3911 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Tobias Grosser5fd8c092015-09-17 17:28:15 +00003912
Michael Kruse7bf39442015-09-10 12:46:52 +00003913 auto AccItr = InsnToMemAcc.find(Inst);
Michael Krusee2bccbb2015-09-18 19:59:43 +00003914 if (PollyDelinearize && AccItr != InsnToMemAcc.end()) {
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003915 std::vector<const SCEV *> Sizes(
3916 AccItr->second.Shape->DelinearizedSizes.begin(),
3917 AccItr->second.Shape->DelinearizedSizes.end());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003918 // Remove the element size. This information is already provided by the
Tobias Grosserd840fc72016-02-04 13:18:42 +00003919 // ElementSize parameter. In case the element size of this access and the
3920 // element size used for delinearization differs the delinearization is
3921 // incorrect. Hence, we invalidate the scop.
3922 //
3923 // TODO: Handle delinearization with differing element sizes.
3924 auto DelinearizedSize =
3925 cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003926 Sizes.pop_back();
Tobias Grosserd840fc72016-02-04 13:18:42 +00003927 if (ElementSize != DelinearizedSize)
3928 scop->invalidate(DELINEARIZATION, Inst.getDebugLoc());
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003929
Johannes Doerfertcea61932016-02-21 19:13:19 +00003930 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, true,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00003931 AccItr->second.DelinearizedSubscripts, Sizes, Val);
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003932 return true;
Michael Krusee2bccbb2015-09-18 19:59:43 +00003933 }
Tobias Grosserdb543ed2016-02-02 16:46:49 +00003934 return false;
3935}
3936
Johannes Doerfertcea61932016-02-21 19:13:19 +00003937bool ScopInfo::buildAccessMemIntrinsic(
3938 MemAccInst Inst, Loop *L, Region *R,
3939 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3940 const InvariantLoadsSetTy &ScopRIL) {
3941 if (!Inst.isMemIntrinsic())
3942 return false;
3943
3944 auto *LengthVal = SE->getSCEVAtScope(Inst.asMemIntrinsic()->getLength(), L);
3945 assert(LengthVal);
3946
Johannes Doerferta7920982016-02-25 14:08:48 +00003947 // Check if the length val is actually affine or if we overapproximate it
3948 InvariantLoadsSetTy AccessILS;
3949 bool LengthIsAffine = isAffineExpr(R, LengthVal, *SE, nullptr, &AccessILS);
3950 for (LoadInst *LInst : AccessILS)
3951 if (!ScopRIL.count(LInst))
3952 LengthIsAffine = false;
3953 if (!LengthIsAffine)
3954 LengthVal = nullptr;
3955
Johannes Doerfertcea61932016-02-21 19:13:19 +00003956 auto *DestPtrVal = Inst.asMemIntrinsic()->getDest();
3957 assert(DestPtrVal);
3958 auto *DestAccFunc = SE->getSCEVAtScope(DestPtrVal, L);
3959 assert(DestAccFunc);
3960 auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(DestAccFunc));
3961 assert(DestPtrSCEV);
3962 DestAccFunc = SE->getMinusSCEV(DestAccFunc, DestPtrSCEV);
3963 addArrayAccess(Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
3964 IntegerType::getInt8Ty(DestPtrVal->getContext()), false,
3965 {DestAccFunc, LengthVal}, {}, Inst.getValueOperand());
3966
3967 if (!Inst.isMemTransferInst())
3968 return true;
3969
3970 auto *SrcPtrVal = Inst.asMemTransferInst()->getSource();
3971 assert(SrcPtrVal);
3972 auto *SrcAccFunc = SE->getSCEVAtScope(SrcPtrVal, L);
3973 assert(SrcAccFunc);
3974 auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccFunc));
3975 assert(SrcPtrSCEV);
3976 SrcAccFunc = SE->getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
3977 addArrayAccess(Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
3978 IntegerType::getInt8Ty(SrcPtrVal->getContext()), false,
3979 {SrcAccFunc, LengthVal}, {}, Inst.getValueOperand());
3980
3981 return true;
3982}
3983
Johannes Doerferta7920982016-02-25 14:08:48 +00003984bool ScopInfo::buildAccessCallInst(
3985 MemAccInst Inst, Loop *L, Region *R,
3986 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
3987 const InvariantLoadsSetTy &ScopRIL) {
3988 if (!Inst.isCallInst())
3989 return false;
3990
3991 auto &CI = *Inst.asCallInst();
3992 if (CI.doesNotAccessMemory() || isIgnoredIntrinsic(&CI))
3993 return true;
3994
3995 bool ReadOnly = false;
3996 auto *AF = SE->getConstant(IntegerType::getInt64Ty(CI.getContext()), 0);
3997 auto *CalledFunction = CI.getCalledFunction();
3998 switch (AA->getModRefBehavior(CalledFunction)) {
3999 case llvm::FMRB_UnknownModRefBehavior:
4000 llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
4001 case llvm::FMRB_DoesNotAccessMemory:
4002 return true;
4003 case llvm::FMRB_OnlyReadsMemory:
4004 GlobalReads.push_back(&CI);
4005 return true;
4006 case llvm::FMRB_OnlyReadsArgumentPointees:
4007 ReadOnly = true;
4008 // Fall through
4009 case llvm::FMRB_OnlyAccessesArgumentPointees:
4010 auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
4011 for (const auto &Arg : CI.arg_operands()) {
4012 if (!Arg->getType()->isPointerTy())
4013 continue;
4014
4015 auto *ArgSCEV = SE->getSCEVAtScope(Arg, L);
4016 if (ArgSCEV->isZero())
4017 continue;
4018
4019 auto *ArgBasePtr = cast<SCEVUnknown>(SE->getPointerBase(ArgSCEV));
4020 addArrayAccess(Inst, AccType, ArgBasePtr->getValue(),
4021 ArgBasePtr->getType(), false, {AF}, {}, &CI);
4022 }
4023 return true;
4024 }
4025
4026 return true;
4027}
4028
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004029void ScopInfo::buildAccessSingleDim(
4030 MemAccInst Inst, Loop *L, Region *R,
4031 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
4032 const InvariantLoadsSetTy &ScopRIL) {
4033 Value *Address = Inst.getPointerOperand();
4034 Value *Val = Inst.getValueOperand();
Johannes Doerfertcea61932016-02-21 19:13:19 +00004035 Type *ElementType = Val->getType();
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004036 enum MemoryAccess::AccessType Type =
4037 Inst.isLoad() ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
4038
4039 const SCEV *AccessFunction = SE->getSCEVAtScope(Address, L);
4040 const SCEVUnknown *BasePointer =
4041 dyn_cast<SCEVUnknown>(SE->getPointerBase(AccessFunction));
4042
4043 assert(BasePointer && "Could not find base pointer");
4044 AccessFunction = SE->getMinusSCEV(AccessFunction, BasePointer);
Michael Kruse7bf39442015-09-10 12:46:52 +00004045
4046 // Check if the access depends on a loop contained in a non-affine subregion.
4047 bool isVariantInNonAffineLoop = false;
4048 if (BoxedLoops) {
4049 SetVector<const Loop *> Loops;
4050 findLoops(AccessFunction, Loops);
4051 for (const Loop *L : Loops)
4052 if (BoxedLoops->count(L))
4053 isVariantInNonAffineLoop = true;
4054 }
4055
Johannes Doerfert09e36972015-10-07 20:17:36 +00004056 InvariantLoadsSetTy AccessILS;
4057 bool IsAffine =
4058 !isVariantInNonAffineLoop &&
4059 isAffineExpr(R, AccessFunction, *SE, BasePointer->getValue(), &AccessILS);
4060
4061 for (LoadInst *LInst : AccessILS)
4062 if (!ScopRIL.count(LInst))
4063 IsAffine = false;
Michael Kruse7bf39442015-09-10 12:46:52 +00004064
Michael Krusee2bccbb2015-09-18 19:59:43 +00004065 if (!IsAffine && Type == MemoryAccess::MUST_WRITE)
4066 Type = MemoryAccess::MAY_WRITE;
Michael Kruse7bf39442015-09-10 12:46:52 +00004067
Johannes Doerfertcea61932016-02-21 19:13:19 +00004068 addArrayAccess(Inst, Type, BasePointer->getValue(), ElementType, IsAffine,
Tobias Grosser5d51afe2016-02-02 16:46:45 +00004069 {AccessFunction}, {}, Val);
Michael Kruse7bf39442015-09-10 12:46:52 +00004070}
4071
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004072void ScopInfo::buildMemoryAccess(
4073 MemAccInst Inst, Loop *L, Region *R,
4074 const ScopDetection::BoxedLoopsSetTy *BoxedLoops,
Hongbin Zheng22623202016-02-15 00:20:58 +00004075 const InvariantLoadsSetTy &ScopRIL, const MapInsnToMemAcc &InsnToMemAcc) {
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004076
Johannes Doerfertcea61932016-02-21 19:13:19 +00004077 if (buildAccessMemIntrinsic(Inst, L, R, BoxedLoops, ScopRIL))
4078 return;
4079
Johannes Doerferta7920982016-02-25 14:08:48 +00004080 if (buildAccessCallInst(Inst, L, R, BoxedLoops, ScopRIL))
4081 return;
4082
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004083 if (buildAccessMultiDimFixed(Inst, L, R, BoxedLoops, ScopRIL))
4084 return;
4085
Hongbin Zheng22623202016-02-15 00:20:58 +00004086 if (buildAccessMultiDimParam(Inst, L, R, BoxedLoops, ScopRIL, InsnToMemAcc))
Tobias Grosserdb543ed2016-02-02 16:46:49 +00004087 return;
4088
4089 buildAccessSingleDim(Inst, L, R, BoxedLoops, ScopRIL);
4090}
4091
Hongbin Zheng22623202016-02-15 00:20:58 +00004092void ScopInfo::buildAccessFunctions(Region &R, Region &SR,
4093 const MapInsnToMemAcc &InsnToMemAcc) {
Michael Kruse7bf39442015-09-10 12:46:52 +00004094
4095 if (SD->isNonAffineSubRegion(&SR, &R)) {
4096 for (BasicBlock *BB : SR.blocks())
Hongbin Zheng22623202016-02-15 00:20:58 +00004097 buildAccessFunctions(R, *BB, InsnToMemAcc, &SR);
Michael Kruse7bf39442015-09-10 12:46:52 +00004098 return;
4099 }
4100
4101 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4102 if (I->isSubRegion())
Hongbin Zheng22623202016-02-15 00:20:58 +00004103 buildAccessFunctions(R, *I->getNodeAs<Region>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004104 else
Hongbin Zheng22623202016-02-15 00:20:58 +00004105 buildAccessFunctions(R, *I->getNodeAs<BasicBlock>(), InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004106}
4107
Johannes Doerferta8781032016-02-02 14:14:40 +00004108void ScopInfo::buildStmts(Region &R, Region &SR) {
Michael Krusecac948e2015-10-02 13:53:07 +00004109
Johannes Doerferta8781032016-02-02 14:14:40 +00004110 if (SD->isNonAffineSubRegion(&SR, &R)) {
Michael Krusecac948e2015-10-02 13:53:07 +00004111 scop->addScopStmt(nullptr, &SR);
4112 return;
4113 }
4114
4115 for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
4116 if (I->isSubRegion())
Johannes Doerferta8781032016-02-02 14:14:40 +00004117 buildStmts(R, *I->getNodeAs<Region>());
Michael Krusecac948e2015-10-02 13:53:07 +00004118 else
4119 scop->addScopStmt(I->getNodeAs<BasicBlock>(), nullptr);
4120}
4121
Michael Krused868b5d2015-09-10 15:25:24 +00004122void ScopInfo::buildAccessFunctions(Region &R, BasicBlock &BB,
Hongbin Zheng22623202016-02-15 00:20:58 +00004123 const MapInsnToMemAcc &InsnToMemAcc,
Michael Krused868b5d2015-09-10 15:25:24 +00004124 Region *NonAffineSubRegion,
4125 bool IsExitBlock) {
Tobias Grosser910cf262015-11-11 20:15:49 +00004126 // We do not build access functions for error blocks, as they may contain
4127 // instructions we can not model.
Johannes Doerfertc36d39b2016-02-02 14:14:20 +00004128 if (isErrorBlock(BB, R, *LI, *DT) && !IsExitBlock)
Tobias Grosser910cf262015-11-11 20:15:49 +00004129 return;
4130
Michael Kruse7bf39442015-09-10 12:46:52 +00004131 Loop *L = LI->getLoopFor(&BB);
4132
4133 // The set of loops contained in non-affine subregions that are part of R.
4134 const ScopDetection::BoxedLoopsSetTy *BoxedLoops = SD->getBoxedLoops(&R);
4135
Johannes Doerfert09e36972015-10-07 20:17:36 +00004136 // The set of loads that are required to be invariant.
4137 auto &ScopRIL = *SD->getRequiredInvariantLoads(&R);
4138
Michael Kruse2e02d562016-02-06 09:19:40 +00004139 for (Instruction &Inst : BB) {
4140 PHINode *PHI = dyn_cast<PHINode>(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004141 if (PHI)
Michael Krusee2bccbb2015-09-18 19:59:43 +00004142 buildPHIAccesses(PHI, R, NonAffineSubRegion, IsExitBlock);
Michael Kruse7bf39442015-09-10 12:46:52 +00004143
4144 // For the exit block we stop modeling after the last PHI node.
4145 if (!PHI && IsExitBlock)
4146 break;
4147
Johannes Doerfert09e36972015-10-07 20:17:36 +00004148 // TODO: At this point we only know that elements of ScopRIL have to be
4149 // invariant and will be hoisted for the SCoP to be processed. Though,
4150 // there might be other invariant accesses that will be hoisted and
4151 // that would allow to make a non-affine access affine.
Michael Kruse70131d32016-01-27 17:09:17 +00004152 if (auto MemInst = MemAccInst::dyn_cast(Inst))
Hongbin Zheng22623202016-02-15 00:20:58 +00004153 buildMemoryAccess(MemInst, L, &R, BoxedLoops, ScopRIL, InsnToMemAcc);
Michael Kruse7bf39442015-09-10 12:46:52 +00004154
Michael Kruse2e02d562016-02-06 09:19:40 +00004155 if (isIgnoredIntrinsic(&Inst))
Michael Kruse7bf39442015-09-10 12:46:52 +00004156 continue;
4157
Michael Kruse2e02d562016-02-06 09:19:40 +00004158 if (!PHI)
4159 buildScalarDependences(&Inst);
4160 if (!IsExitBlock)
4161 buildEscapingDependences(&Inst);
Michael Kruse7bf39442015-09-10 12:46:52 +00004162 }
Michael Krusee2bccbb2015-09-18 19:59:43 +00004163}
Michael Kruse7bf39442015-09-10 12:46:52 +00004164
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004165MemoryAccess *ScopInfo::addMemoryAccess(BasicBlock *BB, Instruction *Inst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004166 MemoryAccess::AccessType AccType,
4167 Value *BaseAddress, Type *ElementType,
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004168 bool Affine, Value *AccessValue,
4169 ArrayRef<const SCEV *> Subscripts,
4170 ArrayRef<const SCEV *> Sizes,
4171 ScopArrayInfo::MemoryKind Kind) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004172 ScopStmt *Stmt = scop->getStmtFor(BB);
Michael Krusecac948e2015-10-02 13:53:07 +00004173
4174 // Do not create a memory access for anything not in the SCoP. It would be
4175 // ignored anyway.
4176 if (!Stmt)
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004177 return nullptr;
Michael Krusecac948e2015-10-02 13:53:07 +00004178
Hongbin Zheng660f3cc2016-02-13 15:12:58 +00004179 AccFuncSetType &AccList = scop->getOrCreateAccessFunctions(BB);
Michael Krusee2bccbb2015-09-18 19:59:43 +00004180 Value *BaseAddr = BaseAddress;
4181 std::string BaseName = getIslCompatibleName("MemRef_", BaseAddr, "");
4182
Tobias Grosserf4f68702015-12-14 15:05:37 +00004183 bool isKnownMustAccess = false;
4184
4185 // Accesses in single-basic block statements are always excuted.
4186 if (Stmt->isBlockStmt())
4187 isKnownMustAccess = true;
4188
4189 if (Stmt->isRegionStmt()) {
4190 // Accesses that dominate the exit block of a non-affine region are always
4191 // executed. In non-affine regions there may exist MK_Values that do not
4192 // dominate the exit. MK_Values will always dominate the exit and MK_PHIs
4193 // only if there is at most one PHI_WRITE in the non-affine region.
4194 if (DT->dominates(BB, Stmt->getRegion()->getExit()))
4195 isKnownMustAccess = true;
4196 }
4197
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004198 // Non-affine PHI writes do not "happen" at a particular instruction, but
4199 // after exiting the statement. Therefore they are guaranteed execute and
4200 // overwrite the old value.
4201 if (Kind == ScopArrayInfo::MK_PHI || Kind == ScopArrayInfo::MK_ExitPHI)
4202 isKnownMustAccess = true;
4203
Johannes Doerfertcea61932016-02-21 19:13:19 +00004204 if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
4205 AccType = MemoryAccess::MAY_WRITE;
Michael Krusecac948e2015-10-02 13:53:07 +00004206
Johannes Doerfertcea61932016-02-21 19:13:19 +00004207 AccList.emplace_back(Stmt, Inst, AccType, BaseAddress, ElementType, Affine,
Tobias Grossera535dff2015-12-13 19:59:01 +00004208 Subscripts, Sizes, AccessValue, Kind, BaseName);
Michael Krusecac948e2015-10-02 13:53:07 +00004209 Stmt->addAccess(&AccList.back());
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004210 return &AccList.back();
Michael Kruse7bf39442015-09-10 12:46:52 +00004211}
4212
Michael Kruse70131d32016-01-27 17:09:17 +00004213void ScopInfo::addArrayAccess(MemAccInst MemAccInst,
Johannes Doerfertcea61932016-02-21 19:13:19 +00004214 MemoryAccess::AccessType AccType,
4215 Value *BaseAddress, Type *ElementType,
4216 bool IsAffine, ArrayRef<const SCEV *> Subscripts,
Tobias Grossera535dff2015-12-13 19:59:01 +00004217 ArrayRef<const SCEV *> Sizes,
4218 Value *AccessValue) {
Johannes Doerferta7920982016-02-25 14:08:48 +00004219 ArrayBasePointers.insert(BaseAddress);
Johannes Doerfertcea61932016-02-21 19:13:19 +00004220 addMemoryAccess(MemAccInst.getParent(), MemAccInst, AccType, BaseAddress,
4221 ElementType, IsAffine, AccessValue, Subscripts, Sizes,
Tobias Grossera535dff2015-12-13 19:59:01 +00004222 ScopArrayInfo::MK_Array);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004223}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004224
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004225void ScopInfo::ensureValueWrite(Instruction *Inst) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004226 ScopStmt *Stmt = scop->getStmtFor(Inst);
Michael Kruse436db622016-01-26 13:33:10 +00004227
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004228 // Inst not defined within this SCoP.
Michael Kruse436db622016-01-26 13:33:10 +00004229 if (!Stmt)
4230 return;
4231
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004232 // Do not process further if the instruction is already written.
4233 if (Stmt->lookupValueWriteOf(Inst))
Michael Kruse436db622016-01-26 13:33:10 +00004234 return;
4235
Johannes Doerfertcea61932016-02-21 19:13:19 +00004236 addMemoryAccess(Inst->getParent(), Inst, MemoryAccess::MUST_WRITE, Inst,
4237 Inst->getType(), true, Inst, ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004238 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_Value);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004239}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004240
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004241void ScopInfo::ensureValueRead(Value *V, BasicBlock *UserBB) {
Michael Krusefd463082016-01-27 22:51:56 +00004242
Michael Kruse2e02d562016-02-06 09:19:40 +00004243 // There cannot be an "access" for literal constants. BasicBlock references
4244 // (jump destinations) also never change.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004245 if ((isa<Constant>(V) && !isa<GlobalVariable>(V)) || isa<BasicBlock>(V))
Michael Kruse2e02d562016-02-06 09:19:40 +00004246 return;
4247
Michael Krusefd463082016-01-27 22:51:56 +00004248 // If the instruction can be synthesized and the user is in the region we do
4249 // not need to add a value dependences.
4250 Region &ScopRegion = scop->getRegion();
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004251 if (canSynthesize(V, LI, SE, &ScopRegion))
Michael Krusefd463082016-01-27 22:51:56 +00004252 return;
4253
Michael Kruse2e02d562016-02-06 09:19:40 +00004254 // Do not build scalar dependences for required invariant loads as we will
4255 // hoist them later on anyway or drop the SCoP if we cannot.
Johannes Doerferta90943d2016-02-21 16:37:25 +00004256 auto *ScopRIL = SD->getRequiredInvariantLoads(&ScopRegion);
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004257 if (ScopRIL->count(dyn_cast<LoadInst>(V)))
Michael Kruse2e02d562016-02-06 09:19:40 +00004258 return;
4259
4260 // Determine the ScopStmt containing the value's definition and use. There is
4261 // no defining ScopStmt if the value is a function argument, a global value,
4262 // or defined outside the SCoP.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004263 Instruction *ValueInst = dyn_cast<Instruction>(V);
Michael Kruse6f7721f2016-02-24 22:08:19 +00004264 ScopStmt *ValueStmt = ValueInst ? scop->getStmtFor(ValueInst) : nullptr;
Michael Kruse2e02d562016-02-06 09:19:40 +00004265
Michael Kruse6f7721f2016-02-24 22:08:19 +00004266 ScopStmt *UserStmt = scop->getStmtFor(UserBB);
Michael Krusead28e5a2016-01-26 13:33:15 +00004267
4268 // We do not model uses outside the scop.
4269 if (!UserStmt)
4270 return;
4271
Michael Kruse2e02d562016-02-06 09:19:40 +00004272 // Add MemoryAccess for invariant values only if requested.
4273 if (!ModelReadOnlyScalars && !ValueStmt)
4274 return;
4275
4276 // Ignore use-def chains within the same ScopStmt.
4277 if (ValueStmt == UserStmt)
4278 return;
4279
Michael Krusead28e5a2016-01-26 13:33:15 +00004280 // Do not create another MemoryAccess for reloading the value if one already
4281 // exists.
Johannes Doerfert68898ce2016-02-21 16:36:21 +00004282 if (UserStmt->lookupValueReadOf(V))
Michael Krusead28e5a2016-01-26 13:33:15 +00004283 return;
4284
Johannes Doerfertcea61932016-02-21 19:13:19 +00004285 addMemoryAccess(UserBB, nullptr, MemoryAccess::READ, V, V->getType(), true, V,
Michael Kruse8d0b7342015-09-25 21:21:00 +00004286 ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
Tobias Grossera535dff2015-12-13 19:59:01 +00004287 ScopArrayInfo::MK_Value);
Michael Kruse2e02d562016-02-06 09:19:40 +00004288 if (ValueInst)
4289 ensureValueWrite(ValueInst);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004290}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004291
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004292void ScopInfo::ensurePHIWrite(PHINode *PHI, BasicBlock *IncomingBlock,
4293 Value *IncomingValue, bool IsExitBlock) {
Michael Kruse6f7721f2016-02-24 22:08:19 +00004294 ScopStmt *IncomingStmt = scop->getStmtFor(IncomingBlock);
Michael Kruse2e02d562016-02-06 09:19:40 +00004295 if (!IncomingStmt)
4296 return;
4297
4298 // Take care for the incoming value being available in the incoming block.
4299 // This must be done before the check for multiple PHI writes because multiple
4300 // exiting edges from subregion each can be the effective written value of the
4301 // subregion. As such, all of them must be made available in the subregion
4302 // statement.
4303 ensureValueRead(IncomingValue, IncomingBlock);
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004304
4305 // Do not add more than one MemoryAccess per PHINode and ScopStmt.
4306 if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
4307 assert(Acc->getAccessInstruction() == PHI);
4308 Acc->addIncoming(IncomingBlock, IncomingValue);
4309 return;
4310 }
4311
4312 MemoryAccess *Acc = addMemoryAccess(
Michael Kruse375cb5f2016-02-24 22:08:24 +00004313 IncomingStmt->getEntryBlock(), PHI, MemoryAccess::MUST_WRITE, PHI,
4314 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4315 ArrayRef<const SCEV *>(),
Michael Kruseee6a4fc2016-01-26 13:33:27 +00004316 IsExitBlock ? ScopArrayInfo::MK_ExitPHI : ScopArrayInfo::MK_PHI);
4317 assert(Acc);
4318 Acc->addIncoming(IncomingBlock, IncomingValue);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004319}
Johannes Doerfertb92e2182016-02-21 16:37:58 +00004320
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004321void ScopInfo::addPHIReadAccess(PHINode *PHI) {
Johannes Doerfertcea61932016-02-21 19:13:19 +00004322 addMemoryAccess(PHI->getParent(), PHI, MemoryAccess::READ, PHI,
4323 PHI->getType(), true, PHI, ArrayRef<const SCEV *>(),
4324 ArrayRef<const SCEV *>(), ScopArrayInfo::MK_PHI);
Michael Kruse33d6c0b2015-09-25 18:53:27 +00004325}
4326
Michael Krusedaf66942015-12-13 22:10:37 +00004327void ScopInfo::buildScop(Region &R, AssumptionCache &AC) {
Michael Kruse9d080092015-09-11 21:41:48 +00004328 unsigned MaxLoopDepth = getMaxLoopDepthInRegion(R, *LI, *SD);
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004329 scop.reset(new Scop(R, *SE, MaxLoopDepth));
Michael Kruse7bf39442015-09-10 12:46:52 +00004330
Johannes Doerferta8781032016-02-02 14:14:40 +00004331 buildStmts(R, R);
Hongbin Zheng22623202016-02-15 00:20:58 +00004332 buildAccessFunctions(R, R, *SD->getInsnToMemAccMap(&R));
Michael Kruse7bf39442015-09-10 12:46:52 +00004333
4334 // In case the region does not have an exiting block we will later (during
4335 // code generation) split the exit block. This will move potential PHI nodes
4336 // from the current exit block into the new region exiting block. Hence, PHI
4337 // nodes that are at this point not part of the region will be.
4338 // To handle these PHI nodes later we will now model their operands as scalar
4339 // accesses. Note that we do not model anything in the exit block if we have
4340 // an exiting block in the region, as there will not be any splitting later.
4341 if (!R.getExitingBlock())
Hongbin Zheng22623202016-02-15 00:20:58 +00004342 buildAccessFunctions(R, *R.getExit(), *SD->getInsnToMemAccMap(&R), nullptr,
4343 /* IsExitBlock */ true);
Michael Kruse7bf39442015-09-10 12:46:52 +00004344
Johannes Doerferta7920982016-02-25 14:08:48 +00004345 // Create memory accesses for global reads since all arrays are now known.
4346 auto *AF = SE->getConstant(IntegerType::getInt64Ty(SE->getContext()), 0);
4347 for (auto *GlobalRead : GlobalReads)
4348 for (auto *BP : ArrayBasePointers)
4349 addArrayAccess(MemAccInst(GlobalRead), MemoryAccess::READ, BP,
4350 BP->getType(), false, {AF}, {}, GlobalRead);
4351
Hongbin Zheng192f69a2016-02-13 15:12:54 +00004352 scop->init(*AA, AC, *SD, *DT, *LI);
Michael Kruse7bf39442015-09-10 12:46:52 +00004353}
4354
Michael Krused868b5d2015-09-10 15:25:24 +00004355void ScopInfo::print(raw_ostream &OS, const Module *) const {
Michael Kruse9d080092015-09-11 21:41:48 +00004356 if (!scop) {
Michael Krused868b5d2015-09-10 15:25:24 +00004357 OS << "Invalid Scop!\n";
Michael Kruse9d080092015-09-11 21:41:48 +00004358 return;
4359 }
4360
Michael Kruse9d080092015-09-11 21:41:48 +00004361 scop->print(OS);
Michael Kruse7bf39442015-09-10 12:46:52 +00004362}
4363
Hongbin Zhengfec32802016-02-13 15:13:02 +00004364void ScopInfo::clear() { scop.reset(); }
Michael Kruse7bf39442015-09-10 12:46:52 +00004365
4366//===----------------------------------------------------------------------===//
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004367ScopInfo::ScopInfo() : RegionPass(ID) {}
Tobias Grosserb76f38532011-08-20 11:11:25 +00004368
Hongbin Zheng8831eb72016-02-17 15:49:21 +00004369ScopInfo::~ScopInfo() { clear(); }
Tobias Grosserb76f38532011-08-20 11:11:25 +00004370
Tobias Grosser75805372011-04-29 06:27:02 +00004371void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chandler Carruthf5579872015-01-17 14:16:56 +00004372 AU.addRequired<LoopInfoWrapperPass>();
Matt Arsenault8ca36812014-07-19 18:40:17 +00004373 AU.addRequired<RegionInfoPass>();
Johannes Doerfert96425c22015-08-30 21:13:53 +00004374 AU.addRequired<DominatorTreeWrapperPass>();
Michael Krused868b5d2015-09-10 15:25:24 +00004375 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4376 AU.addRequiredTransitive<ScopDetection>();
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004377 AU.addRequired<AAResultsWrapperPass>();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004378 AU.addRequired<AssumptionCacheTracker>();
Tobias Grosser75805372011-04-29 06:27:02 +00004379 AU.setPreservesAll();
4380}
4381
4382bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
Michael Krused868b5d2015-09-10 15:25:24 +00004383 SD = &getAnalysis<ScopDetection>();
Tobias Grosser75805372011-04-29 06:27:02 +00004384
Michael Krused868b5d2015-09-10 15:25:24 +00004385 if (!SD->isMaxRegionInScop(*R))
4386 return false;
4387
4388 Function *F = R->getEntry()->getParent();
4389 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4390 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4391 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Johannes Doerferta1f291e2016-02-02 14:15:13 +00004392 DL = &F->getParent()->getDataLayout();
Michael Krusedaf66942015-12-13 22:10:37 +00004393 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004394 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(*F);
Michael Krused868b5d2015-09-10 15:25:24 +00004395
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004396 DebugLoc Beg, End;
4397 getDebugLocations(R, Beg, End);
4398 std::string Msg = "SCoP begins here.";
4399 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, Beg, Msg);
4400
Michael Krusedaf66942015-12-13 22:10:37 +00004401 buildScop(*R, AC);
Tobias Grosser75805372011-04-29 06:27:02 +00004402
Tobias Grosserd6a50b32015-05-30 06:26:21 +00004403 DEBUG(scop->print(dbgs()));
4404
Michael Kruseafe06702015-10-02 16:33:27 +00004405 if (scop->isEmpty() || !scop->hasFeasibleRuntimeContext()) {
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004406 Msg = "SCoP ends here but was dismissed.";
Hongbin Zhengfec32802016-02-13 15:13:02 +00004407 scop.reset();
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004408 } else {
4409 Msg = "SCoP ends here.";
4410 ++ScopFound;
4411 if (scop->getMaxLoopDepth() > 0)
4412 ++RichScopFound;
Johannes Doerfert43788c52015-08-20 05:58:56 +00004413 }
4414
Johannes Doerfert48fe86f2015-11-12 02:32:32 +00004415 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, End, Msg);
4416
Tobias Grosser75805372011-04-29 06:27:02 +00004417 return false;
4418}
4419
4420char ScopInfo::ID = 0;
4421
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004422Pass *polly::createScopInfoPass() { return new ScopInfo(); }
4423
Tobias Grosser73600b82011-10-08 00:30:40 +00004424INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
4425 "Polly - Create polyhedral description of Scops", false,
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00004426 false);
Chandler Carruth66ef16b2015-09-09 22:13:56 +00004427INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
Johannes Doerfert2af10e22015-11-12 03:25:01 +00004428INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker);
Chandler Carruthf5579872015-01-17 14:16:56 +00004429INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
Matt Arsenault8ca36812014-07-19 18:40:17 +00004430INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
Tobias Grosserc5bcf242015-08-17 10:57:08 +00004431INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
Johannes Doerfertff9d1982015-02-24 12:00:50 +00004432INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Johannes Doerfert96425c22015-08-30 21:13:53 +00004433INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser73600b82011-10-08 00:30:40 +00004434INITIALIZE_PASS_END(ScopInfo, "polly-scops",
4435 "Polly - Create polyhedral description of Scops", false,
4436 false)