1 //===--------- ScopInfo.cpp  - Create Scops from LLVM IR ------------------===//
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 represantation is shared among several tools in the polyhedral
16 // community, which are e.g. Cloog, Pluto, Loopo, Graphite.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "polly/CodeGen/BlockGenerators.h"
21 #include "polly/LinkAllPasses.h"
22 #include "polly/ScopInfo.h"
23 #include "polly/Options.h"
24 #include "polly/Support/GICHelper.h"
25 #include "polly/Support/SCEVValidator.h"
26 #include "polly/Support/ScopHelper.h"
27 #include "polly/TempScopInfo.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/RegionIterator.h"
33 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
34 #include "llvm/Support/Debug.h"
35 
36 #include "isl/constraint.h"
37 #include "isl/set.h"
38 #include "isl/map.h"
39 #include "isl/union_map.h"
40 #include "isl/aff.h"
41 #include "isl/printer.h"
42 #include "isl/local_space.h"
43 #include "isl/options.h"
44 #include "isl/val.h"
45 
46 #include <sstream>
47 #include <string>
48 #include <vector>
49 
50 using namespace llvm;
51 using namespace polly;
52 
53 #define DEBUG_TYPE "polly-scops"
54 
55 STATISTIC(ScopFound, "Number of valid Scops");
56 STATISTIC(RichScopFound, "Number of Scops containing a loop");
57 
58 // Multiplicative reductions can be disabled seperately as these kind of
59 // operations can overflow easily. Additive reductions and bit operations
60 // are in contrast pretty stable.
61 static cl::opt<bool> DisableMultiplicativeReductions(
62     "polly-disable-multiplicative-reductions",
63     cl::desc("Disable multiplicative reductions"), cl::Hidden, cl::ZeroOrMore,
64     cl::init(false), cl::cat(PollyCategory));
65 
66 /// Translate a 'const SCEV *' expression in an isl_pw_aff.
67 struct SCEVAffinator : public SCEVVisitor<SCEVAffinator, isl_pw_aff *> {
68 public:
69   /// @brief Translate a 'const SCEV *' to an isl_pw_aff.
70   ///
71   /// @param Stmt The location at which the scalar evolution expression
72   ///             is evaluated.
73   /// @param Expr The expression that is translated.
74   static __isl_give isl_pw_aff *getPwAff(ScopStmt *Stmt, const SCEV *Expr);
75 
76 private:
77   isl_ctx *Ctx;
78   int NbLoopSpaces;
79   const Scop *S;
80 
81   SCEVAffinator(const ScopStmt *Stmt);
82   int getLoopDepth(const Loop *L);
83 
84   __isl_give isl_pw_aff *visit(const SCEV *Expr);
85   __isl_give isl_pw_aff *visitConstant(const SCEVConstant *Expr);
86   __isl_give isl_pw_aff *visitTruncateExpr(const SCEVTruncateExpr *Expr);
87   __isl_give isl_pw_aff *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr);
88   __isl_give isl_pw_aff *visitSignExtendExpr(const SCEVSignExtendExpr *Expr);
89   __isl_give isl_pw_aff *visitAddExpr(const SCEVAddExpr *Expr);
90   __isl_give isl_pw_aff *visitMulExpr(const SCEVMulExpr *Expr);
91   __isl_give isl_pw_aff *visitUDivExpr(const SCEVUDivExpr *Expr);
92   __isl_give isl_pw_aff *visitAddRecExpr(const SCEVAddRecExpr *Expr);
93   __isl_give isl_pw_aff *visitSMaxExpr(const SCEVSMaxExpr *Expr);
94   __isl_give isl_pw_aff *visitUMaxExpr(const SCEVUMaxExpr *Expr);
95   __isl_give isl_pw_aff *visitUnknown(const SCEVUnknown *Expr);
96 
97   friend struct SCEVVisitor<SCEVAffinator, isl_pw_aff *>;
98 };
99 
100 SCEVAffinator::SCEVAffinator(const ScopStmt *Stmt)
101     : Ctx(Stmt->getIslCtx()), NbLoopSpaces(Stmt->getNumIterators()),
102       S(Stmt->getParent()) {}
103 
104 __isl_give isl_pw_aff *SCEVAffinator::getPwAff(ScopStmt *Stmt,
105                                                const SCEV *Scev) {
106   Scop *S = Stmt->getParent();
107   const Region *Reg = &S->getRegion();
108 
109   S->addParams(getParamsInAffineExpr(Reg, Scev, *S->getSE()));
110 
111   SCEVAffinator Affinator(Stmt);
112   return Affinator.visit(Scev);
113 }
114 
115 __isl_give isl_pw_aff *SCEVAffinator::visit(const SCEV *Expr) {
116   // In case the scev is a valid parameter, we do not further analyze this
117   // expression, but create a new parameter in the isl_pw_aff. This allows us
118   // to treat subexpressions that we cannot translate into an piecewise affine
119   // expression, as constant parameters of the piecewise affine expression.
120   if (isl_id *Id = S->getIdForParam(Expr)) {
121     isl_space *Space = isl_space_set_alloc(Ctx, 1, NbLoopSpaces);
122     Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
123 
124     isl_set *Domain = isl_set_universe(isl_space_copy(Space));
125     isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
126     Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
127 
128     return isl_pw_aff_alloc(Domain, Affine);
129   }
130 
131   return SCEVVisitor<SCEVAffinator, isl_pw_aff *>::visit(Expr);
132 }
133 
134 __isl_give isl_pw_aff *SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
135   ConstantInt *Value = Expr->getValue();
136   isl_val *v;
137 
138   // LLVM does not define if an integer value is interpreted as a signed or
139   // unsigned value. Hence, without further information, it is unknown how
140   // this value needs to be converted to GMP. At the moment, we only support
141   // signed operations. So we just interpret it as signed. Later, there are
142   // two options:
143   //
144   // 1. We always interpret any value as signed and convert the values on
145   //    demand.
146   // 2. We pass down the signedness of the calculation and use it to interpret
147   //    this constant correctly.
148   v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
149 
150   isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
151   isl_local_space *ls = isl_local_space_from_space(isl_space_copy(Space));
152   isl_aff *Affine = isl_aff_zero_on_domain(ls);
153   isl_set *Domain = isl_set_universe(Space);
154 
155   Affine = isl_aff_add_constant_val(Affine, v);
156 
157   return isl_pw_aff_alloc(Domain, Affine);
158 }
159 
160 __isl_give isl_pw_aff *
161 SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
162   llvm_unreachable("SCEVTruncateExpr not yet supported");
163 }
164 
165 __isl_give isl_pw_aff *
166 SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
167   llvm_unreachable("SCEVZeroExtendExpr not yet supported");
168 }
169 
170 __isl_give isl_pw_aff *
171 SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
172   // Assuming the value is signed, a sign extension is basically a noop.
173   // TODO: Reconsider this as soon as we support unsigned values.
174   return visit(Expr->getOperand());
175 }
176 
177 __isl_give isl_pw_aff *SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
178   isl_pw_aff *Sum = visit(Expr->getOperand(0));
179 
180   for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
181     isl_pw_aff *NextSummand = visit(Expr->getOperand(i));
182     Sum = isl_pw_aff_add(Sum, NextSummand);
183   }
184 
185   // TODO: Check for NSW and NUW.
186 
187   return Sum;
188 }
189 
190 __isl_give isl_pw_aff *SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
191   isl_pw_aff *Product = visit(Expr->getOperand(0));
192 
193   for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
194     isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
195 
196     if (!isl_pw_aff_is_cst(Product) && !isl_pw_aff_is_cst(NextOperand)) {
197       isl_pw_aff_free(Product);
198       isl_pw_aff_free(NextOperand);
199       return nullptr;
200     }
201 
202     Product = isl_pw_aff_mul(Product, NextOperand);
203   }
204 
205   // TODO: Check for NSW and NUW.
206   return Product;
207 }
208 
209 __isl_give isl_pw_aff *SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
210   llvm_unreachable("SCEVUDivExpr not yet supported");
211 }
212 
213 __isl_give isl_pw_aff *
214 SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
215   assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
216 
217   // Directly generate isl_pw_aff for Expr if 'start' is zero.
218   if (Expr->getStart()->isZero()) {
219     assert(S->getRegion().contains(Expr->getLoop()) &&
220            "Scop does not contain the loop referenced in this AddRec");
221 
222     isl_pw_aff *Start = visit(Expr->getStart());
223     isl_pw_aff *Step = visit(Expr->getOperand(1));
224     isl_space *Space = isl_space_set_alloc(Ctx, 0, NbLoopSpaces);
225     isl_local_space *LocalSpace = isl_local_space_from_space(Space);
226 
227     int loopDimension = getLoopDepth(Expr->getLoop());
228 
229     isl_aff *LAff = isl_aff_set_coefficient_si(
230         isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
231     isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
232 
233     // TODO: Do we need to check for NSW and NUW?
234     return isl_pw_aff_add(Start, isl_pw_aff_mul(Step, LPwAff));
235   }
236 
237   // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
238   // if 'start' is not zero.
239   ScalarEvolution &SE = *S->getSE();
240   const SCEV *ZeroStartExpr = SE.getAddRecExpr(
241       SE.getConstant(Expr->getStart()->getType(), 0),
242       Expr->getStepRecurrence(SE), Expr->getLoop(), SCEV::FlagAnyWrap);
243 
244   isl_pw_aff *ZeroStartResult = visit(ZeroStartExpr);
245   isl_pw_aff *Start = visit(Expr->getStart());
246 
247   return isl_pw_aff_add(ZeroStartResult, Start);
248 }
249 
250 __isl_give isl_pw_aff *SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
251   isl_pw_aff *Max = visit(Expr->getOperand(0));
252 
253   for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
254     isl_pw_aff *NextOperand = visit(Expr->getOperand(i));
255     Max = isl_pw_aff_max(Max, NextOperand);
256   }
257 
258   return Max;
259 }
260 
261 __isl_give isl_pw_aff *SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
262   llvm_unreachable("SCEVUMaxExpr not yet supported");
263 }
264 
265 __isl_give isl_pw_aff *SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
266   llvm_unreachable("Unknowns are always parameters");
267 }
268 
269 int SCEVAffinator::getLoopDepth(const Loop *L) {
270   Loop *outerLoop = S->getRegion().outermostLoopInRegion(const_cast<Loop *>(L));
271   assert(outerLoop && "Scop does not contain this loop");
272   return L->getLoopDepth() - outerLoop->getLoopDepth();
273 }
274 
275 /// @brief Return the reduction type for a given binary operator
276 static MemoryAccess::ReductionType getReductionType(const BinaryOperator *BinOp,
277                                                     const Instruction *Load) {
278   if (!BinOp)
279     return MemoryAccess::RT_NONE;
280   switch (BinOp->getOpcode()) {
281   case Instruction::FAdd:
282     if (!BinOp->hasUnsafeAlgebra())
283       return MemoryAccess::RT_NONE;
284   // Fall through
285   case Instruction::Add:
286     return MemoryAccess::RT_ADD;
287   case Instruction::Or:
288     return MemoryAccess::RT_BOR;
289   case Instruction::Xor:
290     return MemoryAccess::RT_BXOR;
291   case Instruction::And:
292     return MemoryAccess::RT_BAND;
293   case Instruction::FMul:
294     if (!BinOp->hasUnsafeAlgebra())
295       return MemoryAccess::RT_NONE;
296   // Fall through
297   case Instruction::Mul:
298     if (DisableMultiplicativeReductions)
299       return MemoryAccess::RT_NONE;
300     return MemoryAccess::RT_MUL;
301   default:
302     return MemoryAccess::RT_NONE;
303   }
304 }
305 //===----------------------------------------------------------------------===//
306 
307 MemoryAccess::~MemoryAccess() {
308   isl_map_free(AccessRelation);
309   isl_map_free(newAccessRelation);
310 }
311 
312 static void replace(std::string &str, const std::string &find,
313                     const std::string &replace) {
314   size_t pos = 0;
315   while ((pos = str.find(find, pos)) != std::string::npos) {
316     str.replace(pos, find.length(), replace);
317     pos += replace.length();
318   }
319 }
320 
321 static void makeIslCompatible(std::string &str) {
322   str.erase(0, 1);
323   replace(str, ".", "_");
324   replace(str, "\"", "_");
325 }
326 
327 void MemoryAccess::setBaseName() {
328   raw_string_ostream OS(BaseName);
329   getBaseAddr()->printAsOperand(OS, false);
330   BaseName = OS.str();
331 
332   makeIslCompatible(BaseName);
333   BaseName = "MemRef_" + BaseName;
334 }
335 
336 isl_map *MemoryAccess::getAccessRelation() const {
337   return isl_map_copy(AccessRelation);
338 }
339 
340 std::string MemoryAccess::getAccessRelationStr() const {
341   return stringFromIslObj(AccessRelation);
342 }
343 
344 __isl_give isl_space *MemoryAccess::getAccessRelationSpace() const {
345   return isl_map_get_space(AccessRelation);
346 }
347 
348 isl_map *MemoryAccess::getNewAccessRelation() const {
349   return isl_map_copy(newAccessRelation);
350 }
351 
352 isl_basic_map *MemoryAccess::createBasicAccessMap(ScopStmt *Statement) {
353   isl_space *Space = isl_space_set_alloc(Statement->getIslCtx(), 0, 1);
354   Space = isl_space_set_tuple_name(Space, isl_dim_set, getBaseName().c_str());
355   Space = isl_space_align_params(Space, Statement->getDomainSpace());
356 
357   return isl_basic_map_from_domain_and_range(
358       isl_basic_set_universe(Statement->getDomainSpace()),
359       isl_basic_set_universe(Space));
360 }
361 
362 // Formalize no out-of-bound access assumption
363 //
364 // When delinearizing array accesses we optimistically assume that the
365 // delinearized accesses do not access out of bound locations (the subscript
366 // expression of each array evaluates for each statement instance that is
367 // executed to a value that is larger than zero and strictly smaller than the
368 // size of the corresponding dimension). The only exception is the outermost
369 // dimension for which we do not assume any upper bound.  At this point we
370 // formalize this assumption to ensure that at code generation time the relevant
371 // run-time checks can be generated.
372 //
373 // To find the set of constraints necessary to avoid out of bound accesses, we
374 // first build the set of data locations that are not within array bounds. We
375 // then apply the reverse access relation to obtain the set of iterations that
376 // may contain invalid accesses and reduce this set of iterations to the ones
377 // that are actually executed by intersecting them with the domain of the
378 // statement. If we now project out all loop dimensions, we obtain a set of
379 // parameters that may cause statement instances to be executed that may
380 // possibly yield out of bound memory accesses. The complement of these
381 // constraints is the set of constraints that needs to be assumed to ensure such
382 // statement instances are never executed.
383 void MemoryAccess::assumeNoOutOfBound(const IRAccess &Access) {
384   isl_space *Space = isl_space_range(getAccessRelationSpace());
385   isl_set *Outside = isl_set_empty(isl_space_copy(Space));
386   for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
387     isl_local_space *LS = isl_local_space_from_space(isl_space_copy(Space));
388     isl_pw_aff *Var =
389         isl_pw_aff_var_on_domain(isl_local_space_copy(LS), isl_dim_set, i);
390     isl_pw_aff *Zero = isl_pw_aff_zero_on_domain(LS);
391 
392     isl_set *DimOutside;
393 
394     if (i == 0) {
395       DimOutside = isl_pw_aff_lt_set(Var, Zero);
396     } else {
397       DimOutside = isl_pw_aff_lt_set(isl_pw_aff_copy(Var), Zero);
398       isl_pw_aff *SizeE =
399           SCEVAffinator::getPwAff(Statement, Access.Sizes[i - 1]);
400 
401       SizeE = isl_pw_aff_drop_dims(SizeE, isl_dim_in, 0,
402                                    Statement->getNumIterators());
403       SizeE = isl_pw_aff_add_dims(SizeE, isl_dim_in,
404                                   isl_space_dim(Space, isl_dim_set));
405       SizeE = isl_pw_aff_set_tuple_id(
406           SizeE, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
407 
408       DimOutside = isl_set_union(DimOutside, isl_pw_aff_le_set(SizeE, Var));
409     }
410 
411     Outside = isl_set_union(Outside, DimOutside);
412   }
413 
414   Outside = isl_set_apply(Outside, isl_map_reverse(getAccessRelation()));
415   Outside = isl_set_intersect(Outside, Statement->getDomain());
416   Outside = isl_set_params(Outside);
417   Outside = isl_set_complement(Outside);
418   Statement->getParent()->addAssumption(Outside);
419   isl_space_free(Space);
420 }
421 
422 MemoryAccess::MemoryAccess(const IRAccess &Access, const Instruction *AccInst,
423                            ScopStmt *Statement)
424     : Statement(Statement), Inst(AccInst), newAccessRelation(nullptr) {
425 
426   BaseAddr = Access.getBase();
427   setBaseName();
428 
429   if (!Access.isAffine()) {
430     // We overapproximate non-affine accesses with a possible access to the
431     // whole array. For read accesses it does not make a difference, if an
432     // access must or may happen. However, for write accesses it is important to
433     // differentiate between writes that must happen and writes that may happen.
434     AccessRelation = isl_map_from_basic_map(createBasicAccessMap(Statement));
435     Type = Access.isRead() ? READ : MAY_WRITE;
436     return;
437   }
438 
439   Type = Access.isRead() ? READ : MUST_WRITE;
440 
441   isl_space *Space = isl_space_alloc(Statement->getIslCtx(), 0,
442                                      Statement->getNumIterators(), 0);
443   AccessRelation = isl_map_universe(Space);
444 
445   for (int i = 0, Size = Access.Subscripts.size(); i < Size; ++i) {
446     isl_pw_aff *Affine =
447         SCEVAffinator::getPwAff(Statement, Access.Subscripts[i]);
448 
449     if (Size == 1) {
450       // For the non delinearized arrays, divide the access function of the last
451       // subscript by the size of the elements in the array.
452       //
453       // A stride one array access in C expressed as A[i] is expressed in
454       // LLVM-IR as something like A[i * elementsize]. This hides the fact that
455       // two subsequent values of 'i' index two values that are stored next to
456       // each other in memory. By this division we make this characteristic
457       // obvious again.
458       isl_val *v;
459       v = isl_val_int_from_si(isl_pw_aff_get_ctx(Affine),
460                               Access.getElemSizeInBytes());
461       Affine = isl_pw_aff_scale_down_val(Affine, v);
462     }
463 
464     isl_map *SubscriptMap = isl_map_from_pw_aff(Affine);
465 
466     AccessRelation = isl_map_flat_range_product(AccessRelation, SubscriptMap);
467   }
468 
469   Space = Statement->getDomainSpace();
470   AccessRelation = isl_map_set_tuple_id(
471       AccessRelation, isl_dim_in, isl_space_get_tuple_id(Space, isl_dim_set));
472   isl_space_free(Space);
473   AccessRelation = isl_map_set_tuple_name(AccessRelation, isl_dim_out,
474                                           getBaseName().c_str());
475   assumeNoOutOfBound(Access);
476 }
477 
478 void MemoryAccess::realignParams() {
479   isl_space *ParamSpace = Statement->getParent()->getParamSpace();
480   AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
481 }
482 
483 MemoryAccess::MemoryAccess(const Value *BaseAddress, ScopStmt *Statement)
484     : Type(READ), BaseAddr(BaseAddress), Statement(Statement),
485       newAccessRelation(nullptr) {
486 
487   isl_basic_map *BasicAccessMap = createBasicAccessMap(Statement);
488   AccessRelation = isl_map_from_basic_map(BasicAccessMap);
489   isl_space *ParamSpace = Statement->getParent()->getParamSpace();
490   AccessRelation = isl_map_align_params(AccessRelation, ParamSpace);
491 }
492 
493 raw_ostream &polly::operator<<(raw_ostream &OS,
494                                MemoryAccess::ReductionType RT) {
495   switch (RT) {
496   case MemoryAccess::RT_NONE:
497     OS << "NONE";
498     break;
499   case MemoryAccess::RT_ADD:
500     OS << "ADD";
501     break;
502   case MemoryAccess::RT_MUL:
503     OS << "MUL";
504     break;
505   case MemoryAccess::RT_BOR:
506     OS << "BOR";
507     break;
508   case MemoryAccess::RT_BXOR:
509     OS << "BXOR";
510     break;
511   case MemoryAccess::RT_BAND:
512     OS << "BAND";
513     break;
514   }
515   return OS;
516 }
517 
518 void MemoryAccess::print(raw_ostream &OS) const {
519   switch (Type) {
520   case READ:
521     OS.indent(12) << "ReadAccess :=\t";
522     break;
523   case MUST_WRITE:
524     OS.indent(12) << "MustWriteAccess :=\t";
525     break;
526   case MAY_WRITE:
527     OS.indent(12) << "MayWriteAccess :=\t";
528     break;
529   }
530   OS << "[Reduction Type: " << getReductionType() << "]\n";
531   OS.indent(16) << getAccessRelationStr() << ";\n";
532 }
533 
534 void MemoryAccess::dump() const { print(errs()); }
535 
536 // Create a map in the size of the provided set domain, that maps from the
537 // one element of the provided set domain to another element of the provided
538 // set domain.
539 // The mapping is limited to all points that are equal in all but the last
540 // dimension and for which the last dimension of the input is strict smaller
541 // than the last dimension of the output.
542 //
543 //   getEqualAndLarger(set[i0, i1, ..., iX]):
544 //
545 //   set[i0, i1, ..., iX] -> set[o0, o1, ..., oX]
546 //     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1), iX < oX
547 //
548 static isl_map *getEqualAndLarger(isl_space *setDomain) {
549   isl_space *Space = isl_space_map_from_set(setDomain);
550   isl_map *Map = isl_map_universe(isl_space_copy(Space));
551   isl_local_space *MapLocalSpace = isl_local_space_from_space(Space);
552   unsigned lastDimension = isl_map_dim(Map, isl_dim_in) - 1;
553 
554   // Set all but the last dimension to be equal for the input and output
555   //
556   //   input[i0, i1, ..., iX] -> output[o0, o1, ..., oX]
557   //     : i0 = o0, i1 = o1, ..., i(X-1) = o(X-1)
558   for (unsigned i = 0; i < lastDimension; ++i)
559     Map = isl_map_equate(Map, isl_dim_in, i, isl_dim_out, i);
560 
561   // Set the last dimension of the input to be strict smaller than the
562   // last dimension of the output.
563   //
564   //   input[?,?,?,...,iX] -> output[?,?,?,...,oX] : iX < oX
565   //
566   isl_val *v;
567   isl_ctx *Ctx = isl_map_get_ctx(Map);
568   isl_constraint *c = isl_inequality_alloc(isl_local_space_copy(MapLocalSpace));
569   v = isl_val_int_from_si(Ctx, -1);
570   c = isl_constraint_set_coefficient_val(c, isl_dim_in, lastDimension, v);
571   v = isl_val_int_from_si(Ctx, 1);
572   c = isl_constraint_set_coefficient_val(c, isl_dim_out, lastDimension, v);
573   v = isl_val_int_from_si(Ctx, -1);
574   c = isl_constraint_set_constant_val(c, v);
575 
576   Map = isl_map_add_constraint(Map, c);
577 
578   isl_local_space_free(MapLocalSpace);
579   return Map;
580 }
581 
582 isl_set *MemoryAccess::getStride(__isl_take const isl_map *Schedule) const {
583   isl_map *S = const_cast<isl_map *>(Schedule);
584   isl_map *AccessRelation = getAccessRelation();
585   isl_space *Space = isl_space_range(isl_map_get_space(S));
586   isl_map *NextScatt = getEqualAndLarger(Space);
587 
588   S = isl_map_reverse(S);
589   NextScatt = isl_map_lexmin(NextScatt);
590 
591   NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(S));
592   NextScatt = isl_map_apply_range(NextScatt, isl_map_copy(AccessRelation));
593   NextScatt = isl_map_apply_domain(NextScatt, S);
594   NextScatt = isl_map_apply_domain(NextScatt, AccessRelation);
595 
596   isl_set *Deltas = isl_map_deltas(NextScatt);
597   return Deltas;
598 }
599 
600 bool MemoryAccess::isStrideX(__isl_take const isl_map *Schedule,
601                              int StrideWidth) const {
602   isl_set *Stride, *StrideX;
603   bool IsStrideX;
604 
605   Stride = getStride(Schedule);
606   StrideX = isl_set_universe(isl_set_get_space(Stride));
607   StrideX = isl_set_fix_si(StrideX, isl_dim_set, 0, StrideWidth);
608   IsStrideX = isl_set_is_equal(Stride, StrideX);
609 
610   isl_set_free(StrideX);
611   isl_set_free(Stride);
612 
613   return IsStrideX;
614 }
615 
616 bool MemoryAccess::isStrideZero(const isl_map *Schedule) const {
617   return isStrideX(Schedule, 0);
618 }
619 
620 bool MemoryAccess::isScalar() const {
621   return isl_map_n_out(AccessRelation) == 0;
622 }
623 
624 bool MemoryAccess::isStrideOne(const isl_map *Schedule) const {
625   return isStrideX(Schedule, 1);
626 }
627 
628 void MemoryAccess::setNewAccessRelation(isl_map *newAccess) {
629   isl_map_free(newAccessRelation);
630   newAccessRelation = newAccess;
631 }
632 
633 //===----------------------------------------------------------------------===//
634 
635 isl_map *ScopStmt::getScattering() const { return isl_map_copy(Scattering); }
636 
637 void ScopStmt::restrictDomain(__isl_take isl_set *NewDomain) {
638   assert(isl_set_is_subset(NewDomain, Domain) &&
639          "New domain is not a subset of old domain!");
640   isl_set_free(Domain);
641   Domain = NewDomain;
642   Scattering = isl_map_intersect_domain(Scattering, isl_set_copy(Domain));
643 }
644 
645 void ScopStmt::setScattering(isl_map *NewScattering) {
646   assert(NewScattering && "New scattering is nullptr");
647   isl_map_free(Scattering);
648   Scattering = NewScattering;
649 }
650 
651 void ScopStmt::buildScattering(SmallVectorImpl<unsigned> &Scatter) {
652   unsigned NbIterators = getNumIterators();
653   unsigned NbScatteringDims = Parent.getMaxLoopDepth() * 2 + 1;
654 
655   isl_space *Space = isl_space_set_alloc(getIslCtx(), 0, NbScatteringDims);
656   Space = isl_space_set_tuple_name(Space, isl_dim_out, "scattering");
657 
658   Scattering = isl_map_from_domain_and_range(isl_set_universe(getDomainSpace()),
659                                              isl_set_universe(Space));
660 
661   // Loop dimensions.
662   for (unsigned i = 0; i < NbIterators; ++i)
663     Scattering =
664         isl_map_equate(Scattering, isl_dim_out, 2 * i + 1, isl_dim_in, i);
665 
666   // Constant dimensions
667   for (unsigned i = 0; i < NbIterators + 1; ++i)
668     Scattering = isl_map_fix_si(Scattering, isl_dim_out, 2 * i, Scatter[i]);
669 
670   // Fill scattering dimensions.
671   for (unsigned i = 2 * NbIterators + 1; i < NbScatteringDims; ++i)
672     Scattering = isl_map_fix_si(Scattering, isl_dim_out, i, 0);
673 
674   Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
675 }
676 
677 void ScopStmt::buildAccesses(TempScop &tempScop, const Region &CurRegion) {
678   for (auto &&Access : *tempScop.getAccessFunctions(BB)) {
679     MemAccs.push_back(new MemoryAccess(Access.first, Access.second, this));
680 
681     // We do not track locations for scalar memory accesses at the moment.
682     //
683     // We do not have a use for this information at the moment. If we need this
684     // at some point, the "instruction -> access" mapping needs to be enhanced
685     // as a single instruction could then possibly perform multiple accesses.
686     if (!Access.first.isScalar()) {
687       assert(!InstructionToAccess.count(Access.second) &&
688              "Unexpected 1-to-N mapping on instruction to access map!");
689       InstructionToAccess[Access.second] = MemAccs.back();
690     }
691   }
692 }
693 
694 void ScopStmt::realignParams() {
695   for (MemoryAccess *MA : *this)
696     MA->realignParams();
697 
698   Domain = isl_set_align_params(Domain, Parent.getParamSpace());
699   Scattering = isl_map_align_params(Scattering, Parent.getParamSpace());
700 }
701 
702 __isl_give isl_set *ScopStmt::buildConditionSet(const Comparison &Comp) {
703   isl_pw_aff *L = SCEVAffinator::getPwAff(this, Comp.getLHS());
704   isl_pw_aff *R = SCEVAffinator::getPwAff(this, Comp.getRHS());
705 
706   switch (Comp.getPred()) {
707   case ICmpInst::ICMP_EQ:
708     return isl_pw_aff_eq_set(L, R);
709   case ICmpInst::ICMP_NE:
710     return isl_pw_aff_ne_set(L, R);
711   case ICmpInst::ICMP_SLT:
712     return isl_pw_aff_lt_set(L, R);
713   case ICmpInst::ICMP_SLE:
714     return isl_pw_aff_le_set(L, R);
715   case ICmpInst::ICMP_SGT:
716     return isl_pw_aff_gt_set(L, R);
717   case ICmpInst::ICMP_SGE:
718     return isl_pw_aff_ge_set(L, R);
719   case ICmpInst::ICMP_ULT:
720   case ICmpInst::ICMP_UGT:
721   case ICmpInst::ICMP_ULE:
722   case ICmpInst::ICMP_UGE:
723     llvm_unreachable("Unsigned comparisons not yet supported");
724   default:
725     llvm_unreachable("Non integer predicate not supported");
726   }
727 }
728 
729 __isl_give isl_set *ScopStmt::addLoopBoundsToDomain(__isl_take isl_set *Domain,
730                                                     TempScop &tempScop) {
731   isl_space *Space;
732   isl_local_space *LocalSpace;
733 
734   Space = isl_set_get_space(Domain);
735   LocalSpace = isl_local_space_from_space(Space);
736 
737   for (int i = 0, e = getNumIterators(); i != e; ++i) {
738     isl_aff *Zero = isl_aff_zero_on_domain(isl_local_space_copy(LocalSpace));
739     isl_pw_aff *IV =
740         isl_pw_aff_from_aff(isl_aff_set_coefficient_si(Zero, isl_dim_in, i, 1));
741 
742     // 0 <= IV.
743     isl_set *LowerBound = isl_pw_aff_nonneg_set(isl_pw_aff_copy(IV));
744     Domain = isl_set_intersect(Domain, LowerBound);
745 
746     // IV <= LatchExecutions.
747     const Loop *L = getLoopForDimension(i);
748     const SCEV *LatchExecutions = tempScop.getLoopBound(L);
749     isl_pw_aff *UpperBound = SCEVAffinator::getPwAff(this, LatchExecutions);
750     isl_set *UpperBoundSet = isl_pw_aff_le_set(IV, UpperBound);
751     Domain = isl_set_intersect(Domain, UpperBoundSet);
752   }
753 
754   isl_local_space_free(LocalSpace);
755   return Domain;
756 }
757 
758 __isl_give isl_set *ScopStmt::addConditionsToDomain(__isl_take isl_set *Domain,
759                                                     TempScop &tempScop,
760                                                     const Region &CurRegion) {
761   const Region *TopRegion = tempScop.getMaxRegion().getParent(),
762                *CurrentRegion = &CurRegion;
763   const BasicBlock *BranchingBB = BB;
764 
765   do {
766     if (BranchingBB != CurrentRegion->getEntry()) {
767       if (const BBCond *Condition = tempScop.getBBCond(BranchingBB))
768         for (const auto &C : *Condition) {
769           isl_set *ConditionSet = buildConditionSet(C);
770           Domain = isl_set_intersect(Domain, ConditionSet);
771         }
772     }
773     BranchingBB = CurrentRegion->getEntry();
774     CurrentRegion = CurrentRegion->getParent();
775   } while (TopRegion != CurrentRegion);
776 
777   return Domain;
778 }
779 
780 __isl_give isl_set *ScopStmt::buildDomain(TempScop &tempScop,
781                                           const Region &CurRegion) {
782   isl_space *Space;
783   isl_set *Domain;
784   isl_id *Id;
785 
786   Space = isl_space_set_alloc(getIslCtx(), 0, getNumIterators());
787 
788   Id = isl_id_alloc(getIslCtx(), getBaseName(), this);
789 
790   Domain = isl_set_universe(Space);
791   Domain = addLoopBoundsToDomain(Domain, tempScop);
792   Domain = addConditionsToDomain(Domain, tempScop, CurRegion);
793   Domain = isl_set_set_tuple_id(Domain, Id);
794 
795   return Domain;
796 }
797 
798 ScopStmt::ScopStmt(Scop &parent, TempScop &tempScop, const Region &CurRegion,
799                    BasicBlock &bb, SmallVectorImpl<Loop *> &Nest,
800                    SmallVectorImpl<unsigned> &Scatter)
801     : Parent(parent), BB(&bb), IVS(Nest.size()), NestLoops(Nest.size()) {
802   // Setup the induction variables.
803   for (unsigned i = 0, e = Nest.size(); i < e; ++i) {
804     if (!SCEVCodegen) {
805       PHINode *PN = Nest[i]->getCanonicalInductionVariable();
806       assert(PN && "Non canonical IV in Scop!");
807       IVS[i] = PN;
808     }
809     NestLoops[i] = Nest[i];
810   }
811 
812   raw_string_ostream OS(BaseName);
813   bb.printAsOperand(OS, false);
814   BaseName = OS.str();
815 
816   makeIslCompatible(BaseName);
817   BaseName = "Stmt_" + BaseName;
818 
819   Domain = buildDomain(tempScop, CurRegion);
820   buildScattering(Scatter);
821   buildAccesses(tempScop, CurRegion);
822   checkForReductions();
823 }
824 
825 /// @brief Collect loads which might form a reduction chain with @p StoreMA
826 ///
827 /// Check if the stored value for @p StoreMA is a binary operator with one or
828 /// two loads as operands. If the binary operand is commutative & associative,
829 /// used only once (by @p StoreMA) and its load operands are also used only
830 /// once, we have found a possible reduction chain. It starts at an operand
831 /// load and includes the binary operator and @p StoreMA.
832 ///
833 /// Note: We allow only one use to ensure the load and binary operator cannot
834 ///       escape this block or into any other store except @p StoreMA.
835 void ScopStmt::collectCandiateReductionLoads(
836     MemoryAccess *StoreMA, SmallVectorImpl<MemoryAccess *> &Loads) {
837   auto *Store = dyn_cast<StoreInst>(StoreMA->getAccessInstruction());
838   if (!Store)
839     return;
840 
841   // Skip if there is not one binary operator between the load and the store
842   auto *BinOp = dyn_cast<BinaryOperator>(Store->getValueOperand());
843   if (!BinOp)
844     return;
845 
846   // Skip if the binary operators has multiple uses
847   if (BinOp->getNumUses() != 1)
848     return;
849 
850   // Skip if the opcode of the binary operator is not commutative/associative
851   if (!BinOp->isCommutative() || !BinOp->isAssociative())
852     return;
853 
854   // Skip if the binary operator is outside the current SCoP
855   if (BinOp->getParent() != Store->getParent())
856     return;
857 
858   // Skip if it is a multiplicative reduction and we disabled them
859   if (DisableMultiplicativeReductions &&
860       (BinOp->getOpcode() == Instruction::Mul ||
861        BinOp->getOpcode() == Instruction::FMul))
862     return;
863 
864   // Check the binary operator operands for a candidate load
865   auto *PossibleLoad0 = dyn_cast<LoadInst>(BinOp->getOperand(0));
866   auto *PossibleLoad1 = dyn_cast<LoadInst>(BinOp->getOperand(1));
867   if (!PossibleLoad0 && !PossibleLoad1)
868     return;
869 
870   // A load is only a candidate if it cannot escape (thus has only this use)
871   if (PossibleLoad0 && PossibleLoad0->getNumUses() == 1)
872     if (PossibleLoad0->getParent() == Store->getParent())
873       Loads.push_back(lookupAccessFor(PossibleLoad0));
874   if (PossibleLoad1 && PossibleLoad1->getNumUses() == 1)
875     if (PossibleLoad1->getParent() == Store->getParent())
876       Loads.push_back(lookupAccessFor(PossibleLoad1));
877 }
878 
879 /// @brief Check for reductions in this ScopStmt
880 ///
881 /// Iterate over all store memory accesses and check for valid binary reduction
882 /// like chains. For all candidates we check if they have the same base address
883 /// and there are no other accesses which overlap with them. The base address
884 /// check rules out impossible reductions candidates early. The overlap check,
885 /// together with the "only one user" check in collectCandiateReductionLoads,
886 /// guarantees that none of the intermediate results will escape during
887 /// execution of the loop nest. We basically check here that no other memory
888 /// access can access the same memory as the potential reduction.
889 void ScopStmt::checkForReductions() {
890   SmallVector<MemoryAccess *, 2> Loads;
891   SmallVector<std::pair<MemoryAccess *, MemoryAccess *>, 4> Candidates;
892 
893   // First collect candidate load-store reduction chains by iterating over all
894   // stores and collecting possible reduction loads.
895   for (MemoryAccess *StoreMA : MemAccs) {
896     if (StoreMA->isRead())
897       continue;
898 
899     Loads.clear();
900     collectCandiateReductionLoads(StoreMA, Loads);
901     for (MemoryAccess *LoadMA : Loads)
902       Candidates.push_back(std::make_pair(LoadMA, StoreMA));
903   }
904 
905   // Then check each possible candidate pair.
906   for (const auto &CandidatePair : Candidates) {
907     bool Valid = true;
908     isl_map *LoadAccs = CandidatePair.first->getAccessRelation();
909     isl_map *StoreAccs = CandidatePair.second->getAccessRelation();
910 
911     // Skip those with obviously unequal base addresses.
912     if (!isl_map_has_equal_space(LoadAccs, StoreAccs)) {
913       isl_map_free(LoadAccs);
914       isl_map_free(StoreAccs);
915       continue;
916     }
917 
918     // And check if the remaining for overlap with other memory accesses.
919     isl_map *AllAccsRel = isl_map_union(LoadAccs, StoreAccs);
920     AllAccsRel = isl_map_intersect_domain(AllAccsRel, getDomain());
921     isl_set *AllAccs = isl_map_range(AllAccsRel);
922 
923     for (MemoryAccess *MA : MemAccs) {
924       if (MA == CandidatePair.first || MA == CandidatePair.second)
925         continue;
926 
927       isl_map *AccRel =
928           isl_map_intersect_domain(MA->getAccessRelation(), getDomain());
929       isl_set *Accs = isl_map_range(AccRel);
930 
931       if (isl_set_has_equal_space(AllAccs, Accs) || isl_set_free(Accs)) {
932         isl_set *OverlapAccs = isl_set_intersect(Accs, isl_set_copy(AllAccs));
933         Valid = Valid && isl_set_is_empty(OverlapAccs);
934         isl_set_free(OverlapAccs);
935       }
936     }
937 
938     isl_set_free(AllAccs);
939     if (!Valid)
940       continue;
941 
942     const LoadInst *Load =
943         dyn_cast<const LoadInst>(CandidatePair.first->getAccessInstruction());
944     MemoryAccess::ReductionType RT =
945         getReductionType(dyn_cast<BinaryOperator>(Load->user_back()), Load);
946 
947     // If no overlapping access was found we mark the load and store as
948     // reduction like.
949     CandidatePair.first->markAsReductionLike(RT);
950     CandidatePair.second->markAsReductionLike(RT);
951   }
952 }
953 
954 std::string ScopStmt::getDomainStr() const { return stringFromIslObj(Domain); }
955 
956 std::string ScopStmt::getScatteringStr() const {
957   return stringFromIslObj(Scattering);
958 }
959 
960 unsigned ScopStmt::getNumParams() const { return Parent.getNumParams(); }
961 
962 unsigned ScopStmt::getNumIterators() const {
963   // The final read has one dimension with one element.
964   if (!BB)
965     return 1;
966 
967   return NestLoops.size();
968 }
969 
970 unsigned ScopStmt::getNumScattering() const {
971   return isl_map_dim(Scattering, isl_dim_out);
972 }
973 
974 const char *ScopStmt::getBaseName() const { return BaseName.c_str(); }
975 
976 const PHINode *
977 ScopStmt::getInductionVariableForDimension(unsigned Dimension) const {
978   return IVS[Dimension];
979 }
980 
981 const Loop *ScopStmt::getLoopForDimension(unsigned Dimension) const {
982   return NestLoops[Dimension];
983 }
984 
985 isl_ctx *ScopStmt::getIslCtx() const { return Parent.getIslCtx(); }
986 
987 isl_set *ScopStmt::getDomain() const { return isl_set_copy(Domain); }
988 
989 isl_space *ScopStmt::getDomainSpace() const {
990   return isl_set_get_space(Domain);
991 }
992 
993 isl_id *ScopStmt::getDomainId() const { return isl_set_get_tuple_id(Domain); }
994 
995 ScopStmt::~ScopStmt() {
996   while (!MemAccs.empty()) {
997     delete MemAccs.back();
998     MemAccs.pop_back();
999   }
1000 
1001   isl_set_free(Domain);
1002   isl_map_free(Scattering);
1003 }
1004 
1005 void ScopStmt::print(raw_ostream &OS) const {
1006   OS << "\t" << getBaseName() << "\n";
1007   OS.indent(12) << "Domain :=\n";
1008 
1009   if (Domain) {
1010     OS.indent(16) << getDomainStr() << ";\n";
1011   } else
1012     OS.indent(16) << "n/a\n";
1013 
1014   OS.indent(12) << "Scattering :=\n";
1015 
1016   if (Domain) {
1017     OS.indent(16) << getScatteringStr() << ";\n";
1018   } else
1019     OS.indent(16) << "n/a\n";
1020 
1021   for (MemoryAccess *Access : MemAccs)
1022     Access->print(OS);
1023 }
1024 
1025 void ScopStmt::dump() const { print(dbgs()); }
1026 
1027 //===----------------------------------------------------------------------===//
1028 /// Scop class implement
1029 
1030 void Scop::setContext(__isl_take isl_set *NewContext) {
1031   NewContext = isl_set_align_params(NewContext, isl_set_get_space(Context));
1032   isl_set_free(Context);
1033   Context = NewContext;
1034 }
1035 
1036 void Scop::addParams(std::vector<const SCEV *> NewParameters) {
1037   for (const SCEV *Parameter : NewParameters) {
1038     if (ParameterIds.find(Parameter) != ParameterIds.end())
1039       continue;
1040 
1041     int dimension = Parameters.size();
1042 
1043     Parameters.push_back(Parameter);
1044     ParameterIds[Parameter] = dimension;
1045   }
1046 }
1047 
1048 __isl_give isl_id *Scop::getIdForParam(const SCEV *Parameter) const {
1049   ParamIdType::const_iterator IdIter = ParameterIds.find(Parameter);
1050 
1051   if (IdIter == ParameterIds.end())
1052     return nullptr;
1053 
1054   std::string ParameterName;
1055 
1056   if (const SCEVUnknown *ValueParameter = dyn_cast<SCEVUnknown>(Parameter)) {
1057     Value *Val = ValueParameter->getValue();
1058     ParameterName = Val->getName();
1059   }
1060 
1061   if (ParameterName == "" || ParameterName.substr(0, 2) == "p_")
1062     ParameterName = "p_" + utostr_32(IdIter->second);
1063 
1064   return isl_id_alloc(getIslCtx(), ParameterName.c_str(),
1065                       const_cast<void *>((const void *)Parameter));
1066 }
1067 
1068 void Scop::buildContext() {
1069   isl_space *Space = isl_space_params_alloc(IslCtx, 0);
1070   Context = isl_set_universe(isl_space_copy(Space));
1071   AssumedContext = isl_set_universe(Space);
1072 }
1073 
1074 void Scop::addParameterBounds() {
1075   for (unsigned i = 0; i < isl_set_dim(Context, isl_dim_param); ++i) {
1076     isl_val *V;
1077     isl_id *Id;
1078     const SCEV *Scev;
1079     const IntegerType *T;
1080 
1081     Id = isl_set_get_dim_id(Context, isl_dim_param, i);
1082     Scev = (const SCEV *)isl_id_get_user(Id);
1083     T = dyn_cast<IntegerType>(Scev->getType());
1084     isl_id_free(Id);
1085 
1086     assert(T && "Not an integer type");
1087     int Width = T->getBitWidth();
1088 
1089     V = isl_val_int_from_si(IslCtx, Width - 1);
1090     V = isl_val_2exp(V);
1091     V = isl_val_neg(V);
1092     Context = isl_set_lower_bound_val(Context, isl_dim_param, i, V);
1093 
1094     V = isl_val_int_from_si(IslCtx, Width - 1);
1095     V = isl_val_2exp(V);
1096     V = isl_val_sub_ui(V, 1);
1097     Context = isl_set_upper_bound_val(Context, isl_dim_param, i, V);
1098   }
1099 }
1100 
1101 void Scop::realignParams() {
1102   // Add all parameters into a common model.
1103   isl_space *Space = isl_space_params_alloc(IslCtx, ParameterIds.size());
1104 
1105   for (const auto &ParamID : ParameterIds) {
1106     const SCEV *Parameter = ParamID.first;
1107     isl_id *id = getIdForParam(Parameter);
1108     Space = isl_space_set_dim_id(Space, isl_dim_param, ParamID.second, id);
1109   }
1110 
1111   // Align the parameters of all data structures to the model.
1112   Context = isl_set_align_params(Context, Space);
1113 
1114   for (ScopStmt *Stmt : *this)
1115     Stmt->realignParams();
1116 }
1117 
1118 void Scop::simplifyAssumedContext() {
1119   // The parameter constraints of the iteration domains give us a set of
1120   // constraints that need to hold for all cases where at least a single
1121   // statement iteration is executed in the whole scop. We now simplify the
1122   // assumed context under the assumption that such constraints hold and at
1123   // least a single statement iteration is executed. For cases where no
1124   // statement instances are executed, the assumptions we have taken about
1125   // the executed code do not matter and can be changed.
1126   //
1127   // WARNING: This only holds if the assumptions we have taken do not reduce
1128   //          the set of statement instances that are executed. Otherwise we
1129   //          may run into a case where the iteration domains suggest that
1130   //          for a certain set of parameter constraints no code is executed,
1131   //          but in the original program some computation would have been
1132   //          performed. In such a case, modifying the run-time conditions and
1133   //          possibly influencing the run-time check may cause certain scops
1134   //          to not be executed.
1135   //
1136   // Example:
1137   //
1138   //   When delinearizing the following code:
1139   //
1140   //     for (long i = 0; i < 100; i++)
1141   //       for (long j = 0; j < m; j++)
1142   //         A[i+p][j] = 1.0;
1143   //
1144   //   we assume that the condition m <= 0 or (m >= 1 and p >= 0) holds as
1145   //   otherwise we would access out of bound data. Now, knowing that code is
1146   //   only executed for the case m >= 0, it is sufficient to assume p >= 0.
1147   AssumedContext =
1148       isl_set_gist_params(AssumedContext, isl_union_set_params(getDomains()));
1149 }
1150 
1151 Scop::Scop(TempScop &tempScop, LoopInfo &LI, ScalarEvolution &ScalarEvolution,
1152            isl_ctx *Context)
1153     : SE(&ScalarEvolution), R(tempScop.getMaxRegion()),
1154       MaxLoopDepth(tempScop.getMaxLoopDepth()) {
1155   IslCtx = Context;
1156   buildContext();
1157 
1158   SmallVector<Loop *, 8> NestLoops;
1159   SmallVector<unsigned, 8> Scatter;
1160 
1161   Scatter.assign(MaxLoopDepth + 1, 0);
1162 
1163   // Build the iteration domain, access functions and scattering functions
1164   // traversing the region tree.
1165   buildScop(tempScop, getRegion(), NestLoops, Scatter, LI);
1166 
1167   realignParams();
1168   addParameterBounds();
1169   simplifyAssumedContext();
1170 
1171   assert(NestLoops.empty() && "NestLoops not empty at top level!");
1172 }
1173 
1174 Scop::~Scop() {
1175   isl_set_free(Context);
1176   isl_set_free(AssumedContext);
1177 
1178   // Free the statements;
1179   for (ScopStmt *Stmt : *this)
1180     delete Stmt;
1181 }
1182 
1183 std::string Scop::getContextStr() const { return stringFromIslObj(Context); }
1184 std::string Scop::getAssumedContextStr() const {
1185   return stringFromIslObj(AssumedContext);
1186 }
1187 
1188 std::string Scop::getNameStr() const {
1189   std::string ExitName, EntryName;
1190   raw_string_ostream ExitStr(ExitName);
1191   raw_string_ostream EntryStr(EntryName);
1192 
1193   R.getEntry()->printAsOperand(EntryStr, false);
1194   EntryStr.str();
1195 
1196   if (R.getExit()) {
1197     R.getExit()->printAsOperand(ExitStr, false);
1198     ExitStr.str();
1199   } else
1200     ExitName = "FunctionExit";
1201 
1202   return EntryName + "---" + ExitName;
1203 }
1204 
1205 __isl_give isl_set *Scop::getContext() const { return isl_set_copy(Context); }
1206 __isl_give isl_space *Scop::getParamSpace() const {
1207   return isl_set_get_space(this->Context);
1208 }
1209 
1210 __isl_give isl_set *Scop::getAssumedContext() const {
1211   return isl_set_copy(AssumedContext);
1212 }
1213 
1214 void Scop::addAssumption(__isl_take isl_set *Set) {
1215   AssumedContext = isl_set_intersect(AssumedContext, Set);
1216 }
1217 
1218 void Scop::printContext(raw_ostream &OS) const {
1219   OS << "Context:\n";
1220 
1221   if (!Context) {
1222     OS.indent(4) << "n/a\n\n";
1223     return;
1224   }
1225 
1226   OS.indent(4) << getContextStr() << "\n";
1227 
1228   OS.indent(4) << "Assumed Context:\n";
1229   if (!AssumedContext) {
1230     OS.indent(4) << "n/a\n\n";
1231     return;
1232   }
1233 
1234   OS.indent(4) << getAssumedContextStr() << "\n";
1235 
1236   for (const SCEV *Parameter : Parameters) {
1237     int Dim = ParameterIds.find(Parameter)->second;
1238     OS.indent(4) << "p" << Dim << ": " << *Parameter << "\n";
1239   }
1240 }
1241 
1242 void Scop::printStatements(raw_ostream &OS) const {
1243   OS << "Statements {\n";
1244 
1245   for (ScopStmt *Stmt : *this)
1246     OS.indent(4) << *Stmt;
1247 
1248   OS.indent(4) << "}\n";
1249 }
1250 
1251 void Scop::print(raw_ostream &OS) const {
1252   OS.indent(4) << "Function: " << getRegion().getEntry()->getParent()->getName()
1253                << "\n";
1254   OS.indent(4) << "Region: " << getNameStr() << "\n";
1255   printContext(OS.indent(4));
1256   printStatements(OS.indent(4));
1257 }
1258 
1259 void Scop::dump() const { print(dbgs()); }
1260 
1261 isl_ctx *Scop::getIslCtx() const { return IslCtx; }
1262 
1263 __isl_give isl_union_set *Scop::getDomains() {
1264   isl_union_set *Domain = isl_union_set_empty(getParamSpace());
1265 
1266   for (ScopStmt *Stmt : *this)
1267     Domain = isl_union_set_add_set(Domain, Stmt->getDomain());
1268 
1269   return Domain;
1270 }
1271 
1272 __isl_give isl_union_map *Scop::getMustWrites() {
1273   isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1274 
1275   for (ScopStmt *Stmt : *this) {
1276     for (MemoryAccess *MA : *Stmt) {
1277       if (!MA->isMustWrite())
1278         continue;
1279 
1280       isl_set *Domain = Stmt->getDomain();
1281       isl_map *AccessDomain = MA->getAccessRelation();
1282       AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1283       Write = isl_union_map_add_map(Write, AccessDomain);
1284     }
1285   }
1286   return isl_union_map_coalesce(Write);
1287 }
1288 
1289 __isl_give isl_union_map *Scop::getMayWrites() {
1290   isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1291 
1292   for (ScopStmt *Stmt : *this) {
1293     for (MemoryAccess *MA : *Stmt) {
1294       if (!MA->isMayWrite())
1295         continue;
1296 
1297       isl_set *Domain = Stmt->getDomain();
1298       isl_map *AccessDomain = MA->getAccessRelation();
1299       AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1300       Write = isl_union_map_add_map(Write, AccessDomain);
1301     }
1302   }
1303   return isl_union_map_coalesce(Write);
1304 }
1305 
1306 __isl_give isl_union_map *Scop::getWrites() {
1307   isl_union_map *Write = isl_union_map_empty(this->getParamSpace());
1308 
1309   for (ScopStmt *Stmt : *this) {
1310     for (MemoryAccess *MA : *Stmt) {
1311       if (!MA->isWrite())
1312         continue;
1313 
1314       isl_set *Domain = Stmt->getDomain();
1315       isl_map *AccessDomain = MA->getAccessRelation();
1316       AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1317       Write = isl_union_map_add_map(Write, AccessDomain);
1318     }
1319   }
1320   return isl_union_map_coalesce(Write);
1321 }
1322 
1323 __isl_give isl_union_map *Scop::getReads() {
1324   isl_union_map *Read = isl_union_map_empty(getParamSpace());
1325 
1326   for (ScopStmt *Stmt : *this) {
1327     for (MemoryAccess *MA : *Stmt) {
1328       if (!MA->isRead())
1329         continue;
1330 
1331       isl_set *Domain = Stmt->getDomain();
1332       isl_map *AccessDomain = MA->getAccessRelation();
1333 
1334       AccessDomain = isl_map_intersect_domain(AccessDomain, Domain);
1335       Read = isl_union_map_add_map(Read, AccessDomain);
1336     }
1337   }
1338   return isl_union_map_coalesce(Read);
1339 }
1340 
1341 __isl_give isl_union_map *Scop::getSchedule() {
1342   isl_union_map *Schedule = isl_union_map_empty(getParamSpace());
1343 
1344   for (ScopStmt *Stmt : *this)
1345     Schedule = isl_union_map_add_map(Schedule, Stmt->getScattering());
1346 
1347   return isl_union_map_coalesce(Schedule);
1348 }
1349 
1350 bool Scop::restrictDomains(__isl_take isl_union_set *Domain) {
1351   bool Changed = false;
1352   for (ScopStmt *Stmt : *this) {
1353     isl_union_set *StmtDomain = isl_union_set_from_set(Stmt->getDomain());
1354     isl_union_set *NewStmtDomain = isl_union_set_intersect(
1355         isl_union_set_copy(StmtDomain), isl_union_set_copy(Domain));
1356 
1357     if (isl_union_set_is_subset(StmtDomain, NewStmtDomain)) {
1358       isl_union_set_free(StmtDomain);
1359       isl_union_set_free(NewStmtDomain);
1360       continue;
1361     }
1362 
1363     Changed = true;
1364 
1365     isl_union_set_free(StmtDomain);
1366     NewStmtDomain = isl_union_set_coalesce(NewStmtDomain);
1367 
1368     if (isl_union_set_is_empty(NewStmtDomain)) {
1369       Stmt->restrictDomain(isl_set_empty(Stmt->getDomainSpace()));
1370       isl_union_set_free(NewStmtDomain);
1371     } else
1372       Stmt->restrictDomain(isl_set_from_union_set(NewStmtDomain));
1373   }
1374   isl_union_set_free(Domain);
1375   return Changed;
1376 }
1377 
1378 ScalarEvolution *Scop::getSE() const { return SE; }
1379 
1380 bool Scop::isTrivialBB(BasicBlock *BB, TempScop &tempScop) {
1381   if (tempScop.getAccessFunctions(BB))
1382     return false;
1383 
1384   return true;
1385 }
1386 
1387 void Scop::buildScop(TempScop &tempScop, const Region &CurRegion,
1388                      SmallVectorImpl<Loop *> &NestLoops,
1389                      SmallVectorImpl<unsigned> &Scatter, LoopInfo &LI) {
1390   Loop *L = castToLoop(CurRegion, LI);
1391 
1392   if (L)
1393     NestLoops.push_back(L);
1394 
1395   unsigned loopDepth = NestLoops.size();
1396   assert(Scatter.size() > loopDepth && "Scatter not big enough!");
1397 
1398   for (Region::const_element_iterator I = CurRegion.element_begin(),
1399                                       E = CurRegion.element_end();
1400        I != E; ++I)
1401     if (I->isSubRegion())
1402       buildScop(tempScop, *(I->getNodeAs<Region>()), NestLoops, Scatter, LI);
1403     else {
1404       BasicBlock *BB = I->getNodeAs<BasicBlock>();
1405 
1406       if (isTrivialBB(BB, tempScop))
1407         continue;
1408 
1409       Stmts.push_back(
1410           new ScopStmt(*this, tempScop, CurRegion, *BB, NestLoops, Scatter));
1411 
1412       // Increasing the Scattering function is OK for the moment, because
1413       // we are using a depth first iterator and the program is well structured.
1414       ++Scatter[loopDepth];
1415     }
1416 
1417   if (!L)
1418     return;
1419 
1420   // Exiting a loop region.
1421   Scatter[loopDepth] = 0;
1422   NestLoops.pop_back();
1423   ++Scatter[loopDepth - 1];
1424 }
1425 
1426 //===----------------------------------------------------------------------===//
1427 ScopInfo::ScopInfo() : RegionPass(ID), scop(0) {
1428   ctx = isl_ctx_alloc();
1429   isl_options_set_on_error(ctx, ISL_ON_ERROR_ABORT);
1430 }
1431 
1432 ScopInfo::~ScopInfo() {
1433   clear();
1434   isl_ctx_free(ctx);
1435 }
1436 
1437 void ScopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1438   AU.addRequired<LoopInfo>();
1439   AU.addRequired<RegionInfoPass>();
1440   AU.addRequired<ScalarEvolution>();
1441   AU.addRequired<TempScopInfo>();
1442   AU.setPreservesAll();
1443 }
1444 
1445 bool ScopInfo::runOnRegion(Region *R, RGPassManager &RGM) {
1446   LoopInfo &LI = getAnalysis<LoopInfo>();
1447   ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1448 
1449   TempScop *tempScop = getAnalysis<TempScopInfo>().getTempScop(R);
1450 
1451   // This region is no Scop.
1452   if (!tempScop) {
1453     scop = 0;
1454     return false;
1455   }
1456 
1457   // Statistics.
1458   ++ScopFound;
1459   if (tempScop->getMaxLoopDepth() > 0)
1460     ++RichScopFound;
1461 
1462   scop = new Scop(*tempScop, LI, SE, ctx);
1463 
1464   return false;
1465 }
1466 
1467 char ScopInfo::ID = 0;
1468 
1469 Pass *polly::createScopInfoPass() { return new ScopInfo(); }
1470 
1471 INITIALIZE_PASS_BEGIN(ScopInfo, "polly-scops",
1472                       "Polly - Create polyhedral description of Scops", false,
1473                       false);
1474 INITIALIZE_PASS_DEPENDENCY(LoopInfo);
1475 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
1476 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1477 INITIALIZE_PASS_DEPENDENCY(TempScopInfo);
1478 INITIALIZE_PASS_END(ScopInfo, "polly-scops",
1479                     "Polly - Create polyhedral description of Scops", false,
1480                     false)
1481