1 //===--------- ScopInfo.cpp ----------------------------------------------===//
2 //
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 //
15 // This representation is shared among several tools in the polyhedral
16 // community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "polly/ScopInfo.h"
21 #include "polly/LinkAllPasses.h"
22 #include "polly/Options.h"
23 #include "polly/ScopBuilder.h"
24 #include "polly/Support/GICHelper.h"
25 #include "polly/Support/SCEVValidator.h"
26 #include "polly/Support/ScopHelper.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/MapVector.h"
29 #include "llvm/ADT/PostOrderIterator.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/Loads.h"
37 #include "llvm/Analysis/LoopInfo.h"
38 #include "llvm/Analysis/LoopIterator.h"
39 #include "llvm/Analysis/RegionIterator.h"
40 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
41 #include "llvm/IR/DiagnosticInfo.h"
42 #include "llvm/Support/Debug.h"
43 #include "isl/aff.h"
44 #include "isl/constraint.h"
45 #include "isl/local_space.h"
46 #include "isl/map.h"
47 #include "isl/options.h"
48 #include "isl/printer.h"
49 #include "isl/schedule.h"
50 #include "isl/schedule_node.h"
51 #include "isl/set.h"
52 #include "isl/union_map.h"
53 #include "isl/union_set.h"
54 #include "isl/val.h"
55 #include <sstream>
56 #include <string>
57 #include <vector>
58 
59 using namespace llvm;
60 using namespace polly;
61 
62 #define DEBUG_TYPE "polly-scops"
63 
64 STATISTIC(AssumptionsAliasing, "Number of aliasing assumptions taken.");
65 STATISTIC(AssumptionsInbounds, "Number of inbounds assumptions taken.");
66 STATISTIC(AssumptionsWrapping, "Number of wrapping assumptions taken.");
67 STATISTIC(AssumptionsUnsigned, "Number of unsigned assumptions taken.");
68 STATISTIC(AssumptionsComplexity, "Number of too complex SCoPs.");
69 STATISTIC(AssumptionsUnprofitable, "Number of unprofitable SCoPs.");
70 STATISTIC(AssumptionsErrorBlock, "Number of error block assumptions taken.");
71 STATISTIC(AssumptionsInfiniteLoop, "Number of bounded loop assumptions taken.");
72 STATISTIC(AssumptionsInvariantLoad,
73           "Number of invariant loads assumptions taken.");
74 STATISTIC(AssumptionsDelinearization,
75           "Number of delinearization assumptions taken.");
76 
77 STATISTIC(NumLoopsInScop, "Number of loops in scops");
78 STATISTIC(NumScopsDepthOne, "Number of scops with maximal loop depth 1");
79 STATISTIC(NumScopsDepthTwo, "Number of scops with maximal loop depth 2");
80 STATISTIC(NumScopsDepthThree, "Number of scops with maximal loop depth 3");
81 STATISTIC(NumScopsDepthFour, "Number of scops with maximal loop depth 4");
82 STATISTIC(NumScopsDepthFive, "Number of scops with maximal loop depth 5");
83 STATISTIC(NumScopsDepthLarger,
84           "Number of scops with maximal loop depth 6 and larger");
85 STATISTIC(MaxNumLoopsInScop, "Maximal number of loops in scops");
86 
87 // The maximal number of basic sets we allow during domain construction to
88 // be created. More complex scops will result in very high compile time and
89 // are also unlikely to result in good code
90 static int const MaxDisjunctsInDomain = 20;
91 
92 // The number of disjunct in the context after which we stop to add more
93 // disjuncts. This parameter is there to avoid exponential growth in the
94 // number of disjunct when adding non-convex sets to the context.
95 static int const MaxDisjunctsInContext = 4;
96 
97 static cl::opt<bool> PollyRemarksMinimal(
98     "polly-remarks-minimal",
99     cl::desc("Do not emit remarks about assumptions that are known"),
100     cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
101 
102 // Multiplicative reductions can be disabled separately as these kind of
103 // operations can overflow easily. Additive reductions and bit operations
104 // are in contrast pretty stable.
105 static cl::opt<bool> DisableMultiplicativeReductions(
106     "polly-disable-multiplicative-reductions",
107     cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
108     cl::init(false), cl::cat(PollyCategory));
109 
110 static cl::opt<unsigned> RunTimeChecksMaxParameters(
111     "polly-rtc-max-parameters",
112     cl::desc("The maximal number of parameters allowed in RTCs."), cl::Hidden,
113     cl::ZeroOrMore, cl::init(8), cl::cat(PollyCategory));
114 
115 static cl::opt<unsigned> RunTimeChecksMaxArraysPerGroup(
116     "polly-rtc-max-arrays-per-group",
117     cl::desc("The maximal number of arrays to compare in each alias group."),
118     cl::Hidden, cl::ZeroOrMore, cl::init(20), cl::cat(PollyCategory));
119 
120 static cl::opt<std::string> UserContextStr(
121     "polly-context", cl::value_desc("isl parameter set"),
122     cl::desc("Provide additional constraints on the context parameters"),
123     cl::init(""), cl::cat(PollyCategory));
124 
125 static cl::opt<bool> DetectReductions("polly-detect-reductions",
126                                       cl::desc("Detect and exploit reductions"),
127                                       cl::Hidden, cl::ZeroOrMore,
128                                       cl::init(true), cl::cat(PollyCategory));
129 
130 static cl::opt<bool>
131     IslOnErrorAbort("polly-on-isl-error-abort",
132                     cl::desc("Abort if an isl error is encountered"),
133                     cl::init(true), cl::cat(PollyCategory));
134 
135 static cl::opt<bool> UnprofitableScalarAccs(
136     "polly-unprofitable-scalar-accs",
137     cl::desc("Count statements with scalar accesses as not optimizable"),
138     cl::Hidden, cl::init(true), cl::cat(PollyCategory));
139 
140 //===----------------------------------------------------------------------===//
141 
142 // Create a sequence of two schedules. Either argument may be null and is
143 // interpreted as the empty schedule. Can also return null if both schedules are
144 // empty.
145 static __isl_give isl_schedule *
146 combineInSequence(__isl_take isl_schedule *Prev,
147                   __isl_take isl_schedule *Succ) {
148   if (!Prev)
149     return Succ;
150   if (!Succ)
151     return Prev;
152 
153   return isl_schedule_sequence(Prev, Succ);
154 }
155 
156 static __isl_give isl_set *addRangeBoundsToSet(__isl_take isl_set *S,
157                                                const ConstantRange &Range,
158                                                int dim,
159                                                enum isl_dim_type type) {
160   isl_val *V;
161   isl_ctx *Ctx = isl_set_get_ctx(S);
162 
163   // The upper and lower bound for a parameter value is derived either from
164   // the data type of the parameter or from the - possibly more restrictive -
165   // range metadata.
166   V = isl_valFromAPInt(Ctx, Range.getSignedMin(), true);
167   S = isl_set_lower_bound_val(S, type, dim, V);
168   V = isl_valFromAPInt(Ctx, Range.getSignedMax(), true);
169   S = isl_set_upper_bound_val(S, type, dim, V);
170 
171   if (Range.isFullSet())
172     return S;
173 
174   if (isl_set_n_basic_set(S) > MaxDisjunctsInContext)
175     return S;
176 
177   // In case of signed wrapping, we can refine the set of valid values by
178   // excluding the part not covered by the wrapping range.
179   if (Range.isSignWrappedSet()) {
180     V = isl_valFromAPInt(Ctx, Range.getLower(), true);
181     isl_set *SLB = isl_set_lower_bound_val(isl_set_copy(S), type, dim, V);
182 
183     V = isl_valFromAPInt(Ctx, Range.getUpper(), true);
184     V = isl_val_sub_ui(V, 1);
185     isl_set *SUB = isl_set_upper_bound_val(S, type, dim, V);
186     S = isl_set_union(SLB, SUB);
187   }
188 
189   return S;
190 }
191 
192 static const ScopArrayInfo *identifyBasePtrOriginSAI(Scop *S, Value *BasePtr) {
193   LoadInst *BasePtrLI = dyn_cast<LoadInst>(BasePtr);
194   if (!BasePtrLI)
195     return nullptr;
196 
197   if (!S->contains(BasePtrLI))
198     return nullptr;
199 
200   ScalarEvolution &SE = *S->getSE();
201 
202   auto *OriginBaseSCEV =
203       SE.getPointerBase(SE.getSCEV(BasePtrLI->getPointerOperand()));
204   if (!OriginBaseSCEV)
205     return nullptr;
206 
207   auto *OriginBaseSCEVUnknown = dyn_cast<SCEVUnknown>(OriginBaseSCEV);
208   if (!OriginBaseSCEVUnknown)
209     return nullptr;
210 
211   return S->getScopArrayInfo(OriginBaseSCEVUnknown->getValue(),
212                              MemoryKind::Array);
213 }
214 
215 ScopArrayInfo::ScopArrayInfo(Value *BasePtr, Type *ElementType, isl_ctx *Ctx,
216                              ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
217                              const DataLayout &DL, Scop *S,
218                              const char *BaseName)
219     : BasePtr(BasePtr), ElementType(ElementType), Kind(Kind), DL(DL), S(*S) {
220   std::string BasePtrName =
221       BaseName ? BaseName
222                : getIslCompatibleName("MemRef_", BasePtr,
223                                       Kind == MemoryKind::PHI ? "__phi" : "");
224   Id = isl_id_alloc(Ctx, BasePtrName.c_str(), this);
225 
226   updateSizes(Sizes);
227 
228   if (!BasePtr || Kind != MemoryKind::Array) {
229     BasePtrOriginSAI = nullptr;
230     return;
231   }
232 
233   BasePtrOriginSAI = identifyBasePtrOriginSAI(S, BasePtr);
234   if (BasePtrOriginSAI)
235     const_cast<ScopArrayInfo *>(BasePtrOriginSAI)->addDerivedSAI(this);
236 }
237 
238 __isl_give isl_space *ScopArrayInfo::getSpace() const {
239   auto *Space =
240       isl_space_set_alloc(isl_id_get_ctx(Id), 0, getNumberOfDimensions());
241   Space = isl_space_set_tuple_id(Space, isl_dim_set, isl_id_copy(Id));
242   return Space;
243 }
244 
245 bool ScopArrayInfo::isReadOnly() {
246   isl_union_set *WriteSet = isl_union_map_range(S.getWrites());
247   isl_space *Space = getSpace();
248   WriteSet = isl_union_set_intersect(
249       WriteSet, isl_union_set_from_set(isl_set_universe(Space)));
250 
251   bool IsReadOnly = isl_union_set_is_empty(WriteSet);
252   isl_union_set_free(WriteSet);
253 
254   return IsReadOnly;
255 }
256 
257 void ScopArrayInfo::updateElementType(Type *NewElementType) {
258   if (NewElementType == ElementType)
259     return;
260 
261   auto OldElementSize = DL.getTypeAllocSizeInBits(ElementType);
262   auto NewElementSize = DL.getTypeAllocSizeInBits(NewElementType);
263 
264   if (NewElementSize == OldElementSize || NewElementSize == 0)
265     return;
266 
267   if (NewElementSize % OldElementSize == 0 && NewElementSize < OldElementSize) {
268     ElementType = NewElementType;
269   } else {
270     auto GCD = GreatestCommonDivisor64(NewElementSize, OldElementSize);
271     ElementType = IntegerType::get(ElementType->getContext(), GCD);
272   }
273 }
274 
275 bool ScopArrayInfo::updateSizes(ArrayRef<const SCEV *> NewSizes,
276                                 bool CheckConsistency) {
277   int SharedDims = std::min(NewSizes.size(), DimensionSizes.size());
278   int ExtraDimsNew = NewSizes.size() - SharedDims;
279   int ExtraDimsOld = DimensionSizes.size() - SharedDims;
280 
281   if (CheckConsistency) {
282     for (int i = 0; i < SharedDims; i++) {
283       auto *NewSize = NewSizes[i + ExtraDimsNew];
284       auto *KnownSize = DimensionSizes[i + ExtraDimsOld];
285       if (NewSize && KnownSize && NewSize != KnownSize)
286         return false;
287     }
288 
289     if (DimensionSizes.size() >= NewSizes.size())
290       return true;
291   }
292 
293   DimensionSizes.clear();
294   DimensionSizes.insert(DimensionSizes.begin(), NewSizes.begin(),
295                         NewSizes.end());
296   for (isl_pw_aff *Size : DimensionSizesPw)
297     isl_pw_aff_free(Size);
298   DimensionSizesPw.clear();
299   for (const SCEV *Expr : DimensionSizes) {
300     if (!Expr) {
301       DimensionSizesPw.push_back(nullptr);
302       continue;
303     }
304     isl_pw_aff *Size = S.getPwAffOnly(Expr);
305     DimensionSizesPw.push_back(Size);
306   }
307   return true;
308 }
309 
310 ScopArrayInfo::~ScopArrayInfo() {
311   isl_id_free(Id);
312   for (isl_pw_aff *Size : DimensionSizesPw)
313     isl_pw_aff_free(Size);
314 }
315 
316 std::string ScopArrayInfo::getName() const { return isl_id_get_name(Id); }
317 
318 int ScopArrayInfo::getElemSizeInBytes() const {
319   return DL.getTypeAllocSize(ElementType);
320 }
321 
322 __isl_give isl_id *ScopArrayInfo::getBasePtrId() const {
323   return isl_id_copy(Id);
324 }
325 
326 void ScopArrayInfo::dump() const { print(errs()); }
327 
328 void ScopArrayInfo::print(raw_ostream &OS, bool SizeAsPwAff) const {
329   OS.indent(8) << *getElementType() << " " << getName();
330   unsigned u = 0;
331   if (getNumberOfDimensions() > 0 && !getDimensionSize(0)) {
332     OS << "[*]";
333     u++;
334   }
335   for (; u < getNumberOfDimensions(); u++) {
336     OS << "[";
337 
338     if (SizeAsPwAff) {
339       auto *Size = getDimensionSizePw(u);
340       OS << " " << Size << " ";
341       isl_pw_aff_free(Size);
342     } else {
343       OS << *getDimensionSize(u);
344     }
345 
346     OS << "]";
347   }
348 
349   OS << ";";
350 
351   if (BasePtrOriginSAI)
352     OS << " [BasePtrOrigin: " << BasePtrOriginSAI->getName() << "]";
353 
354   OS << " // Element size " << getElemSizeInBytes() << "\n";
355 }
356 
357 const ScopArrayInfo *
358 ScopArrayInfo::getFromAccessFunction(__isl_keep isl_pw_multi_aff *PMA) {
359   isl_id *Id = isl_pw_multi_aff_get_tuple_id(PMA, isl_dim_out);
360   assert(Id && "Output dimension didn't have an ID");
361   return getFromId(Id);
362 }
363 
364 const ScopArrayInfo *ScopArrayInfo::getFromId(__isl_take isl_id *Id) {
365   void *User = isl_id_get_user(Id);
366   const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
367   isl_id_free(Id);
368   return SAI;
369 }
370 
371 void MemoryAccess::wrapConstantDimensions() {
372   auto *SAI = getScopArrayInfo();
373   auto *ArraySpace = SAI->getSpace();
374   auto *Ctx = isl_space_get_ctx(ArraySpace);
375   unsigned DimsArray = SAI->getNumberOfDimensions();
376 
377   auto *DivModAff = isl_multi_aff_identity(isl_space_map_from_domain_and_range(
378       isl_space_copy(ArraySpace), isl_space_copy(ArraySpace)));
379   auto *LArraySpace = isl_local_space_from_space(ArraySpace);
380 
381   // Begin with last dimension, to iteratively carry into higher dimensions.
382   for (int i = DimsArray - 1; i > 0; i--) {
383     auto *DimSize = SAI->getDimensionSize(i);
384     auto *DimSizeCst = dyn_cast<SCEVConstant>(DimSize);
385 
386     // This transformation is not applicable to dimensions with dynamic size.
387     if (!DimSizeCst)
388       continue;
389 
390     // This transformation is not applicable to dimensions of size zero.
391     if (DimSize->isZero())
392       continue;
393 
394     auto *DimSizeVal = isl_valFromAPInt(Ctx, DimSizeCst->getAPInt(), false);
395     auto *Var = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
396                                       isl_dim_set, i);
397     auto *PrevVar = isl_aff_var_on_domain(isl_local_space_copy(LArraySpace),
398                                           isl_dim_set, i - 1);
399 
400     // Compute: index % size
401     // Modulo must apply in the divide of the previous iteration, if any.
402     auto *Modulo = isl_aff_copy(Var);
403     Modulo = isl_aff_mod_val(Modulo, isl_val_copy(DimSizeVal));
404     Modulo = isl_aff_pullback_multi_aff(Modulo, isl_multi_aff_copy(DivModAff));
405 
406     // Compute: floor(index / size)
407     auto *Divide = Var;
408     Divide = isl_aff_div(
409         Divide,
410         isl_aff_val_on_domain(isl_local_space_copy(LArraySpace), DimSizeVal));
411     Divide = isl_aff_floor(Divide);
412     Divide = isl_aff_add(Divide, PrevVar);
413     Divide = isl_aff_pullback_multi_aff(Divide, isl_multi_aff_copy(DivModAff));
414 
415     // Apply Modulo and Divide.
416     DivModAff = isl_multi_aff_set_aff(DivModAff, i, Modulo);
417     DivModAff = isl_multi_aff_set_aff(DivModAff, i - 1, Divide);
418   }
419 
420   // Apply all modulo/divides on the accesses.
421   AccessRelation =
422       isl_map_apply_range(AccessRelation, isl_map_from_multi_aff(DivModAff));
423   AccessRelation = isl_map_detect_equalities(AccessRelation);
424   isl_local_space_free(LArraySpace);
425 }
426 
427 void MemoryAccess::updateDimensionality() {
428   auto *SAI = getScopArrayInfo();
429   auto *ArraySpace = SAI->getSpace();
430   auto *AccessSpace = isl_space_range(isl_map_get_space(AccessRelation));
431   auto *Ctx = isl_space_get_ctx(AccessSpace);
432 
433   auto DimsArray = isl_space_dim(ArraySpace, isl_dim_set);
434   auto DimsAccess = isl_space_dim(AccessSpace, isl_dim_set);
435   auto DimsMissing = DimsArray - DimsAccess;
436 
437   auto *BB = getStatement()->getEntryBlock();
438   auto &DL = BB->getModule()->getDataLayout();
439   unsigned ArrayElemSize = SAI->getElemSizeInBytes();
440   unsigned ElemBytes = DL.getTypeAllocSize(getElementType());
441 
442   auto *Map = isl_map_from_domain_and_range(
443       isl_set_universe(AccessSpace),
444       isl_set_universe(isl_space_copy(ArraySpace)));
445 
446   for (unsigned i = 0; i < DimsMissing; i++)
447     Map = isl_map_fix_si(Map, isl_dim_out, i, 0);
448 
449   for (unsigned i = DimsMissing; i < DimsArray; i++)
450     Map = isl_map_equate(Map, isl_dim_in, i - DimsMissing, isl_dim_out, i);
451 
452   AccessRelation = isl_map_apply_range(AccessRelation, Map);
453 
454   // For the non delinearized arrays, divide the access function of the last
455   // subscript by the size of the elements in the array.
456   //
457   // A stride one array access in C expressed as A[i] is expressed in
458   // LLVM-IR as something like A[i * elementsize]. This hides the fact that
459   // two subsequent values of 'i' index two values that are stored next to
460   // each other in memory. By this division we make this characteristic
461   // obvious again. If the base pointer was accessed with offsets not divisible
462   // by the accesses element size, we will have chosen a smaller ArrayElemSize
463   // that divides the offsets of all accesses to this base pointer.
464   if (DimsAccess == 1) {
465     isl_val *V = isl_val_int_from_si(Ctx, ArrayElemSize);
466     AccessRelation = isl_map_floordiv_val(AccessRelation, V);
467   }
468 
469   // We currently do this only if we added at least one dimension, which means
470   // some dimension's indices have not been specified, an indicator that some
471   // index values have been added together.
472   // TODO: Investigate general usefulness; Effect on unit tests is to make index
473   // expressions more complicated.
474   if (DimsMissing)
475     wrapConstantDimensions();
476 
477   if (!isAffine())
478     computeBoundsOnAccessRelation(ArrayElemSize);
479 
480   // Introduce multi-element accesses in case the type loaded by this memory
481   // access is larger than the canonical element type of the array.
482   //
483   // An access ((float *)A)[i] to an array char *A is modeled as
484   // {[i] -> A[o] : 4 i <= o <= 4 i + 3
485   if (ElemBytes > ArrayElemSize) {
486     assert(ElemBytes % ArrayElemSize == 0 &&
487            "Loaded element size should be multiple of canonical element size");
488     auto *Map = isl_map_from_domain_and_range(
489         isl_set_universe(isl_space_copy(ArraySpace)),
490         isl_set_universe(isl_space_copy(ArraySpace)));
491     for (unsigned i = 0; i < DimsArray - 1; i++)
492       Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
493 
494     isl_constraint *C;
495     isl_local_space *LS;
496 
497     LS = isl_local_space_from_space(isl_map_get_space(Map));
498     int Num = ElemBytes / getScopArrayInfo()->getElemSizeInBytes();
499 
500     C = isl_constraint_alloc_inequality(isl_local_space_copy(LS));
501     C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, Num - 1));
502     C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, 1);
503     C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, -1);
504     Map = isl_map_add_constraint(Map, C);
505 
506     C = isl_constraint_alloc_inequality(LS);
507     C = isl_constraint_set_coefficient_si(C, isl_dim_in, DimsArray - 1, -1);
508     C = isl_constraint_set_coefficient_si(C, isl_dim_out, DimsArray - 1, 1);
509     C = isl_constraint_set_constant_val(C, isl_val_int_from_si(Ctx, 0));
510     Map = isl_map_add_constraint(Map, C);
511     AccessRelation = isl_map_apply_range(AccessRelation, Map);
512   }
513 
514   isl_space_free(ArraySpace);
515 }
516 
517 const std::string
518 MemoryAccess::getReductionOperatorStr(MemoryAccess::ReductionType RT) {
519   switch (RT) {
520   case MemoryAccess::RT_NONE:
521     llvm_unreachable("Requested a reduction operator string for a memory "
522                      "access which isn't a reduction");
523   case MemoryAccess::RT_ADD:
524     return "+";
525   case MemoryAccess::RT_MUL:
526     return "*";
527   case MemoryAccess::RT_BOR:
528     return "|";
529   case MemoryAccess::RT_BXOR:
530     return "^";
531   case MemoryAccess::RT_BAND:
532     return "&";
533   }
534   llvm_unreachable("Unknown reduction type");
535   return "";
536 }
537 
538 /// Return the reduction type for a given binary operator.
539 static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
540                                                     const Instruction *Load) {
541   if (!BinOp)
542     return MemoryAccess::RT_NONE;
543   switch (BinOp->getOpcode()) {
544   case Instruction::FAdd:
545     if (!BinOp->hasUnsafeAlgebra())
546       return MemoryAccess::RT_NONE;
547   // Fall through
548   case Instruction::Add:
549     return MemoryAccess::RT_ADD;
550   case Instruction::Or:
551     return MemoryAccess::RT_BOR;
552   case Instruction::Xor:
553     return MemoryAccess::RT_BXOR;
554   case Instruction::And:
555     return MemoryAccess::RT_BAND;
556   case Instruction::FMul:
557     if (!BinOp->hasUnsafeAlgebra())
558       return MemoryAccess::RT_NONE;
559   // Fall through
560   case Instruction::Mul:
561     if (DisableMultiplicativeReductions)
562       return MemoryAccess::RT_NONE;
563     return MemoryAccess::RT_MUL;
564   default:
565     return MemoryAccess::RT_NONE;
566   }
567 }
568 
569 MemoryAccess::~MemoryAccess() {
570   isl_id_free(Id);
571   isl_set_free(InvalidDomain);
572   isl_map_free(AccessRelation);
573   isl_map_free(NewAccessRelation);
574 }
575 
576 const ScopArrayInfo *MemoryAccess::getOriginalScopArrayInfo() const {
577   isl_id *ArrayId = getArrayId();
578   void *User = isl_id_get_user(ArrayId);
579   const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
580   isl_id_free(ArrayId);
581   return SAI;
582 }
583 
584 const ScopArrayInfo *MemoryAccess::getLatestScopArrayInfo() const {
585   isl_id *ArrayId = getLatestArrayId();
586   void *User = isl_id_get_user(ArrayId);
587   const ScopArrayInfo *SAI = static_cast<ScopArrayInfo *>(User);
588   isl_id_free(ArrayId);
589   return SAI;
590 }
591 
592 __isl_give isl_id *MemoryAccess::getOriginalArrayId() const {
593   return isl_map_get_tuple_id(AccessRelation, isl_dim_out);
594 }
595 
596 __isl_give isl_id *MemoryAccess::getLatestArrayId() const {
597   if (!hasNewAccessRelation())
598     return getOriginalArrayId();
599   return isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
600 }
601 
602 __isl_give isl_map *MemoryAccess::getAddressFunction() const {
603   return isl_map_lexmin(getAccessRelation());
604 }
605 
606 __isl_give isl_pw_multi_aff *MemoryAccess::applyScheduleToAccessRelation(
607     __isl_take isl_union_map *USchedule) const {
608   isl_map *Schedule, *ScheduledAccRel;
609   isl_union_set *UDomain;
610 
611   UDomain = isl_union_set_from_set(getStatement()->getDomain());
612   USchedule = isl_union_map_intersect_domain(USchedule, UDomain);
613   Schedule = isl_map_from_union_map(USchedule);
614   ScheduledAccRel = isl_map_apply_domain(getAddressFunction(), Schedule);
615   return isl_pw_multi_aff_from_map(ScheduledAccRel);
616 }
617 
618 __isl_give isl_map *MemoryAccess::getOriginalAccessRelation() const {
619   return isl_map_copy(AccessRelation);
620 }
621 
622 std::string MemoryAccess::getOriginalAccessRelationStr() const {
623   return stringFromIslObj(AccessRelation);
624 }
625 
626 __isl_give isl_space *MemoryAccess::getOriginalAccessRelationSpace() const {
627   return isl_map_get_space(AccessRelation);
628 }
629 
630 __isl_give isl_map *MemoryAccess::getNewAccessRelation() const {
631   return isl_map_copy(NewAccessRelation);
632 }
633 
634 std::string MemoryAccess::getNewAccessRelationStr() const {
635   return stringFromIslObj(NewAccessRelation);
636 }
637 
638 __isl_give isl_basic_map *
639 MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
640   isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
641   Space = isl_space_align_params(Space, Statement->getDomainSpace());
642 
643   return isl_basic_map_from_domain_and_range(
644       isl_basic_set_universe(Statement->getDomainSpace()),
645       isl_basic_set_universe(Space));
646 }
647 
648 // Formalize no out-of-bound access assumption
649 //
650 // When delinearizing array accesses we optimistically assume that the
651 // delinearized accesses do not access out of bound locations (the subscript
652 // expression of each array evaluates for each statement instance that is
653 // executed to a value that is larger than zero and strictly smaller than the
654 // size of the corresponding dimension). The only exception is the outermost
655 // dimension for which we do not need to assume any upper bound.  At this point
656 // we formalize this assumption to ensure that at code generation time the
657 // relevant run-time checks can be generated.
658 //
659 // To find the set of constraints necessary to avoid out of bound accesses, we
660 // first build the set of data locations that are not within array bounds. We
661 // then apply the reverse access relation to obtain the set of iterations that
662 // may contain invalid accesses and reduce this set of iterations to the ones
663 // that are actually executed by intersecting them with the domain of the
664 // statement. If we now project out all loop dimensions, we obtain a set of
665 // parameters that may cause statement instances to be executed that may
666 // possibly yield out of bound memory accesses. The complement of these
667 // constraints is the set of constraints that needs to be assumed to ensure such
668 // statement instances are never executed.
669 void MemoryAccess::assumeNoOutOfBound() {
670   auto *SAI = getScopArrayInfo();
671   isl_space *Space = isl_space_range(getOriginalAccessRelationSpace());
672   isl_set *Outside = isl_set_empty(isl_space_copy(Space));
673   for (int i = 1, Size = isl_space_dim(Space, isl_dim_set); i < Size; ++i) {
674     isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
675     isl_pw_aff *Var =
676         isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
677     isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
678 
679     isl_set *DimOutside;
680 
681     DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
682     isl_pw_aff *SizeE = SAI->getDimensionSizePw(i);
683     SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
684                                 isl_space_dim(Space, isl_dim_set));
685     SizeE = isl_pw_aff_set_tuple_id(SizeE, isl_dim_in,
686                                     isl_space_get_tuple_id(Space, isl_dim_set));
687 
688     DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
689 
690     Outside = isl_set_union(Outside, DimOutside);
691   }
692 
693   Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
694   Outside = isl_set_intersect(Outside, Statement->getDomain());
695   Outside = isl_set_params(Outside);
696 
697   // Remove divs to avoid the construction of overly complicated assumptions.
698   // Doing so increases the set of parameter combinations that are assumed to
699   // not appear. This is always save, but may make the resulting run-time check
700   // bail out more often than strictly necessary.
701   Outside = isl_set_remove_divs(Outside);
702   Outside = isl_set_complement(Outside);
703   const auto &Loc = getAccessInstruction()
704                         ? getAccessInstruction()->getDebugLoc()
705                         : DebugLoc();
706   Statement->getParent()->recordAssumption(INBOUNDS, Outside, Loc,
707                                            AS_ASSUMPTION);
708   isl_space_free(Space);
709 }
710 
711 void MemoryAccess::buildMemIntrinsicAccessRelation() {
712   assert(isMemoryIntrinsic());
713   assert(Subscripts.size() == 2 && Sizes.size() == 1);
714 
715   auto *SubscriptPWA = getPwAff(Subscripts[0]);
716   auto *SubscriptMap = isl_map_from_pw_aff(SubscriptPWA);
717 
718   isl_map *LengthMap;
719   if (Subscripts[1] == nullptr) {
720     LengthMap = isl_map_universe(isl_map_get_space(SubscriptMap));
721   } else {
722     auto *LengthPWA = getPwAff(Subscripts[1]);
723     LengthMap = isl_map_from_pw_aff(LengthPWA);
724     auto *RangeSpace = isl_space_range(isl_map_get_space(LengthMap));
725     LengthMap = isl_map_apply_range(LengthMap, isl_map_lex_gt(RangeSpace));
726   }
727   LengthMap = isl_map_lower_bound_si(LengthMap, isl_dim_out, 0, 0);
728   LengthMap = isl_map_align_params(LengthMap, isl_map_get_space(SubscriptMap));
729   SubscriptMap =
730       isl_map_align_params(SubscriptMap, isl_map_get_space(LengthMap));
731   LengthMap = isl_map_sum(LengthMap, SubscriptMap);
732   AccessRelation = isl_map_set_tuple_id(LengthMap, isl_dim_in,
733                                         getStatement()->getDomainId());
734 }
735 
736 void MemoryAccess::computeBoundsOnAccessRelation(unsigned ElementSize) {
737   ScalarEvolution *SE = Statement->getParent()->getSE();
738 
739   auto MAI = MemAccInst(getAccessInstruction());
740   if (isa<MemIntrinsic>(MAI))
741     return;
742 
743   Value *Ptr = MAI.getPointerOperand();
744   if (!Ptr || !SE->isSCEVable(Ptr->getType()))
745     return;
746 
747   auto *PtrSCEV = SE->getSCEV(Ptr);
748   if (isa<SCEVCouldNotCompute>(PtrSCEV))
749     return;
750 
751   auto *BasePtrSCEV = SE->getPointerBase(PtrSCEV);
752   if (BasePtrSCEV && !isa<SCEVCouldNotCompute>(BasePtrSCEV))
753     PtrSCEV = SE->getMinusSCEV(PtrSCEV, BasePtrSCEV);
754 
755   const ConstantRange &Range = SE->getSignedRange(PtrSCEV);
756   if (Range.isFullSet())
757     return;
758 
759   if (Range.isWrappedSet())
760     return;
761 
762   bool isWrapping = Range.isSignWrappedSet();
763 
764   unsigned BW = Range.getBitWidth();
765   const auto One = APInt(BW, 1);
766   const auto LB = isWrapping ? Range.getLower() : Range.getSignedMin();
767   const auto UB = isWrapping ? (Range.getUpper() - One) : Range.getSignedMax();
768 
769   auto Min = LB.sdiv(APInt(BW, ElementSize));
770   auto Max = UB.sdiv(APInt(BW, ElementSize)) + One;
771 
772   assert(Min.sle(Max) && "Minimum expected to be less or equal than max");
773 
774   isl_set *AccessRange = isl_map_range(isl_map_copy(AccessRelation));
775   AccessRange =
776       addRangeBoundsToSet(AccessRange, ConstantRange(Min, Max), 0, isl_dim_set);
777   AccessRelation = isl_map_intersect_range(AccessRelation, AccessRange);
778 }
779 
780 void MemoryAccess::foldAccessRelation() {
781   if (Sizes.size() < 2 || isa<SCEVConstant>(Sizes[1]))
782     return;
783 
784   int Size = Subscripts.size();
785 
786   for (int i = Size - 2; i >= 0; --i) {
787     isl_space *Space;
788     isl_map *MapOne, *MapTwo;
789     isl_pw_aff *DimSize = getPwAff(Sizes[i + 1]);
790 
791     isl_space *SpaceSize = isl_pw_aff_get_space(DimSize);
792     isl_pw_aff_free(DimSize);
793     isl_id *ParamId = isl_space_get_dim_id(SpaceSize, isl_dim_param, 0);
794 
795     Space = isl_map_get_space(AccessRelation);
796     Space = isl_space_map_from_set(isl_space_range(Space));
797     Space = isl_space_align_params(Space, SpaceSize);
798 
799     int ParamLocation = isl_space_find_dim_by_id(Space, isl_dim_param, ParamId);
800     isl_id_free(ParamId);
801 
802     MapOne = isl_map_universe(isl_space_copy(Space));
803     for (int j = 0; j < Size; ++j)
804       MapOne = isl_map_equate(MapOne, isl_dim_in, j, isl_dim_out, j);
805     MapOne = isl_map_lower_bound_si(MapOne, isl_dim_in, i + 1, 0);
806 
807     MapTwo = isl_map_universe(isl_space_copy(Space));
808     for (int j = 0; j < Size; ++j)
809       if (j < i || j > i + 1)
810         MapTwo = isl_map_equate(MapTwo, isl_dim_in, j, isl_dim_out, j);
811 
812     isl_local_space *LS = isl_local_space_from_space(Space);
813     isl_constraint *C;
814     C = isl_equality_alloc(isl_local_space_copy(LS));
815     C = isl_constraint_set_constant_si(C, -1);
816     C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, 1);
817     C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, -1);
818     MapTwo = isl_map_add_constraint(MapTwo, C);
819     C = isl_equality_alloc(LS);
820     C = isl_constraint_set_coefficient_si(C, isl_dim_in, i + 1, 1);
821     C = isl_constraint_set_coefficient_si(C, isl_dim_out, i + 1, -1);
822     C = isl_constraint_set_coefficient_si(C, isl_dim_param, ParamLocation, 1);
823     MapTwo = isl_map_add_constraint(MapTwo, C);
824     MapTwo = isl_map_upper_bound_si(MapTwo, isl_dim_in, i + 1, -1);
825 
826     MapOne = isl_map_union(MapOne, MapTwo);
827     AccessRelation = isl_map_apply_range(AccessRelation, MapOne);
828   }
829 
830   isl_id *BaseAddrId = getScopArrayInfo()->getBasePtrId();
831   auto Space = Statement->getDomainSpace();
832   AccessRelation = isl_map_set_tuple_id(
833       AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
834   AccessRelation =
835       isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
836   AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
837   isl_space_free(Space);
838 }
839 
840 /// Check if @p Expr is divisible by @p Size.
841 static bool isDivisible(const SCEV *Expr, unsigned Size, ScalarEvolution &SE) {
842   assert(Size != 0);
843   if (Size == 1)
844     return true;
845 
846   // Only one factor needs to be divisible.
847   if (auto *MulExpr = dyn_cast<SCEVMulExpr>(Expr)) {
848     for (auto *FactorExpr : MulExpr->operands())
849       if (isDivisible(FactorExpr, Size, SE))
850         return true;
851     return false;
852   }
853 
854   // For other n-ary expressions (Add, AddRec, Max,...) all operands need
855   // to be divisble.
856   if (auto *NAryExpr = dyn_cast<SCEVNAryExpr>(Expr)) {
857     for (auto *OpExpr : NAryExpr->operands())
858       if (!isDivisible(OpExpr, Size, SE))
859         return false;
860     return true;
861   }
862 
863   auto *SizeSCEV = SE.getConstant(Expr->getType(), Size);
864   auto *UDivSCEV = SE.getUDivExpr(Expr, SizeSCEV);
865   auto *MulSCEV = SE.getMulExpr(UDivSCEV, SizeSCEV);
866   return MulSCEV == Expr;
867 }
868 
869 void MemoryAccess::buildAccessRelation(const ScopArrayInfo *SAI) {
870   assert(!AccessRelation && "AccessReltation already built");
871 
872   // Initialize the invalid domain which describes all iterations for which the
873   // access relation is not modeled correctly.
874   auto *StmtInvalidDomain = getStatement()->getInvalidDomain();
875   InvalidDomain = isl_set_empty(isl_set_get_space(StmtInvalidDomain));
876   isl_set_free(StmtInvalidDomain);
877 
878   isl_ctx *Ctx = isl_id_get_ctx(Id);
879   isl_id *BaseAddrId = SAI->getBasePtrId();
880 
881   if (getAccessInstruction() && isa<MemIntrinsic>(getAccessInstruction())) {
882     buildMemIntrinsicAccessRelation();
883     AccessRelation =
884         isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
885     return;
886   }
887 
888   if (!isAffine()) {
889     // We overapproximate non-affine accesses with a possible access to the
890     // whole array. For read accesses it does not make a difference, if an
891     // access must or may happen. However, for write accesses it is important to
892     // differentiate between writes that must happen and writes that may happen.
893     if (!AccessRelation)
894       AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
895 
896     AccessRelation =
897         isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
898     return;
899   }
900 
901   isl_space *Space = isl_space_alloc(Ctx, 0, Statement->getNumIterators(), 0);
902   AccessRelation = isl_map_universe(Space);
903 
904   for (int i = 0, Size = Subscripts.size(); i < Size; ++i) {
905     isl_pw_aff *Affine = getPwAff(Subscripts[i]);
906     isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
907     AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
908   }
909 
910   Space = Statement->getDomainSpace();
911   AccessRelation = isl_map_set_tuple_id(
912       AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
913   AccessRelation =
914       isl_map_set_tuple_id(AccessRelation, isl_dim_out, BaseAddrId);
915 
916   AccessRelation = isl_map_gist_domain(AccessRelation, Statement->getDomain());
917   isl_space_free(Space);
918 }
919 
920 MemoryAccess::MemoryAccess(ScopStmt *Stmt, Instruction *AccessInst,
921                            AccessType AccType, Value *BaseAddress,
922                            Type *ElementType, bool Affine,
923                            ArrayRef<const SCEV *> Subscripts,
924                            ArrayRef<const SCEV *> Sizes, Value *AccessValue,
925                            MemoryKind Kind, StringRef BaseName)
926     : Kind(Kind), AccType(AccType), RedType(RT_NONE), Statement(Stmt),
927       InvalidDomain(nullptr), BaseAddr(BaseAddress), BaseName(BaseName),
928       ElementType(ElementType), Sizes(Sizes.begin(), Sizes.end()),
929       AccessInstruction(AccessInst), AccessValue(AccessValue), IsAffine(Affine),
930       Subscripts(Subscripts.begin(), Subscripts.end()), AccessRelation(nullptr),
931       NewAccessRelation(nullptr) {
932   static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
933   const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
934 
935   std::string IdName =
936       getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
937   Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
938 }
939 
940 MemoryAccess::MemoryAccess(ScopStmt *Stmt, AccessType AccType,
941                            __isl_take isl_map *AccRel)
942     : Kind(MemoryKind::Array), AccType(AccType), RedType(RT_NONE),
943       Statement(Stmt), InvalidDomain(nullptr), AccessInstruction(nullptr),
944       IsAffine(true), AccessRelation(nullptr), NewAccessRelation(AccRel) {
945   auto *ArrayInfoId = isl_map_get_tuple_id(NewAccessRelation, isl_dim_out);
946   auto *SAI = ScopArrayInfo::getFromId(ArrayInfoId);
947   Sizes.push_back(nullptr);
948   for (unsigned i = 1; i < SAI->getNumberOfDimensions(); i++)
949     Sizes.push_back(SAI->getDimensionSize(i));
950   ElementType = SAI->getElementType();
951   BaseAddr = SAI->getBasePtr();
952   BaseName = SAI->getName();
953   static const std::string TypeStrings[] = {"", "_Read", "_Write", "_MayWrite"};
954   const std::string Access = TypeStrings[AccType] + utostr(Stmt->size()) + "_";
955 
956   std::string IdName =
957       getIslCompatibleName(Stmt->getBaseName(), Access, BaseName);
958   Id = isl_id_alloc(Stmt->getParent()->getIslCtx(), IdName.c_str(), this);
959 }
960 
961 void MemoryAccess::realignParams() {
962   auto *Ctx = Statement->getParent()->getContext();
963   InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
964   AccessRelation = isl_map_gist_params(AccessRelation, Ctx);
965 }
966 
967 const std::string MemoryAccess::getReductionOperatorStr() const {
968   return MemoryAccess::getReductionOperatorStr(getReductionType());
969 }
970 
971 __isl_give isl_id *MemoryAccess::getId() const { return isl_id_copy(Id); }
972 
973 raw_ostream &polly::operator<<(raw_ostream &OS,
974                                MemoryAccess::ReductionType RT) {
975   if (RT == MemoryAccess::RT_NONE)
976     OS << "NONE";
977   else
978     OS << MemoryAccess::getReductionOperatorStr(RT);
979   return OS;
980 }
981 
982 void MemoryAccess::print(raw_ostream &OS) const {
983   switch (AccType) {
984   case READ:
985     OS.indent(12) << "ReadAccess :=\t";
986     break;
987   case MUST_WRITE:
988     OS.indent(12) << "MustWriteAccess :=\t";
989     break;
990   case MAY_WRITE:
991     OS.indent(12) << "MayWriteAccess :=\t";
992     break;
993   }
994   OS << "[Reduction Type: " << getReductionType() << "] ";
995   OS << "[Scalar: " << isScalarKind() << "]\n";
996   OS.indent(16) << getOriginalAccessRelationStr() << ";\n";
997   if (hasNewAccessRelation())
998     OS.indent(11) << "new: " << getNewAccessRelationStr() << ";\n";
999 }
1000 
1001 void MemoryAccess::dump() const { print(errs()); }
1002 
1003 __isl_give isl_pw_aff *MemoryAccess::getPwAff(const SCEV *E) {
1004   auto *Stmt = getStatement();
1005   PWACtx PWAC = Stmt->getParent()->getPwAff(E, Stmt->getEntryBlock());
1006   isl_set *StmtDom = isl_set_reset_tuple_id(getStatement()->getDomain());
1007   isl_set *NewInvalidDom = isl_set_intersect(StmtDom, PWAC.second);
1008   InvalidDomain = isl_set_union(InvalidDomain, NewInvalidDom);
1009   return PWAC.first;
1010 }
1011 
1012 // Create a map in the size of the provided set domain, that maps from the
1013 // one element of the provided set domain to another element of the provided
1014 // set domain.
1015 // The mapping is limited to all points that are equal in all but the last
1016 // dimension and for which the last dimension of the input is strict smaller
1017 // than the last dimension of the output.
1018 //
1019 //   getEqualAndLarger(set[i0, i1, ..., iX]):
1020 //
1021 //   set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
1022 //     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
1023 //
1024 static isl_map *getEqualAndLarger(__isl_take isl_space *setDomain) {
1025   isl_space *Space = isl_space_map_from_set(setDomain);
1026   isl_map *Map = isl_map_universe(Space);
1027   unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
1028 
1029   // Set all but the last dimension to be equal for the input and output
1030   //
1031   //   input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
1032   //     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
1033   for (unsigned i = 0; i < lastDimension; ++i)
1034     Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
1035 
1036   // Set the last dimension of the input to be strict smaller than the
1037   // last dimension of the output.
1038   //
1039   //   input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
1040   Map = isl_map_order_lt(Map, isl_dim_in, lastDimension, isl_dim_out,
1041                          lastDimension);
1042   return Map;
1043 }
1044 
1045 __isl_give isl_set *
1046 MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
1047   isl_map *S = const_cast<isl_map *>(Schedule);
1048   isl_map *AccessRelation = getAccessRelation();
1049   isl_space *Space = isl_space_range(isl_map_get_space(S));
1050   isl_map *NextScatt = getEqualAndLarger(Space);
1051 
1052   S = isl_map_reverse(S);
1053   NextScatt = isl_map_lexmin(NextScatt);
1054 
1055   NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
1056   NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
1057   NextScatt = isl_map_apply_domain(NextScatt, S);
1058   NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
1059 
1060   isl_set *Deltas = isl_map_deltas(NextScatt);
1061   return Deltas;
1062 }
1063 
1064 bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
1065                              int StrideWidth) const {
1066   isl_set *Stride, *StrideX;
1067   bool IsStrideX;
1068 
1069   Stride = getStride(Schedule);
1070   StrideX = isl_set_universe(isl_set_get_space(Stride));
1071   for (unsigned i = 0; i < isl_set_dim(StrideX, isl_dim_set) - 1; i++)
1072     StrideX = isl_set_fix_si(StrideX, isl_dim_set, i, 0);
1073   StrideX = isl_set_fix_si(StrideX, isl_dim_set,
1074                            isl_set_dim(StrideX, isl_dim_set) - 1, StrideWidth);
1075   IsStrideX = isl_set_is_subset(Stride, StrideX);
1076 
1077   isl_set_free(StrideX);
1078   isl_set_free(Stride);
1079 
1080   return IsStrideX;
1081 }
1082 
1083 bool MemoryAccess::isStrideZero(__isl_take const isl_map *Schedule) const {
1084   return isStrideX(Schedule, 0);
1085 }
1086 
1087 bool MemoryAccess::isStrideOne(__isl_take const isl_map *Schedule) const {
1088   return isStrideX(Schedule, 1);
1089 }
1090 
1091 void MemoryAccess::setAccessRelation(__isl_take isl_map *NewAccess) {
1092   isl_map_free(AccessRelation);
1093   AccessRelation = NewAccess;
1094 }
1095 
1096 void MemoryAccess::setNewAccessRelation(__isl_take isl_map *NewAccess) {
1097   assert(NewAccess);
1098 
1099 #ifndef NDEBUG
1100   // Check domain space compatibility.
1101   auto *NewSpace = isl_map_get_space(NewAccess);
1102   auto *NewDomainSpace = isl_space_domain(isl_space_copy(NewSpace));
1103   auto *OriginalDomainSpace = getStatement()->getDomainSpace();
1104   assert(isl_space_has_equal_tuples(OriginalDomainSpace, NewDomainSpace));
1105   isl_space_free(NewDomainSpace);
1106   isl_space_free(OriginalDomainSpace);
1107 
1108   // Check whether there is an access for every statement instance.
1109   auto *StmtDomain = getStatement()->getDomain();
1110   StmtDomain = isl_set_intersect_params(
1111       StmtDomain, getStatement()->getParent()->getContext());
1112   auto *NewDomain = isl_map_domain(isl_map_copy(NewAccess));
1113   assert(isl_set_is_subset(StmtDomain, NewDomain) &&
1114          "Partial accesses not supported");
1115   isl_set_free(NewDomain);
1116   isl_set_free(StmtDomain);
1117 
1118   auto *NewAccessSpace = isl_space_range(NewSpace);
1119   assert(isl_space_has_tuple_id(NewAccessSpace, isl_dim_set) &&
1120          "Must specify the array that is accessed");
1121   auto *NewArrayId = isl_space_get_tuple_id(NewAccessSpace, isl_dim_set);
1122   auto *SAI = static_cast<ScopArrayInfo *>(isl_id_get_user(NewArrayId));
1123   assert(SAI && "Must set a ScopArrayInfo");
1124 
1125   if (SAI->isArrayKind() && SAI->getBasePtrOriginSAI()) {
1126     InvariantEquivClassTy *EqClass =
1127         getStatement()->getParent()->lookupInvariantEquivClass(
1128             SAI->getBasePtr());
1129     assert(EqClass &&
1130            "Access functions to indirect arrays must have an invariant and "
1131            "hoisted base pointer");
1132   }
1133 
1134   // Check whether access dimensions correspond to number of dimensions of the
1135   // accesses array.
1136   auto Dims = SAI->getNumberOfDimensions();
1137   assert(isl_space_dim(NewAccessSpace, isl_dim_set) == Dims &&
1138          "Access dims must match array dims");
1139   isl_space_free(NewAccessSpace);
1140   isl_id_free(NewArrayId);
1141 #endif
1142 
1143   isl_map_free(NewAccessRelation);
1144   NewAccessRelation = NewAccess;
1145 }
1146 
1147 //===----------------------------------------------------------------------===//
1148 
1149 __isl_give isl_map *ScopStmt::getSchedule() const {
1150   isl_set *Domain = getDomain();
1151   if (isl_set_is_empty(Domain)) {
1152     isl_set_free(Domain);
1153     return isl_map_from_aff(
1154         isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1155   }
1156   auto *Schedule = getParent()->getSchedule();
1157   if (!Schedule) {
1158     isl_set_free(Domain);
1159     return nullptr;
1160   }
1161   Schedule = isl_union_map_intersect_domain(
1162       Schedule, isl_union_set_from_set(isl_set_copy(Domain)));
1163   if (isl_union_map_is_empty(Schedule)) {
1164     isl_set_free(Domain);
1165     isl_union_map_free(Schedule);
1166     return isl_map_from_aff(
1167         isl_aff_zero_on_domain(isl_local_space_from_space(getDomainSpace())));
1168   }
1169   auto *M = isl_map_from_union_map(Schedule);
1170   M = isl_map_coalesce(M);
1171   M = isl_map_gist_domain(M, Domain);
1172   M = isl_map_coalesce(M);
1173   return M;
1174 }
1175 
1176 __isl_give isl_pw_aff *ScopStmt::getPwAff(const SCEV *E, bool NonNegative) {
1177   PWACtx PWAC = getParent()->getPwAff(E, getEntryBlock(), NonNegative);
1178   InvalidDomain = isl_set_union(InvalidDomain, PWAC.second);
1179   return PWAC.first;
1180 }
1181 
1182 void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
1183   assert(isl_set_is_subset(NewDomain, Domain) &&
1184          "New domain is not a subset of old domain!");
1185   isl_set_free(Domain);
1186   Domain = NewDomain;
1187 }
1188 
1189 void ScopStmt::buildAccessRelations() {
1190   Scop &S = *getParent();
1191   for (MemoryAccess *Access : MemAccs) {
1192     Type *ElementType = Access->getElementType();
1193 
1194     MemoryKind Ty;
1195     if (Access->isPHIKind())
1196       Ty = MemoryKind::PHI;
1197     else if (Access->isExitPHIKind())
1198       Ty = MemoryKind::ExitPHI;
1199     else if (Access->isValueKind())
1200       Ty = MemoryKind::Value;
1201     else
1202       Ty = MemoryKind::Array;
1203 
1204     auto *SAI = S.getOrCreateScopArrayInfo(Access->getOriginalBaseAddr(),
1205                                            ElementType, Access->Sizes, Ty);
1206     Access->buildAccessRelation(SAI);
1207   }
1208 }
1209 
1210 void ScopStmt::addAccess(MemoryAccess *Access) {
1211   Instruction *AccessInst = Access->getAccessInstruction();
1212 
1213   if (Access->isArrayKind()) {
1214     MemoryAccessList &MAL = InstructionToAccess[AccessInst];
1215     MAL.emplace_front(Access);
1216   } else if (Access->isValueKind() && Access->isWrite()) {
1217     Instruction *AccessVal = cast<Instruction>(Access->getAccessValue());
1218     assert(Parent.getStmtFor(AccessVal) == this);
1219     assert(!ValueWrites.lookup(AccessVal));
1220 
1221     ValueWrites[AccessVal] = Access;
1222   } else if (Access->isValueKind() && Access->isRead()) {
1223     Value *AccessVal = Access->getAccessValue();
1224     assert(!ValueReads.lookup(AccessVal));
1225 
1226     ValueReads[AccessVal] = Access;
1227   } else if (Access->isAnyPHIKind() && Access->isWrite()) {
1228     PHINode *PHI = cast<PHINode>(Access->getAccessValue());
1229     assert(!PHIWrites.lookup(PHI));
1230 
1231     PHIWrites[PHI] = Access;
1232   }
1233 
1234   MemAccs.push_back(Access);
1235 }
1236 
1237 void ScopStmt::realignParams() {
1238   for (MemoryAccess *MA : *this)
1239     MA->realignParams();
1240 
1241   auto *Ctx = Parent.getContext();
1242   InvalidDomain = isl_set_gist_params(InvalidDomain, isl_set_copy(Ctx));
1243   Domain = isl_set_gist_params(Domain, Ctx);
1244 }
1245 
1246 /// Add @p BSet to the set @p User if @p BSet is bounded.
1247 static isl_stat collectBoundedParts(__isl_take isl_basic_set *BSet,
1248                                     void *User) {
1249   isl_set **BoundedParts = static_cast<isl_set **>(User);
1250   if (isl_basic_set_is_bounded(BSet))
1251     *BoundedParts = isl_set_union(*BoundedParts, isl_set_from_basic_set(BSet));
1252   else
1253     isl_basic_set_free(BSet);
1254   return isl_stat_ok;
1255 }
1256 
1257 /// Return the bounded parts of @p S.
1258 static __isl_give isl_set *collectBoundedParts(__isl_take isl_set *S) {
1259   isl_set *BoundedParts = isl_set_empty(isl_set_get_space(S));
1260   isl_set_foreach_basic_set(S, collectBoundedParts, &BoundedParts);
1261   isl_set_free(S);
1262   return BoundedParts;
1263 }
1264 
1265 /// Compute the (un)bounded parts of @p S wrt. to dimension @p Dim.
1266 ///
1267 /// @returns A separation of @p S into first an unbounded then a bounded subset,
1268 ///          both with regards to the dimension @p Dim.
1269 static std::pair<__isl_give isl_set *, __isl_give isl_set *>
1270 partitionSetParts(__isl_take isl_set *S, unsigned Dim) {
1271 
1272   for (unsigned u = 0, e = isl_set_n_dim(S); u < e; u++)
1273     S = isl_set_lower_bound_si(S, isl_dim_set, u, 0);
1274 
1275   unsigned NumDimsS = isl_set_n_dim(S);
1276   isl_set *OnlyDimS = isl_set_copy(S);
1277 
1278   // Remove dimensions that are greater than Dim as they are not interesting.
1279   assert(NumDimsS >= Dim + 1);
1280   OnlyDimS =
1281       isl_set_project_out(OnlyDimS, isl_dim_set, Dim + 1, NumDimsS - Dim - 1);
1282 
1283   // Create artificial parametric upper bounds for dimensions smaller than Dim
1284   // as we are not interested in them.
1285   OnlyDimS = isl_set_insert_dims(OnlyDimS, isl_dim_param, 0, Dim);
1286   for (unsigned u = 0; u < Dim; u++) {
1287     isl_constraint *C = isl_inequality_alloc(
1288         isl_local_space_from_space(isl_set_get_space(OnlyDimS)));
1289     C = isl_constraint_set_coefficient_si(C, isl_dim_param, u, 1);
1290     C = isl_constraint_set_coefficient_si(C, isl_dim_set, u, -1);
1291     OnlyDimS = isl_set_add_constraint(OnlyDimS, C);
1292   }
1293 
1294   // Collect all bounded parts of OnlyDimS.
1295   isl_set *BoundedParts = collectBoundedParts(OnlyDimS);
1296 
1297   // Create the dimensions greater than Dim again.
1298   BoundedParts = isl_set_insert_dims(BoundedParts, isl_dim_set, Dim + 1,
1299                                      NumDimsS - Dim - 1);
1300 
1301   // Remove the artificial upper bound parameters again.
1302   BoundedParts = isl_set_remove_dims(BoundedParts, isl_dim_param, 0, Dim);
1303 
1304   isl_set *UnboundedParts = isl_set_subtract(S, isl_set_copy(BoundedParts));
1305   return std::make_pair(UnboundedParts, BoundedParts);
1306 }
1307 
1308 /// Set the dimension Ids from @p From in @p To.
1309 static __isl_give isl_set *setDimensionIds(__isl_keep isl_set *From,
1310                                            __isl_take isl_set *To) {
1311   for (unsigned u = 0, e = isl_set_n_dim(From); u < e; u++) {
1312     isl_id *DimId = isl_set_get_dim_id(From, isl_dim_set, u);
1313     To = isl_set_set_dim_id(To, isl_dim_set, u, DimId);
1314   }
1315   return To;
1316 }
1317 
1318 /// Create the conditions under which @p L @p Pred @p R is true.
1319 static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1320                                              __isl_take isl_pw_aff *L,
1321                                              __isl_take isl_pw_aff *R) {
1322   switch (Pred) {
1323   case ICmpInst::ICMP_EQ:
1324     return isl_pw_aff_eq_set(L, R);
1325   case ICmpInst::ICMP_NE:
1326     return isl_pw_aff_ne_set(L, R);
1327   case ICmpInst::ICMP_SLT:
1328     return isl_pw_aff_lt_set(L, R);
1329   case ICmpInst::ICMP_SLE:
1330     return isl_pw_aff_le_set(L, R);
1331   case ICmpInst::ICMP_SGT:
1332     return isl_pw_aff_gt_set(L, R);
1333   case ICmpInst::ICMP_SGE:
1334     return isl_pw_aff_ge_set(L, R);
1335   case ICmpInst::ICMP_ULT:
1336     return isl_pw_aff_lt_set(L, R);
1337   case ICmpInst::ICMP_UGT:
1338     return isl_pw_aff_gt_set(L, R);
1339   case ICmpInst::ICMP_ULE:
1340     return isl_pw_aff_le_set(L, R);
1341   case ICmpInst::ICMP_UGE:
1342     return isl_pw_aff_ge_set(L, R);
1343   default:
1344     llvm_unreachable("Non integer predicate not supported");
1345   }
1346 }
1347 
1348 /// Create the conditions under which @p L @p Pred @p R is true.
1349 ///
1350 /// Helper function that will make sure the dimensions of the result have the
1351 /// same isl_id's as the @p Domain.
1352 static __isl_give isl_set *buildConditionSet(ICmpInst::Predicate Pred,
1353                                              __isl_take isl_pw_aff *L,
1354                                              __isl_take isl_pw_aff *R,
1355                                              __isl_keep isl_set *Domain) {
1356   isl_set *ConsequenceCondSet = buildConditionSet(Pred, L, R);
1357   return setDimensionIds(Domain, ConsequenceCondSet);
1358 }
1359 
1360 /// Build the conditions sets for the switch @p SI in the @p Domain.
1361 ///
1362 /// This will fill @p ConditionSets with the conditions under which control
1363 /// will be moved from @p SI to its successors. Hence, @p ConditionSets will
1364 /// have as many elements as @p SI has successors.
1365 static bool
1366 buildConditionSets(ScopStmt &Stmt, SwitchInst *SI, Loop *L,
1367                    __isl_keep isl_set *Domain,
1368                    SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1369 
1370   Value *Condition = getConditionFromTerminator(SI);
1371   assert(Condition && "No condition for switch");
1372 
1373   Scop &S = *Stmt.getParent();
1374   ScalarEvolution &SE = *S.getSE();
1375   isl_pw_aff *LHS, *RHS;
1376   LHS = Stmt.getPwAff(SE.getSCEVAtScope(Condition, L));
1377 
1378   unsigned NumSuccessors = SI->getNumSuccessors();
1379   ConditionSets.resize(NumSuccessors);
1380   for (auto &Case : SI->cases()) {
1381     unsigned Idx = Case.getSuccessorIndex();
1382     ConstantInt *CaseValue = Case.getCaseValue();
1383 
1384     RHS = Stmt.getPwAff(SE.getSCEV(CaseValue));
1385     isl_set *CaseConditionSet =
1386         buildConditionSet(ICmpInst::ICMP_EQ, isl_pw_aff_copy(LHS), RHS, Domain);
1387     ConditionSets[Idx] = isl_set_coalesce(
1388         isl_set_intersect(CaseConditionSet, isl_set_copy(Domain)));
1389   }
1390 
1391   assert(ConditionSets[0] == nullptr && "Default condition set was set");
1392   isl_set *ConditionSetUnion = isl_set_copy(ConditionSets[1]);
1393   for (unsigned u = 2; u < NumSuccessors; u++)
1394     ConditionSetUnion =
1395         isl_set_union(ConditionSetUnion, isl_set_copy(ConditionSets[u]));
1396   ConditionSets[0] = setDimensionIds(
1397       Domain, isl_set_subtract(isl_set_copy(Domain), ConditionSetUnion));
1398 
1399   isl_pw_aff_free(LHS);
1400 
1401   return true;
1402 }
1403 
1404 /// Build the conditions sets for the branch condition @p Condition in
1405 /// the @p Domain.
1406 ///
1407 /// This will fill @p ConditionSets with the conditions under which control
1408 /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1409 /// have as many elements as @p TI has successors. If @p TI is nullptr the
1410 /// context under which @p Condition is true/false will be returned as the
1411 /// new elements of @p ConditionSets.
1412 static bool
1413 buildConditionSets(ScopStmt &Stmt, Value *Condition, TerminatorInst *TI,
1414                    Loop *L, __isl_keep isl_set *Domain,
1415                    SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1416 
1417   Scop &S = *Stmt.getParent();
1418   isl_set *ConsequenceCondSet = nullptr;
1419   if (auto *CCond = dyn_cast<ConstantInt>(Condition)) {
1420     if (CCond->isZero())
1421       ConsequenceCondSet = isl_set_empty(isl_set_get_space(Domain));
1422     else
1423       ConsequenceCondSet = isl_set_universe(isl_set_get_space(Domain));
1424   } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Condition)) {
1425     auto Opcode = BinOp->getOpcode();
1426     assert(Opcode == Instruction::And || Opcode == Instruction::Or);
1427 
1428     bool Valid = buildConditionSets(Stmt, BinOp->getOperand(0), TI, L, Domain,
1429                                     ConditionSets) &&
1430                  buildConditionSets(Stmt, BinOp->getOperand(1), TI, L, Domain,
1431                                     ConditionSets);
1432     if (!Valid) {
1433       while (!ConditionSets.empty())
1434         isl_set_free(ConditionSets.pop_back_val());
1435       return false;
1436     }
1437 
1438     isl_set_free(ConditionSets.pop_back_val());
1439     isl_set *ConsCondPart0 = ConditionSets.pop_back_val();
1440     isl_set_free(ConditionSets.pop_back_val());
1441     isl_set *ConsCondPart1 = ConditionSets.pop_back_val();
1442 
1443     if (Opcode == Instruction::And)
1444       ConsequenceCondSet = isl_set_intersect(ConsCondPart0, ConsCondPart1);
1445     else
1446       ConsequenceCondSet = isl_set_union(ConsCondPart0, ConsCondPart1);
1447   } else {
1448     auto *ICond = dyn_cast<ICmpInst>(Condition);
1449     assert(ICond &&
1450            "Condition of exiting branch was neither constant nor ICmp!");
1451 
1452     ScalarEvolution &SE = *S.getSE();
1453     isl_pw_aff *LHS, *RHS;
1454     // For unsigned comparisons we assumed the signed bit of neither operand
1455     // to be set. The comparison is equal to a signed comparison under this
1456     // assumption.
1457     bool NonNeg = ICond->isUnsigned();
1458     LHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(0), L), NonNeg);
1459     RHS = Stmt.getPwAff(SE.getSCEVAtScope(ICond->getOperand(1), L), NonNeg);
1460     ConsequenceCondSet =
1461         buildConditionSet(ICond->getPredicate(), LHS, RHS, Domain);
1462   }
1463 
1464   // If no terminator was given we are only looking for parameter constraints
1465   // under which @p Condition is true/false.
1466   if (!TI)
1467     ConsequenceCondSet = isl_set_params(ConsequenceCondSet);
1468   assert(ConsequenceCondSet);
1469   ConsequenceCondSet = isl_set_coalesce(
1470       isl_set_intersect(ConsequenceCondSet, isl_set_copy(Domain)));
1471 
1472   isl_set *AlternativeCondSet = nullptr;
1473   bool TooComplex =
1474       isl_set_n_basic_set(ConsequenceCondSet) >= MaxDisjunctsInDomain;
1475 
1476   if (!TooComplex) {
1477     AlternativeCondSet = isl_set_subtract(isl_set_copy(Domain),
1478                                           isl_set_copy(ConsequenceCondSet));
1479     TooComplex =
1480         isl_set_n_basic_set(AlternativeCondSet) >= MaxDisjunctsInDomain;
1481   }
1482 
1483   if (TooComplex) {
1484     S.invalidate(COMPLEXITY, TI ? TI->getDebugLoc() : DebugLoc());
1485     isl_set_free(AlternativeCondSet);
1486     isl_set_free(ConsequenceCondSet);
1487     return false;
1488   }
1489 
1490   ConditionSets.push_back(ConsequenceCondSet);
1491   ConditionSets.push_back(isl_set_coalesce(AlternativeCondSet));
1492 
1493   return true;
1494 }
1495 
1496 /// Build the conditions sets for the terminator @p TI in the @p Domain.
1497 ///
1498 /// This will fill @p ConditionSets with the conditions under which control
1499 /// will be moved from @p TI to its successors. Hence, @p ConditionSets will
1500 /// have as many elements as @p TI has successors.
1501 static bool
1502 buildConditionSets(ScopStmt &Stmt, TerminatorInst *TI, Loop *L,
1503                    __isl_keep isl_set *Domain,
1504                    SmallVectorImpl<__isl_give isl_set *> &ConditionSets) {
1505 
1506   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
1507     return buildConditionSets(Stmt, SI, L, Domain, ConditionSets);
1508 
1509   assert(isa<BranchInst>(TI) && "Terminator was neither branch nor switch.");
1510 
1511   if (TI->getNumSuccessors() == 1) {
1512     ConditionSets.push_back(isl_set_copy(Domain));
1513     return true;
1514   }
1515 
1516   Value *Condition = getConditionFromTerminator(TI);
1517   assert(Condition && "No condition for Terminator");
1518 
1519   return buildConditionSets(Stmt, Condition, TI, L, Domain, ConditionSets);
1520 }
1521 
1522 void ScopStmt::buildDomain() {
1523   isl_id *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1524 
1525   Domain = getParent()->getDomainConditions(this);
1526   Domain = isl_set_set_tuple_id(Domain, Id);
1527 }
1528 
1529 void ScopStmt::collectSurroundingLoops() {
1530   for (unsigned u = 0, e = isl_set_n_dim(Domain); u < e; u++) {
1531     isl_id *DimId = isl_set_get_dim_id(Domain, isl_dim_set, u);
1532     NestLoops.push_back(static_cast<Loop *>(isl_id_get_user(DimId)));
1533     isl_id_free(DimId);
1534   }
1535 }
1536 
1537 ScopStmt::ScopStmt(Scop &parent, Region &R)
1538     : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(nullptr),
1539       R(&R), Build(nullptr) {
1540 
1541   BaseName = getIslCompatibleName("Stmt_", R.getNameStr(), "");
1542 }
1543 
1544 ScopStmt::ScopStmt(Scop &parent, BasicBlock &bb)
1545     : Parent(parent), InvalidDomain(nullptr), Domain(nullptr), BB(&bb),
1546       R(nullptr), Build(nullptr) {
1547 
1548   BaseName = getIslCompatibleName("Stmt_", &bb, "");
1549 }
1550 
1551 ScopStmt::ScopStmt(Scop &parent, __isl_take isl_map *SourceRel,
1552                    __isl_take isl_map *TargetRel, __isl_take isl_set *NewDomain)
1553     : Parent(parent), InvalidDomain(nullptr), Domain(NewDomain), BB(nullptr),
1554       R(nullptr), Build(nullptr) {
1555   BaseName = getIslCompatibleName("CopyStmt_", "",
1556                                   std::to_string(parent.getCopyStmtsNum()));
1557   auto *Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
1558   Domain = isl_set_set_tuple_id(Domain, isl_id_copy(Id));
1559   TargetRel = isl_map_set_tuple_id(TargetRel, isl_dim_in, Id);
1560   auto *Access =
1561       new MemoryAccess(this, MemoryAccess::AccessType::MUST_WRITE, TargetRel);
1562   parent.addAccessFunction(Access);
1563   addAccess(Access);
1564   SourceRel = isl_map_set_tuple_id(SourceRel, isl_dim_in, isl_id_copy(Id));
1565   Access = new MemoryAccess(this, MemoryAccess::AccessType::READ, SourceRel);
1566   parent.addAccessFunction(Access);
1567   addAccess(Access);
1568 }
1569 
1570 void ScopStmt::init(LoopInfo &LI) {
1571   assert(!Domain && "init must be called only once");
1572 
1573   buildDomain();
1574   collectSurroundingLoops();
1575   buildAccessRelations();
1576 
1577   if (DetectReductions)
1578     checkForReductions();
1579 }
1580 
1581 /// Collect loads which might form a reduction chain with @p StoreMA.
1582 ///
1583 /// Check if the stored value for @p StoreMA is a binary operator with one or
1584 /// two loads as operands. If the binary operand is commutative & associative,
1585 /// used only once (by @p StoreMA) and its load operands are also used only
1586 /// once, we have found a possible reduction chain. It starts at an operand
1587 /// load and includes the binary operator and @p StoreMA.
1588 ///
1589 /// Note: We allow only one use to ensure the load and binary operator cannot
1590 ///       escape this block or into any other store except @p StoreMA.
1591 void ScopStmt::collectCandiateReductionLoads(
1592     MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
1593   auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
1594   if (!Store)
1595     return;
1596 
1597   // Skip if there is not one binary operator between the load and the store
1598   auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
1599   if (!BinOp)
1600     return;
1601 
1602   // Skip if the binary operators has multiple uses
1603   if (BinOp->getNumUses() != 1)
1604     return;
1605 
1606   // Skip if the opcode of the binary operator is not commutative/associative
1607   if (!BinOp->isCommutative() || !BinOp->isAssociative())
1608     return;
1609 
1610   // Skip if the binary operator is outside the current SCoP
1611   if (BinOp->getParent() != Store->getParent())
1612     return;
1613 
1614   // Skip if it is a multiplicative reduction and we disabled them
1615   if (DisableMultiplicativeReductions &&
1616       (BinOp->getOpcode() == Instruction::Mul ||
1617        BinOp->getOpcode() == Instruction::FMul))
1618     return;
1619 
1620   // Check the binary operator operands for a candidate load
1621   auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
1622   auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
1623   if (!PossibleLoad0 && !PossibleLoad1)
1624     return;
1625 
1626   // A load is only a candidate if it cannot escape (thus has only this use)
1627   if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
1628     if (PossibleLoad0->getParent() == Store->getParent())
1629       Loads.push_back(&getArrayAccessFor(PossibleLoad0));
1630   if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
1631     if (PossibleLoad1->getParent() == Store->getParent())
1632       Loads.push_back(&getArrayAccessFor(PossibleLoad1));
1633 }
1634 
1635 /// Check for reductions in this ScopStmt.
1636 ///
1637 /// Iterate over all store memory accesses and check for valid binary reduction
1638 /// like chains. For all candidates we check if they have the same base address
1639 /// and there are no other accesses which overlap with them. The base address
1640 /// check rules out impossible reductions candidates early. The overlap check,
1641 /// together with the "only one user" check in collectCandiateReductionLoads,
1642 /// guarantees that none of the intermediate results will escape during
1643 /// execution of the loop nest. We basically check here that no other memory
1644 /// access can access the same memory as the potential reduction.
1645 void ScopStmt::checkForReductions() {
1646   SmallVector<MemoryAccess *, 2> Loads;
1647   SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
1648 
1649   // First collect candidate load-store reduction chains by iterating over all
1650   // stores and collecting possible reduction loads.
1651   for (MemoryAccess *StoreMA : MemAccs) {
1652     if (StoreMA->isRead())
1653       continue;
1654 
1655     Loads.clear();
1656     collectCandiateReductionLoads(StoreMA, Loads);
1657     for (MemoryAccess *LoadMA : Loads)
1658       Candidates.push_back(std::make_pair(LoadMA, StoreMA));
1659   }
1660 
1661   // Then check each possible candidate pair.
1662   for (const auto &CandidatePair : Candidates) {
1663     bool Valid = true;
1664     isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
1665     isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
1666 
1667     // Skip those with obviously unequal base addresses.
1668     if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
1669       isl_map_free(LoadAccs);
1670       isl_map_free(StoreAccs);
1671       continue;
1672     }
1673 
1674     // And check if the remaining for overlap with other memory accesses.
1675     isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
1676     AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
1677     isl_set *AllAccs = isl_map_range(AllAccsRel);
1678 
1679     for (MemoryAccess *MA : MemAccs) {
1680       if (MA == CandidatePair.first || MA == CandidatePair.second)
1681         continue;
1682 
1683       isl_map *AccRel =
1684           isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
1685       isl_set *Accs = isl_map_range(AccRel);
1686 
1687       if (isl_set_has_equal_space(AllAccs, Accs)) {
1688         isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
1689         Valid = Valid && isl_set_is_empty(OverlapAccs);
1690         isl_set_free(OverlapAccs);
1691       } else {
1692         isl_set_free(Accs);
1693       }
1694     }
1695 
1696     isl_set_free(AllAccs);
1697     if (!Valid)
1698       continue;
1699 
1700     const LoadInst *Load =
1701         dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
1702     MemoryAccess::ReductionType RT =
1703         getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
1704 
1705     // If no overlapping access was found we mark the load and store as
1706     // reduction like.
1707     CandidatePair.first->markAsReductionLike(RT);
1708     CandidatePair.second->markAsReductionLike(RT);
1709   }
1710 }
1711 
1712 std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
1713 
1714 std::string ScopStmt::getScheduleStr() const {
1715   auto *S = getSchedule();
1716   if (!S)
1717     return "";
1718   auto Str = stringFromIslObj(S);
1719   isl_map_free(S);
1720   return Str;
1721 }
1722 
1723 void ScopStmt::setInvalidDomain(__isl_take isl_set *ID) {
1724   isl_set_free(InvalidDomain);
1725   InvalidDomain = ID;
1726 }
1727 
1728 BasicBlock *ScopStmt::getEntryBlock() const {
1729   if (isBlockStmt())
1730     return getBasicBlock();
1731   return getRegion()->getEntry();
1732 }
1733 
1734 unsigned ScopStmt::getNumIterators() const { return NestLoops.size(); }
1735 
1736 const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
1737 
1738 Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
1739   return NestLoops[Dimension];
1740 }
1741 
1742 isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
1743 
1744 __isl_give isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
1745 
1746 __isl_give isl_space *ScopStmt::getDomainSpace() const {
1747   return isl_set_get_space(Domain);
1748 }
1749 
1750 __isl_give isl_id *ScopStmt::getDomainId() const {
1751   return isl_set_get_tuple_id(Domain);
1752 }
1753 
1754 ScopStmt::~ScopStmt() {
1755   isl_set_free(Domain);
1756   isl_set_free(InvalidDomain);
1757 }
1758 
1759 void ScopStmt::print(raw_ostream &OS) const {
1760   OS << "\t" << getBaseName() << "\n";
1761   OS.indent(12) << "Domain :=\n";
1762 
1763   if (Domain) {
1764     OS.indent(16) << getDomainStr() << ";\n";
1765   } else
1766     OS.indent(16) << "n/a\n";
1767 
1768   OS.indent(12) << "Schedule :=\n";
1769 
1770   if (Domain) {
1771     OS.indent(16) << getScheduleStr() << ";\n";
1772   } else
1773     OS.indent(16) << "n/a\n";
1774 
1775   for (MemoryAccess *Access : MemAccs)
1776     Access->print(OS);
1777 }
1778 
1779 void ScopStmt::dump() const { print(dbgs()); }
1780 
1781 void ScopStmt::removeMemoryAccess(MemoryAccess *MA) {
1782   // Remove the memory accesses from this statement together with all scalar
1783   // accesses that were caused by it. MemoryKind::Value READs have no access
1784   // instruction, hence would not be removed by this function. However, it is
1785   // only used for invariant LoadInst accesses, its arguments are always affine,
1786   // hence synthesizable, and therefore there are no MemoryKind::Value READ
1787   // accesses to be removed.
1788   auto Predicate = [&](MemoryAccess *Acc) {
1789     return Acc->getAccessInstruction() == MA->getAccessInstruction();
1790   };
1791   MemAccs.erase(std::remove_if(MemAccs.begin(), MemAccs.end(), Predicate),
1792                 MemAccs.end());
1793   InstructionToAccess.erase(MA->getAccessInstruction());
1794 }
1795 
1796 //===----------------------------------------------------------------------===//
1797 /// Scop class implement
1798 
1799 void Scop::setContext(__isl_take isl_set *NewContext) {
1800   NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1801   isl_set_free(Context);
1802   Context = NewContext;
1803 }
1804 
1805 /// Remap parameter values but keep AddRecs valid wrt. invariant loads.
1806 struct SCEVSensitiveParameterRewriter
1807     : public SCEVRewriteVisitor<SCEVSensitiveParameterRewriter> {
1808   ValueToValueMap &VMap;
1809 
1810 public:
1811   SCEVSensitiveParameterRewriter(ValueToValueMap &VMap, ScalarEvolution &SE)
1812       : SCEVRewriteVisitor(SE), VMap(VMap) {}
1813 
1814   static const SCEV *rewrite(const SCEV *E, ScalarEvolution &SE,
1815                              ValueToValueMap &VMap) {
1816     SCEVSensitiveParameterRewriter SSPR(VMap, SE);
1817     return SSPR.visit(E);
1818   }
1819 
1820   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
1821     auto *Start = visit(E->getStart());
1822     auto *AddRec = SE.getAddRecExpr(SE.getConstant(E->getType(), 0),
1823                                     visit(E->getStepRecurrence(SE)),
1824                                     E->getLoop(), SCEV::FlagAnyWrap);
1825     return SE.getAddExpr(Start, AddRec);
1826   }
1827 
1828   const SCEV *visitUnknown(const SCEVUnknown *E) {
1829     if (auto *NewValue = VMap.lookup(E->getValue()))
1830       return SE.getUnknown(NewValue);
1831     return E;
1832   }
1833 };
1834 
1835 const SCEV *Scop::getRepresentingInvariantLoadSCEV(const SCEV *S) {
1836   return SCEVSensitiveParameterRewriter::rewrite(S, *SE, InvEquivClassVMap);
1837 }
1838 
1839 void Scop::createParameterId(const SCEV *Parameter) {
1840   assert(Parameters.count(Parameter));
1841   assert(!ParameterIds.count(Parameter));
1842 
1843   std::string ParameterName = "p_" + std::to_string(getNumParams() - 1);
1844 
1845   if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1846     Value *Val = ValueParameter->getValue();
1847 
1848     // If this parameter references a specific Value and this value has a name
1849     // we use this name as it is likely to be unique and more useful than just
1850     // a number.
1851     if (Val->hasName())
1852       ParameterName = Val->getName();
1853     else if (LoadInst *LI = dyn_cast<LoadInst>(Val)) {
1854       auto *LoadOrigin = LI->getPointerOperand()->stripInBoundsOffsets();
1855       if (LoadOrigin->hasName()) {
1856         ParameterName += "_loaded_from_";
1857         ParameterName +=
1858             LI->getPointerOperand()->stripInBoundsOffsets()->getName();
1859       }
1860     }
1861   }
1862 
1863   ParameterName = getIslCompatibleName("", ParameterName, "");
1864 
1865   auto *Id = isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1866                           const_cast<void *>((const void *)Parameter));
1867   ParameterIds[Parameter] = Id;
1868 }
1869 
1870 void Scop::addParams(const ParameterSetTy &NewParameters) {
1871   for (const SCEV *Parameter : NewParameters) {
1872     // Normalize the SCEV to get the representing element for an invariant load.
1873     Parameter = extractConstantFactor(Parameter, *SE).second;
1874     Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1875 
1876     if (Parameters.insert(Parameter))
1877       createParameterId(Parameter);
1878   }
1879 }
1880 
1881 __isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) {
1882   // Normalize the SCEV to get the representing element for an invariant load.
1883   Parameter = getRepresentingInvariantLoadSCEV(Parameter);
1884   return isl_id_copy(ParameterIds.lookup(Parameter));
1885 }
1886 
1887 __isl_give isl_set *
1888 Scop::addNonEmptyDomainConstraints(__isl_take isl_set *C) const {
1889   isl_set *DomainContext = isl_union_set_params(getDomains());
1890   return isl_set_intersect_params(C, DomainContext);
1891 }
1892 
1893 bool Scop::isDominatedBy(const DominatorTree &DT, BasicBlock *BB) const {
1894   return DT.dominates(BB, getEntry());
1895 }
1896 
1897 void Scop::addUserAssumptions(DominatorTree &DT, LoopInfo &LI) {
1898   auto &F = getFunction();
1899 
1900   // TODO: Walk the DominatorTree from getRegion().getExit() to its root in
1901   // order to not iterate over blocks we skip anyways.
1902   for (auto &BB : F) {
1903     bool InScop = contains(&BB);
1904     if (!InScop && !isDominatedBy(DT, &BB))
1905       continue;
1906 
1907     for (auto &Assumption : BB) {
1908       auto *CI = dyn_cast_or_null<IntrinsicInst>(&Assumption);
1909       if (!CI || CI->getNumArgOperands() != 1 ||
1910           CI->getIntrinsicID() != Intrinsic::assume)
1911         continue;
1912 
1913       auto *L = LI.getLoopFor(CI->getParent());
1914       auto *Val = CI->getArgOperand(0);
1915       ParameterSetTy DetectedParams;
1916       if (!isAffineConstraint(Val, &R, L, *SE, DetectedParams)) {
1917         emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F,
1918                                        CI->getDebugLoc(),
1919                                        "Non-affine user assumption ignored.");
1920         continue;
1921       }
1922 
1923       // Collect all newly introduced parameters.
1924       ParameterSetTy NewParams;
1925       for (auto *Param : DetectedParams) {
1926         Param = extractConstantFactor(Param, *SE).second;
1927         Param = getRepresentingInvariantLoadSCEV(Param);
1928         if (Parameters.count(Param))
1929           continue;
1930         NewParams.insert(Param);
1931       }
1932 
1933       SmallVector<isl_set *, 2> ConditionSets;
1934       auto *TI = InScop ? CI->getParent()->getTerminator() : nullptr;
1935       auto &Stmt = InScop ? *getStmtFor(CI->getParent()) : *Stmts.begin();
1936       auto *Dom = InScop ? getDomainConditions(&Stmt) : isl_set_copy(Context);
1937       bool Valid = buildConditionSets(Stmt, Val, TI, L, Dom, ConditionSets);
1938       isl_set_free(Dom);
1939 
1940       if (!Valid)
1941         continue;
1942 
1943       isl_set *AssumptionCtx = nullptr;
1944       if (InScop) {
1945         AssumptionCtx = isl_set_complement(isl_set_params(ConditionSets[1]));
1946         isl_set_free(ConditionSets[0]);
1947       } else {
1948         AssumptionCtx = isl_set_complement(ConditionSets[1]);
1949         AssumptionCtx = isl_set_intersect(AssumptionCtx, ConditionSets[0]);
1950       }
1951 
1952       // Project out newly introduced parameters as they are not otherwise
1953       // useful.
1954       if (!NewParams.empty()) {
1955         for (unsigned u = 0; u < isl_set_n_param(AssumptionCtx); u++) {
1956           auto *Id = isl_set_get_dim_id(AssumptionCtx, isl_dim_param, u);
1957           auto *Param = static_cast<const SCEV *>(isl_id_get_user(Id));
1958           isl_id_free(Id);
1959 
1960           if (!NewParams.count(Param))
1961             continue;
1962 
1963           AssumptionCtx =
1964               isl_set_project_out(AssumptionCtx, isl_dim_param, u--, 1);
1965         }
1966       }
1967 
1968       emitOptimizationRemarkAnalysis(
1969           F.getContext(), DEBUG_TYPE, F, CI->getDebugLoc(),
1970           "Use user assumption: " + stringFromIslObj(AssumptionCtx));
1971       Context = isl_set_intersect(Context, AssumptionCtx);
1972     }
1973   }
1974 }
1975 
1976 void Scop::addUserContext() {
1977   if (UserContextStr.empty())
1978     return;
1979 
1980   isl_set *UserContext =
1981       isl_set_read_from_str(getIslCtx(), UserContextStr.c_str());
1982   isl_space *Space = getParamSpace();
1983   if (isl_space_dim(Space, isl_dim_param) !=
1984       isl_set_dim(UserContext, isl_dim_param)) {
1985     auto SpaceStr = isl_space_to_str(Space);
1986     errs() << "Error: the context provided in -polly-context has not the same "
1987            << "number of dimensions than the computed context. Due to this "
1988            << "mismatch, the -polly-context option is ignored. Please provide "
1989            << "the context in the parameter space: " << SpaceStr << ".\n";
1990     free(SpaceStr);
1991     isl_set_free(UserContext);
1992     isl_space_free(Space);
1993     return;
1994   }
1995 
1996   for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1997     auto *NameContext = isl_set_get_dim_name(Context, isl_dim_param, i);
1998     auto *NameUserContext = isl_set_get_dim_name(UserContext, isl_dim_param, i);
1999 
2000     if (strcmp(NameContext, NameUserContext) != 0) {
2001       auto SpaceStr = isl_space_to_str(Space);
2002       errs() << "Error: the name of dimension " << i
2003              << " provided in -polly-context "
2004              << "is '" << NameUserContext << "', but the name in the computed "
2005              << "context is '" << NameContext
2006              << "'. Due to this name mismatch, "
2007              << "the -polly-context option is ignored. Please provide "
2008              << "the context in the parameter space: " << SpaceStr << ".\n";
2009       free(SpaceStr);
2010       isl_set_free(UserContext);
2011       isl_space_free(Space);
2012       return;
2013     }
2014 
2015     UserContext =
2016         isl_set_set_dim_id(UserContext, isl_dim_param, i,
2017                            isl_space_get_dim_id(Space, isl_dim_param, i));
2018   }
2019 
2020   Context = isl_set_intersect(Context, UserContext);
2021   isl_space_free(Space);
2022 }
2023 
2024 void Scop::buildInvariantEquivalenceClasses() {
2025   DenseMap<std::pair<const SCEV *, Type *>, LoadInst *> EquivClasses;
2026 
2027   const InvariantLoadsSetTy &RIL = getRequiredInvariantLoads();
2028   for (LoadInst *LInst : RIL) {
2029     const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
2030 
2031     Type *Ty = LInst->getType();
2032     LoadInst *&ClassRep = EquivClasses[std::make_pair(PointerSCEV, Ty)];
2033     if (ClassRep) {
2034       InvEquivClassVMap[LInst] = ClassRep;
2035       continue;
2036     }
2037 
2038     ClassRep = LInst;
2039     InvariantEquivClasses.emplace_back(
2040         InvariantEquivClassTy{PointerSCEV, MemoryAccessList(), nullptr, Ty});
2041   }
2042 }
2043 
2044 void Scop::buildContext() {
2045   isl_space *Space = isl_space_params_alloc(getIslCtx(), 0);
2046   Context = isl_set_universe(isl_space_copy(Space));
2047   InvalidContext = isl_set_empty(isl_space_copy(Space));
2048   AssumedContext = isl_set_universe(Space);
2049 }
2050 
2051 void Scop::addParameterBounds() {
2052   unsigned PDim = 0;
2053   for (auto *Parameter : Parameters) {
2054     ConstantRange SRange = SE->getSignedRange(Parameter);
2055     Context = addRangeBoundsToSet(Context, SRange, PDim++, isl_dim_param);
2056   }
2057 }
2058 
2059 void Scop::realignParams() {
2060   // Add all parameters into a common model.
2061   isl_space *Space = isl_space_params_alloc(getIslCtx(), ParameterIds.size());
2062 
2063   unsigned PDim = 0;
2064   for (const auto *Parameter : Parameters) {
2065     isl_id *id = getIdForParam(Parameter);
2066     Space = isl_space_set_dim_id(Space, isl_dim_param, PDim++, id);
2067   }
2068 
2069   // Align the parameters of all data structures to the model.
2070   Context = isl_set_align_params(Context, Space);
2071 
2072   // As all parameters are known add bounds to them.
2073   addParameterBounds();
2074 
2075   for (ScopStmt &Stmt : *this)
2076     Stmt.realignParams();
2077 
2078   // Simplify the schedule according to the context too.
2079   Schedule = isl_schedule_gist_domain_params(Schedule, getContext());
2080 }
2081 
2082 static __isl_give isl_set *
2083 simplifyAssumptionContext(__isl_take isl_set *AssumptionContext,
2084                           const Scop &S) {
2085   // If we have modeled all blocks in the SCoP that have side effects we can
2086   // simplify the context with the constraints that are needed for anything to
2087   // be executed at all. However, if we have error blocks in the SCoP we already
2088   // assumed some parameter combinations cannot occur and removed them from the
2089   // domains, thus we cannot use the remaining domain to simplify the
2090   // assumptions.
2091   if (!S.hasErrorBlock()) {
2092     isl_set *DomainParameters = isl_union_set_params(S.getDomains());
2093     AssumptionContext =
2094         isl_set_gist_params(AssumptionContext, DomainParameters);
2095   }
2096 
2097   AssumptionContext = isl_set_gist_params(AssumptionContext, S.getContext());
2098   return AssumptionContext;
2099 }
2100 
2101 void Scop::simplifyContexts() {
2102   // The parameter constraints of the iteration domains give us a set of
2103   // constraints that need to hold for all cases where at least a single
2104   // statement iteration is executed in the whole scop. We now simplify the
2105   // assumed context under the assumption that such constraints hold and at
2106   // least a single statement iteration is executed. For cases where no
2107   // statement instances are executed, the assumptions we have taken about
2108   // the executed code do not matter and can be changed.
2109   //
2110   // WARNING: This only holds if the assumptions we have taken do not reduce
2111   //          the set of statement instances that are executed. Otherwise we
2112   //          may run into a case where the iteration domains suggest that
2113   //          for a certain set of parameter constraints no code is executed,
2114   //          but in the original program some computation would have been
2115   //          performed. In such a case, modifying the run-time conditions and
2116   //          possibly influencing the run-time check may cause certain scops
2117   //          to not be executed.
2118   //
2119   // Example:
2120   //
2121   //   When delinearizing the following code:
2122   //
2123   //     for (long i = 0; i < 100; i++)
2124   //       for (long j = 0; j < m; j++)
2125   //         A[i+p][j] = 1.0;
2126   //
2127   //   we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
2128   //   otherwise we would access out of bound data. Now, knowing that code is
2129   //   only executed for the case m >= 0, it is sufficient to assume p >= 0.
2130   AssumedContext = simplifyAssumptionContext(AssumedContext, *this);
2131   InvalidContext = isl_set_align_params(InvalidContext, getParamSpace());
2132 }
2133 
2134 /// Add the minimal/maximal access in @p Set to @p User.
2135 static isl_stat buildMinMaxAccess(__isl_take isl_set *Set, void *User) {
2136   Scop::MinMaxVectorTy *MinMaxAccesses = (Scop::MinMaxVectorTy *)User;
2137   isl_pw_multi_aff *MinPMA, *MaxPMA;
2138   isl_pw_aff *LastDimAff;
2139   isl_aff *OneAff;
2140   unsigned Pos;
2141 
2142   Set = isl_set_remove_divs(Set);
2143 
2144   if (isl_set_n_basic_set(Set) >= MaxDisjunctsInDomain) {
2145     isl_set_free(Set);
2146     return isl_stat_error;
2147   }
2148 
2149   // Restrict the number of parameters involved in the access as the lexmin/
2150   // lexmax computation will take too long if this number is high.
2151   //
2152   // Experiments with a simple test case using an i7 4800MQ:
2153   //
2154   //  #Parameters involved | Time (in sec)
2155   //            6          |     0.01
2156   //            7          |     0.04
2157   //            8          |     0.12
2158   //            9          |     0.40
2159   //           10          |     1.54
2160   //           11          |     6.78
2161   //           12          |    30.38
2162   //
2163   if (isl_set_n_param(Set) > RunTimeChecksMaxParameters) {
2164     unsigned InvolvedParams = 0;
2165     for (unsigned u = 0, e = isl_set_n_param(Set); u < e; u++)
2166       if (isl_set_involves_dims(Set, isl_dim_param, u, 1))
2167         InvolvedParams++;
2168 
2169     if (InvolvedParams > RunTimeChecksMaxParameters) {
2170       isl_set_free(Set);
2171       return isl_stat_error;
2172     }
2173   }
2174 
2175   MinPMA = isl_set_lexmin_pw_multi_aff(isl_set_copy(Set));
2176   MaxPMA = isl_set_lexmax_pw_multi_aff(isl_set_copy(Set));
2177 
2178   MinPMA = isl_pw_multi_aff_coalesce(MinPMA);
2179   MaxPMA = isl_pw_multi_aff_coalesce(MaxPMA);
2180 
2181   // Adjust the last dimension of the maximal access by one as we want to
2182   // enclose the accessed memory region by MinPMA and MaxPMA. The pointer
2183   // we test during code generation might now point after the end of the
2184   // allocated array but we will never dereference it anyway.
2185   assert(isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) &&
2186          "Assumed at least one output dimension");
2187   Pos = isl_pw_multi_aff_dim(MaxPMA, isl_dim_out) - 1;
2188   LastDimAff = isl_pw_multi_aff_get_pw_aff(MaxPMA, Pos);
2189   OneAff = isl_aff_zero_on_domain(
2190       isl_local_space_from_space(isl_pw_aff_get_domain_space(LastDimAff)));
2191   OneAff = isl_aff_add_constant_si(OneAff, 1);
2192   LastDimAff = isl_pw_aff_add(LastDimAff, isl_pw_aff_from_aff(OneAff));
2193   MaxPMA = isl_pw_multi_aff_set_pw_aff(MaxPMA, Pos, LastDimAff);
2194 
2195   MinMaxAccesses->push_back(std::make_pair(MinPMA, MaxPMA));
2196 
2197   isl_set_free(Set);
2198   return isl_stat_ok;
2199 }
2200 
2201 static __isl_give isl_set *getAccessDomain(MemoryAccess *MA) {
2202   isl_set *Domain = MA->getStatement()->getDomain();
2203   Domain = isl_set_project_out(Domain, isl_dim_set, 0, isl_set_n_dim(Domain));
2204   return isl_set_reset_tuple_id(Domain);
2205 }
2206 
2207 /// Wrapper function to calculate minimal/maximal accesses to each array.
2208 static bool calculateMinMaxAccess(Scop::AliasGroupTy AliasGroup, Scop &S,
2209                                   Scop::MinMaxVectorTy &MinMaxAccesses) {
2210 
2211   MinMaxAccesses.reserve(AliasGroup.size());
2212 
2213   isl_union_set *Domains = S.getDomains();
2214   isl_union_map *Accesses = isl_union_map_empty(S.getParamSpace());
2215 
2216   for (MemoryAccess *MA : AliasGroup)
2217     Accesses = isl_union_map_add_map(Accesses, MA->getAccessRelation());
2218 
2219   Accesses = isl_union_map_intersect_domain(Accesses, Domains);
2220   isl_union_set *Locations = isl_union_map_range(Accesses);
2221   Locations = isl_union_set_coalesce(Locations);
2222   Locations = isl_union_set_detect_equalities(Locations);
2223   bool Valid = (0 == isl_union_set_foreach_set(Locations, buildMinMaxAccess,
2224                                                &MinMaxAccesses));
2225   isl_union_set_free(Locations);
2226   return Valid;
2227 }
2228 
2229 /// Helper to treat non-affine regions and basic blocks the same.
2230 ///
2231 ///{
2232 
2233 /// Return the block that is the representing block for @p RN.
2234 static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
2235   return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
2236                            : RN->getNodeAs<BasicBlock>();
2237 }
2238 
2239 /// Return the @p idx'th block that is executed after @p RN.
2240 static inline BasicBlock *
2241 getRegionNodeSuccessor(RegionNode *RN, TerminatorInst *TI, unsigned idx) {
2242   if (RN->isSubRegion()) {
2243     assert(idx == 0);
2244     return RN->getNodeAs<Region>()->getExit();
2245   }
2246   return TI->getSuccessor(idx);
2247 }
2248 
2249 /// Return the smallest loop surrounding @p RN.
2250 static inline Loop *getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
2251   if (!RN->isSubRegion())
2252     return LI.getLoopFor(RN->getNodeAs<BasicBlock>());
2253 
2254   Region *NonAffineSubRegion = RN->getNodeAs<Region>();
2255   Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
2256   while (L && NonAffineSubRegion->contains(L))
2257     L = L->getParentLoop();
2258   return L;
2259 }
2260 
2261 static inline unsigned getNumBlocksInRegionNode(RegionNode *RN) {
2262   if (!RN->isSubRegion())
2263     return 1;
2264 
2265   Region *R = RN->getNodeAs<Region>();
2266   return std::distance(R->block_begin(), R->block_end());
2267 }
2268 
2269 static bool containsErrorBlock(RegionNode *RN, const Region &R, LoopInfo &LI,
2270                                const DominatorTree &DT) {
2271   if (!RN->isSubRegion())
2272     return isErrorBlock(*RN->getNodeAs<BasicBlock>(), R, LI, DT);
2273   for (BasicBlock *BB : RN->getNodeAs<Region>()->blocks())
2274     if (isErrorBlock(*BB, R, LI, DT))
2275       return true;
2276   return false;
2277 }
2278 
2279 ///}
2280 
2281 static inline __isl_give isl_set *addDomainDimId(__isl_take isl_set *Domain,
2282                                                  unsigned Dim, Loop *L) {
2283   Domain = isl_set_lower_bound_si(Domain, isl_dim_set, Dim, -1);
2284   isl_id *DimId =
2285       isl_id_alloc(isl_set_get_ctx(Domain), nullptr, static_cast<void *>(L));
2286   return isl_set_set_dim_id(Domain, isl_dim_set, Dim, DimId);
2287 }
2288 
2289 __isl_give isl_set *Scop::getDomainConditions(const ScopStmt *Stmt) const {
2290   return getDomainConditions(Stmt->getEntryBlock());
2291 }
2292 
2293 __isl_give isl_set *Scop::getDomainConditions(BasicBlock *BB) const {
2294   auto DIt = DomainMap.find(BB);
2295   if (DIt != DomainMap.end())
2296     return isl_set_copy(DIt->getSecond());
2297 
2298   auto &RI = *R.getRegionInfo();
2299   auto *BBR = RI.getRegionFor(BB);
2300   while (BBR->getEntry() == BB)
2301     BBR = BBR->getParent();
2302   return getDomainConditions(BBR->getEntry());
2303 }
2304 
2305 bool Scop::buildDomains(Region *R, DominatorTree &DT, LoopInfo &LI) {
2306 
2307   bool IsOnlyNonAffineRegion = isNonAffineSubRegion(R);
2308   auto *EntryBB = R->getEntry();
2309   auto *L = IsOnlyNonAffineRegion ? nullptr : LI.getLoopFor(EntryBB);
2310   int LD = getRelativeLoopDepth(L);
2311   auto *S = isl_set_universe(isl_space_set_alloc(getIslCtx(), 0, LD + 1));
2312 
2313   while (LD-- >= 0) {
2314     S = addDomainDimId(S, LD + 1, L);
2315     L = L->getParentLoop();
2316   }
2317 
2318   // Initialize the invalid domain.
2319   auto *EntryStmt = getStmtFor(EntryBB);
2320   EntryStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(S)));
2321 
2322   DomainMap[EntryBB] = S;
2323 
2324   if (IsOnlyNonAffineRegion)
2325     return !containsErrorBlock(R->getNode(), *R, LI, DT);
2326 
2327   if (!buildDomainsWithBranchConstraints(R, DT, LI))
2328     return false;
2329 
2330   if (!propagateDomainConstraints(R, DT, LI))
2331     return false;
2332 
2333   // Error blocks and blocks dominated by them have been assumed to never be
2334   // executed. Representing them in the Scop does not add any value. In fact,
2335   // it is likely to cause issues during construction of the ScopStmts. The
2336   // contents of error blocks have not been verified to be expressible and
2337   // will cause problems when building up a ScopStmt for them.
2338   // Furthermore, basic blocks dominated by error blocks may reference
2339   // instructions in the error block which, if the error block is not modeled,
2340   // can themselves not be constructed properly. To this end we will replace
2341   // the domains of error blocks and those only reachable via error blocks
2342   // with an empty set. Additionally, we will record for each block under which
2343   // parameter combination it would be reached via an error block in its
2344   // InvalidDomain. This information is needed during load hoisting.
2345   if (!propagateInvalidStmtDomains(R, DT, LI))
2346     return false;
2347 
2348   return true;
2349 }
2350 
2351 /// Adjust the dimensions of @p Dom that was constructed for @p OldL
2352 ///        to be compatible to domains constructed for loop @p NewL.
2353 ///
2354 /// This function assumes @p NewL and @p OldL are equal or there is a CFG
2355 /// edge from @p OldL to @p NewL.
2356 static __isl_give isl_set *adjustDomainDimensions(Scop &S,
2357                                                   __isl_take isl_set *Dom,
2358                                                   Loop *OldL, Loop *NewL) {
2359 
2360   // If the loops are the same there is nothing to do.
2361   if (NewL == OldL)
2362     return Dom;
2363 
2364   int OldDepth = S.getRelativeLoopDepth(OldL);
2365   int NewDepth = S.getRelativeLoopDepth(NewL);
2366   // If both loops are non-affine loops there is nothing to do.
2367   if (OldDepth == -1 && NewDepth == -1)
2368     return Dom;
2369 
2370   // Distinguish three cases:
2371   //   1) The depth is the same but the loops are not.
2372   //      => One loop was left one was entered.
2373   //   2) The depth increased from OldL to NewL.
2374   //      => One loop was entered, none was left.
2375   //   3) The depth decreased from OldL to NewL.
2376   //      => Loops were left were difference of the depths defines how many.
2377   if (OldDepth == NewDepth) {
2378     assert(OldL->getParentLoop() == NewL->getParentLoop());
2379     Dom = isl_set_project_out(Dom, isl_dim_set, NewDepth, 1);
2380     Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2381     Dom = addDomainDimId(Dom, NewDepth, NewL);
2382   } else if (OldDepth < NewDepth) {
2383     assert(OldDepth + 1 == NewDepth);
2384     auto &R = S.getRegion();
2385     (void)R;
2386     assert(NewL->getParentLoop() == OldL ||
2387            ((!OldL || !R.contains(OldL)) && R.contains(NewL)));
2388     Dom = isl_set_add_dims(Dom, isl_dim_set, 1);
2389     Dom = addDomainDimId(Dom, NewDepth, NewL);
2390   } else {
2391     assert(OldDepth > NewDepth);
2392     int Diff = OldDepth - NewDepth;
2393     int NumDim = isl_set_n_dim(Dom);
2394     assert(NumDim >= Diff);
2395     Dom = isl_set_project_out(Dom, isl_dim_set, NumDim - Diff, Diff);
2396   }
2397 
2398   return Dom;
2399 }
2400 
2401 bool Scop::propagateInvalidStmtDomains(Region *R, DominatorTree &DT,
2402                                        LoopInfo &LI) {
2403   auto &BoxedLoops = getBoxedLoops();
2404 
2405   ReversePostOrderTraversal<Region *> RTraversal(R);
2406   for (auto *RN : RTraversal) {
2407 
2408     // Recurse for affine subregions but go on for basic blocks and non-affine
2409     // subregions.
2410     if (RN->isSubRegion()) {
2411       Region *SubRegion = RN->getNodeAs<Region>();
2412       if (!isNonAffineSubRegion(SubRegion)) {
2413         propagateInvalidStmtDomains(SubRegion, DT, LI);
2414         continue;
2415       }
2416     }
2417 
2418     bool ContainsErrorBlock = containsErrorBlock(RN, getRegion(), LI, DT);
2419     BasicBlock *BB = getRegionNodeBasicBlock(RN);
2420     ScopStmt *Stmt = getStmtFor(BB);
2421     isl_set *&Domain = DomainMap[BB];
2422     assert(Domain && "Cannot propagate a nullptr");
2423 
2424     auto *InvalidDomain = Stmt->getInvalidDomain();
2425     bool IsInvalidBlock =
2426         ContainsErrorBlock || isl_set_is_subset(Domain, InvalidDomain);
2427 
2428     if (!IsInvalidBlock) {
2429       InvalidDomain = isl_set_intersect(InvalidDomain, isl_set_copy(Domain));
2430     } else {
2431       isl_set_free(InvalidDomain);
2432       InvalidDomain = Domain;
2433       isl_set *DomPar = isl_set_params(isl_set_copy(Domain));
2434       recordAssumption(ERRORBLOCK, DomPar, BB->getTerminator()->getDebugLoc(),
2435                        AS_RESTRICTION);
2436       Domain = nullptr;
2437     }
2438 
2439     if (isl_set_is_empty(InvalidDomain)) {
2440       Stmt->setInvalidDomain(InvalidDomain);
2441       continue;
2442     }
2443 
2444     auto *BBLoop = getRegionNodeLoop(RN, LI);
2445     auto *TI = BB->getTerminator();
2446     unsigned NumSuccs = RN->isSubRegion() ? 1 : TI->getNumSuccessors();
2447     for (unsigned u = 0; u < NumSuccs; u++) {
2448       auto *SuccBB = getRegionNodeSuccessor(RN, TI, u);
2449       auto *SuccStmt = getStmtFor(SuccBB);
2450 
2451       // Skip successors outside the SCoP.
2452       if (!SuccStmt)
2453         continue;
2454 
2455       // Skip backedges.
2456       if (DT.dominates(SuccBB, BB))
2457         continue;
2458 
2459       auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2460       auto *AdjustedInvalidDomain = adjustDomainDimensions(
2461           *this, isl_set_copy(InvalidDomain), BBLoop, SuccBBLoop);
2462       auto *SuccInvalidDomain = SuccStmt->getInvalidDomain();
2463       SuccInvalidDomain =
2464           isl_set_union(SuccInvalidDomain, AdjustedInvalidDomain);
2465       SuccInvalidDomain = isl_set_coalesce(SuccInvalidDomain);
2466       unsigned NumConjucts = isl_set_n_basic_set(SuccInvalidDomain);
2467       SuccStmt->setInvalidDomain(SuccInvalidDomain);
2468 
2469       // Check if the maximal number of domain disjunctions was reached.
2470       // In case this happens we will bail.
2471       if (NumConjucts < MaxDisjunctsInDomain)
2472         continue;
2473 
2474       isl_set_free(InvalidDomain);
2475       invalidate(COMPLEXITY, TI->getDebugLoc());
2476       return false;
2477     }
2478 
2479     Stmt->setInvalidDomain(InvalidDomain);
2480   }
2481 
2482   return true;
2483 }
2484 
2485 void Scop::propagateDomainConstraintsToRegionExit(
2486     BasicBlock *BB, Loop *BBLoop,
2487     SmallPtrSetImpl<BasicBlock *> &FinishedExitBlocks, LoopInfo &LI) {
2488 
2489   // Check if the block @p BB is the entry of a region. If so we propagate it's
2490   // domain to the exit block of the region. Otherwise we are done.
2491   auto *RI = R.getRegionInfo();
2492   auto *BBReg = RI ? RI->getRegionFor(BB) : nullptr;
2493   auto *ExitBB = BBReg ? BBReg->getExit() : nullptr;
2494   if (!BBReg || BBReg->getEntry() != BB || !contains(ExitBB))
2495     return;
2496 
2497   auto &BoxedLoops = getBoxedLoops();
2498   // Do not propagate the domain if there is a loop backedge inside the region
2499   // that would prevent the exit block from being executed.
2500   auto *L = BBLoop;
2501   while (L && contains(L)) {
2502     SmallVector<BasicBlock *, 4> LatchBBs;
2503     BBLoop->getLoopLatches(LatchBBs);
2504     for (auto *LatchBB : LatchBBs)
2505       if (BB != LatchBB && BBReg->contains(LatchBB))
2506         return;
2507     L = L->getParentLoop();
2508   }
2509 
2510   auto *Domain = DomainMap[BB];
2511   assert(Domain && "Cannot propagate a nullptr");
2512 
2513   auto *ExitBBLoop = getFirstNonBoxedLoopFor(ExitBB, LI, BoxedLoops);
2514 
2515   // Since the dimensions of @p BB and @p ExitBB might be different we have to
2516   // adjust the domain before we can propagate it.
2517   auto *AdjustedDomain =
2518       adjustDomainDimensions(*this, isl_set_copy(Domain), BBLoop, ExitBBLoop);
2519   auto *&ExitDomain = DomainMap[ExitBB];
2520 
2521   // If the exit domain is not yet created we set it otherwise we "add" the
2522   // current domain.
2523   ExitDomain =
2524       ExitDomain ? isl_set_union(AdjustedDomain, ExitDomain) : AdjustedDomain;
2525 
2526   // Initialize the invalid domain.
2527   auto *ExitStmt = getStmtFor(ExitBB);
2528   ExitStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(ExitDomain)));
2529 
2530   FinishedExitBlocks.insert(ExitBB);
2531 }
2532 
2533 bool Scop::buildDomainsWithBranchConstraints(Region *R, DominatorTree &DT,
2534                                              LoopInfo &LI) {
2535   // To create the domain for each block in R we iterate over all blocks and
2536   // subregions in R and propagate the conditions under which the current region
2537   // element is executed. To this end we iterate in reverse post order over R as
2538   // it ensures that we first visit all predecessors of a region node (either a
2539   // basic block or a subregion) before we visit the region node itself.
2540   // Initially, only the domain for the SCoP region entry block is set and from
2541   // there we propagate the current domain to all successors, however we add the
2542   // condition that the successor is actually executed next.
2543   // As we are only interested in non-loop carried constraints here we can
2544   // simply skip loop back edges.
2545 
2546   SmallPtrSet<BasicBlock *, 8> FinishedExitBlocks;
2547   ReversePostOrderTraversal<Region *> RTraversal(R);
2548   for (auto *RN : RTraversal) {
2549 
2550     // Recurse for affine subregions but go on for basic blocks and non-affine
2551     // subregions.
2552     if (RN->isSubRegion()) {
2553       Region *SubRegion = RN->getNodeAs<Region>();
2554       if (!isNonAffineSubRegion(SubRegion)) {
2555         if (!buildDomainsWithBranchConstraints(SubRegion, DT, LI))
2556           return false;
2557         continue;
2558       }
2559     }
2560 
2561     if (containsErrorBlock(RN, getRegion(), LI, DT))
2562       HasErrorBlock = true;
2563 
2564     BasicBlock *BB = getRegionNodeBasicBlock(RN);
2565     TerminatorInst *TI = BB->getTerminator();
2566 
2567     if (isa<UnreachableInst>(TI))
2568       continue;
2569 
2570     isl_set *Domain = DomainMap.lookup(BB);
2571     if (!Domain)
2572       continue;
2573     MaxLoopDepth = std::max(MaxLoopDepth, isl_set_n_dim(Domain));
2574 
2575     auto *BBLoop = getRegionNodeLoop(RN, LI);
2576     // Propagate the domain from BB directly to blocks that have a superset
2577     // domain, at the moment only region exit nodes of regions that start in BB.
2578     propagateDomainConstraintsToRegionExit(BB, BBLoop, FinishedExitBlocks, LI);
2579 
2580     // If all successors of BB have been set a domain through the propagation
2581     // above we do not need to build condition sets but can just skip this
2582     // block. However, it is important to note that this is a local property
2583     // with regards to the region @p R. To this end FinishedExitBlocks is a
2584     // local variable.
2585     auto IsFinishedRegionExit = [&FinishedExitBlocks](BasicBlock *SuccBB) {
2586       return FinishedExitBlocks.count(SuccBB);
2587     };
2588     if (std::all_of(succ_begin(BB), succ_end(BB), IsFinishedRegionExit))
2589       continue;
2590 
2591     // Build the condition sets for the successor nodes of the current region
2592     // node. If it is a non-affine subregion we will always execute the single
2593     // exit node, hence the single entry node domain is the condition set. For
2594     // basic blocks we use the helper function buildConditionSets.
2595     SmallVector<isl_set *, 8> ConditionSets;
2596     if (RN->isSubRegion())
2597       ConditionSets.push_back(isl_set_copy(Domain));
2598     else if (!buildConditionSets(*getStmtFor(BB), TI, BBLoop, Domain,
2599                                  ConditionSets))
2600       return false;
2601 
2602     // Now iterate over the successors and set their initial domain based on
2603     // their condition set. We skip back edges here and have to be careful when
2604     // we leave a loop not to keep constraints over a dimension that doesn't
2605     // exist anymore.
2606     assert(RN->isSubRegion() || TI->getNumSuccessors() == ConditionSets.size());
2607     for (unsigned u = 0, e = ConditionSets.size(); u < e; u++) {
2608       isl_set *CondSet = ConditionSets[u];
2609       BasicBlock *SuccBB = getRegionNodeSuccessor(RN, TI, u);
2610 
2611       auto *SuccStmt = getStmtFor(SuccBB);
2612       // Skip blocks outside the region.
2613       if (!SuccStmt) {
2614         isl_set_free(CondSet);
2615         continue;
2616       }
2617 
2618       // If we propagate the domain of some block to "SuccBB" we do not have to
2619       // adjust the domain.
2620       if (FinishedExitBlocks.count(SuccBB)) {
2621         isl_set_free(CondSet);
2622         continue;
2623       }
2624 
2625       // Skip back edges.
2626       if (DT.dominates(SuccBB, BB)) {
2627         isl_set_free(CondSet);
2628         continue;
2629       }
2630 
2631       auto &BoxedLoops = getBoxedLoops();
2632       auto *SuccBBLoop = getFirstNonBoxedLoopFor(SuccBB, LI, BoxedLoops);
2633       CondSet = adjustDomainDimensions(*this, CondSet, BBLoop, SuccBBLoop);
2634 
2635       // Set the domain for the successor or merge it with an existing domain in
2636       // case there are multiple paths (without loop back edges) to the
2637       // successor block.
2638       isl_set *&SuccDomain = DomainMap[SuccBB];
2639 
2640       if (SuccDomain) {
2641         SuccDomain = isl_set_coalesce(isl_set_union(SuccDomain, CondSet));
2642       } else {
2643         // Initialize the invalid domain.
2644         SuccStmt->setInvalidDomain(isl_set_empty(isl_set_get_space(CondSet)));
2645         SuccDomain = CondSet;
2646       }
2647 
2648       // Check if the maximal number of domain disjunctions was reached.
2649       // In case this happens we will clean up and bail.
2650       if (isl_set_n_basic_set(SuccDomain) < MaxDisjunctsInDomain)
2651         continue;
2652 
2653       invalidate(COMPLEXITY, DebugLoc());
2654       while (++u < ConditionSets.size())
2655         isl_set_free(ConditionSets[u]);
2656       return false;
2657     }
2658   }
2659 
2660   return true;
2661 }
2662 
2663 __isl_give isl_set *
2664 Scop::getPredecessorDomainConstraints(BasicBlock *BB,
2665                                       __isl_keep isl_set *Domain,
2666                                       DominatorTree &DT, LoopInfo &LI) {
2667   // If @p BB is the ScopEntry we are done
2668   if (R.getEntry() == BB)
2669     return isl_set_universe(isl_set_get_space(Domain));
2670 
2671   // The set of boxed loops (loops in non-affine subregions) for this SCoP.
2672   auto &BoxedLoops = getBoxedLoops();
2673 
2674   // The region info of this function.
2675   auto &RI = *R.getRegionInfo();
2676 
2677   auto *BBLoop = getFirstNonBoxedLoopFor(BB, LI, BoxedLoops);
2678 
2679   // A domain to collect all predecessor domains, thus all conditions under
2680   // which the block is executed. To this end we start with the empty domain.
2681   isl_set *PredDom = isl_set_empty(isl_set_get_space(Domain));
2682 
2683   // Set of regions of which the entry block domain has been propagated to BB.
2684   // all predecessors inside any of the regions can be skipped.
2685   SmallSet<Region *, 8> PropagatedRegions;
2686 
2687   for (auto *PredBB : predecessors(BB)) {
2688     // Skip backedges.
2689     if (DT.dominates(BB, PredBB))
2690       continue;
2691 
2692     // If the predecessor is in a region we used for propagation we can skip it.
2693     auto PredBBInRegion = [PredBB](Region *PR) { return PR->contains(PredBB); };
2694     if (std::any_of(PropagatedRegions.begin(), PropagatedRegions.end(),
2695                     PredBBInRegion)) {
2696       continue;
2697     }
2698 
2699     // Check if there is a valid region we can use for propagation, thus look
2700     // for a region that contains the predecessor and has @p BB as exit block.
2701     auto *PredR = RI.getRegionFor(PredBB);
2702     while (PredR->getExit() != BB && !PredR->contains(BB))
2703       PredR->getParent();
2704 
2705     // If a valid region for propagation was found use the entry of that region
2706     // for propagation, otherwise the PredBB directly.
2707     if (PredR->getExit() == BB) {
2708       PredBB = PredR->getEntry();
2709       PropagatedRegions.insert(PredR);
2710     }
2711 
2712     auto *PredBBDom = getDomainConditions(PredBB);
2713     auto *PredBBLoop = getFirstNonBoxedLoopFor(PredBB, LI, BoxedLoops);
2714     PredBBDom = adjustDomainDimensions(*this, PredBBDom, PredBBLoop, BBLoop);
2715 
2716     PredDom = isl_set_union(PredDom, PredBBDom);
2717   }
2718 
2719   return PredDom;
2720 }
2721 
2722 bool Scop::propagateDomainConstraints(Region *R, DominatorTree &DT,
2723                                       LoopInfo &LI) {
2724   // Iterate over the region R and propagate the domain constrains from the
2725   // predecessors to the current node. In contrast to the
2726   // buildDomainsWithBranchConstraints function, this one will pull the domain
2727   // information from the predecessors instead of pushing it to the successors.
2728   // Additionally, we assume the domains to be already present in the domain
2729   // map here. However, we iterate again in reverse post order so we know all
2730   // predecessors have been visited before a block or non-affine subregion is
2731   // visited.
2732 
2733   ReversePostOrderTraversal<Region *> RTraversal(R);
2734   for (auto *RN : RTraversal) {
2735 
2736     // Recurse for affine subregions but go on for basic blocks and non-affine
2737     // subregions.
2738     if (RN->isSubRegion()) {
2739       Region *SubRegion = RN->getNodeAs<Region>();
2740       if (!isNonAffineSubRegion(SubRegion)) {
2741         if (!propagateDomainConstraints(SubRegion, DT, LI))
2742           return false;
2743         continue;
2744       }
2745     }
2746 
2747     BasicBlock *BB = getRegionNodeBasicBlock(RN);
2748     isl_set *&Domain = DomainMap[BB];
2749     assert(Domain);
2750 
2751     // Under the union of all predecessor conditions we can reach this block.
2752     auto *PredDom = getPredecessorDomainConstraints(BB, Domain, DT, LI);
2753     Domain = isl_set_coalesce(isl_set_intersect(Domain, PredDom));
2754     Domain = isl_set_align_params(Domain, getParamSpace());
2755 
2756     Loop *BBLoop = getRegionNodeLoop(RN, LI);
2757     if (BBLoop && BBLoop->getHeader() == BB && contains(BBLoop))
2758       if (!addLoopBoundsToHeaderDomain(BBLoop, LI))
2759         return false;
2760   }
2761 
2762   return true;
2763 }
2764 
2765 /// Create a map to map from a given iteration to a subsequent iteration.
2766 ///
2767 /// This map maps from SetSpace -> SetSpace where the dimensions @p Dim
2768 /// is incremented by one and all other dimensions are equal, e.g.,
2769 ///             [i0, i1, i2, i3] -> [i0, i1, i2 + 1, i3]
2770 ///
2771 /// if @p Dim is 2 and @p SetSpace has 4 dimensions.
2772 static __isl_give isl_map *
2773 createNextIterationMap(__isl_take isl_space *SetSpace, unsigned Dim) {
2774   auto *MapSpace = isl_space_map_from_set(SetSpace);
2775   auto *NextIterationMap = isl_map_universe(isl_space_copy(MapSpace));
2776   for (unsigned u = 0; u < isl_map_n_in(NextIterationMap); u++)
2777     if (u != Dim)
2778       NextIterationMap =
2779           isl_map_equate(NextIterationMap, isl_dim_in, u, isl_dim_out, u);
2780   auto *C = isl_constraint_alloc_equality(isl_local_space_from_space(MapSpace));
2781   C = isl_constraint_set_constant_si(C, 1);
2782   C = isl_constraint_set_coefficient_si(C, isl_dim_in, Dim, 1);
2783   C = isl_constraint_set_coefficient_si(C, isl_dim_out, Dim, -1);
2784   NextIterationMap = isl_map_add_constraint(NextIterationMap, C);
2785   return NextIterationMap;
2786 }
2787 
2788 bool Scop::addLoopBoundsToHeaderDomain(Loop *L, LoopInfo &LI) {
2789   int LoopDepth = getRelativeLoopDepth(L);
2790   assert(LoopDepth >= 0 && "Loop in region should have at least depth one");
2791 
2792   BasicBlock *HeaderBB = L->getHeader();
2793   assert(DomainMap.count(HeaderBB));
2794   isl_set *&HeaderBBDom = DomainMap[HeaderBB];
2795 
2796   isl_map *NextIterationMap =
2797       createNextIterationMap(isl_set_get_space(HeaderBBDom), LoopDepth);
2798 
2799   isl_set *UnionBackedgeCondition =
2800       isl_set_empty(isl_set_get_space(HeaderBBDom));
2801 
2802   SmallVector<llvm::BasicBlock *, 4> LatchBlocks;
2803   L->getLoopLatches(LatchBlocks);
2804 
2805   for (BasicBlock *LatchBB : LatchBlocks) {
2806 
2807     // If the latch is only reachable via error statements we skip it.
2808     isl_set *LatchBBDom = DomainMap.lookup(LatchBB);
2809     if (!LatchBBDom)
2810       continue;
2811 
2812     isl_set *BackedgeCondition = nullptr;
2813 
2814     TerminatorInst *TI = LatchBB->getTerminator();
2815     BranchInst *BI = dyn_cast<BranchInst>(TI);
2816     assert(BI && "Only branch instructions allowed in loop latches");
2817 
2818     if (BI->isUnconditional())
2819       BackedgeCondition = isl_set_copy(LatchBBDom);
2820     else {
2821       SmallVector<isl_set *, 8> ConditionSets;
2822       int idx = BI->getSuccessor(0) != HeaderBB;
2823       if (!buildConditionSets(*getStmtFor(LatchBB), TI, L, LatchBBDom,
2824                               ConditionSets)) {
2825         isl_map_free(NextIterationMap);
2826         isl_set_free(UnionBackedgeCondition);
2827         return false;
2828       }
2829 
2830       // Free the non back edge condition set as we do not need it.
2831       isl_set_free(ConditionSets[1 - idx]);
2832 
2833       BackedgeCondition = ConditionSets[idx];
2834     }
2835 
2836     int LatchLoopDepth = getRelativeLoopDepth(LI.getLoopFor(LatchBB));
2837     assert(LatchLoopDepth >= LoopDepth);
2838     BackedgeCondition =
2839         isl_set_project_out(BackedgeCondition, isl_dim_set, LoopDepth + 1,
2840                             LatchLoopDepth - LoopDepth);
2841     UnionBackedgeCondition =
2842         isl_set_union(UnionBackedgeCondition, BackedgeCondition);
2843   }
2844 
2845   isl_map *ForwardMap = isl_map_lex_le(isl_set_get_space(HeaderBBDom));
2846   for (int i = 0; i < LoopDepth; i++)
2847     ForwardMap = isl_map_equate(ForwardMap, isl_dim_in, i, isl_dim_out, i);
2848 
2849   isl_set *UnionBackedgeConditionComplement =
2850       isl_set_complement(UnionBackedgeCondition);
2851   UnionBackedgeConditionComplement = isl_set_lower_bound_si(
2852       UnionBackedgeConditionComplement, isl_dim_set, LoopDepth, 0);
2853   UnionBackedgeConditionComplement =
2854       isl_set_apply(UnionBackedgeConditionComplement, ForwardMap);
2855   HeaderBBDom = isl_set_subtract(HeaderBBDom, UnionBackedgeConditionComplement);
2856   HeaderBBDom = isl_set_apply(HeaderBBDom, NextIterationMap);
2857 
2858   auto Parts = partitionSetParts(HeaderBBDom, LoopDepth);
2859   HeaderBBDom = Parts.second;
2860 
2861   // Check if there is a <nsw> tagged AddRec for this loop and if so do not add
2862   // the bounded assumptions to the context as they are already implied by the
2863   // <nsw> tag.
2864   if (Affinator.hasNSWAddRecForLoop(L)) {
2865     isl_set_free(Parts.first);
2866     return true;
2867   }
2868 
2869   isl_set *UnboundedCtx = isl_set_params(Parts.first);
2870   recordAssumption(INFINITELOOP, UnboundedCtx,
2871                    HeaderBB->getTerminator()->getDebugLoc(), AS_RESTRICTION);
2872   return true;
2873 }
2874 
2875 MemoryAccess *Scop::lookupBasePtrAccess(MemoryAccess *MA) {
2876   Value *PointerBase = MA->getOriginalBaseAddr();
2877 
2878   auto *PointerBaseInst = dyn_cast<Instruction>(PointerBase);
2879   if (!PointerBaseInst)
2880     return nullptr;
2881 
2882   auto *BasePtrStmt = getStmtFor(PointerBaseInst);
2883   if (!BasePtrStmt)
2884     return nullptr;
2885 
2886   return BasePtrStmt->getArrayAccessOrNULLFor(PointerBaseInst);
2887 }
2888 
2889 bool Scop::hasNonHoistableBasePtrInScop(MemoryAccess *MA,
2890                                         __isl_keep isl_union_map *Writes) {
2891   if (auto *BasePtrMA = lookupBasePtrAccess(MA)) {
2892     auto *NHCtx = getNonHoistableCtx(BasePtrMA, Writes);
2893     bool Hoistable = NHCtx != nullptr;
2894     isl_set_free(NHCtx);
2895     return !Hoistable;
2896   }
2897 
2898   Value *BaseAddr = MA->getOriginalBaseAddr();
2899   if (auto *BasePtrInst = dyn_cast<Instruction>(BaseAddr))
2900     if (!isa<LoadInst>(BasePtrInst))
2901       return contains(BasePtrInst);
2902 
2903   return false;
2904 }
2905 
2906 bool Scop::buildAliasChecks(AliasAnalysis &AA) {
2907   if (!PollyUseRuntimeAliasChecks)
2908     return true;
2909 
2910   if (buildAliasGroups(AA)) {
2911     // Aliasing assumptions do not go through addAssumption but we still want to
2912     // collect statistics so we do it here explicitly.
2913     if (MinMaxAliasGroups.size())
2914       AssumptionsAliasing++;
2915     return true;
2916   }
2917 
2918   // If a problem occurs while building the alias groups we need to delete
2919   // this SCoP and pretend it wasn't valid in the first place. To this end
2920   // we make the assumed context infeasible.
2921   invalidate(ALIASING, DebugLoc());
2922 
2923   DEBUG(dbgs() << "\n\nNOTE: Run time checks for " << getNameStr()
2924                << " could not be created as the number of parameters involved "
2925                   "is too high. The SCoP will be "
2926                   "dismissed.\nUse:\n\t--polly-rtc-max-parameters=X\nto adjust "
2927                   "the maximal number of parameters but be advised that the "
2928                   "compile time might increase exponentially.\n\n");
2929   return false;
2930 }
2931 
2932 std::tuple<Scop::AliasGroupVectorTy, DenseSet<const ScopArrayInfo *>>
2933 Scop::buildAliasGroupsForAccesses(AliasAnalysis &AA) {
2934   AliasSetTracker AST(AA);
2935 
2936   DenseMap<Value *, MemoryAccess *> PtrToAcc;
2937   DenseSet<const ScopArrayInfo *> HasWriteAccess;
2938   for (ScopStmt &Stmt : *this) {
2939 
2940     isl_set *StmtDomain = Stmt.getDomain();
2941     bool StmtDomainEmpty = isl_set_is_empty(StmtDomain);
2942     isl_set_free(StmtDomain);
2943 
2944     // Statements with an empty domain will never be executed.
2945     if (StmtDomainEmpty)
2946       continue;
2947 
2948     for (MemoryAccess *MA : Stmt) {
2949       if (MA->isScalarKind())
2950         continue;
2951       if (!MA->isRead())
2952         HasWriteAccess.insert(MA->getScopArrayInfo());
2953       MemAccInst Acc(MA->getAccessInstruction());
2954       if (MA->isRead() && isa<MemTransferInst>(Acc))
2955         PtrToAcc[cast<MemTransferInst>(Acc)->getRawSource()] = MA;
2956       else
2957         PtrToAcc[Acc.getPointerOperand()] = MA;
2958       AST.add(Acc);
2959     }
2960   }
2961 
2962   AliasGroupVectorTy AliasGroups;
2963   for (AliasSet &AS : AST) {
2964     if (AS.isMustAlias() || AS.isForwardingAliasSet())
2965       continue;
2966     AliasGroupTy AG;
2967     for (auto &PR : AS)
2968       AG.push_back(PtrToAcc[PR.getValue()]);
2969     if (AG.size() < 2)
2970       continue;
2971     AliasGroups.push_back(std::move(AG));
2972   }
2973 
2974   return std::make_tuple(AliasGroups, HasWriteAccess);
2975 }
2976 
2977 void Scop::splitAliasGroupsByDomain(AliasGroupVectorTy &AliasGroups) {
2978   for (unsigned u = 0; u < AliasGroups.size(); u++) {
2979     AliasGroupTy NewAG;
2980     AliasGroupTy &AG = AliasGroups[u];
2981     AliasGroupTy::iterator AGI = AG.begin();
2982     isl_set *AGDomain = getAccessDomain(*AGI);
2983     while (AGI != AG.end()) {
2984       MemoryAccess *MA = *AGI;
2985       isl_set *MADomain = getAccessDomain(MA);
2986       if (isl_set_is_disjoint(AGDomain, MADomain)) {
2987         NewAG.push_back(MA);
2988         AGI = AG.erase(AGI);
2989         isl_set_free(MADomain);
2990       } else {
2991         AGDomain = isl_set_union(AGDomain, MADomain);
2992         AGI++;
2993       }
2994     }
2995     if (NewAG.size() > 1)
2996       AliasGroups.push_back(std::move(NewAG));
2997     isl_set_free(AGDomain);
2998   }
2999 }
3000 
3001 bool Scop::buildAliasGroups(AliasAnalysis &AA) {
3002   // To create sound alias checks we perform the following steps:
3003   //   o) We partition each group into read only and non read only accesses.
3004   //   o) For each group with more than one base pointer we then compute minimal
3005   //      and maximal accesses to each array of a group in read only and non
3006   //      read only partitions separately.
3007   AliasGroupVectorTy AliasGroups;
3008   DenseSet<const ScopArrayInfo *> HasWriteAccess;
3009 
3010   std::tie(AliasGroups, HasWriteAccess) = buildAliasGroupsForAccesses(AA);
3011 
3012   splitAliasGroupsByDomain(AliasGroups);
3013 
3014   for (AliasGroupTy &AG : AliasGroups) {
3015     bool Valid = buildAliasGroup(AG, HasWriteAccess);
3016     if (!Valid)
3017       return false;
3018   }
3019 
3020   return true;
3021 }
3022 
3023 bool Scop::buildAliasGroup(Scop::AliasGroupTy &AliasGroup,
3024                            DenseSet<const ScopArrayInfo *> HasWriteAccess) {
3025   AliasGroupTy ReadOnlyAccesses;
3026   AliasGroupTy ReadWriteAccesses;
3027   SmallPtrSet<const ScopArrayInfo *, 4> ReadWriteArrays;
3028   SmallPtrSet<const ScopArrayInfo *, 4> ReadOnlyArrays;
3029 
3030   auto &F = getFunction();
3031 
3032   if (AliasGroup.size() < 2)
3033     return true;
3034 
3035   for (MemoryAccess *Access : AliasGroup) {
3036     emitOptimizationRemarkAnalysis(
3037         F.getContext(), DEBUG_TYPE, F,
3038         Access->getAccessInstruction()->getDebugLoc(),
3039         "Possibly aliasing pointer, use restrict keyword.");
3040 
3041     const ScopArrayInfo *Array = Access->getScopArrayInfo();
3042     if (HasWriteAccess.count(Array)) {
3043       ReadWriteArrays.insert(Array);
3044       ReadWriteAccesses.push_back(Access);
3045     } else {
3046       ReadOnlyArrays.insert(Array);
3047       ReadOnlyAccesses.push_back(Access);
3048     }
3049   }
3050 
3051   // If there are no read-only pointers, and less than two read-write pointers,
3052   // no alias check is needed.
3053   if (ReadOnlyAccesses.empty() && ReadWriteArrays.size() <= 1)
3054     return true;
3055 
3056   // If there is no read-write pointer, no alias check is needed.
3057   if (ReadWriteArrays.empty())
3058     return true;
3059 
3060   // For non-affine accesses, no alias check can be generated as we cannot
3061   // compute a sufficiently tight lower and upper bound: bail out.
3062   for (MemoryAccess *MA : AliasGroup) {
3063     if (!MA->isAffine()) {
3064       invalidate(ALIASING, MA->getAccessInstruction()->getDebugLoc());
3065       return false;
3066     }
3067   }
3068 
3069   // Ensure that for all memory accesses for which we generate alias checks,
3070   // their base pointers are available.
3071   for (MemoryAccess *MA : AliasGroup) {
3072     if (MemoryAccess *BasePtrMA = lookupBasePtrAccess(MA))
3073       addRequiredInvariantLoad(
3074           cast<LoadInst>(BasePtrMA->getAccessInstruction()));
3075   }
3076 
3077   MinMaxAliasGroups.emplace_back();
3078   MinMaxVectorPairTy &pair = MinMaxAliasGroups.back();
3079   MinMaxVectorTy &MinMaxAccessesReadWrite = pair.first;
3080   MinMaxVectorTy &MinMaxAccessesReadOnly = pair.second;
3081 
3082   bool Valid;
3083 
3084   Valid =
3085       calculateMinMaxAccess(ReadWriteAccesses, *this, MinMaxAccessesReadWrite);
3086 
3087   if (!Valid)
3088     return false;
3089 
3090   // Bail out if the number of values we need to compare is too large.
3091   // This is important as the number of comparisons grows quadratically with
3092   // the number of values we need to compare.
3093   if (MinMaxAccessesReadWrite.size() + ReadOnlyArrays.size() >
3094       RunTimeChecksMaxArraysPerGroup)
3095     return false;
3096 
3097   Valid =
3098       calculateMinMaxAccess(ReadOnlyAccesses, *this, MinMaxAccessesReadOnly);
3099 
3100   if (!Valid)
3101     return false;
3102 
3103   return true;
3104 }
3105 
3106 /// Get the smallest loop that contains @p S but is not in @p S.
3107 static Loop *getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
3108   // Start with the smallest loop containing the entry and expand that
3109   // loop until it contains all blocks in the region. If there is a loop
3110   // containing all blocks in the region check if it is itself contained
3111   // and if so take the parent loop as it will be the smallest containing
3112   // the region but not contained by it.
3113   Loop *L = LI.getLoopFor(S.getEntry());
3114   while (L) {
3115     bool AllContained = true;
3116     for (auto *BB : S.blocks())
3117       AllContained &= L->contains(BB);
3118     if (AllContained)
3119       break;
3120     L = L->getParentLoop();
3121   }
3122 
3123   return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
3124 }
3125 
3126 Scop::Scop(Region &R, ScalarEvolution &ScalarEvolution, LoopInfo &LI,
3127            ScopDetection::DetectionContext &DC)
3128     : SE(&ScalarEvolution), R(R), IsOptimized(false),
3129       HasSingleExitEdge(R.getExitingBlock()), HasErrorBlock(false),
3130       MaxLoopDepth(0), CopyStmtsNum(0), DC(DC),
3131       IslCtx(isl_ctx_alloc(), isl_ctx_free), Context(nullptr),
3132       Affinator(this, LI), AssumedContext(nullptr), InvalidContext(nullptr),
3133       Schedule(nullptr) {
3134   if (IslOnErrorAbort)
3135     isl_options_set_on_error(getIslCtx(), ISL_ON_ERROR_ABORT);
3136   buildContext();
3137 }
3138 
3139 void Scop::foldSizeConstantsToRight() {
3140   isl_union_set *Accessed = isl_union_map_range(getAccesses());
3141 
3142   for (auto Array : arrays()) {
3143     if (Array->getNumberOfDimensions() <= 1)
3144       continue;
3145 
3146     isl_space *Space = Array->getSpace();
3147 
3148     Space = isl_space_align_params(Space, isl_union_set_get_space(Accessed));
3149 
3150     if (!isl_union_set_contains(Accessed, Space)) {
3151       isl_space_free(Space);
3152       continue;
3153     }
3154 
3155     isl_set *Elements = isl_union_set_extract_set(Accessed, Space);
3156 
3157     isl_map *Transform =
3158         isl_map_universe(isl_space_map_from_set(Array->getSpace()));
3159 
3160     std::vector<int> Int;
3161 
3162     int Dims = isl_set_dim(Elements, isl_dim_set);
3163     for (int i = 0; i < Dims; i++) {
3164       isl_set *DimOnly =
3165           isl_set_project_out(isl_set_copy(Elements), isl_dim_set, 0, i);
3166       DimOnly = isl_set_project_out(DimOnly, isl_dim_set, 1, Dims - i - 1);
3167       DimOnly = isl_set_lower_bound_si(DimOnly, isl_dim_set, 0, 0);
3168 
3169       isl_basic_set *DimHull = isl_set_affine_hull(DimOnly);
3170 
3171       if (i == Dims - 1) {
3172         Int.push_back(1);
3173         Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3174         isl_basic_set_free(DimHull);
3175         continue;
3176       }
3177 
3178       if (isl_basic_set_dim(DimHull, isl_dim_div) == 1) {
3179         isl_aff *Diff = isl_basic_set_get_div(DimHull, 0);
3180         isl_val *Val = isl_aff_get_denominator_val(Diff);
3181         isl_aff_free(Diff);
3182 
3183         int ValInt = 1;
3184 
3185         if (isl_val_is_int(Val))
3186           ValInt = isl_val_get_num_si(Val);
3187         isl_val_free(Val);
3188 
3189         Int.push_back(ValInt);
3190 
3191         isl_constraint *C = isl_constraint_alloc_equality(
3192             isl_local_space_from_space(isl_map_get_space(Transform)));
3193         C = isl_constraint_set_coefficient_si(C, isl_dim_out, i, ValInt);
3194         C = isl_constraint_set_coefficient_si(C, isl_dim_in, i, -1);
3195         Transform = isl_map_add_constraint(Transform, C);
3196         isl_basic_set_free(DimHull);
3197         continue;
3198       }
3199 
3200       isl_basic_set *ZeroSet = isl_basic_set_copy(DimHull);
3201       ZeroSet = isl_basic_set_fix_si(ZeroSet, isl_dim_set, 0, 0);
3202 
3203       int ValInt = 1;
3204       if (isl_basic_set_is_equal(ZeroSet, DimHull)) {
3205         ValInt = 0;
3206       }
3207 
3208       Int.push_back(ValInt);
3209       Transform = isl_map_equate(Transform, isl_dim_in, i, isl_dim_out, i);
3210       isl_basic_set_free(DimHull);
3211       isl_basic_set_free(ZeroSet);
3212     }
3213 
3214     isl_set *MappedElements = isl_map_domain(isl_map_copy(Transform));
3215 
3216     if (!isl_set_is_subset(Elements, MappedElements)) {
3217       isl_set_free(Elements);
3218       isl_set_free(MappedElements);
3219       isl_map_free(Transform);
3220       continue;
3221     }
3222 
3223     isl_set_free(MappedElements);
3224 
3225     bool CanFold = true;
3226 
3227     if (Int[0] <= 1)
3228       CanFold = false;
3229 
3230     unsigned NumDims = Array->getNumberOfDimensions();
3231     for (unsigned i = 1; i < NumDims - 1; i++)
3232       if (Int[0] != Int[i] && Int[i])
3233         CanFold = false;
3234 
3235     if (!CanFold) {
3236       isl_set_free(Elements);
3237       isl_map_free(Transform);
3238       continue;
3239     }
3240 
3241     for (auto &Access : AccessFunctions)
3242       if (Access->getScopArrayInfo() == Array)
3243         Access->setAccessRelation(isl_map_apply_range(
3244             Access->getAccessRelation(), isl_map_copy(Transform)));
3245 
3246     isl_map_free(Transform);
3247 
3248     std::vector<const SCEV *> Sizes;
3249     for (unsigned i = 0; i < NumDims; i++) {
3250       auto Size = Array->getDimensionSize(i);
3251 
3252       if (i == NumDims - 1)
3253         Size = SE->getMulExpr(Size, SE->getConstant(Size->getType(), Int[0]));
3254       Sizes.push_back(Size);
3255     }
3256 
3257     Array->updateSizes(Sizes, false /* CheckConsistency */);
3258 
3259     isl_set_free(Elements);
3260   }
3261   isl_union_set_free(Accessed);
3262   return;
3263 }
3264 
3265 void Scop::finalizeAccesses() {
3266   updateAccessDimensionality();
3267   foldSizeConstantsToRight();
3268   foldAccessRelations();
3269   assumeNoOutOfBounds();
3270 }
3271 
3272 void Scop::init(AliasAnalysis &AA, DominatorTree &DT, LoopInfo &LI) {
3273   buildInvariantEquivalenceClasses();
3274 
3275   if (!buildDomains(&R, DT, LI))
3276     return;
3277 
3278   addUserAssumptions(DT, LI);
3279 
3280   // Remove empty statements.
3281   // Exit early in case there are no executable statements left in this scop.
3282   simplifySCoP(false);
3283   if (Stmts.empty())
3284     return;
3285 
3286   // The ScopStmts now have enough information to initialize themselves.
3287   for (ScopStmt &Stmt : Stmts)
3288     Stmt.init(LI);
3289 
3290   // Check early for a feasible runtime context.
3291   if (!hasFeasibleRuntimeContext())
3292     return;
3293 
3294   // Check early for profitability. Afterwards it cannot change anymore,
3295   // only the runtime context could become infeasible.
3296   if (!isProfitable()) {
3297     invalidate(PROFITABLE, DebugLoc());
3298     return;
3299   }
3300 
3301   buildSchedule(LI);
3302 
3303   finalizeAccesses();
3304 
3305   realignParams();
3306   addUserContext();
3307 
3308   // After the context was fully constructed, thus all our knowledge about
3309   // the parameters is in there, we add all recorded assumptions to the
3310   // assumed/invalid context.
3311   addRecordedAssumptions();
3312 
3313   simplifyContexts();
3314   if (!buildAliasChecks(AA))
3315     return;
3316 
3317   hoistInvariantLoads();
3318   verifyInvariantLoads();
3319   simplifySCoP(true);
3320 
3321   // Check late for a feasible runtime context because profitability did not
3322   // change.
3323   if (!hasFeasibleRuntimeContext())
3324     return;
3325 }
3326 
3327 Scop::~Scop() {
3328   isl_set_free(Context);
3329   isl_set_free(AssumedContext);
3330   isl_set_free(InvalidContext);
3331   isl_schedule_free(Schedule);
3332 
3333   for (auto &It : ParameterIds)
3334     isl_id_free(It.second);
3335 
3336   for (auto It : DomainMap)
3337     isl_set_free(It.second);
3338 
3339   for (auto &AS : RecordedAssumptions)
3340     isl_set_free(AS.Set);
3341 
3342   // Free the alias groups
3343   for (MinMaxVectorPairTy &MinMaxAccessPair : MinMaxAliasGroups) {
3344     for (MinMaxAccessTy &MMA : MinMaxAccessPair.first) {
3345       isl_pw_multi_aff_free(MMA.first);
3346       isl_pw_multi_aff_free(MMA.second);
3347     }
3348     for (MinMaxAccessTy &MMA : MinMaxAccessPair.second) {
3349       isl_pw_multi_aff_free(MMA.first);
3350       isl_pw_multi_aff_free(MMA.second);
3351     }
3352   }
3353 
3354   for (const auto &IAClass : InvariantEquivClasses)
3355     isl_set_free(IAClass.ExecutionContext);
3356 
3357   // Explicitly release all Scop objects and the underlying isl objects before
3358   // we release the isl context.
3359   Stmts.clear();
3360   ScopArrayInfoSet.clear();
3361   ScopArrayInfoMap.clear();
3362   ScopArrayNameMap.clear();
3363   AccessFunctions.clear();
3364 }
3365 
3366 void Scop::updateAccessDimensionality() {
3367   // Check all array accesses for each base pointer and find a (virtual) element
3368   // size for the base pointer that divides all access functions.
3369   for (ScopStmt &Stmt : *this)
3370     for (MemoryAccess *Access : Stmt) {
3371       if (!Access->isArrayKind())
3372         continue;
3373       ScopArrayInfo *Array =
3374           const_cast<ScopArrayInfo *>(Access->getScopArrayInfo());
3375 
3376       if (Array->getNumberOfDimensions() != 1)
3377         continue;
3378       unsigned DivisibleSize = Array->getElemSizeInBytes();
3379       const SCEV *Subscript = Access->getSubscript(0);
3380       while (!isDivisible(Subscript, DivisibleSize, *SE))
3381         DivisibleSize /= 2;
3382       auto *Ty = IntegerType::get(SE->getContext(), DivisibleSize * 8);
3383       Array->updateElementType(Ty);
3384     }
3385 
3386   for (auto &Stmt : *this)
3387     for (auto &Access : Stmt)
3388       Access->updateDimensionality();
3389 }
3390 
3391 void Scop::foldAccessRelations() {
3392   for (auto &Stmt : *this)
3393     for (auto &Access : Stmt)
3394       Access->foldAccessRelation();
3395 }
3396 
3397 void Scop::assumeNoOutOfBounds() {
3398   for (auto &Stmt : *this)
3399     for (auto &Access : Stmt)
3400       Access->assumeNoOutOfBound();
3401 }
3402 
3403 void Scop::simplifySCoP(bool AfterHoisting) {
3404   for (auto StmtIt = Stmts.begin(), StmtEnd = Stmts.end(); StmtIt != StmtEnd;) {
3405     ScopStmt &Stmt = *StmtIt;
3406 
3407     bool RemoveStmt = Stmt.isEmpty();
3408     if (!RemoveStmt)
3409       RemoveStmt = !DomainMap[Stmt.getEntryBlock()];
3410 
3411     // Remove read only statements only after invariant loop hoisting.
3412     if (!RemoveStmt && AfterHoisting) {
3413       bool OnlyRead = true;
3414       for (MemoryAccess *MA : Stmt) {
3415         if (MA->isRead())
3416           continue;
3417 
3418         OnlyRead = false;
3419         break;
3420       }
3421 
3422       RemoveStmt = OnlyRead;
3423     }
3424 
3425     if (!RemoveStmt) {
3426       StmtIt++;
3427       continue;
3428     }
3429 
3430     // Remove the statement because it is unnecessary.
3431     if (Stmt.isRegionStmt())
3432       for (BasicBlock *BB : Stmt.getRegion()->blocks())
3433         StmtMap.erase(BB);
3434     else
3435       StmtMap.erase(Stmt.getBasicBlock());
3436 
3437     StmtIt = Stmts.erase(StmtIt);
3438   }
3439 }
3440 
3441 InvariantEquivClassTy *Scop::lookupInvariantEquivClass(Value *Val) {
3442   LoadInst *LInst = dyn_cast<LoadInst>(Val);
3443   if (!LInst)
3444     return nullptr;
3445 
3446   if (Value *Rep = InvEquivClassVMap.lookup(LInst))
3447     LInst = cast<LoadInst>(Rep);
3448 
3449   Type *Ty = LInst->getType();
3450   const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3451   for (auto &IAClass : InvariantEquivClasses) {
3452     if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
3453       continue;
3454 
3455     auto &MAs = IAClass.InvariantAccesses;
3456     for (auto *MA : MAs)
3457       if (MA->getAccessInstruction() == Val)
3458         return &IAClass;
3459   }
3460 
3461   return nullptr;
3462 }
3463 
3464 /// Check if @p MA can always be hoisted without execution context.
3465 static bool canAlwaysBeHoisted(MemoryAccess *MA, bool StmtInvalidCtxIsEmpty,
3466                                bool MAInvalidCtxIsEmpty,
3467                                bool NonHoistableCtxIsEmpty) {
3468   LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3469   const DataLayout &DL = LInst->getParent()->getModule()->getDataLayout();
3470   // TODO: We can provide more information for better but more expensive
3471   //       results.
3472   if (!isDereferenceableAndAlignedPointer(LInst->getPointerOperand(),
3473                                           LInst->getAlignment(), DL))
3474     return false;
3475 
3476   // If the location might be overwritten we do not hoist it unconditionally.
3477   //
3478   // TODO: This is probably to conservative.
3479   if (!NonHoistableCtxIsEmpty)
3480     return false;
3481 
3482   // If a dereferencable load is in a statement that is modeled precisely we can
3483   // hoist it.
3484   if (StmtInvalidCtxIsEmpty && MAInvalidCtxIsEmpty)
3485     return true;
3486 
3487   // Even if the statement is not modeled precisely we can hoist the load if it
3488   // does not involve any parameters that might have been specialized by the
3489   // statement domain.
3490   for (unsigned u = 0, e = MA->getNumSubscripts(); u < e; u++)
3491     if (!isa<SCEVConstant>(MA->getSubscript(u)))
3492       return false;
3493   return true;
3494 }
3495 
3496 void Scop::addInvariantLoads(ScopStmt &Stmt, InvariantAccessesTy &InvMAs) {
3497 
3498   if (InvMAs.empty())
3499     return;
3500 
3501   auto *StmtInvalidCtx = Stmt.getInvalidContext();
3502   bool StmtInvalidCtxIsEmpty = isl_set_is_empty(StmtInvalidCtx);
3503 
3504   // Get the context under which the statement is executed but remove the error
3505   // context under which this statement is reached.
3506   isl_set *DomainCtx = isl_set_params(Stmt.getDomain());
3507   DomainCtx = isl_set_subtract(DomainCtx, StmtInvalidCtx);
3508 
3509   if (isl_set_n_basic_set(DomainCtx) >= MaxDisjunctsInDomain) {
3510     auto *AccInst = InvMAs.front().MA->getAccessInstruction();
3511     invalidate(COMPLEXITY, AccInst->getDebugLoc());
3512     isl_set_free(DomainCtx);
3513     for (auto &InvMA : InvMAs)
3514       isl_set_free(InvMA.NonHoistableCtx);
3515     return;
3516   }
3517 
3518   // Project out all parameters that relate to loads in the statement. Otherwise
3519   // we could have cyclic dependences on the constraints under which the
3520   // hoisted loads are executed and we could not determine an order in which to
3521   // pre-load them. This happens because not only lower bounds are part of the
3522   // domain but also upper bounds.
3523   for (auto &InvMA : InvMAs) {
3524     auto *MA = InvMA.MA;
3525     Instruction *AccInst = MA->getAccessInstruction();
3526     if (SE->isSCEVable(AccInst->getType())) {
3527       SetVector<Value *> Values;
3528       for (const SCEV *Parameter : Parameters) {
3529         Values.clear();
3530         findValues(Parameter, *SE, Values);
3531         if (!Values.count(AccInst))
3532           continue;
3533 
3534         if (isl_id *ParamId = getIdForParam(Parameter)) {
3535           int Dim = isl_set_find_dim_by_id(DomainCtx, isl_dim_param, ParamId);
3536           DomainCtx = isl_set_eliminate(DomainCtx, isl_dim_param, Dim, 1);
3537           isl_id_free(ParamId);
3538         }
3539       }
3540     }
3541   }
3542 
3543   for (auto &InvMA : InvMAs) {
3544     auto *MA = InvMA.MA;
3545     auto *NHCtx = InvMA.NonHoistableCtx;
3546 
3547     // Check for another invariant access that accesses the same location as
3548     // MA and if found consolidate them. Otherwise create a new equivalence
3549     // class at the end of InvariantEquivClasses.
3550     LoadInst *LInst = cast<LoadInst>(MA->getAccessInstruction());
3551     Type *Ty = LInst->getType();
3552     const SCEV *PointerSCEV = SE->getSCEV(LInst->getPointerOperand());
3553 
3554     auto *MAInvalidCtx = MA->getInvalidContext();
3555     bool NonHoistableCtxIsEmpty = isl_set_is_empty(NHCtx);
3556     bool MAInvalidCtxIsEmpty = isl_set_is_empty(MAInvalidCtx);
3557 
3558     isl_set *MACtx;
3559     // Check if we know that this pointer can be speculatively accessed.
3560     if (canAlwaysBeHoisted(MA, StmtInvalidCtxIsEmpty, MAInvalidCtxIsEmpty,
3561                            NonHoistableCtxIsEmpty)) {
3562       MACtx = isl_set_universe(isl_set_get_space(DomainCtx));
3563       isl_set_free(MAInvalidCtx);
3564       isl_set_free(NHCtx);
3565     } else {
3566       MACtx = isl_set_copy(DomainCtx);
3567       MACtx = isl_set_subtract(MACtx, isl_set_union(MAInvalidCtx, NHCtx));
3568       MACtx = isl_set_gist_params(MACtx, getContext());
3569     }
3570 
3571     bool Consolidated = false;
3572     for (auto &IAClass : InvariantEquivClasses) {
3573       if (PointerSCEV != IAClass.IdentifyingPointer || Ty != IAClass.AccessType)
3574         continue;
3575 
3576       // If the pointer and the type is equal check if the access function wrt.
3577       // to the domain is equal too. It can happen that the domain fixes
3578       // parameter values and these can be different for distinct part of the
3579       // SCoP. If this happens we cannot consolidate the loads but need to
3580       // create a new invariant load equivalence class.
3581       auto &MAs = IAClass.InvariantAccesses;
3582       if (!MAs.empty()) {
3583         auto *LastMA = MAs.front();
3584 
3585         auto *AR = isl_map_range(MA->getAccessRelation());
3586         auto *LastAR = isl_map_range(LastMA->getAccessRelation());
3587         bool SameAR = isl_set_is_equal(AR, LastAR);
3588         isl_set_free(AR);
3589         isl_set_free(LastAR);
3590 
3591         if (!SameAR)
3592           continue;
3593       }
3594 
3595       // Add MA to the list of accesses that are in this class.
3596       MAs.push_front(MA);
3597 
3598       Consolidated = true;
3599 
3600       // Unify the execution context of the class and this statement.
3601       isl_set *&IAClassDomainCtx = IAClass.ExecutionContext;
3602       if (IAClassDomainCtx)
3603         IAClassDomainCtx =
3604             isl_set_coalesce(isl_set_union(IAClassDomainCtx, MACtx));
3605       else
3606         IAClassDomainCtx = MACtx;
3607       break;
3608     }
3609 
3610     if (Consolidated)
3611       continue;
3612 
3613     // If we did not consolidate MA, thus did not find an equivalence class
3614     // for it, we create a new one.
3615     InvariantEquivClasses.emplace_back(
3616         InvariantEquivClassTy{PointerSCEV, MemoryAccessList{MA}, MACtx, Ty});
3617   }
3618 
3619   isl_set_free(DomainCtx);
3620 }
3621 
3622 __isl_give isl_set *Scop::getNonHoistableCtx(MemoryAccess *Access,
3623                                              __isl_keep isl_union_map *Writes) {
3624   // TODO: Loads that are not loop carried, hence are in a statement with
3625   //       zero iterators, are by construction invariant, though we
3626   //       currently "hoist" them anyway. This is necessary because we allow
3627   //       them to be treated as parameters (e.g., in conditions) and our code
3628   //       generation would otherwise use the old value.
3629 
3630   auto &Stmt = *Access->getStatement();
3631   BasicBlock *BB = Stmt.getEntryBlock();
3632 
3633   if (Access->isScalarKind() || Access->isWrite() || !Access->isAffine() ||
3634       Access->isMemoryIntrinsic())
3635     return nullptr;
3636 
3637   // Skip accesses that have an invariant base pointer which is defined but
3638   // not loaded inside the SCoP. This can happened e.g., if a readnone call
3639   // returns a pointer that is used as a base address. However, as we want
3640   // to hoist indirect pointers, we allow the base pointer to be defined in
3641   // the region if it is also a memory access. Each ScopArrayInfo object
3642   // that has a base pointer origin has a base pointer that is loaded and
3643   // that it is invariant, thus it will be hoisted too. However, if there is
3644   // no base pointer origin we check that the base pointer is defined
3645   // outside the region.
3646   auto *LI = cast<LoadInst>(Access->getAccessInstruction());
3647   if (hasNonHoistableBasePtrInScop(Access, Writes))
3648     return nullptr;
3649 
3650   // Skip accesses in non-affine subregions as they might not be executed
3651   // under the same condition as the entry of the non-affine subregion.
3652   if (BB != LI->getParent())
3653     return nullptr;
3654 
3655   isl_map *AccessRelation = Access->getAccessRelation();
3656   assert(!isl_map_is_empty(AccessRelation));
3657 
3658   if (isl_map_involves_dims(AccessRelation, isl_dim_in, 0,
3659                             Stmt.getNumIterators())) {
3660     isl_map_free(AccessRelation);
3661     return nullptr;
3662   }
3663 
3664   AccessRelation = isl_map_intersect_domain(AccessRelation, Stmt.getDomain());
3665   isl_set *AccessRange = isl_map_range(AccessRelation);
3666 
3667   isl_union_map *Written = isl_union_map_intersect_range(
3668       isl_union_map_copy(Writes), isl_union_set_from_set(AccessRange));
3669   auto *WrittenCtx = isl_union_map_params(Written);
3670   bool IsWritten = !isl_set_is_empty(WrittenCtx);
3671 
3672   if (!IsWritten)
3673     return WrittenCtx;
3674 
3675   WrittenCtx = isl_set_remove_divs(WrittenCtx);
3676   bool TooComplex = isl_set_n_basic_set(WrittenCtx) >= MaxDisjunctsInDomain;
3677   if (TooComplex || !isRequiredInvariantLoad(LI)) {
3678     isl_set_free(WrittenCtx);
3679     return nullptr;
3680   }
3681 
3682   addAssumption(INVARIANTLOAD, isl_set_copy(WrittenCtx), LI->getDebugLoc(),
3683                 AS_RESTRICTION);
3684   return WrittenCtx;
3685 }
3686 
3687 void Scop::verifyInvariantLoads() {
3688   auto &RIL = getRequiredInvariantLoads();
3689   for (LoadInst *LI : RIL) {
3690     assert(LI && contains(LI));
3691     ScopStmt *Stmt = getStmtFor(LI);
3692     if (Stmt && Stmt->getArrayAccessOrNULLFor(LI)) {
3693       invalidate(INVARIANTLOAD, LI->getDebugLoc());
3694       return;
3695     }
3696   }
3697 }
3698 
3699 void Scop::hoistInvariantLoads() {
3700   if (!PollyInvariantLoadHoisting)
3701     return;
3702 
3703   isl_union_map *Writes = getWrites();
3704   for (ScopStmt &Stmt : *this) {
3705     InvariantAccessesTy InvariantAccesses;
3706 
3707     for (MemoryAccess *Access : Stmt)
3708       if (auto *NHCtx = getNonHoistableCtx(Access, Writes))
3709         InvariantAccesses.push_back({Access, NHCtx});
3710 
3711     // Transfer the memory access from the statement to the SCoP.
3712     for (auto InvMA : InvariantAccesses)
3713       Stmt.removeMemoryAccess(InvMA.MA);
3714     addInvariantLoads(Stmt, InvariantAccesses);
3715   }
3716   isl_union_map_free(Writes);
3717 }
3718 
3719 const ScopArrayInfo *
3720 Scop::getOrCreateScopArrayInfo(Value *BasePtr, Type *ElementType,
3721                                ArrayRef<const SCEV *> Sizes, MemoryKind Kind,
3722                                const char *BaseName) {
3723   assert((BasePtr || BaseName) &&
3724          "BasePtr and BaseName can not be nullptr at the same time.");
3725   assert(!(BasePtr && BaseName) && "BaseName is redundant.");
3726   auto &SAI = BasePtr ? ScopArrayInfoMap[std::make_pair(BasePtr, Kind)]
3727                       : ScopArrayNameMap[BaseName];
3728   if (!SAI) {
3729     auto &DL = getFunction().getParent()->getDataLayout();
3730     SAI.reset(new ScopArrayInfo(BasePtr, ElementType, getIslCtx(), Sizes, Kind,
3731                                 DL, this, BaseName));
3732     ScopArrayInfoSet.insert(SAI.get());
3733   } else {
3734     SAI->updateElementType(ElementType);
3735     // In case of mismatching array sizes, we bail out by setting the run-time
3736     // context to false.
3737     if (!SAI->updateSizes(Sizes))
3738       invalidate(DELINEARIZATION, DebugLoc());
3739   }
3740   return SAI.get();
3741 }
3742 
3743 const ScopArrayInfo *
3744 Scop::createScopArrayInfo(Type *ElementType, const std::string &BaseName,
3745                           const std::vector<unsigned> &Sizes) {
3746   auto *DimSizeType = Type::getInt64Ty(getSE()->getContext());
3747   std::vector<const SCEV *> SCEVSizes;
3748 
3749   for (auto size : Sizes)
3750     if (size)
3751       SCEVSizes.push_back(getSE()->getConstant(DimSizeType, size, false));
3752     else
3753       SCEVSizes.push_back(nullptr);
3754 
3755   auto *SAI = getOrCreateScopArrayInfo(nullptr, ElementType, SCEVSizes,
3756                                        MemoryKind::Array, BaseName.c_str());
3757   return SAI;
3758 }
3759 
3760 const ScopArrayInfo *Scop::getScopArrayInfo(Value *BasePtr, MemoryKind Kind) {
3761   auto *SAI = ScopArrayInfoMap[std::make_pair(BasePtr, Kind)].get();
3762   assert(SAI && "No ScopArrayInfo available for this base pointer");
3763   return SAI;
3764 }
3765 
3766 std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
3767 
3768 std::string Scop::getAssumedContextStr() const {
3769   assert(AssumedContext && "Assumed context not yet built");
3770   return stringFromIslObj(AssumedContext);
3771 }
3772 
3773 std::string Scop::getInvalidContextStr() const {
3774   return stringFromIslObj(InvalidContext);
3775 }
3776 
3777 std::string Scop::getNameStr() const {
3778   std::string ExitName, EntryName;
3779   raw_string_ostream ExitStr(ExitName);
3780   raw_string_ostream EntryStr(EntryName);
3781 
3782   R.getEntry()->printAsOperand(EntryStr, false);
3783   EntryStr.str();
3784 
3785   if (R.getExit()) {
3786     R.getExit()->printAsOperand(ExitStr, false);
3787     ExitStr.str();
3788   } else
3789     ExitName = "FunctionExit";
3790 
3791   return EntryName + "---" + ExitName;
3792 }
3793 
3794 __isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
3795 __isl_give isl_space *Scop::getParamSpace() const {
3796   return isl_set_get_space(Context);
3797 }
3798 
3799 __isl_give isl_set *Scop::getAssumedContext() const {
3800   assert(AssumedContext && "Assumed context not yet built");
3801   return isl_set_copy(AssumedContext);
3802 }
3803 
3804 bool Scop::isProfitable() const {
3805   if (PollyProcessUnprofitable)
3806     return true;
3807 
3808   if (isEmpty())
3809     return false;
3810 
3811   unsigned OptimizableStmtsOrLoops = 0;
3812   for (auto &Stmt : *this) {
3813     if (Stmt.getNumIterators() == 0)
3814       continue;
3815 
3816     bool ContainsArrayAccs = false;
3817     bool ContainsScalarAccs = false;
3818     for (auto *MA : Stmt) {
3819       if (MA->isRead())
3820         continue;
3821       ContainsArrayAccs |= MA->isArrayKind();
3822       ContainsScalarAccs |= MA->isScalarKind();
3823     }
3824 
3825     if (!UnprofitableScalarAccs || (ContainsArrayAccs && !ContainsScalarAccs))
3826       OptimizableStmtsOrLoops += Stmt.getNumIterators();
3827   }
3828 
3829   return OptimizableStmtsOrLoops > 1;
3830 }
3831 
3832 bool Scop::hasFeasibleRuntimeContext() const {
3833   auto *PositiveContext = getAssumedContext();
3834   auto *NegativeContext = getInvalidContext();
3835   PositiveContext = addNonEmptyDomainConstraints(PositiveContext);
3836   bool IsFeasible = !(isl_set_is_empty(PositiveContext) ||
3837                       isl_set_is_subset(PositiveContext, NegativeContext));
3838   isl_set_free(PositiveContext);
3839   if (!IsFeasible) {
3840     isl_set_free(NegativeContext);
3841     return false;
3842   }
3843 
3844   auto *DomainContext = isl_union_set_params(getDomains());
3845   IsFeasible = !isl_set_is_subset(DomainContext, NegativeContext);
3846   IsFeasible &= !isl_set_is_subset(Context, NegativeContext);
3847   isl_set_free(NegativeContext);
3848   isl_set_free(DomainContext);
3849 
3850   return IsFeasible;
3851 }
3852 
3853 static std::string toString(AssumptionKind Kind) {
3854   switch (Kind) {
3855   case ALIASING:
3856     return "No-aliasing";
3857   case INBOUNDS:
3858     return "Inbounds";
3859   case WRAPPING:
3860     return "No-overflows";
3861   case UNSIGNED:
3862     return "Signed-unsigned";
3863   case COMPLEXITY:
3864     return "Low complexity";
3865   case PROFITABLE:
3866     return "Profitable";
3867   case ERRORBLOCK:
3868     return "No-error";
3869   case INFINITELOOP:
3870     return "Finite loop";
3871   case INVARIANTLOAD:
3872     return "Invariant load";
3873   case DELINEARIZATION:
3874     return "Delinearization";
3875   }
3876   llvm_unreachable("Unknown AssumptionKind!");
3877 }
3878 
3879 bool Scop::isEffectiveAssumption(__isl_keep isl_set *Set, AssumptionSign Sign) {
3880   if (Sign == AS_ASSUMPTION) {
3881     if (isl_set_is_subset(Context, Set))
3882       return false;
3883 
3884     if (isl_set_is_subset(AssumedContext, Set))
3885       return false;
3886   } else {
3887     if (isl_set_is_disjoint(Set, Context))
3888       return false;
3889 
3890     if (isl_set_is_subset(Set, InvalidContext))
3891       return false;
3892   }
3893   return true;
3894 }
3895 
3896 bool Scop::trackAssumption(AssumptionKind Kind, __isl_keep isl_set *Set,
3897                            DebugLoc Loc, AssumptionSign Sign) {
3898   if (PollyRemarksMinimal && !isEffectiveAssumption(Set, Sign))
3899     return false;
3900 
3901   // Do never emit trivial assumptions as they only clutter the output.
3902   if (!PollyRemarksMinimal) {
3903     isl_set *Univ = nullptr;
3904     if (Sign == AS_ASSUMPTION)
3905       Univ = isl_set_universe(isl_set_get_space(Set));
3906 
3907     bool IsTrivial = (Sign == AS_RESTRICTION && isl_set_is_empty(Set)) ||
3908                      (Sign == AS_ASSUMPTION && isl_set_is_equal(Univ, Set));
3909     isl_set_free(Univ);
3910 
3911     if (IsTrivial)
3912       return false;
3913   }
3914 
3915   switch (Kind) {
3916   case ALIASING:
3917     AssumptionsAliasing++;
3918     break;
3919   case INBOUNDS:
3920     AssumptionsInbounds++;
3921     break;
3922   case WRAPPING:
3923     AssumptionsWrapping++;
3924     break;
3925   case UNSIGNED:
3926     AssumptionsUnsigned++;
3927     break;
3928   case COMPLEXITY:
3929     AssumptionsComplexity++;
3930     break;
3931   case PROFITABLE:
3932     AssumptionsUnprofitable++;
3933     break;
3934   case ERRORBLOCK:
3935     AssumptionsErrorBlock++;
3936     break;
3937   case INFINITELOOP:
3938     AssumptionsInfiniteLoop++;
3939     break;
3940   case INVARIANTLOAD:
3941     AssumptionsInvariantLoad++;
3942     break;
3943   case DELINEARIZATION:
3944     AssumptionsDelinearization++;
3945     break;
3946   }
3947 
3948   auto &F = getFunction();
3949   auto Suffix = Sign == AS_ASSUMPTION ? " assumption:\t" : " restriction:\t";
3950   std::string Msg = toString(Kind) + Suffix + stringFromIslObj(Set);
3951   emitOptimizationRemarkAnalysis(F.getContext(), DEBUG_TYPE, F, Loc, Msg);
3952   return true;
3953 }
3954 
3955 void Scop::addAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3956                          DebugLoc Loc, AssumptionSign Sign) {
3957   // Simplify the assumptions/restrictions first.
3958   Set = isl_set_gist_params(Set, getContext());
3959 
3960   if (!trackAssumption(Kind, Set, Loc, Sign)) {
3961     isl_set_free(Set);
3962     return;
3963   }
3964 
3965   if (Sign == AS_ASSUMPTION) {
3966     AssumedContext = isl_set_intersect(AssumedContext, Set);
3967     AssumedContext = isl_set_coalesce(AssumedContext);
3968   } else {
3969     InvalidContext = isl_set_union(InvalidContext, Set);
3970     InvalidContext = isl_set_coalesce(InvalidContext);
3971   }
3972 }
3973 
3974 void Scop::recordAssumption(AssumptionKind Kind, __isl_take isl_set *Set,
3975                             DebugLoc Loc, AssumptionSign Sign, BasicBlock *BB) {
3976   assert((isl_set_is_params(Set) || BB) &&
3977          "Assumptions without a basic block must be parameter sets");
3978   RecordedAssumptions.push_back({Kind, Sign, Set, Loc, BB});
3979 }
3980 
3981 void Scop::addRecordedAssumptions() {
3982   while (!RecordedAssumptions.empty()) {
3983     const Assumption &AS = RecordedAssumptions.pop_back_val();
3984 
3985     if (!AS.BB) {
3986       addAssumption(AS.Kind, AS.Set, AS.Loc, AS.Sign);
3987       continue;
3988     }
3989 
3990     // If the domain was deleted the assumptions are void.
3991     isl_set *Dom = getDomainConditions(AS.BB);
3992     if (!Dom) {
3993       isl_set_free(AS.Set);
3994       continue;
3995     }
3996 
3997     // If a basic block was given use its domain to simplify the assumption.
3998     // In case of restrictions we know they only have to hold on the domain,
3999     // thus we can intersect them with the domain of the block. However, for
4000     // assumptions the domain has to imply them, thus:
4001     //                     _              _____
4002     //   Dom => S   <==>   A v B   <==>   A - B
4003     //
4004     // To avoid the complement we will register A - B as a restriction not an
4005     // assumption.
4006     isl_set *S = AS.Set;
4007     if (AS.Sign == AS_RESTRICTION)
4008       S = isl_set_params(isl_set_intersect(S, Dom));
4009     else /* (AS.Sign == AS_ASSUMPTION) */
4010       S = isl_set_params(isl_set_subtract(Dom, S));
4011 
4012     addAssumption(AS.Kind, S, AS.Loc, AS_RESTRICTION);
4013   }
4014 }
4015 
4016 void Scop::invalidate(AssumptionKind Kind, DebugLoc Loc) {
4017   addAssumption(Kind, isl_set_empty(getParamSpace()), Loc, AS_ASSUMPTION);
4018 }
4019 
4020 __isl_give isl_set *Scop::getInvalidContext() const {
4021   return isl_set_copy(InvalidContext);
4022 }
4023 
4024 void Scop::printContext(raw_ostream &OS) const {
4025   OS << "Context:\n";
4026   OS.indent(4) << Context << "\n";
4027 
4028   OS.indent(4) << "Assumed Context:\n";
4029   OS.indent(4) << AssumedContext << "\n";
4030 
4031   OS.indent(4) << "Invalid Context:\n";
4032   OS.indent(4) << InvalidContext << "\n";
4033 
4034   unsigned Dim = 0;
4035   for (const SCEV *Parameter : Parameters)
4036     OS.indent(4) << "p" << Dim++ << ": " << *Parameter << "\n";
4037 }
4038 
4039 void Scop::printAliasAssumptions(raw_ostream &OS) const {
4040   int noOfGroups = 0;
4041   for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
4042     if (Pair.second.size() == 0)
4043       noOfGroups += 1;
4044     else
4045       noOfGroups += Pair.second.size();
4046   }
4047 
4048   OS.indent(4) << "Alias Groups (" << noOfGroups << "):\n";
4049   if (MinMaxAliasGroups.empty()) {
4050     OS.indent(8) << "n/a\n";
4051     return;
4052   }
4053 
4054   for (const MinMaxVectorPairTy &Pair : MinMaxAliasGroups) {
4055 
4056     // If the group has no read only accesses print the write accesses.
4057     if (Pair.second.empty()) {
4058       OS.indent(8) << "[[";
4059       for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
4060         OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4061            << ">";
4062       }
4063       OS << " ]]\n";
4064     }
4065 
4066     for (const MinMaxAccessTy &MMAReadOnly : Pair.second) {
4067       OS.indent(8) << "[[";
4068       OS << " <" << MMAReadOnly.first << ", " << MMAReadOnly.second << ">";
4069       for (const MinMaxAccessTy &MMANonReadOnly : Pair.first) {
4070         OS << " <" << MMANonReadOnly.first << ", " << MMANonReadOnly.second
4071            << ">";
4072       }
4073       OS << " ]]\n";
4074     }
4075   }
4076 }
4077 
4078 void Scop::printStatements(raw_ostream &OS) const {
4079   OS << "Statements {\n";
4080 
4081   for (const ScopStmt &Stmt : *this)
4082     OS.indent(4) << Stmt;
4083 
4084   OS.indent(4) << "}\n";
4085 }
4086 
4087 void Scop::printArrayInfo(raw_ostream &OS) const {
4088   OS << "Arrays {\n";
4089 
4090   for (auto &Array : arrays())
4091     Array->print(OS);
4092 
4093   OS.indent(4) << "}\n";
4094 
4095   OS.indent(4) << "Arrays (Bounds as pw_affs) {\n";
4096 
4097   for (auto &Array : arrays())
4098     Array->print(OS, /* SizeAsPwAff */ true);
4099 
4100   OS.indent(4) << "}\n";
4101 }
4102 
4103 void Scop::print(raw_ostream &OS) const {
4104   OS.indent(4) << "Function: " << getFunction().getName() << "\n";
4105   OS.indent(4) << "Region: " << getNameStr() << "\n";
4106   OS.indent(4) << "Max Loop Depth:  " << getMaxLoopDepth() << "\n";
4107   OS.indent(4) << "Invariant Accesses: {\n";
4108   for (const auto &IAClass : InvariantEquivClasses) {
4109     const auto &MAs = IAClass.InvariantAccesses;
4110     if (MAs.empty()) {
4111       OS.indent(12) << "Class Pointer: " << *IAClass.IdentifyingPointer << "\n";
4112     } else {
4113       MAs.front()->print(OS);
4114       OS.indent(12) << "Execution Context: " << IAClass.ExecutionContext
4115                     << "\n";
4116     }
4117   }
4118   OS.indent(4) << "}\n";
4119   printContext(OS.indent(4));
4120   printArrayInfo(OS.indent(4));
4121   printAliasAssumptions(OS);
4122   printStatements(OS.indent(4));
4123 }
4124 
4125 void Scop::dump() const { print(dbgs()); }
4126 
4127 isl_ctx *Scop::getIslCtx() const { return IslCtx.get(); }
4128 
4129 __isl_give PWACtx Scop::getPwAff(const SCEV *E, BasicBlock *BB,
4130                                  bool NonNegative) {
4131   // First try to use the SCEVAffinator to generate a piecewise defined
4132   // affine function from @p E in the context of @p BB. If that tasks becomes to
4133   // complex the affinator might return a nullptr. In such a case we invalidate
4134   // the SCoP and return a dummy value. This way we do not need to add error
4135   // handling code to all users of this function.
4136   auto PWAC = Affinator.getPwAff(E, BB);
4137   if (PWAC.first) {
4138     // TODO: We could use a heuristic and either use:
4139     //         SCEVAffinator::takeNonNegativeAssumption
4140     //       or
4141     //         SCEVAffinator::interpretAsUnsigned
4142     //       to deal with unsigned or "NonNegative" SCEVs.
4143     if (NonNegative)
4144       Affinator.takeNonNegativeAssumption(PWAC);
4145     return PWAC;
4146   }
4147 
4148   auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
4149   invalidate(COMPLEXITY, DL);
4150   return Affinator.getPwAff(SE->getZero(E->getType()), BB);
4151 }
4152 
4153 __isl_give isl_union_set *Scop::getDomains() const {
4154   isl_union_set *Domain = isl_union_set_empty(getParamSpace());
4155 
4156   for (const ScopStmt &Stmt : *this)
4157     Domain = isl_union_set_add_set(Domain, Stmt.getDomain());
4158 
4159   return Domain;
4160 }
4161 
4162 __isl_give isl_pw_aff *Scop::getPwAffOnly(const SCEV *E, BasicBlock *BB) {
4163   PWACtx PWAC = getPwAff(E, BB);
4164   isl_set_free(PWAC.second);
4165   return PWAC.first;
4166 }
4167 
4168 __isl_give isl_union_map *
4169 Scop::getAccessesOfType(std::function<bool(MemoryAccess &)> Predicate) {
4170   isl_union_map *Accesses = isl_union_map_empty(getParamSpace());
4171 
4172   for (ScopStmt &Stmt : *this) {
4173     for (MemoryAccess *MA : Stmt) {
4174       if (!Predicate(*MA))
4175         continue;
4176 
4177       isl_set *Domain = Stmt.getDomain();
4178       isl_map *AccessDomain = MA->getAccessRelation();
4179       AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
4180       Accesses = isl_union_map_add_map(Accesses, AccessDomain);
4181     }
4182   }
4183   return isl_union_map_coalesce(Accesses);
4184 }
4185 
4186 __isl_give isl_union_map *Scop::getMustWrites() {
4187   return getAccessesOfType([](MemoryAccess &MA) { return MA.isMustWrite(); });
4188 }
4189 
4190 __isl_give isl_union_map *Scop::getMayWrites() {
4191   return getAccessesOfType([](MemoryAccess &MA) { return MA.isMayWrite(); });
4192 }
4193 
4194 __isl_give isl_union_map *Scop::getWrites() {
4195   return getAccessesOfType([](MemoryAccess &MA) { return MA.isWrite(); });
4196 }
4197 
4198 __isl_give isl_union_map *Scop::getReads() {
4199   return getAccessesOfType([](MemoryAccess &MA) { return MA.isRead(); });
4200 }
4201 
4202 __isl_give isl_union_map *Scop::getAccesses() {
4203   return getAccessesOfType([](MemoryAccess &MA) { return true; });
4204 }
4205 
4206 // Check whether @p Node is an extension node.
4207 //
4208 // @return true if @p Node is an extension node.
4209 isl_bool isNotExtNode(__isl_keep isl_schedule_node *Node, void *User) {
4210   if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension)
4211     return isl_bool_error;
4212   else
4213     return isl_bool_true;
4214 }
4215 
4216 bool Scop::containsExtensionNode(__isl_keep isl_schedule *Schedule) {
4217   return isl_schedule_foreach_schedule_node_top_down(Schedule, isNotExtNode,
4218                                                      nullptr) == isl_stat_error;
4219 }
4220 
4221 __isl_give isl_union_map *Scop::getSchedule() const {
4222   auto *Tree = getScheduleTree();
4223   if (containsExtensionNode(Tree)) {
4224     isl_schedule_free(Tree);
4225     return nullptr;
4226   }
4227   auto *S = isl_schedule_get_map(Tree);
4228   isl_schedule_free(Tree);
4229   return S;
4230 }
4231 
4232 __isl_give isl_schedule *Scop::getScheduleTree() const {
4233   return isl_schedule_intersect_domain(isl_schedule_copy(Schedule),
4234                                        getDomains());
4235 }
4236 
4237 void Scop::setSchedule(__isl_take isl_union_map *NewSchedule) {
4238   auto *S = isl_schedule_from_domain(getDomains());
4239   S = isl_schedule_insert_partial_schedule(
4240       S, isl_multi_union_pw_aff_from_union_map(NewSchedule));
4241   isl_schedule_free(Schedule);
4242   Schedule = S;
4243 }
4244 
4245 void Scop::setScheduleTree(__isl_take isl_schedule *NewSchedule) {
4246   isl_schedule_free(Schedule);
4247   Schedule = NewSchedule;
4248 }
4249 
4250 bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
4251   bool Changed = false;
4252   for (ScopStmt &Stmt : *this) {
4253     isl_union_set *StmtDomain = isl_union_set_from_set(Stmt.getDomain());
4254     isl_union_set *NewStmtDomain = isl_union_set_intersect(
4255         isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
4256 
4257     if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
4258       isl_union_set_free(StmtDomain);
4259       isl_union_set_free(NewStmtDomain);
4260       continue;
4261     }
4262 
4263     Changed = true;
4264 
4265     isl_union_set_free(StmtDomain);
4266     NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
4267 
4268     if (isl_union_set_is_empty(NewStmtDomain)) {
4269       Stmt.restrictDomain(isl_set_empty(Stmt.getDomainSpace()));
4270       isl_union_set_free(NewStmtDomain);
4271     } else
4272       Stmt.restrictDomain(isl_set_from_union_set(NewStmtDomain));
4273   }
4274   isl_union_set_free(Domain);
4275   return Changed;
4276 }
4277 
4278 ScalarEvolution *Scop::getSE() const { return SE; }
4279 
4280 struct MapToDimensionDataTy {
4281   int N;
4282   isl_union_pw_multi_aff *Res;
4283 };
4284 
4285 // Create a function that maps the elements of 'Set' to its N-th dimension and
4286 // add it to User->Res.
4287 //
4288 // @param Set        The input set.
4289 // @param User->N    The dimension to map to.
4290 // @param User->Res  The isl_union_pw_multi_aff to which to add the result.
4291 //
4292 // @returns   isl_stat_ok if no error occured, othewise isl_stat_error.
4293 static isl_stat mapToDimension_AddSet(__isl_take isl_set *Set, void *User) {
4294   struct MapToDimensionDataTy *Data = (struct MapToDimensionDataTy *)User;
4295   int Dim;
4296   isl_space *Space;
4297   isl_pw_multi_aff *PMA;
4298 
4299   Dim = isl_set_dim(Set, isl_dim_set);
4300   Space = isl_set_get_space(Set);
4301   PMA = isl_pw_multi_aff_project_out_map(Space, isl_dim_set, Data->N,
4302                                          Dim - Data->N);
4303   if (Data->N > 1)
4304     PMA = isl_pw_multi_aff_drop_dims(PMA, isl_dim_out, 0, Data->N - 1);
4305   Data->Res = isl_union_pw_multi_aff_add_pw_multi_aff(Data->Res, PMA);
4306 
4307   isl_set_free(Set);
4308 
4309   return isl_stat_ok;
4310 }
4311 
4312 // Create an isl_multi_union_aff that defines an identity mapping from the
4313 // elements of USet to their N-th dimension.
4314 //
4315 // # Example:
4316 //
4317 //            Domain: { A[i,j]; B[i,j,k] }
4318 //                 N: 1
4319 //
4320 // Resulting Mapping: { {A[i,j] -> [(j)]; B[i,j,k] -> [(j)] }
4321 //
4322 // @param USet   A union set describing the elements for which to generate a
4323 //               mapping.
4324 // @param N      The dimension to map to.
4325 // @returns      A mapping from USet to its N-th dimension.
4326 static __isl_give isl_multi_union_pw_aff *
4327 mapToDimension(__isl_take isl_union_set *USet, int N) {
4328   assert(N >= 0);
4329   assert(USet);
4330   assert(!isl_union_set_is_empty(USet));
4331 
4332   struct MapToDimensionDataTy Data;
4333 
4334   auto *Space = isl_union_set_get_space(USet);
4335   auto *PwAff = isl_union_pw_multi_aff_empty(Space);
4336 
4337   Data = {N, PwAff};
4338 
4339   auto Res = isl_union_set_foreach_set(USet, &mapToDimension_AddSet, &Data);
4340   (void)Res;
4341 
4342   assert(Res == isl_stat_ok);
4343 
4344   isl_union_set_free(USet);
4345   return isl_multi_union_pw_aff_from_union_pw_multi_aff(Data.Res);
4346 }
4347 
4348 void Scop::addScopStmt(BasicBlock *BB) {
4349   assert(BB && "Unexpected nullptr!");
4350   Stmts.emplace_back(*this, *BB);
4351   auto *Stmt = &Stmts.back();
4352   StmtMap[BB] = Stmt;
4353 }
4354 
4355 void Scop::addScopStmt(Region *R) {
4356   assert(R && "Unexpected nullptr!");
4357   Stmts.emplace_back(*this, *R);
4358   auto *Stmt = &Stmts.back();
4359   for (BasicBlock *BB : R->blocks())
4360     StmtMap[BB] = Stmt;
4361 }
4362 
4363 ScopStmt *Scop::addScopStmt(__isl_take isl_map *SourceRel,
4364                             __isl_take isl_map *TargetRel,
4365                             __isl_take isl_set *Domain) {
4366 #ifndef NDEBUG
4367   isl_set *SourceDomain = isl_map_domain(isl_map_copy(SourceRel));
4368   isl_set *TargetDomain = isl_map_domain(isl_map_copy(TargetRel));
4369   assert(isl_set_is_subset(Domain, TargetDomain) &&
4370          "Target access not defined for complete statement domain");
4371   assert(isl_set_is_subset(Domain, SourceDomain) &&
4372          "Source access not defined for complete statement domain");
4373   isl_set_free(SourceDomain);
4374   isl_set_free(TargetDomain);
4375 #endif
4376   Stmts.emplace_back(*this, SourceRel, TargetRel, Domain);
4377   CopyStmtsNum++;
4378   return &(Stmts.back());
4379 }
4380 
4381 void Scop::buildSchedule(LoopInfo &LI) {
4382   Loop *L = getLoopSurroundingScop(*this, LI);
4383   LoopStackTy LoopStack({LoopStackElementTy(L, nullptr, 0)});
4384   buildSchedule(getRegion().getNode(), LoopStack, LI);
4385   assert(LoopStack.size() == 1 && LoopStack.back().L == L);
4386   Schedule = LoopStack[0].Schedule;
4387 }
4388 
4389 /// To generate a schedule for the elements in a Region we traverse the Region
4390 /// in reverse-post-order and add the contained RegionNodes in traversal order
4391 /// to the schedule of the loop that is currently at the top of the LoopStack.
4392 /// For loop-free codes, this results in a correct sequential ordering.
4393 ///
4394 /// Example:
4395 ///           bb1(0)
4396 ///         /     \.
4397 ///      bb2(1)   bb3(2)
4398 ///         \    /  \.
4399 ///          bb4(3)  bb5(4)
4400 ///             \   /
4401 ///              bb6(5)
4402 ///
4403 /// Including loops requires additional processing. Whenever a loop header is
4404 /// encountered, the corresponding loop is added to the @p LoopStack. Starting
4405 /// from an empty schedule, we first process all RegionNodes that are within
4406 /// this loop and complete the sequential schedule at this loop-level before
4407 /// processing about any other nodes. To implement this
4408 /// loop-nodes-first-processing, the reverse post-order traversal is
4409 /// insufficient. Hence, we additionally check if the traversal yields
4410 /// sub-regions or blocks that are outside the last loop on the @p LoopStack.
4411 /// These region-nodes are then queue and only traverse after the all nodes
4412 /// within the current loop have been processed.
4413 void Scop::buildSchedule(Region *R, LoopStackTy &LoopStack, LoopInfo &LI) {
4414   Loop *OuterScopLoop = getLoopSurroundingScop(*this, LI);
4415 
4416   ReversePostOrderTraversal<Region *> RTraversal(R);
4417   std::deque<RegionNode *> WorkList(RTraversal.begin(), RTraversal.end());
4418   std::deque<RegionNode *> DelayList;
4419   bool LastRNWaiting = false;
4420 
4421   // Iterate over the region @p R in reverse post-order but queue
4422   // sub-regions/blocks iff they are not part of the last encountered but not
4423   // completely traversed loop. The variable LastRNWaiting is a flag to indicate
4424   // that we queued the last sub-region/block from the reverse post-order
4425   // iterator. If it is set we have to explore the next sub-region/block from
4426   // the iterator (if any) to guarantee progress. If it is not set we first try
4427   // the next queued sub-region/blocks.
4428   while (!WorkList.empty() || !DelayList.empty()) {
4429     RegionNode *RN;
4430 
4431     if ((LastRNWaiting && !WorkList.empty()) || DelayList.size() == 0) {
4432       RN = WorkList.front();
4433       WorkList.pop_front();
4434       LastRNWaiting = false;
4435     } else {
4436       RN = DelayList.front();
4437       DelayList.pop_front();
4438     }
4439 
4440     Loop *L = getRegionNodeLoop(RN, LI);
4441     if (!contains(L))
4442       L = OuterScopLoop;
4443 
4444     Loop *LastLoop = LoopStack.back().L;
4445     if (LastLoop != L) {
4446       if (LastLoop && !LastLoop->contains(L)) {
4447         LastRNWaiting = true;
4448         DelayList.push_back(RN);
4449         continue;
4450       }
4451       LoopStack.push_back({L, nullptr, 0});
4452     }
4453     buildSchedule(RN, LoopStack, LI);
4454   }
4455 
4456   return;
4457 }
4458 
4459 void Scop::buildSchedule(RegionNode *RN, LoopStackTy &LoopStack, LoopInfo &LI) {
4460 
4461   if (RN->isSubRegion()) {
4462     auto *LocalRegion = RN->getNodeAs<Region>();
4463     if (!isNonAffineSubRegion(LocalRegion)) {
4464       buildSchedule(LocalRegion, LoopStack, LI);
4465       return;
4466     }
4467   }
4468 
4469   auto &LoopData = LoopStack.back();
4470   LoopData.NumBlocksProcessed += getNumBlocksInRegionNode(RN);
4471 
4472   if (auto *Stmt = getStmtFor(RN)) {
4473     auto *UDomain = isl_union_set_from_set(Stmt->getDomain());
4474     auto *StmtSchedule = isl_schedule_from_domain(UDomain);
4475     LoopData.Schedule = combineInSequence(LoopData.Schedule, StmtSchedule);
4476   }
4477 
4478   // Check if we just processed the last node in this loop. If we did, finalize
4479   // the loop by:
4480   //
4481   //   - adding new schedule dimensions
4482   //   - folding the resulting schedule into the parent loop schedule
4483   //   - dropping the loop schedule from the LoopStack.
4484   //
4485   // Then continue to check surrounding loops, which might also have been
4486   // completed by this node.
4487   while (LoopData.L &&
4488          LoopData.NumBlocksProcessed == LoopData.L->getNumBlocks()) {
4489     auto *Schedule = LoopData.Schedule;
4490     auto NumBlocksProcessed = LoopData.NumBlocksProcessed;
4491 
4492     LoopStack.pop_back();
4493     auto &NextLoopData = LoopStack.back();
4494 
4495     if (Schedule) {
4496       auto *Domain = isl_schedule_get_domain(Schedule);
4497       auto *MUPA = mapToDimension(Domain, LoopStack.size());
4498       Schedule = isl_schedule_insert_partial_schedule(Schedule, MUPA);
4499       NextLoopData.Schedule =
4500           combineInSequence(NextLoopData.Schedule, Schedule);
4501     }
4502 
4503     NextLoopData.NumBlocksProcessed += NumBlocksProcessed;
4504     LoopData = NextLoopData;
4505   }
4506 }
4507 
4508 ScopStmt *Scop::getStmtFor(BasicBlock *BB) const {
4509   auto StmtMapIt = StmtMap.find(BB);
4510   if (StmtMapIt == StmtMap.end())
4511     return nullptr;
4512   return StmtMapIt->second;
4513 }
4514 
4515 ScopStmt *Scop::getStmtFor(RegionNode *RN) const {
4516   if (RN->isSubRegion())
4517     return getStmtFor(RN->getNodeAs<Region>());
4518   return getStmtFor(RN->getNodeAs<BasicBlock>());
4519 }
4520 
4521 ScopStmt *Scop::getStmtFor(Region *R) const {
4522   ScopStmt *Stmt = getStmtFor(R->getEntry());
4523   assert(!Stmt || Stmt->getRegion() == R);
4524   return Stmt;
4525 }
4526 
4527 int Scop::getRelativeLoopDepth(const Loop *L) const {
4528   Loop *OuterLoop =
4529       L ? R.outermostLoopInRegion(const_cast<Loop *>(L)) : nullptr;
4530   if (!OuterLoop)
4531     return -1;
4532   return L->getLoopDepth() - OuterLoop->getLoopDepth();
4533 }
4534 
4535 ScopArrayInfo *Scop::getArrayInfoByName(const std::string BaseName) {
4536   for (auto &SAI : arrays()) {
4537     if (SAI->getName() == BaseName)
4538       return SAI;
4539   }
4540   return nullptr;
4541 }
4542 
4543 //===----------------------------------------------------------------------===//
4544 void ScopInfoRegionPass::getAnalysisUsage(AnalysisUsage &AU) const {
4545   AU.addRequired<LoopInfoWrapperPass>();
4546   AU.addRequired<RegionInfoPass>();
4547   AU.addRequired<DominatorTreeWrapperPass>();
4548   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4549   AU.addRequiredTransitive<ScopDetection>();
4550   AU.addRequired<AAResultsWrapperPass>();
4551   AU.setPreservesAll();
4552 }
4553 
4554 void updateLoopCountStatistic(ScopDetection::LoopStats Stats) {
4555   NumLoopsInScop += Stats.NumLoops;
4556   MaxNumLoopsInScop =
4557       std::max(MaxNumLoopsInScop.getValue(), (unsigned)Stats.NumLoops);
4558 
4559   if (Stats.MaxDepth == 1)
4560     NumScopsDepthOne++;
4561   else if (Stats.MaxDepth == 2)
4562     NumScopsDepthTwo++;
4563   else if (Stats.MaxDepth == 3)
4564     NumScopsDepthThree++;
4565   else if (Stats.MaxDepth == 4)
4566     NumScopsDepthFour++;
4567   else if (Stats.MaxDepth == 5)
4568     NumScopsDepthFive++;
4569   else
4570     NumScopsDepthLarger++;
4571 }
4572 
4573 bool ScopInfoRegionPass::runOnRegion(Region *R, RGPassManager &RGM) {
4574   auto &SD = getAnalysis<ScopDetection>();
4575 
4576   if (!SD.isMaxRegionInScop(*R))
4577     return false;
4578 
4579   Function *F = R->getEntry()->getParent();
4580   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4581   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4582   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4583   auto const &DL = F->getParent()->getDataLayout();
4584   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4585 
4586   ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
4587   S = SB.getScop(); // take ownership of scop object
4588 
4589   if (S) {
4590     ScopDetection::LoopStats Stats =
4591         ScopDetection::countBeneficialLoops(&S->getRegion(), SE, LI, 0);
4592     updateLoopCountStatistic(Stats);
4593   }
4594 
4595   return false;
4596 }
4597 
4598 void ScopInfoRegionPass::print(raw_ostream &OS, const Module *) const {
4599   if (S)
4600     S->print(OS);
4601   else
4602     OS << "Invalid Scop!\n";
4603 }
4604 
4605 char ScopInfoRegionPass::ID = 0;
4606 
4607 Pass *polly::createScopInfoRegionPassPass() { return new ScopInfoRegionPass(); }
4608 
4609 INITIALIZE_PASS_BEGIN(ScopInfoRegionPass, "polly-scops",
4610                       "Polly - Create polyhedral description of Scops", false,
4611                       false);
4612 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4613 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4614 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4615 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4616 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4617 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4618 INITIALIZE_PASS_END(ScopInfoRegionPass, "polly-scops",
4619                     "Polly - Create polyhedral description of Scops", false,
4620                     false)
4621 
4622 //===----------------------------------------------------------------------===//
4623 void ScopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
4624   AU.addRequired<LoopInfoWrapperPass>();
4625   AU.addRequired<RegionInfoPass>();
4626   AU.addRequired<DominatorTreeWrapperPass>();
4627   AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
4628   AU.addRequiredTransitive<ScopDetection>();
4629   AU.addRequired<AAResultsWrapperPass>();
4630   AU.setPreservesAll();
4631 }
4632 
4633 bool ScopInfoWrapperPass::runOnFunction(Function &F) {
4634   auto &SD = getAnalysis<ScopDetection>();
4635 
4636   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4637   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4638   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
4639   auto const &DL = F.getParent()->getDataLayout();
4640   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4641 
4642   /// Create polyhedral descripton of scops for all the valid regions of a
4643   /// function.
4644   for (auto &It : SD) {
4645     Region *R = const_cast<Region *>(It);
4646     if (!SD.isMaxRegionInScop(*R))
4647       continue;
4648 
4649     ScopBuilder SB(R, AA, DL, DT, LI, SD, SE);
4650     std::unique_ptr<Scop> S = SB.getScop();
4651     if (!S)
4652       continue;
4653     bool Inserted =
4654         RegionToScopMap.insert(std::make_pair(R, std::move(S))).second;
4655     assert(Inserted && "Building Scop for the same region twice!");
4656     (void)Inserted;
4657   }
4658   return false;
4659 }
4660 
4661 void ScopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
4662   for (auto &It : RegionToScopMap) {
4663     if (It.second)
4664       It.second->print(OS);
4665     else
4666       OS << "Invalid Scop!\n";
4667   }
4668 }
4669 
4670 char ScopInfoWrapperPass::ID = 0;
4671 
4672 Pass *polly::createScopInfoWrapperPassPass() {
4673   return new ScopInfoWrapperPass();
4674 }
4675 
4676 INITIALIZE_PASS_BEGIN(
4677     ScopInfoWrapperPass, "polly-function-scops",
4678     "Polly - Create polyhedral description of all Scops of a function", false,
4679     false);
4680 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass);
4681 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
4682 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
4683 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
4684 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
4685 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
4686 INITIALIZE_PASS_END(
4687     ScopInfoWrapperPass, "polly-function-scops",
4688     "Polly - Create polyhedral description of all Scops of a function", false,
4689     false)
4690