1 //===--------- SCEVAffinator.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 SCEV value.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "polly/Support/SCEVAffinator.h"
15 #include "polly/Options.h"
16 #include "polly/ScopInfo.h"
17 #include "polly/Support/GICHelper.h"
18 #include "polly/Support/SCEVValidator.h"
19 #include "polly/Support/ScopHelper.h"
20 #include "isl/aff.h"
21 #include "isl/local_space.h"
22 #include "isl/set.h"
23 #include "isl/val.h"
24 
25 using namespace llvm;
26 using namespace polly;
27 
28 static cl::opt<bool> IgnoreIntegerWrapping(
29     "polly-ignore-integer-wrapping",
30     cl::desc("Do not build run-time checks to proof absence of integer "
31              "wrapping"),
32     cl::Hidden, cl::ZeroOrMore, cl::init(false), cl::cat(PollyCategory));
33 
34 // The maximal number of basic sets we allow during the construction of a
35 // piecewise affine function. More complex ones will result in very high
36 // compile time.
37 static int const MaxDisjunctionsInPwAff = 100;
38 
39 // The maximal number of bits for which a zero-extend is modeled precisely.
40 static unsigned const MaxZextSmallBitWidth = 7;
41 
42 // The maximal number of bits for which a truncate is modeled precisely.
43 static unsigned const MaxTruncateSmallBitWidth = 31;
44 
45 /// @brief Return true if a zero-extend from @p Width bits is precisely modeled.
46 static bool isPreciseZeroExtend(unsigned Width) {
47   return Width <= MaxZextSmallBitWidth;
48 }
49 
50 /// @brief Return true if a truncate from @p Width bits is precisely modeled.
51 static bool isPreciseTruncate(unsigned Width) {
52   return Width <= MaxTruncateSmallBitWidth;
53 }
54 
55 /// @brief Add the number of basic sets in @p Domain to @p User
56 static isl_stat addNumBasicSets(isl_set *Domain, isl_aff *Aff, void *User) {
57   auto *NumBasicSets = static_cast<unsigned *>(User);
58   *NumBasicSets += isl_set_n_basic_set(Domain);
59   isl_set_free(Domain);
60   isl_aff_free(Aff);
61   return isl_stat_ok;
62 }
63 
64 /// @brief Helper to free a PWACtx object.
65 static void freePWACtx(__isl_take PWACtx &PWAC) {
66   isl_pw_aff_free(PWAC.first);
67   isl_set_free(PWAC.second);
68 }
69 
70 /// @brief Helper to copy a PWACtx object.
71 static __isl_give PWACtx copyPWACtx(const __isl_keep PWACtx &PWAC) {
72   return std::make_pair(isl_pw_aff_copy(PWAC.first), isl_set_copy(PWAC.second));
73 }
74 
75 /// @brief Determine if @p PWAC is too complex to continue.
76 ///
77 /// Note that @p PWAC will be "free" (deallocated) if this function returns
78 /// true, but not if this function returns false.
79 static bool isTooComplex(PWACtx &PWAC) {
80   unsigned NumBasicSets = 0;
81   isl_pw_aff_foreach_piece(PWAC.first, addNumBasicSets, &NumBasicSets);
82   if (NumBasicSets <= MaxDisjunctionsInPwAff)
83     return false;
84   freePWACtx(PWAC);
85   return true;
86 }
87 
88 /// @brief Return the flag describing the possible wrapping of @p Expr.
89 static SCEV::NoWrapFlags getNoWrapFlags(const SCEV *Expr) {
90   if (auto *NAry = dyn_cast<SCEVNAryExpr>(Expr))
91     return NAry->getNoWrapFlags();
92   return SCEV::NoWrapMask;
93 }
94 
95 static void combine(__isl_keep PWACtx &PWAC0, const __isl_take PWACtx &PWAC1,
96                     isl_pw_aff *(Fn)(isl_pw_aff *, isl_pw_aff *)) {
97   PWAC0.first = Fn(PWAC0.first, PWAC1.first);
98   PWAC0.second = isl_set_union(PWAC0.second, PWAC1.second);
99 }
100 
101 /// @brief Set the possible wrapping of @p Expr to @p Flags.
102 static const SCEV *setNoWrapFlags(ScalarEvolution &SE, const SCEV *Expr,
103                                   SCEV::NoWrapFlags Flags) {
104   auto *NAry = dyn_cast<SCEVNAryExpr>(Expr);
105   if (!NAry)
106     return Expr;
107 
108   SmallVector<const SCEV *, 8> Ops(NAry->op_begin(), NAry->op_end());
109   switch (Expr->getSCEVType()) {
110   case scAddExpr:
111     return SE.getAddExpr(Ops, Flags);
112   case scMulExpr:
113     return SE.getMulExpr(Ops, Flags);
114   case scAddRecExpr:
115     return SE.getAddRecExpr(Ops, cast<SCEVAddRecExpr>(Expr)->getLoop(), Flags);
116   default:
117     return Expr;
118   }
119 }
120 
121 static __isl_give isl_pw_aff *getWidthExpValOnDomain(unsigned Width,
122                                                      __isl_take isl_set *Dom) {
123   auto *Ctx = isl_set_get_ctx(Dom);
124   auto *WidthVal = isl_val_int_from_ui(Ctx, Width);
125   auto *ExpVal = isl_val_2exp(WidthVal);
126   return isl_pw_aff_val_on_domain(Dom, ExpVal);
127 }
128 
129 SCEVAffinator::SCEVAffinator(Scop *S, LoopInfo &LI)
130     : S(S), Ctx(S->getIslCtx()), SE(*S->getSE()), LI(LI),
131       TD(S->getFunction().getParent()->getDataLayout()) {}
132 
133 SCEVAffinator::~SCEVAffinator() {
134   for (auto &CachedPair : CachedExpressions)
135     freePWACtx(CachedPair.second);
136 }
137 
138 Loop *SCEVAffinator::getScope() { return BB ? LI.getLoopFor(BB) : nullptr; }
139 
140 void SCEVAffinator::interpretAsUnsigned(__isl_keep PWACtx &PWAC,
141                                         unsigned Width) {
142   auto *PWA = PWAC.first;
143   auto *NonNegDom = isl_pw_aff_nonneg_set(isl_pw_aff_copy(PWA));
144   auto *NonNegPWA = isl_pw_aff_intersect_domain(isl_pw_aff_copy(PWA),
145                                                 isl_set_copy(NonNegDom));
146   auto *ExpPWA = getWidthExpValOnDomain(Width, isl_set_complement(NonNegDom));
147   PWAC.first = isl_pw_aff_union_add(NonNegPWA, isl_pw_aff_add(PWA, ExpPWA));
148 }
149 
150 void SCEVAffinator::takeNonNegativeAssumption(PWACtx &PWAC) {
151   auto *NegPWA = isl_pw_aff_neg(isl_pw_aff_copy(PWAC.first));
152   auto *NegDom = isl_pw_aff_pos_set(NegPWA);
153   PWAC.second = isl_set_union(PWAC.second, isl_set_copy(NegDom));
154   auto *Restriction = BB ? NegDom : isl_set_params(NegDom);
155   auto DL = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
156   S->recordAssumption(UNSIGNED, Restriction, DL, AS_RESTRICTION, BB);
157 }
158 
159 __isl_give PWACtx SCEVAffinator::getPWACtxFromPWA(__isl_take isl_pw_aff *PWA) {
160   return std::make_pair(
161       PWA, isl_set_empty(isl_space_set_alloc(Ctx, 0, NumIterators)));
162 }
163 
164 __isl_give PWACtx SCEVAffinator::getPwAff(const SCEV *Expr, BasicBlock *BB) {
165   this->BB = BB;
166 
167   if (BB) {
168     auto *DC = S->getDomainConditions(BB);
169     NumIterators = isl_set_n_dim(DC);
170     isl_set_free(DC);
171   } else
172     NumIterators = 0;
173 
174   auto *Scope = getScope();
175   S->addParams(getParamsInAffineExpr(&S->getRegion(), Scope, Expr, SE));
176 
177   return visit(Expr);
178 }
179 
180 __isl_give PWACtx SCEVAffinator::checkForWrapping(const SCEV *Expr,
181                                                   PWACtx PWAC) const {
182   // If the SCEV flags do contain NSW (no signed wrap) then PWA already
183   // represents Expr in modulo semantic (it is not allowed to overflow), thus we
184   // are done. Otherwise, we will compute:
185   //   PWA = ((PWA + 2^(n-1)) mod (2 ^ n)) - 2^(n-1)
186   // whereas n is the number of bits of the Expr, hence:
187   //   n = bitwidth(ExprType)
188 
189   if (IgnoreIntegerWrapping || (getNoWrapFlags(Expr) & SCEV::FlagNSW))
190     return PWAC;
191 
192   auto *PWA = PWAC.first;
193   auto *PWAMod = addModuloSemantic(isl_pw_aff_copy(PWA), Expr->getType());
194   auto *NotEqualSet = isl_pw_aff_ne_set(isl_pw_aff_copy(PWA), PWAMod);
195   PWAC.second = isl_set_union(PWAC.second, isl_set_copy(NotEqualSet));
196   PWAC.second = isl_set_coalesce(PWAC.second);
197 
198   const DebugLoc &Loc = BB ? BB->getTerminator()->getDebugLoc() : DebugLoc();
199   NotEqualSet = BB ? NotEqualSet : isl_set_params(NotEqualSet);
200   NotEqualSet = isl_set_coalesce(NotEqualSet);
201 
202   if (isl_set_is_empty(NotEqualSet))
203     isl_set_free(NotEqualSet);
204   else
205     S->recordAssumption(WRAPPING, NotEqualSet, Loc, AS_RESTRICTION, BB);
206 
207   return PWAC;
208 }
209 
210 __isl_give isl_pw_aff *
211 SCEVAffinator::addModuloSemantic(__isl_take isl_pw_aff *PWA,
212                                  Type *ExprType) const {
213   unsigned Width = TD.getTypeSizeInBits(ExprType);
214   isl_ctx *Ctx = isl_pw_aff_get_ctx(PWA);
215 
216   isl_val *ModVal = isl_val_int_from_ui(Ctx, Width);
217   ModVal = isl_val_2exp(ModVal);
218 
219   isl_set *Domain = isl_pw_aff_domain(isl_pw_aff_copy(PWA));
220   isl_pw_aff *AddPW = getWidthExpValOnDomain(Width - 1, Domain);
221 
222   PWA = isl_pw_aff_add(PWA, isl_pw_aff_copy(AddPW));
223   PWA = isl_pw_aff_mod_val(PWA, ModVal);
224   PWA = isl_pw_aff_sub(PWA, AddPW);
225 
226   return PWA;
227 }
228 
229 bool SCEVAffinator::hasNSWAddRecForLoop(Loop *L) const {
230   for (const auto &CachedPair : CachedExpressions) {
231     auto *AddRec = dyn_cast<SCEVAddRecExpr>(CachedPair.first.first);
232     if (!AddRec)
233       continue;
234     if (AddRec->getLoop() != L)
235       continue;
236     if (AddRec->getNoWrapFlags() & SCEV::FlagNSW)
237       return true;
238   }
239 
240   return false;
241 }
242 
243 __isl_give PWACtx SCEVAffinator::visit(const SCEV *Expr) {
244 
245   auto Key = std::make_pair(Expr, BB);
246   PWACtx PWAC = CachedExpressions[Key];
247   if (PWAC.first)
248     return copyPWACtx(PWAC);
249 
250   auto ConstantAndLeftOverPair = extractConstantFactor(Expr, SE);
251   auto *Factor = ConstantAndLeftOverPair.first;
252   Expr = ConstantAndLeftOverPair.second;
253 
254   // In case the scev is a valid parameter, we do not further analyze this
255   // expression, but create a new parameter in the isl_pw_aff. This allows us
256   // to treat subexpressions that we cannot translate into an piecewise affine
257   // expression, as constant parameters of the piecewise affine expression.
258   if (isl_id *Id = S->getIdForParam(Expr)) {
259     isl_space *Space = isl_space_set_alloc(Ctx, 1, NumIterators);
260     Space = isl_space_set_dim_id(Space, isl_dim_param, 0, Id);
261 
262     isl_set *Domain = isl_set_universe(isl_space_copy(Space));
263     isl_aff *Affine = isl_aff_zero_on_domain(isl_local_space_from_space(Space));
264     Affine = isl_aff_add_coefficient_si(Affine, isl_dim_param, 0, 1);
265 
266     PWAC = getPWACtxFromPWA(isl_pw_aff_alloc(Domain, Affine));
267   } else {
268     PWAC = SCEVVisitor<SCEVAffinator, PWACtx>::visit(Expr);
269     PWAC = checkForWrapping(Expr, PWAC);
270   }
271 
272   if (!Factor->getType()->isIntegerTy(1))
273     combine(PWAC, visitConstant(Factor), isl_pw_aff_mul);
274 
275   // For compile time reasons we need to simplify the PWAC before we cache and
276   // return it.
277   PWAC.first = isl_pw_aff_coalesce(PWAC.first);
278   PWAC = checkForWrapping(Key.first, PWAC);
279 
280   CachedExpressions[Key] = copyPWACtx(PWAC);
281   return PWAC;
282 }
283 
284 __isl_give PWACtx SCEVAffinator::visitConstant(const SCEVConstant *Expr) {
285   ConstantInt *Value = Expr->getValue();
286   isl_val *v;
287 
288   // LLVM does not define if an integer value is interpreted as a signed or
289   // unsigned value. Hence, without further information, it is unknown how
290   // this value needs to be converted to GMP. At the moment, we only support
291   // signed operations. So we just interpret it as signed. Later, there are
292   // two options:
293   //
294   // 1. We always interpret any value as signed and convert the values on
295   //    demand.
296   // 2. We pass down the signedness of the calculation and use it to interpret
297   //    this constant correctly.
298   v = isl_valFromAPInt(Ctx, Value->getValue(), /* isSigned */ true);
299 
300   isl_space *Space = isl_space_set_alloc(Ctx, 0, NumIterators);
301   isl_local_space *ls = isl_local_space_from_space(Space);
302   return getPWACtxFromPWA(isl_pw_aff_from_aff(isl_aff_val_on_domain(ls, v)));
303 }
304 
305 __isl_give PWACtx
306 SCEVAffinator::visitTruncateExpr(const SCEVTruncateExpr *Expr) {
307   // Truncate operations are basically modulo operations, thus we can
308   // model them that way. However, for large types we assume the operand
309   // to fit in the new type size instead of introducing a modulo with a very
310   // large constant.
311 
312   auto *Op = Expr->getOperand();
313   auto OpPWAC = visit(Op);
314 
315   unsigned Width = TD.getTypeSizeInBits(Expr->getType());
316   bool Precise = isPreciseTruncate(Width);
317 
318   if (Precise) {
319     OpPWAC.first = addModuloSemantic(OpPWAC.first, Expr->getType());
320     return OpPWAC;
321   }
322 
323   auto *Dom = isl_pw_aff_domain(isl_pw_aff_copy(OpPWAC.first));
324   auto *ExpPWA = getWidthExpValOnDomain(Width - 1, Dom);
325   auto *GreaterDom =
326       isl_pw_aff_ge_set(isl_pw_aff_copy(OpPWAC.first), isl_pw_aff_copy(ExpPWA));
327   auto *SmallerDom =
328       isl_pw_aff_lt_set(isl_pw_aff_copy(OpPWAC.first), isl_pw_aff_neg(ExpPWA));
329   auto *OutOfBoundsDom = isl_set_union(SmallerDom, GreaterDom);
330   OpPWAC.second = isl_set_union(OpPWAC.second, isl_set_copy(OutOfBoundsDom));
331   S->recordAssumption(UNSIGNED, OutOfBoundsDom, DebugLoc(), AS_RESTRICTION, BB);
332 
333   return OpPWAC;
334 }
335 
336 __isl_give PWACtx
337 SCEVAffinator::visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
338   // A zero-extended value can be interpreted as a piecewise defined signed
339   // value. If the value was non-negative it stays the same, otherwise it
340   // is the sum of the original value and 2^n where n is the bit-width of
341   // the original (or operand) type. Examples:
342   //   zext i8 127 to i32 -> { [127] }
343   //   zext i8  -1 to i32 -> { [256 + (-1)] } = { [255] }
344   //   zext i8  %v to i32 -> [v] -> { [v] | v >= 0; [256 + v] | v < 0 }
345   //
346   // However, LLVM/Scalar Evolution uses zero-extend (potentially lead by a
347   // truncate) to represent some forms of modulo computation. The left-hand side
348   // of the condition in the code below would result in the SCEV
349   // "zext i1 <false, +, true>for.body" which is just another description
350   // of the C expression "i & 1 != 0" or, equivalently, "i % 2 != 0".
351   //
352   //   for (i = 0; i < N; i++)
353   //     if (i & 1 != 0 /* == i % 2 */)
354   //       /* do something */
355   //
356   // If we do not make the modulo explicit but only use the mechanism described
357   // above we will get the very restrictive assumption "N < 3", because for all
358   // values of N >= 3 the SCEVAddRecExpr operand of the zero-extend would wrap.
359   // Alternatively, we can make the modulo in the operand explicit in the
360   // resulting piecewise function and thereby avoid the assumption on N. For the
361   // example this would result in the following piecewise affine function:
362   // { [i0] -> [(1)] : 2*floor((-1 + i0)/2) = -1 + i0;
363   //   [i0] -> [(0)] : 2*floor((i0)/2) = i0 }
364   // To this end we can first determine if the (immediate) operand of the
365   // zero-extend can wrap and, in case it might, we will use explicit modulo
366   // semantic to compute the result instead of emitting non-wrapping
367   // assumptions.
368   //
369   // Note that operands with large bit-widths are less likely to be negative
370   // because it would result in a very large access offset or loop bound after
371   // the zero-extend. To this end one can optimistically assume the operand to
372   // be positive and avoid the piecewise definition if the bit-width is bigger
373   // than some threshold (here MaxZextSmallBitWidth).
374   //
375   // We choose to go with a hybrid solution of all modeling techniques described
376   // above. For small bit-widths (up to MaxZextSmallBitWidth) we will model the
377   // wrapping explicitly and use a piecewise defined function. However, if the
378   // bit-width is bigger than MaxZextSmallBitWidth we will employ overflow
379   // assumptions and assume the "former negative" piece will not exist.
380 
381   auto *Op = Expr->getOperand();
382   unsigned Width = TD.getTypeSizeInBits(Op->getType());
383 
384   bool Precise = isPreciseZeroExtend(Width);
385 
386   auto Flags = getNoWrapFlags(Op);
387   auto NoWrapFlags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
388   bool OpCanWrap = Precise && !(Flags & SCEV::FlagNSW);
389   if (OpCanWrap)
390     Op = setNoWrapFlags(SE, Op, NoWrapFlags);
391 
392   auto OpPWAC = visit(Op);
393   if (OpCanWrap)
394     OpPWAC.first = addModuloSemantic(OpPWAC.first, Op->getType());
395 
396   // If the width is to big we assume the negative part does not occur.
397   if (!Precise) {
398     takeNonNegativeAssumption(OpPWAC);
399     return OpPWAC;
400   }
401 
402   // If the width is small build the piece for the non-negative part and
403   // the one for the negative part and unify them.
404   interpretAsUnsigned(OpPWAC, Width);
405   return OpPWAC;
406 }
407 
408 __isl_give PWACtx
409 SCEVAffinator::visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
410   // As all values are represented as signed, a sign extension is a noop.
411   return visit(Expr->getOperand());
412 }
413 
414 __isl_give PWACtx SCEVAffinator::visitAddExpr(const SCEVAddExpr *Expr) {
415   PWACtx Sum = visit(Expr->getOperand(0));
416 
417   for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
418     combine(Sum, visit(Expr->getOperand(i)), isl_pw_aff_add);
419     if (isTooComplex(Sum))
420       return std::make_pair(nullptr, nullptr);
421   }
422 
423   return Sum;
424 }
425 
426 __isl_give PWACtx SCEVAffinator::visitMulExpr(const SCEVMulExpr *Expr) {
427   PWACtx Prod = visit(Expr->getOperand(0));
428 
429   for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
430     combine(Prod, visit(Expr->getOperand(i)), isl_pw_aff_mul);
431     if (isTooComplex(Prod))
432       return std::make_pair(nullptr, nullptr);
433   }
434 
435   return Prod;
436 }
437 
438 __isl_give PWACtx SCEVAffinator::visitAddRecExpr(const SCEVAddRecExpr *Expr) {
439   assert(Expr->isAffine() && "Only affine AddRecurrences allowed");
440 
441   auto Flags = Expr->getNoWrapFlags();
442 
443   // Directly generate isl_pw_aff for Expr if 'start' is zero.
444   if (Expr->getStart()->isZero()) {
445     assert(S->contains(Expr->getLoop()) &&
446            "Scop does not contain the loop referenced in this AddRec");
447 
448     PWACtx Step = visit(Expr->getOperand(1));
449     isl_space *Space = isl_space_set_alloc(Ctx, 0, NumIterators);
450     isl_local_space *LocalSpace = isl_local_space_from_space(Space);
451 
452     unsigned loopDimension = S->getRelativeLoopDepth(Expr->getLoop());
453 
454     isl_aff *LAff = isl_aff_set_coefficient_si(
455         isl_aff_zero_on_domain(LocalSpace), isl_dim_in, loopDimension, 1);
456     isl_pw_aff *LPwAff = isl_pw_aff_from_aff(LAff);
457 
458     Step.first = isl_pw_aff_mul(Step.first, LPwAff);
459     return Step;
460   }
461 
462   // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
463   // if 'start' is not zero.
464   // TODO: Using the original SCEV no-wrap flags is not always safe, however
465   //       as our code generation is reordering the expression anyway it doesn't
466   //       really matter.
467   const SCEV *ZeroStartExpr =
468       SE.getAddRecExpr(SE.getConstant(Expr->getStart()->getType(), 0),
469                        Expr->getStepRecurrence(SE), Expr->getLoop(), Flags);
470 
471   PWACtx Result = visit(ZeroStartExpr);
472   PWACtx Start = visit(Expr->getStart());
473   combine(Result, Start, isl_pw_aff_add);
474   return Result;
475 }
476 
477 __isl_give PWACtx SCEVAffinator::visitSMaxExpr(const SCEVSMaxExpr *Expr) {
478   PWACtx Max = visit(Expr->getOperand(0));
479 
480   for (int i = 1, e = Expr->getNumOperands(); i < e; ++i) {
481     combine(Max, visit(Expr->getOperand(i)), isl_pw_aff_max);
482     if (isTooComplex(Max))
483       return std::make_pair(nullptr, nullptr);
484   }
485 
486   return Max;
487 }
488 
489 __isl_give PWACtx SCEVAffinator::visitUMaxExpr(const SCEVUMaxExpr *Expr) {
490   llvm_unreachable("SCEVUMaxExpr not yet supported");
491 }
492 
493 __isl_give PWACtx SCEVAffinator::visitUDivExpr(const SCEVUDivExpr *Expr) {
494   // The handling of unsigned division is basically the same as for signed
495   // division, except the interpretation of the operands. As the divisor
496   // has to be constant in both cases we can simply interpret it as an
497   // unsigned value without additional complexity in the representation.
498   // For the dividend we could choose from the different representation
499   // schemes introduced for zero-extend operations but for now we will
500   // simply use an assumption.
501   auto *Dividend = Expr->getLHS();
502   auto *Divisor = Expr->getRHS();
503   assert(isa<SCEVConstant>(Divisor) &&
504          "UDiv is no parameter but has a non-constant RHS.");
505 
506   auto DividendPWAC = visit(Dividend);
507   auto DivisorPWAC = visit(Divisor);
508 
509   if (SE.isKnownNegative(Divisor)) {
510     // Interpret negative divisors unsigned. This is a special case of the
511     // piece-wise defined value described for zero-extends as we already know
512     // the actual value of the constant divisor.
513     unsigned Width = TD.getTypeSizeInBits(Expr->getType());
514     auto *DivisorDom = isl_pw_aff_domain(isl_pw_aff_copy(DivisorPWAC.first));
515     auto *WidthExpPWA = getWidthExpValOnDomain(Width, DivisorDom);
516     DivisorPWAC.first = isl_pw_aff_add(DivisorPWAC.first, WidthExpPWA);
517   }
518 
519   // TODO: One can represent the dividend as piece-wise function to be more
520   //       precise but therefor a heuristic is needed.
521 
522   // Assume a non-negative dividend.
523   takeNonNegativeAssumption(DividendPWAC);
524 
525   combine(DividendPWAC, DivisorPWAC, isl_pw_aff_div);
526   DividendPWAC.first = isl_pw_aff_floor(DividendPWAC.first);
527 
528   return DividendPWAC;
529 }
530 
531 __isl_give PWACtx SCEVAffinator::visitSDivInstruction(Instruction *SDiv) {
532   assert(SDiv->getOpcode() == Instruction::SDiv && "Assumed SDiv instruction!");
533 
534   auto *Scope = getScope();
535   auto *Divisor = SDiv->getOperand(1);
536   auto *DivisorSCEV = SE.getSCEVAtScope(Divisor, Scope);
537   auto DivisorPWAC = visit(DivisorSCEV);
538   assert(isa<ConstantInt>(Divisor) &&
539          "SDiv is no parameter but has a non-constant RHS.");
540 
541   auto *Dividend = SDiv->getOperand(0);
542   auto *DividendSCEV = SE.getSCEVAtScope(Dividend, Scope);
543   auto DividendPWAC = visit(DividendSCEV);
544   combine(DividendPWAC, DivisorPWAC, isl_pw_aff_tdiv_q);
545   return DividendPWAC;
546 }
547 
548 __isl_give PWACtx SCEVAffinator::visitSRemInstruction(Instruction *SRem) {
549   assert(SRem->getOpcode() == Instruction::SRem && "Assumed SRem instruction!");
550 
551   auto *Scope = getScope();
552   auto *Divisor = SRem->getOperand(1);
553   auto *DivisorSCEV = SE.getSCEVAtScope(Divisor, Scope);
554   auto DivisorPWAC = visit(DivisorSCEV);
555   assert(isa<ConstantInt>(Divisor) &&
556          "SRem is no parameter but has a non-constant RHS.");
557 
558   auto *Dividend = SRem->getOperand(0);
559   auto *DividendSCEV = SE.getSCEVAtScope(Dividend, Scope);
560   auto DividendPWAC = visit(DividendSCEV);
561   combine(DividendPWAC, DivisorPWAC, isl_pw_aff_tdiv_r);
562   return DividendPWAC;
563 }
564 
565 __isl_give PWACtx SCEVAffinator::visitUnknown(const SCEVUnknown *Expr) {
566   if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
567     switch (I->getOpcode()) {
568     case Instruction::IntToPtr:
569       return visit(SE.getSCEVAtScope(I->getOperand(0), getScope()));
570     case Instruction::PtrToInt:
571       return visit(SE.getSCEVAtScope(I->getOperand(0), getScope()));
572     case Instruction::SDiv:
573       return visitSDivInstruction(I);
574     case Instruction::SRem:
575       return visitSRemInstruction(I);
576     default:
577       break; // Fall through.
578     }
579   }
580 
581   llvm_unreachable(
582       "Unknowns SCEV was neither parameter nor a valid instruction.");
583 }
584