xref: /llvm-project/polly/lib/Support/SCEVValidator.cpp (revision 0a62b2d88767bd2836bcf3182e6d58c89cc84cdf)
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       auto *L = AddRec->getLoop();
510       if (R->contains(L) && !L->contains(Scope)) {
511         HasInRegionDeps = true;
512         return false;
513       }
514     }
515 
516     return true;
517   }
518   bool isDone() { return false; }
519   bool hasDependences() { return HasInRegionDeps; }
520 };
521 
522 namespace polly {
523 /// Find all loops referenced in SCEVAddRecExprs.
524 class SCEVFindLoops {
525   SetVector<const Loop *> &Loops;
526 
527 public:
528   SCEVFindLoops(SetVector<const Loop *> &Loops) : Loops(Loops) {}
529 
530   bool follow(const SCEV *S) {
531     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
532       Loops.insert(AddRec->getLoop());
533     return true;
534   }
535   bool isDone() { return false; }
536 };
537 
538 void findLoops(const SCEV *Expr, SetVector<const Loop *> &Loops) {
539   SCEVFindLoops FindLoops(Loops);
540   SCEVTraversal<SCEVFindLoops> ST(FindLoops);
541   ST.visitAll(Expr);
542 }
543 
544 /// Find all values referenced in SCEVUnknowns.
545 class SCEVFindValues {
546   ScalarEvolution &SE;
547   SetVector<Value *> &Values;
548 
549 public:
550   SCEVFindValues(ScalarEvolution &SE, SetVector<Value *> &Values)
551       : SE(SE), Values(Values) {}
552 
553   bool follow(const SCEV *S) {
554     const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(S);
555     if (!Unknown)
556       return true;
557 
558     Values.insert(Unknown->getValue());
559     Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue());
560     if (!Inst || (Inst->getOpcode() != Instruction::SRem &&
561                   Inst->getOpcode() != Instruction::SDiv))
562       return false;
563 
564     auto *Dividend = SE.getSCEV(Inst->getOperand(1));
565     if (!isa<SCEVConstant>(Dividend))
566       return false;
567 
568     auto *Divisor = SE.getSCEV(Inst->getOperand(0));
569     SCEVFindValues FindValues(SE, Values);
570     SCEVTraversal<SCEVFindValues> ST(FindValues);
571     ST.visitAll(Dividend);
572     ST.visitAll(Divisor);
573 
574     return false;
575   }
576   bool isDone() { return false; }
577 };
578 
579 void findValues(const SCEV *Expr, ScalarEvolution &SE,
580                 SetVector<Value *> &Values) {
581   SCEVFindValues FindValues(SE, Values);
582   SCEVTraversal<SCEVFindValues> ST(FindValues);
583   ST.visitAll(Expr);
584 }
585 
586 bool hasIVParams(const SCEV *Expr) {
587   SCEVHasIVParams HasIVParams;
588   SCEVTraversal<SCEVHasIVParams> ST(HasIVParams);
589   ST.visitAll(Expr);
590   return HasIVParams.hasIVParams();
591 }
592 
593 bool hasScalarDepsInsideRegion(const SCEV *Expr, const Region *R,
594                                llvm::Loop *Scope, bool AllowLoops,
595                                const InvariantLoadsSetTy &ILS) {
596   SCEVInRegionDependences InRegionDeps(R, Scope, AllowLoops, ILS);
597   SCEVTraversal<SCEVInRegionDependences> ST(InRegionDeps);
598   ST.visitAll(Expr);
599   return InRegionDeps.hasDependences();
600 }
601 
602 bool isAffineExpr(const Region *R, llvm::Loop *Scope, const SCEV *Expr,
603                   ScalarEvolution &SE, InvariantLoadsSetTy *ILS) {
604   if (isa<SCEVCouldNotCompute>(Expr))
605     return false;
606 
607   SCEVValidator Validator(R, Scope, SE, ILS);
608   DEBUG({
609     dbgs() << "\n";
610     dbgs() << "Expr: " << *Expr << "\n";
611     dbgs() << "Region: " << R->getNameStr() << "\n";
612     dbgs() << " -> ";
613   });
614 
615   ValidatorResult Result = Validator.visit(Expr);
616 
617   DEBUG({
618     if (Result.isValid())
619       dbgs() << "VALID\n";
620     dbgs() << "\n";
621   });
622 
623   return Result.isValid();
624 }
625 
626 static bool isAffineExpr(Value *V, const Region *R, Loop *Scope,
627                          ScalarEvolution &SE, ParameterSetTy &Params) {
628   auto *E = SE.getSCEV(V);
629   if (isa<SCEVCouldNotCompute>(E))
630     return false;
631 
632   SCEVValidator Validator(R, Scope, SE, nullptr);
633   ValidatorResult Result = Validator.visit(E);
634   if (!Result.isValid())
635     return false;
636 
637   auto ResultParams = Result.getParameters();
638   Params.insert(ResultParams.begin(), ResultParams.end());
639 
640   return true;
641 }
642 
643 bool isAffineConstraint(Value *V, const Region *R, llvm::Loop *Scope,
644                         ScalarEvolution &SE, ParameterSetTy &Params,
645                         bool OrExpr) {
646   if (auto *ICmp = dyn_cast<ICmpInst>(V)) {
647     return isAffineConstraint(ICmp->getOperand(0), R, Scope, SE, Params,
648                               true) &&
649            isAffineConstraint(ICmp->getOperand(1), R, Scope, SE, Params, true);
650   } else if (auto *BinOp = dyn_cast<BinaryOperator>(V)) {
651     auto Opcode = BinOp->getOpcode();
652     if (Opcode == Instruction::And || Opcode == Instruction::Or)
653       return isAffineConstraint(BinOp->getOperand(0), R, Scope, SE, Params,
654                                 false) &&
655              isAffineConstraint(BinOp->getOperand(1), R, Scope, SE, Params,
656                                 false);
657     /* Fall through */
658   }
659 
660   if (!OrExpr)
661     return false;
662 
663   return isAffineExpr(V, R, Scope, SE, Params);
664 }
665 
666 ParameterSetTy getParamsInAffineExpr(const Region *R, Loop *Scope,
667                                      const SCEV *Expr, ScalarEvolution &SE) {
668   if (isa<SCEVCouldNotCompute>(Expr))
669     return ParameterSetTy();
670 
671   InvariantLoadsSetTy ILS;
672   SCEVValidator Validator(R, Scope, SE, &ILS);
673   ValidatorResult Result = Validator.visit(Expr);
674   assert(Result.isValid() && "Requested parameters for an invalid SCEV!");
675 
676   return Result.getParameters();
677 }
678 
679 std::pair<const SCEVConstant *, const SCEV *>
680 extractConstantFactor(const SCEV *S, ScalarEvolution &SE) {
681   auto *ConstPart = cast<SCEVConstant>(SE.getConstant(S->getType(), 1));
682 
683   if (auto *Constant = dyn_cast<SCEVConstant>(S))
684     return std::make_pair(Constant, SE.getConstant(S->getType(), 1));
685 
686   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
687   if (AddRec) {
688     auto *StartExpr = AddRec->getStart();
689     if (StartExpr->isZero()) {
690       auto StepPair = extractConstantFactor(AddRec->getStepRecurrence(SE), SE);
691       auto *LeftOverAddRec =
692           SE.getAddRecExpr(StartExpr, StepPair.second, AddRec->getLoop(),
693                            AddRec->getNoWrapFlags());
694       return std::make_pair(StepPair.first, LeftOverAddRec);
695     }
696     return std::make_pair(ConstPart, S);
697   }
698 
699   if (auto *Add = dyn_cast<SCEVAddExpr>(S)) {
700     SmallVector<const SCEV *, 4> LeftOvers;
701     auto Op0Pair = extractConstantFactor(Add->getOperand(0), SE);
702     auto *Factor = Op0Pair.first;
703     if (SE.isKnownNegative(Factor)) {
704       Factor = cast<SCEVConstant>(SE.getNegativeSCEV(Factor));
705       LeftOvers.push_back(SE.getNegativeSCEV(Op0Pair.second));
706     } else {
707       LeftOvers.push_back(Op0Pair.second);
708     }
709 
710     for (unsigned u = 1, e = Add->getNumOperands(); u < e; u++) {
711       auto OpUPair = extractConstantFactor(Add->getOperand(u), SE);
712       // TODO: Use something smarter than equality here, e.g., gcd.
713       if (Factor == OpUPair.first)
714         LeftOvers.push_back(OpUPair.second);
715       else if (Factor == SE.getNegativeSCEV(OpUPair.first))
716         LeftOvers.push_back(SE.getNegativeSCEV(OpUPair.second));
717       else
718         return std::make_pair(ConstPart, S);
719     }
720 
721     auto *NewAdd = SE.getAddExpr(LeftOvers, Add->getNoWrapFlags());
722     return std::make_pair(Factor, NewAdd);
723   }
724 
725   auto *Mul = dyn_cast<SCEVMulExpr>(S);
726   if (!Mul)
727     return std::make_pair(ConstPart, S);
728 
729   SmallVector<const SCEV *, 4> LeftOvers;
730   for (auto *Op : Mul->operands())
731     if (isa<SCEVConstant>(Op))
732       ConstPart = cast<SCEVConstant>(SE.getMulExpr(ConstPart, Op));
733     else
734       LeftOvers.push_back(Op);
735 
736   return std::make_pair(ConstPart, SE.getMulExpr(LeftOvers));
737 }
738 
739 const SCEV *tryForwardThroughPHI(const SCEV *Expr, Region &R,
740                                  ScalarEvolution &SE, LoopInfo &LI,
741                                  const DominatorTree &DT) {
742   if (auto *Unknown = dyn_cast<SCEVUnknown>(Expr)) {
743     Value *V = Unknown->getValue();
744     auto *PHI = dyn_cast<PHINode>(V);
745     if (!PHI)
746       return Expr;
747 
748     Value *Final = nullptr;
749 
750     for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
751       BasicBlock *Incoming = PHI->getIncomingBlock(i);
752       if (isErrorBlock(*Incoming, R, LI, DT) && R.contains(Incoming))
753         continue;
754       if (Final)
755         return Expr;
756       Final = PHI->getIncomingValue(i);
757     }
758 
759     if (Final)
760       return SE.getSCEV(Final);
761   }
762   return Expr;
763 }
764 
765 Value *getUniqueNonErrorValue(PHINode *PHI, Region *R, LoopInfo &LI,
766                               const DominatorTree &DT) {
767   Value *V = nullptr;
768   for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
769     BasicBlock *BB = PHI->getIncomingBlock(i);
770     if (!isErrorBlock(*BB, *R, LI, DT)) {
771       if (V)
772         return nullptr;
773       V = PHI->getIncomingValue(i);
774     }
775   }
776 
777   return V;
778 }
779 } // namespace polly
780