xref: /llvm-project/polly/lib/Support/SCEVValidator.cpp (revision a1b2086a33dbfe4bea86acbb77611ffafd6245f1)
1 
2 #include "polly/Support/SCEVValidator.h"
3 #include "polly/ScopInfo.h"
4 #include "llvm/Analysis/RegionInfo.h"
5 #include "llvm/Analysis/ScalarEvolution.h"
6 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
7 #include "llvm/Support/Debug.h"
8 
9 using namespace llvm;
10 using namespace polly;
11 
12 #define DEBUG_TYPE "polly-scev-validator"
13 
14 namespace SCEVType {
15 /// The type of a SCEV
16 ///
17 /// To check for the validity of a SCEV we assign to each SCEV a type. The
18 /// possible types are INT, PARAM, IV and INVALID. The order of the types is
19 /// important. The subexpressions of SCEV with a type X can only have a type
20 /// that is smaller or equal than X.
21 enum TYPE {
22   // An integer value.
23   INT,
24 
25   // An expression that is constant during the execution of the Scop,
26   // but that may depend on parameters unknown at compile time.
27   PARAM,
28 
29   // An expression that may change during the execution of the SCoP.
30   IV,
31 
32   // An invalid expression.
33   INVALID
34 };
35 } // namespace SCEVType
36 
37 /// The result the validator returns for a SCEV expression.
38 class ValidatorResult {
39   /// The type of the expression
40   SCEVType::TYPE Type;
41 
42   /// The set of Parameters in the expression.
43   ParameterSetTy Parameters;
44 
45 public:
46   /// The copy constructor
47   ValidatorResult(const ValidatorResult &Source) {
48     Type = Source.Type;
49     Parameters = Source.Parameters;
50   }
51 
52   /// Construct a result with a certain type and no parameters.
53   ValidatorResult(SCEVType::TYPE Type) : Type(Type) {
54     assert(Type != SCEVType::PARAM && "Did you forget to pass the parameter");
55   }
56 
57   /// Construct a result with a certain type and a single parameter.
58   ValidatorResult(SCEVType::TYPE Type, const SCEV *Expr) : Type(Type) {
59     Parameters.insert(Expr);
60   }
61 
62   /// Get the type of the ValidatorResult.
63   SCEVType::TYPE getType() { return Type; }
64 
65   /// Is the analyzed SCEV constant during the execution of the SCoP.
66   bool isConstant() { return Type == SCEVType::INT || Type == SCEVType::PARAM; }
67 
68   /// Is the analyzed SCEV valid.
69   bool isValid() { return Type != SCEVType::INVALID; }
70 
71   /// Is the analyzed SCEV of Type IV.
72   bool isIV() { return Type == SCEVType::IV; }
73 
74   /// Is the analyzed SCEV of Type INT.
75   bool isINT() { return Type == SCEVType::INT; }
76 
77   /// Is the analyzed SCEV of Type PARAM.
78   bool isPARAM() { return Type == SCEVType::PARAM; }
79 
80   /// Get the parameters of this validator result.
81   const ParameterSetTy &getParameters() { return Parameters; }
82 
83   /// Add the parameters of Source to this result.
84   void addParamsFrom(const ValidatorResult &Source) {
85     Parameters.insert(Source.Parameters.begin(), Source.Parameters.end());
86   }
87 
88   /// Merge a result.
89   ///
90   /// This means to merge the parameters and to set the Type to the most
91   /// specific Type that matches both.
92   void merge(const ValidatorResult &ToMerge) {
93     Type = std::max(Type, ToMerge.Type);
94     addParamsFrom(ToMerge);
95   }
96 
97   void print(raw_ostream &OS) {
98     switch (Type) {
99     case SCEVType::INT:
100       OS << "SCEVType::INT";
101       break;
102     case SCEVType::PARAM:
103       OS << "SCEVType::PARAM";
104       break;
105     case SCEVType::IV:
106       OS << "SCEVType::IV";
107       break;
108     case SCEVType::INVALID:
109       OS << "SCEVType::INVALID";
110       break;
111     }
112   }
113 };
114 
115 raw_ostream &operator<<(raw_ostream &OS, class ValidatorResult &VR) {
116   VR.print(OS);
117   return OS;
118 }
119 
120 bool polly::isConstCall(llvm::CallInst *Call) {
121   if (Call->mayReadOrWriteMemory())
122     return false;
123 
124   for (auto &Operand : Call->arg_operands())
125     if (!isa<ConstantInt>(&Operand))
126       return false;
127 
128   return true;
129 }
130 
131 /// Check if a SCEV is valid in a SCoP.
132 struct SCEVValidator
133     : public SCEVVisitor<SCEVValidator, class ValidatorResult> {
134 private:
135   const Region *R;
136   Loop *Scope;
137   ScalarEvolution &SE;
138   InvariantLoadsSetTy *ILS;
139 
140 public:
141   SCEVValidator(const Region *R, Loop *Scope, ScalarEvolution &SE,
142                 InvariantLoadsSetTy *ILS)
143       : R(R), Scope(Scope), SE(SE), ILS(ILS) {}
144 
145   class ValidatorResult visitConstant(const SCEVConstant *Constant) {
146     return ValidatorResult(SCEVType::INT);
147   }
148 
149   class ValidatorResult visitZeroExtendOrTruncateExpr(const SCEV *Expr,
150                                                       const SCEV *Operand) {
151     ValidatorResult Op = visit(Operand);
152     auto Type = Op.getType();
153 
154     // If unsigned operations are allowed return the operand, otherwise
155     // check if we can model the expression without unsigned assumptions.
156     if (PollyAllowUnsignedOperations || Type == SCEVType::INVALID)
157       return Op;
158 
159     if (Type == SCEVType::IV)
160       return ValidatorResult(SCEVType::INVALID);
161     return ValidatorResult(SCEVType::PARAM, Expr);
162   }
163 
164   class ValidatorResult visitTruncateExpr(const SCEVTruncateExpr *Expr) {
165     return visitZeroExtendOrTruncateExpr(Expr, Expr->getOperand());
166   }
167 
168   class ValidatorResult visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
169     return visitZeroExtendOrTruncateExpr(Expr, Expr->getOperand());
170   }
171 
172   class ValidatorResult visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
173     return visit(Expr->getOperand());
174   }
175 
176   class ValidatorResult visitAddExpr(const SCEVAddExpr *Expr) {
177     ValidatorResult Return(SCEVType::INT);
178 
179     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
180       ValidatorResult Op = visit(Expr->getOperand(i));
181       Return.merge(Op);
182 
183       // Early exit.
184       if (!Return.isValid())
185         break;
186     }
187 
188     return Return;
189   }
190 
191   class ValidatorResult visitMulExpr(const SCEVMulExpr *Expr) {
192     ValidatorResult Return(SCEVType::INT);
193 
194     bool HasMultipleParams = false;
195 
196     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
197       ValidatorResult Op = visit(Expr->getOperand(i));
198 
199       if (Op.isINT())
200         continue;
201 
202       if (Op.isPARAM() && Return.isPARAM()) {
203         HasMultipleParams = true;
204         continue;
205       }
206 
207       if ((Op.isIV() || Op.isPARAM()) && !Return.isINT()) {
208         DEBUG(dbgs() << "INVALID: More than one non-int operand in MulExpr\n"
209                      << "\tExpr: " << *Expr << "\n"
210                      << "\tPrevious expression type: " << Return << "\n"
211                      << "\tNext operand (" << Op
212                      << "): " << *Expr->getOperand(i) << "\n");
213 
214         return ValidatorResult(SCEVType::INVALID);
215       }
216 
217       Return.merge(Op);
218     }
219 
220     if (HasMultipleParams && Return.isValid())
221       return ValidatorResult(SCEVType::PARAM, Expr);
222 
223     return Return;
224   }
225 
226   class ValidatorResult visitAddRecExpr(const SCEVAddRecExpr *Expr) {
227     if (!Expr->isAffine()) {
228       DEBUG(dbgs() << "INVALID: AddRec is not affine");
229       return ValidatorResult(SCEVType::INVALID);
230     }
231 
232     ValidatorResult Start = visit(Expr->getStart());
233     ValidatorResult Recurrence = visit(Expr->getStepRecurrence(SE));
234 
235     if (!Start.isValid())
236       return Start;
237 
238     if (!Recurrence.isValid())
239       return Recurrence;
240 
241     auto *L = Expr->getLoop();
242     if (R->contains(L) && (!Scope || !L->contains(Scope))) {
243       DEBUG(dbgs() << "INVALID: Loop of AddRec expression boxed in an a "
244                       "non-affine subregion or has a non-synthesizable exit "
245                       "value.");
246       return ValidatorResult(SCEVType::INVALID);
247     }
248 
249     if (R->contains(L)) {
250       if (Recurrence.isINT()) {
251         ValidatorResult Result(SCEVType::IV);
252         Result.addParamsFrom(Start);
253         return Result;
254       }
255 
256       DEBUG(dbgs() << "INVALID: AddRec within scop has non-int"
257                       "recurrence part");
258       return ValidatorResult(SCEVType::INVALID);
259     }
260 
261     assert(Recurrence.isConstant() && "Expected 'Recurrence' to be constant");
262 
263     // Directly generate ValidatorResult for Expr if 'start' is zero.
264     if (Expr->getStart()->isZero())
265       return ValidatorResult(SCEVType::PARAM, Expr);
266 
267     // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
268     // if 'start' is not zero.
269     const SCEV *ZeroStartExpr = SE.getAddRecExpr(
270         SE.getConstant(Expr->getStart()->getType(), 0),
271         Expr->getStepRecurrence(SE), Expr->getLoop(), Expr->getNoWrapFlags());
272 
273     ValidatorResult ZeroStartResult =
274         ValidatorResult(SCEVType::PARAM, ZeroStartExpr);
275     ZeroStartResult.addParamsFrom(Start);
276 
277     return ZeroStartResult;
278   }
279 
280   class ValidatorResult visitSMaxExpr(const SCEVSMaxExpr *Expr) {
281     ValidatorResult Return(SCEVType::INT);
282 
283     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
284       ValidatorResult Op = visit(Expr->getOperand(i));
285 
286       if (!Op.isValid())
287         return Op;
288 
289       Return.merge(Op);
290     }
291 
292     return Return;
293   }
294 
295   class ValidatorResult visitUMaxExpr(const SCEVUMaxExpr *Expr) {
296     // We do not support unsigned max operations. If 'Expr' is constant during
297     // Scop execution we treat this as a parameter, otherwise we bail out.
298     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
299       ValidatorResult Op = visit(Expr->getOperand(i));
300 
301       if (!Op.isConstant()) {
302         DEBUG(dbgs() << "INVALID: UMaxExpr has a non-constant operand");
303         return ValidatorResult(SCEVType::INVALID);
304       }
305     }
306 
307     return ValidatorResult(SCEVType::PARAM, Expr);
308   }
309 
310   ValidatorResult visitGenericInst(Instruction *I, const SCEV *S) {
311     if (R->contains(I)) {
312       DEBUG(dbgs() << "INVALID: UnknownExpr references an instruction "
313                       "within the region\n");
314       return ValidatorResult(SCEVType::INVALID);
315     }
316 
317     return ValidatorResult(SCEVType::PARAM, S);
318   }
319 
320   ValidatorResult visitCallInstruction(Instruction *I, const SCEV *S) {
321     assert(I->getOpcode() == Instruction::Call && "Call instruction expected");
322 
323     if (R->contains(I)) {
324       auto Call = cast<CallInst>(I);
325 
326       if (!isConstCall(Call))
327         return ValidatorResult(SCEVType::INVALID, S);
328     }
329     return ValidatorResult(SCEVType::PARAM, S);
330   }
331 
332   ValidatorResult visitLoadInstruction(Instruction *I, const SCEV *S) {
333     if (R->contains(I) && ILS) {
334       ILS->insert(cast<LoadInst>(I));
335       return ValidatorResult(SCEVType::PARAM, S);
336     }
337 
338     return visitGenericInst(I, S);
339   }
340 
341   ValidatorResult visitDivision(const SCEV *Dividend, const SCEV *Divisor,
342                                 const SCEV *DivExpr,
343                                 Instruction *SDiv = nullptr) {
344 
345     // First check if we might be able to model the division, thus if the
346     // divisor is constant. If so, check the dividend, otherwise check if
347     // the whole division can be seen as a parameter.
348     if (isa<SCEVConstant>(Divisor) && !Divisor->isZero())
349       return visit(Dividend);
350 
351     // For signed divisions use the SDiv instruction to check for a parameter
352     // division, for unsigned divisions check the operands.
353     if (SDiv)
354       return visitGenericInst(SDiv, DivExpr);
355 
356     ValidatorResult LHS = visit(Dividend);
357     ValidatorResult RHS = visit(Divisor);
358     if (LHS.isConstant() && RHS.isConstant())
359       return ValidatorResult(SCEVType::PARAM, DivExpr);
360 
361     DEBUG(dbgs() << "INVALID: unsigned division of non-constant expressions");
362     return ValidatorResult(SCEVType::INVALID);
363   }
364 
365   ValidatorResult visitUDivExpr(const SCEVUDivExpr *Expr) {
366     if (!PollyAllowUnsignedOperations)
367       return ValidatorResult(SCEVType::INVALID);
368 
369     auto *Dividend = Expr->getLHS();
370     auto *Divisor = Expr->getRHS();
371     return visitDivision(Dividend, Divisor, Expr);
372   }
373 
374   ValidatorResult visitSDivInstruction(Instruction *SDiv, const SCEV *Expr) {
375     assert(SDiv->getOpcode() == Instruction::SDiv &&
376            "Assumed SDiv instruction!");
377 
378     auto *Dividend = SE.getSCEV(SDiv->getOperand(0));
379     auto *Divisor = SE.getSCEV(SDiv->getOperand(1));
380     return visitDivision(Dividend, Divisor, Expr, SDiv);
381   }
382 
383   ValidatorResult visitSRemInstruction(Instruction *SRem, const SCEV *S) {
384     assert(SRem->getOpcode() == Instruction::SRem &&
385            "Assumed SRem instruction!");
386 
387     auto *Divisor = SRem->getOperand(1);
388     auto *CI = dyn_cast<ConstantInt>(Divisor);
389     if (!CI || CI->isZeroValue())
390       return visitGenericInst(SRem, S);
391 
392     auto *Dividend = SRem->getOperand(0);
393     auto *DividendSCEV = SE.getSCEV(Dividend);
394     return visit(DividendSCEV);
395   }
396 
397   ValidatorResult visitUnknown(const SCEVUnknown *Expr) {
398     Value *V = Expr->getValue();
399 
400     if (!Expr->getType()->isIntegerTy() && !Expr->getType()->isPointerTy()) {
401       DEBUG(dbgs() << "INVALID: UnknownExpr is not an integer or pointer");
402       return ValidatorResult(SCEVType::INVALID);
403     }
404 
405     if (isa<UndefValue>(V)) {
406       DEBUG(dbgs() << "INVALID: UnknownExpr references an undef value");
407       return ValidatorResult(SCEVType::INVALID);
408     }
409 
410     if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
411       switch (I->getOpcode()) {
412       case Instruction::IntToPtr:
413         return visit(SE.getSCEVAtScope(I->getOperand(0), Scope));
414       case Instruction::PtrToInt:
415         return visit(SE.getSCEVAtScope(I->getOperand(0), Scope));
416       case Instruction::Load:
417         return visitLoadInstruction(I, Expr);
418       case Instruction::SDiv:
419         return visitSDivInstruction(I, Expr);
420       case Instruction::SRem:
421         return visitSRemInstruction(I, Expr);
422       case Instruction::Call:
423         return visitCallInstruction(I, Expr);
424       default:
425         return visitGenericInst(I, Expr);
426       }
427     }
428 
429     return ValidatorResult(SCEVType::PARAM, Expr);
430   }
431 };
432 
433 class SCEVHasIVParams {
434   bool HasIVParams = false;
435 
436 public:
437   SCEVHasIVParams() {}
438 
439   bool follow(const SCEV *S) {
440     const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(S);
441     if (!Unknown)
442       return true;
443 
444     CallInst *Call = dyn_cast<CallInst>(Unknown->getValue());
445 
446     if (!Call)
447       return true;
448 
449     if (isConstCall(Call)) {
450       HasIVParams = true;
451       return false;
452     }
453 
454     return true;
455   }
456 
457   bool isDone() { return HasIVParams; }
458   bool hasIVParams() { return HasIVParams; }
459 };
460 
461 /// Check whether a SCEV refers to an SSA name defined inside a region.
462 class SCEVInRegionDependences {
463   const Region *R;
464   Loop *Scope;
465   const InvariantLoadsSetTy &ILS;
466   bool AllowLoops;
467   bool HasInRegionDeps = false;
468 
469 public:
470   SCEVInRegionDependences(const Region *R, Loop *Scope, bool AllowLoops,
471                           const InvariantLoadsSetTy &ILS)
472       : R(R), Scope(Scope), ILS(ILS), AllowLoops(AllowLoops) {}
473 
474   bool follow(const SCEV *S) {
475     if (auto Unknown = dyn_cast<SCEVUnknown>(S)) {
476       Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue());
477 
478       CallInst *Call = dyn_cast<CallInst>(Unknown->getValue());
479 
480       if (Call && isConstCall(Call))
481         return false;
482 
483       if (Inst) {
484         // When we invariant load hoist a load, we first make sure that there
485         // can be no dependences created by it in the Scop region. So, we should
486         // not consider scalar dependences to `LoadInst`s that are invariant
487         // load hoisted.
488         //
489         // If this check is not present, then we create data dependences which
490         // are strictly not necessary by tracking the invariant load as a
491         // scalar.
492         LoadInst *LI = dyn_cast<LoadInst>(Inst);
493         if (LI && ILS.count(LI) > 0)
494           return false;
495       }
496 
497       // Return true when Inst is defined inside the region R.
498       if (!Inst || !R->contains(Inst))
499         return true;
500 
501       HasInRegionDeps = true;
502       return false;
503     }
504 
505     if (auto AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
506       if (AllowLoops)
507         return true;
508 
509       if (!Scope) {
510         HasInRegionDeps = true;
511         return false;
512       }
513       auto *L = AddRec->getLoop();
514       if (R->contains(L) && !L->contains(Scope)) {
515         HasInRegionDeps = true;
516         return false;
517       }
518     }
519 
520     return true;
521   }
522   bool isDone() { return false; }
523   bool hasDependences() { return HasInRegionDeps; }
524 };
525 
526 namespace polly {
527 /// Find all loops referenced in SCEVAddRecExprs.
528 class SCEVFindLoops {
529   SetVector<const Loop *> &Loops;
530 
531 public:
532   SCEVFindLoops(SetVector<const Loop *> &Loops) : Loops(Loops) {}
533 
534   bool follow(const SCEV *S) {
535     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
536       Loops.insert(AddRec->getLoop());
537     return true;
538   }
539   bool isDone() { return false; }
540 };
541 
542 void findLoops(const SCEV *Expr, SetVector<const Loop *> &Loops) {
543   SCEVFindLoops FindLoops(Loops);
544   SCEVTraversal<SCEVFindLoops> ST(FindLoops);
545   ST.visitAll(Expr);
546 }
547 
548 /// Find all values referenced in SCEVUnknowns.
549 class SCEVFindValues {
550   ScalarEvolution &SE;
551   SetVector<Value *> &Values;
552 
553 public:
554   SCEVFindValues(ScalarEvolution &SE, SetVector<Value *> &Values)
555       : SE(SE), Values(Values) {}
556 
557   bool follow(const SCEV *S) {
558     const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(S);
559     if (!Unknown)
560       return true;
561 
562     Values.insert(Unknown->getValue());
563     Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue());
564     if (!Inst || (Inst->getOpcode() != Instruction::SRem &&
565                   Inst->getOpcode() != Instruction::SDiv))
566       return false;
567 
568     auto *Dividend = SE.getSCEV(Inst->getOperand(1));
569     if (!isa<SCEVConstant>(Dividend))
570       return false;
571 
572     auto *Divisor = SE.getSCEV(Inst->getOperand(0));
573     SCEVFindValues FindValues(SE, Values);
574     SCEVTraversal<SCEVFindValues> ST(FindValues);
575     ST.visitAll(Dividend);
576     ST.visitAll(Divisor);
577 
578     return false;
579   }
580   bool isDone() { return false; }
581 };
582 
583 void findValues(const SCEV *Expr, ScalarEvolution &SE,
584                 SetVector<Value *> &Values) {
585   SCEVFindValues FindValues(SE, Values);
586   SCEVTraversal<SCEVFindValues> ST(FindValues);
587   ST.visitAll(Expr);
588 }
589 
590 bool hasIVParams(const SCEV *Expr) {
591   SCEVHasIVParams HasIVParams;
592   SCEVTraversal<SCEVHasIVParams> ST(HasIVParams);
593   ST.visitAll(Expr);
594   return HasIVParams.hasIVParams();
595 }
596 
597 bool hasScalarDepsInsideRegion(const SCEV *Expr, const Region *R,
598                                llvm::Loop *Scope, bool AllowLoops,
599                                const InvariantLoadsSetTy &ILS) {
600   SCEVInRegionDependences InRegionDeps(R, Scope, AllowLoops, ILS);
601   SCEVTraversal<SCEVInRegionDependences> ST(InRegionDeps);
602   ST.visitAll(Expr);
603   return InRegionDeps.hasDependences();
604 }
605 
606 bool isAffineExpr(const Region *R, llvm::Loop *Scope, const SCEV *Expr,
607                   ScalarEvolution &SE, InvariantLoadsSetTy *ILS) {
608   if (isa<SCEVCouldNotCompute>(Expr))
609     return false;
610 
611   SCEVValidator Validator(R, Scope, SE, ILS);
612   DEBUG({
613     dbgs() << "\n";
614     dbgs() << "Expr: " << *Expr << "\n";
615     dbgs() << "Region: " << R->getNameStr() << "\n";
616     dbgs() << " -> ";
617   });
618 
619   ValidatorResult Result = Validator.visit(Expr);
620 
621   DEBUG({
622     if (Result.isValid())
623       dbgs() << "VALID\n";
624     dbgs() << "\n";
625   });
626 
627   return Result.isValid();
628 }
629 
630 static bool isAffineExpr(Value *V, const Region *R, Loop *Scope,
631                          ScalarEvolution &SE, ParameterSetTy &Params) {
632   auto *E = SE.getSCEV(V);
633   if (isa<SCEVCouldNotCompute>(E))
634     return false;
635 
636   SCEVValidator Validator(R, Scope, SE, nullptr);
637   ValidatorResult Result = Validator.visit(E);
638   if (!Result.isValid())
639     return false;
640 
641   auto ResultParams = Result.getParameters();
642   Params.insert(ResultParams.begin(), ResultParams.end());
643 
644   return true;
645 }
646 
647 bool isAffineConstraint(Value *V, const Region *R, llvm::Loop *Scope,
648                         ScalarEvolution &SE, ParameterSetTy &Params,
649                         bool OrExpr) {
650   if (auto *ICmp = dyn_cast<ICmpInst>(V)) {
651     return isAffineConstraint(ICmp->getOperand(0), R, Scope, SE, Params,
652                               true) &&
653            isAffineConstraint(ICmp->getOperand(1), R, Scope, SE, Params, true);
654   } else if (auto *BinOp = dyn_cast<BinaryOperator>(V)) {
655     auto Opcode = BinOp->getOpcode();
656     if (Opcode == Instruction::And || Opcode == Instruction::Or)
657       return isAffineConstraint(BinOp->getOperand(0), R, Scope, SE, Params,
658                                 false) &&
659              isAffineConstraint(BinOp->getOperand(1), R, Scope, SE, Params,
660                                 false);
661     /* Fall through */
662   }
663 
664   if (!OrExpr)
665     return false;
666 
667   return isAffineExpr(V, R, Scope, SE, Params);
668 }
669 
670 ParameterSetTy getParamsInAffineExpr(const Region *R, Loop *Scope,
671                                      const SCEV *Expr, ScalarEvolution &SE) {
672   if (isa<SCEVCouldNotCompute>(Expr))
673     return ParameterSetTy();
674 
675   InvariantLoadsSetTy ILS;
676   SCEVValidator Validator(R, Scope, SE, &ILS);
677   ValidatorResult Result = Validator.visit(Expr);
678   assert(Result.isValid() && "Requested parameters for an invalid SCEV!");
679 
680   return Result.getParameters();
681 }
682 
683 std::pair<const SCEVConstant *, const SCEV *>
684 extractConstantFactor(const SCEV *S, ScalarEvolution &SE) {
685   auto *ConstPart = cast<SCEVConstant>(SE.getConstant(S->getType(), 1));
686 
687   if (auto *Constant = dyn_cast<SCEVConstant>(S))
688     return std::make_pair(Constant, SE.getConstant(S->getType(), 1));
689 
690   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
691   if (AddRec) {
692     auto *StartExpr = AddRec->getStart();
693     if (StartExpr->isZero()) {
694       auto StepPair = extractConstantFactor(AddRec->getStepRecurrence(SE), SE);
695       auto *LeftOverAddRec =
696           SE.getAddRecExpr(StartExpr, StepPair.second, AddRec->getLoop(),
697                            AddRec->getNoWrapFlags());
698       return std::make_pair(StepPair.first, LeftOverAddRec);
699     }
700     return std::make_pair(ConstPart, S);
701   }
702 
703   if (auto *Add = dyn_cast<SCEVAddExpr>(S)) {
704     SmallVector<const SCEV *, 4> LeftOvers;
705     auto Op0Pair = extractConstantFactor(Add->getOperand(0), SE);
706     auto *Factor = Op0Pair.first;
707     if (SE.isKnownNegative(Factor)) {
708       Factor = cast<SCEVConstant>(SE.getNegativeSCEV(Factor));
709       LeftOvers.push_back(SE.getNegativeSCEV(Op0Pair.second));
710     } else {
711       LeftOvers.push_back(Op0Pair.second);
712     }
713 
714     for (unsigned u = 1, e = Add->getNumOperands(); u < e; u++) {
715       auto OpUPair = extractConstantFactor(Add->getOperand(u), SE);
716       // TODO: Use something smarter than equality here, e.g., gcd.
717       if (Factor == OpUPair.first)
718         LeftOvers.push_back(OpUPair.second);
719       else if (Factor == SE.getNegativeSCEV(OpUPair.first))
720         LeftOvers.push_back(SE.getNegativeSCEV(OpUPair.second));
721       else
722         return std::make_pair(ConstPart, S);
723     }
724 
725     auto *NewAdd = SE.getAddExpr(LeftOvers, Add->getNoWrapFlags());
726     return std::make_pair(Factor, NewAdd);
727   }
728 
729   auto *Mul = dyn_cast<SCEVMulExpr>(S);
730   if (!Mul)
731     return std::make_pair(ConstPart, S);
732 
733   SmallVector<const SCEV *, 4> LeftOvers;
734   for (auto *Op : Mul->operands())
735     if (isa<SCEVConstant>(Op))
736       ConstPart = cast<SCEVConstant>(SE.getMulExpr(ConstPart, Op));
737     else
738       LeftOvers.push_back(Op);
739 
740   return std::make_pair(ConstPart, SE.getMulExpr(LeftOvers));
741 }
742 } // namespace polly
743