xref: /llvm-project/polly/lib/Support/SCEVValidator.cpp (revision 349506a926c78af36cdcac75d44ac7522f168d06)
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         LLVM_DEBUG(
209             dbgs() << "INVALID: More than one non-int operand in MulExpr\n"
210                    << "\tExpr: " << *Expr << "\n"
211                    << "\tPrevious expression type: " << Return << "\n"
212                    << "\tNext operand (" << Op << "): " << *Expr->getOperand(i)
213                    << "\n");
214 
215         return ValidatorResult(SCEVType::INVALID);
216       }
217 
218       Return.merge(Op);
219     }
220 
221     if (HasMultipleParams && Return.isValid())
222       return ValidatorResult(SCEVType::PARAM, Expr);
223 
224     return Return;
225   }
226 
227   class ValidatorResult visitAddRecExpr(const SCEVAddRecExpr *Expr) {
228     if (!Expr->isAffine()) {
229       LLVM_DEBUG(dbgs() << "INVALID: AddRec is not affine");
230       return ValidatorResult(SCEVType::INVALID);
231     }
232 
233     ValidatorResult Start = visit(Expr->getStart());
234     ValidatorResult Recurrence = visit(Expr->getStepRecurrence(SE));
235 
236     if (!Start.isValid())
237       return Start;
238 
239     if (!Recurrence.isValid())
240       return Recurrence;
241 
242     auto *L = Expr->getLoop();
243     if (R->contains(L) && (!Scope || !L->contains(Scope))) {
244       LLVM_DEBUG(
245           dbgs() << "INVALID: Loop of AddRec expression boxed in an a "
246                     "non-affine subregion or has a non-synthesizable exit "
247                     "value.");
248       return ValidatorResult(SCEVType::INVALID);
249     }
250 
251     if (R->contains(L)) {
252       if (Recurrence.isINT()) {
253         ValidatorResult Result(SCEVType::IV);
254         Result.addParamsFrom(Start);
255         return Result;
256       }
257 
258       LLVM_DEBUG(dbgs() << "INVALID: AddRec within scop has non-int"
259                            "recurrence part");
260       return ValidatorResult(SCEVType::INVALID);
261     }
262 
263     assert(Recurrence.isConstant() && "Expected 'Recurrence' to be constant");
264 
265     // Directly generate ValidatorResult for Expr if 'start' is zero.
266     if (Expr->getStart()->isZero())
267       return ValidatorResult(SCEVType::PARAM, Expr);
268 
269     // Translate AddRecExpr from '{start, +, inc}' into 'start + {0, +, inc}'
270     // if 'start' is not zero.
271     const SCEV *ZeroStartExpr = SE.getAddRecExpr(
272         SE.getConstant(Expr->getStart()->getType(), 0),
273         Expr->getStepRecurrence(SE), Expr->getLoop(), Expr->getNoWrapFlags());
274 
275     ValidatorResult ZeroStartResult =
276         ValidatorResult(SCEVType::PARAM, ZeroStartExpr);
277     ZeroStartResult.addParamsFrom(Start);
278 
279     return ZeroStartResult;
280   }
281 
282   class ValidatorResult visitSMaxExpr(const SCEVSMaxExpr *Expr) {
283     ValidatorResult Return(SCEVType::INT);
284 
285     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
286       ValidatorResult Op = visit(Expr->getOperand(i));
287 
288       if (!Op.isValid())
289         return Op;
290 
291       Return.merge(Op);
292     }
293 
294     return Return;
295   }
296 
297   class ValidatorResult visitUMaxExpr(const SCEVUMaxExpr *Expr) {
298     // We do not support unsigned max operations. If 'Expr' is constant during
299     // Scop execution we treat this as a parameter, otherwise we bail out.
300     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
301       ValidatorResult Op = visit(Expr->getOperand(i));
302 
303       if (!Op.isConstant()) {
304         LLVM_DEBUG(dbgs() << "INVALID: UMaxExpr has a non-constant operand");
305         return ValidatorResult(SCEVType::INVALID);
306       }
307     }
308 
309     return ValidatorResult(SCEVType::PARAM, Expr);
310   }
311 
312   ValidatorResult visitGenericInst(Instruction *I, const SCEV *S) {
313     if (R->contains(I)) {
314       LLVM_DEBUG(dbgs() << "INVALID: UnknownExpr references an instruction "
315                            "within the region\n");
316       return ValidatorResult(SCEVType::INVALID);
317     }
318 
319     return ValidatorResult(SCEVType::PARAM, S);
320   }
321 
322   ValidatorResult visitCallInstruction(Instruction *I, const SCEV *S) {
323     assert(I->getOpcode() == Instruction::Call && "Call instruction expected");
324 
325     if (R->contains(I)) {
326       auto Call = cast<CallInst>(I);
327 
328       if (!isConstCall(Call))
329         return ValidatorResult(SCEVType::INVALID, S);
330     }
331     return ValidatorResult(SCEVType::PARAM, S);
332   }
333 
334   ValidatorResult visitLoadInstruction(Instruction *I, const SCEV *S) {
335     if (R->contains(I) && ILS) {
336       ILS->insert(cast<LoadInst>(I));
337       return ValidatorResult(SCEVType::PARAM, S);
338     }
339 
340     return visitGenericInst(I, S);
341   }
342 
343   ValidatorResult visitDivision(const SCEV *Dividend, const SCEV *Divisor,
344                                 const SCEV *DivExpr,
345                                 Instruction *SDiv = nullptr) {
346 
347     // First check if we might be able to model the division, thus if the
348     // divisor is constant. If so, check the dividend, otherwise check if
349     // the whole division can be seen as a parameter.
350     if (isa<SCEVConstant>(Divisor) && !Divisor->isZero())
351       return visit(Dividend);
352 
353     // For signed divisions use the SDiv instruction to check for a parameter
354     // division, for unsigned divisions check the operands.
355     if (SDiv)
356       return visitGenericInst(SDiv, DivExpr);
357 
358     ValidatorResult LHS = visit(Dividend);
359     ValidatorResult RHS = visit(Divisor);
360     if (LHS.isConstant() && RHS.isConstant())
361       return ValidatorResult(SCEVType::PARAM, DivExpr);
362 
363     LLVM_DEBUG(
364         dbgs() << "INVALID: unsigned division of non-constant expressions");
365     return ValidatorResult(SCEVType::INVALID);
366   }
367 
368   ValidatorResult visitUDivExpr(const SCEVUDivExpr *Expr) {
369     if (!PollyAllowUnsignedOperations)
370       return ValidatorResult(SCEVType::INVALID);
371 
372     auto *Dividend = Expr->getLHS();
373     auto *Divisor = Expr->getRHS();
374     return visitDivision(Dividend, Divisor, Expr);
375   }
376 
377   ValidatorResult visitSDivInstruction(Instruction *SDiv, const SCEV *Expr) {
378     assert(SDiv->getOpcode() == Instruction::SDiv &&
379            "Assumed SDiv instruction!");
380 
381     auto *Dividend = SE.getSCEV(SDiv->getOperand(0));
382     auto *Divisor = SE.getSCEV(SDiv->getOperand(1));
383     return visitDivision(Dividend, Divisor, Expr, SDiv);
384   }
385 
386   ValidatorResult visitSRemInstruction(Instruction *SRem, const SCEV *S) {
387     assert(SRem->getOpcode() == Instruction::SRem &&
388            "Assumed SRem instruction!");
389 
390     auto *Divisor = SRem->getOperand(1);
391     auto *CI = dyn_cast<ConstantInt>(Divisor);
392     if (!CI || CI->isZeroValue())
393       return visitGenericInst(SRem, S);
394 
395     auto *Dividend = SRem->getOperand(0);
396     auto *DividendSCEV = SE.getSCEV(Dividend);
397     return visit(DividendSCEV);
398   }
399 
400   ValidatorResult visitUnknown(const SCEVUnknown *Expr) {
401     Value *V = Expr->getValue();
402 
403     if (!Expr->getType()->isIntegerTy() && !Expr->getType()->isPointerTy()) {
404       LLVM_DEBUG(dbgs() << "INVALID: UnknownExpr is not an integer or pointer");
405       return ValidatorResult(SCEVType::INVALID);
406     }
407 
408     if (isa<UndefValue>(V)) {
409       LLVM_DEBUG(dbgs() << "INVALID: UnknownExpr references an undef value");
410       return ValidatorResult(SCEVType::INVALID);
411     }
412 
413     if (Instruction *I = dyn_cast<Instruction>(Expr->getValue())) {
414       switch (I->getOpcode()) {
415       case Instruction::IntToPtr:
416         return visit(SE.getSCEVAtScope(I->getOperand(0), Scope));
417       case Instruction::PtrToInt:
418         return visit(SE.getSCEVAtScope(I->getOperand(0), Scope));
419       case Instruction::Load:
420         return visitLoadInstruction(I, Expr);
421       case Instruction::SDiv:
422         return visitSDivInstruction(I, Expr);
423       case Instruction::SRem:
424         return visitSRemInstruction(I, Expr);
425       case Instruction::Call:
426         return visitCallInstruction(I, Expr);
427       default:
428         return visitGenericInst(I, Expr);
429       }
430     }
431 
432     return ValidatorResult(SCEVType::PARAM, Expr);
433   }
434 };
435 
436 class SCEVHasIVParams {
437   bool HasIVParams = false;
438 
439 public:
440   SCEVHasIVParams() {}
441 
442   bool follow(const SCEV *S) {
443     const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(S);
444     if (!Unknown)
445       return true;
446 
447     CallInst *Call = dyn_cast<CallInst>(Unknown->getValue());
448 
449     if (!Call)
450       return true;
451 
452     if (isConstCall(Call)) {
453       HasIVParams = true;
454       return false;
455     }
456 
457     return true;
458   }
459 
460   bool isDone() { return HasIVParams; }
461   bool hasIVParams() { return HasIVParams; }
462 };
463 
464 /// Check whether a SCEV refers to an SSA name defined inside a region.
465 class SCEVInRegionDependences {
466   const Region *R;
467   Loop *Scope;
468   const InvariantLoadsSetTy &ILS;
469   bool AllowLoops;
470   bool HasInRegionDeps = false;
471 
472 public:
473   SCEVInRegionDependences(const Region *R, Loop *Scope, bool AllowLoops,
474                           const InvariantLoadsSetTy &ILS)
475       : R(R), Scope(Scope), ILS(ILS), AllowLoops(AllowLoops) {}
476 
477   bool follow(const SCEV *S) {
478     if (auto Unknown = dyn_cast<SCEVUnknown>(S)) {
479       Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue());
480 
481       CallInst *Call = dyn_cast<CallInst>(Unknown->getValue());
482 
483       if (Call && isConstCall(Call))
484         return false;
485 
486       if (Inst) {
487         // When we invariant load hoist a load, we first make sure that there
488         // can be no dependences created by it in the Scop region. So, we should
489         // not consider scalar dependences to `LoadInst`s that are invariant
490         // load hoisted.
491         //
492         // If this check is not present, then we create data dependences which
493         // are strictly not necessary by tracking the invariant load as a
494         // scalar.
495         LoadInst *LI = dyn_cast<LoadInst>(Inst);
496         if (LI && ILS.count(LI) > 0)
497           return false;
498       }
499 
500       // Return true when Inst is defined inside the region R.
501       if (!Inst || !R->contains(Inst))
502         return true;
503 
504       HasInRegionDeps = true;
505       return false;
506     }
507 
508     if (auto AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
509       if (AllowLoops)
510         return true;
511 
512       auto *L = AddRec->getLoop();
513       if (R->contains(L) && !L->contains(Scope)) {
514         HasInRegionDeps = true;
515         return false;
516       }
517     }
518 
519     return true;
520   }
521   bool isDone() { return false; }
522   bool hasDependences() { return HasInRegionDeps; }
523 };
524 
525 namespace polly {
526 /// Find all loops referenced in SCEVAddRecExprs.
527 class SCEVFindLoops {
528   SetVector<const Loop *> &Loops;
529 
530 public:
531   SCEVFindLoops(SetVector<const Loop *> &Loops) : Loops(Loops) {}
532 
533   bool follow(const SCEV *S) {
534     if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
535       Loops.insert(AddRec->getLoop());
536     return true;
537   }
538   bool isDone() { return false; }
539 };
540 
541 void findLoops(const SCEV *Expr, SetVector<const Loop *> &Loops) {
542   SCEVFindLoops FindLoops(Loops);
543   SCEVTraversal<SCEVFindLoops> ST(FindLoops);
544   ST.visitAll(Expr);
545 }
546 
547 /// Find all values referenced in SCEVUnknowns.
548 class SCEVFindValues {
549   ScalarEvolution &SE;
550   SetVector<Value *> &Values;
551 
552 public:
553   SCEVFindValues(ScalarEvolution &SE, SetVector<Value *> &Values)
554       : SE(SE), Values(Values) {}
555 
556   bool follow(const SCEV *S) {
557     const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(S);
558     if (!Unknown)
559       return true;
560 
561     Values.insert(Unknown->getValue());
562     Instruction *Inst = dyn_cast<Instruction>(Unknown->getValue());
563     if (!Inst || (Inst->getOpcode() != Instruction::SRem &&
564                   Inst->getOpcode() != Instruction::SDiv))
565       return false;
566 
567     auto *Dividend = SE.getSCEV(Inst->getOperand(1));
568     if (!isa<SCEVConstant>(Dividend))
569       return false;
570 
571     auto *Divisor = SE.getSCEV(Inst->getOperand(0));
572     SCEVFindValues FindValues(SE, Values);
573     SCEVTraversal<SCEVFindValues> ST(FindValues);
574     ST.visitAll(Dividend);
575     ST.visitAll(Divisor);
576 
577     return false;
578   }
579   bool isDone() { return false; }
580 };
581 
582 void findValues(const SCEV *Expr, ScalarEvolution &SE,
583                 SetVector<Value *> &Values) {
584   SCEVFindValues FindValues(SE, Values);
585   SCEVTraversal<SCEVFindValues> ST(FindValues);
586   ST.visitAll(Expr);
587 }
588 
589 bool hasIVParams(const SCEV *Expr) {
590   SCEVHasIVParams HasIVParams;
591   SCEVTraversal<SCEVHasIVParams> ST(HasIVParams);
592   ST.visitAll(Expr);
593   return HasIVParams.hasIVParams();
594 }
595 
596 bool hasScalarDepsInsideRegion(const SCEV *Expr, const Region *R,
597                                llvm::Loop *Scope, bool AllowLoops,
598                                const InvariantLoadsSetTy &ILS) {
599   SCEVInRegionDependences InRegionDeps(R, Scope, AllowLoops, ILS);
600   SCEVTraversal<SCEVInRegionDependences> ST(InRegionDeps);
601   ST.visitAll(Expr);
602   return InRegionDeps.hasDependences();
603 }
604 
605 bool isAffineExpr(const Region *R, llvm::Loop *Scope, const SCEV *Expr,
606                   ScalarEvolution &SE, InvariantLoadsSetTy *ILS) {
607   if (isa<SCEVCouldNotCompute>(Expr))
608     return false;
609 
610   SCEVValidator Validator(R, Scope, SE, ILS);
611   LLVM_DEBUG({
612     dbgs() << "\n";
613     dbgs() << "Expr: " << *Expr << "\n";
614     dbgs() << "Region: " << R->getNameStr() << "\n";
615     dbgs() << " -> ";
616   });
617 
618   ValidatorResult Result = Validator.visit(Expr);
619 
620   LLVM_DEBUG({
621     if (Result.isValid())
622       dbgs() << "VALID\n";
623     dbgs() << "\n";
624   });
625 
626   return Result.isValid();
627 }
628 
629 static bool isAffineExpr(Value *V, const Region *R, Loop *Scope,
630                          ScalarEvolution &SE, ParameterSetTy &Params) {
631   auto *E = SE.getSCEV(V);
632   if (isa<SCEVCouldNotCompute>(E))
633     return false;
634 
635   SCEVValidator Validator(R, Scope, SE, nullptr);
636   ValidatorResult Result = Validator.visit(E);
637   if (!Result.isValid())
638     return false;
639 
640   auto ResultParams = Result.getParameters();
641   Params.insert(ResultParams.begin(), ResultParams.end());
642 
643   return true;
644 }
645 
646 bool isAffineConstraint(Value *V, const Region *R, llvm::Loop *Scope,
647                         ScalarEvolution &SE, ParameterSetTy &Params,
648                         bool OrExpr) {
649   if (auto *ICmp = dyn_cast<ICmpInst>(V)) {
650     return isAffineConstraint(ICmp->getOperand(0), R, Scope, SE, Params,
651                               true) &&
652            isAffineConstraint(ICmp->getOperand(1), R, Scope, SE, Params, true);
653   } else if (auto *BinOp = dyn_cast<BinaryOperator>(V)) {
654     auto Opcode = BinOp->getOpcode();
655     if (Opcode == Instruction::And || Opcode == Instruction::Or)
656       return isAffineConstraint(BinOp->getOperand(0), R, Scope, SE, Params,
657                                 false) &&
658              isAffineConstraint(BinOp->getOperand(1), R, Scope, SE, Params,
659                                 false);
660     /* Fall through */
661   }
662 
663   if (!OrExpr)
664     return false;
665 
666   return isAffineExpr(V, R, Scope, SE, Params);
667 }
668 
669 ParameterSetTy getParamsInAffineExpr(const Region *R, Loop *Scope,
670                                      const SCEV *Expr, ScalarEvolution &SE) {
671   if (isa<SCEVCouldNotCompute>(Expr))
672     return ParameterSetTy();
673 
674   InvariantLoadsSetTy ILS;
675   SCEVValidator Validator(R, Scope, SE, &ILS);
676   ValidatorResult Result = Validator.visit(Expr);
677   assert(Result.isValid() && "Requested parameters for an invalid SCEV!");
678 
679   return Result.getParameters();
680 }
681 
682 std::pair<const SCEVConstant *, const SCEV *>
683 extractConstantFactor(const SCEV *S, ScalarEvolution &SE) {
684   auto *ConstPart = cast<SCEVConstant>(SE.getConstant(S->getType(), 1));
685 
686   if (auto *Constant = dyn_cast<SCEVConstant>(S))
687     return std::make_pair(Constant, SE.getConstant(S->getType(), 1));
688 
689   auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
690   if (AddRec) {
691     auto *StartExpr = AddRec->getStart();
692     if (StartExpr->isZero()) {
693       auto StepPair = extractConstantFactor(AddRec->getStepRecurrence(SE), SE);
694       auto *LeftOverAddRec =
695           SE.getAddRecExpr(StartExpr, StepPair.second, AddRec->getLoop(),
696                            AddRec->getNoWrapFlags());
697       return std::make_pair(StepPair.first, LeftOverAddRec);
698     }
699     return std::make_pair(ConstPart, S);
700   }
701 
702   if (auto *Add = dyn_cast<SCEVAddExpr>(S)) {
703     SmallVector<const SCEV *, 4> LeftOvers;
704     auto Op0Pair = extractConstantFactor(Add->getOperand(0), SE);
705     auto *Factor = Op0Pair.first;
706     if (SE.isKnownNegative(Factor)) {
707       Factor = cast<SCEVConstant>(SE.getNegativeSCEV(Factor));
708       LeftOvers.push_back(SE.getNegativeSCEV(Op0Pair.second));
709     } else {
710       LeftOvers.push_back(Op0Pair.second);
711     }
712 
713     for (unsigned u = 1, e = Add->getNumOperands(); u < e; u++) {
714       auto OpUPair = extractConstantFactor(Add->getOperand(u), SE);
715       // TODO: Use something smarter than equality here, e.g., gcd.
716       if (Factor == OpUPair.first)
717         LeftOvers.push_back(OpUPair.second);
718       else if (Factor == SE.getNegativeSCEV(OpUPair.first))
719         LeftOvers.push_back(SE.getNegativeSCEV(OpUPair.second));
720       else
721         return std::make_pair(ConstPart, S);
722     }
723 
724     auto *NewAdd = SE.getAddExpr(LeftOvers, Add->getNoWrapFlags());
725     return std::make_pair(Factor, NewAdd);
726   }
727 
728   auto *Mul = dyn_cast<SCEVMulExpr>(S);
729   if (!Mul)
730     return std::make_pair(ConstPart, S);
731 
732   SmallVector<const SCEV *, 4> LeftOvers;
733   for (auto *Op : Mul->operands())
734     if (isa<SCEVConstant>(Op))
735       ConstPart = cast<SCEVConstant>(SE.getMulExpr(ConstPart, Op));
736     else
737       LeftOvers.push_back(Op);
738 
739   return std::make_pair(ConstPart, SE.getMulExpr(LeftOvers));
740 }
741 
742 const SCEV *tryForwardThroughPHI(const SCEV *Expr, Region &R,
743                                  ScalarEvolution &SE, LoopInfo &LI,
744                                  const DominatorTree &DT) {
745   if (auto *Unknown = dyn_cast<SCEVUnknown>(Expr)) {
746     Value *V = Unknown->getValue();
747     auto *PHI = dyn_cast<PHINode>(V);
748     if (!PHI)
749       return Expr;
750 
751     Value *Final = nullptr;
752 
753     for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
754       BasicBlock *Incoming = PHI->getIncomingBlock(i);
755       if (isErrorBlock(*Incoming, R, LI, DT) && R.contains(Incoming))
756         continue;
757       if (Final)
758         return Expr;
759       Final = PHI->getIncomingValue(i);
760     }
761 
762     if (Final)
763       return SE.getSCEV(Final);
764   }
765   return Expr;
766 }
767 
768 Value *getUniqueNonErrorValue(PHINode *PHI, Region *R, LoopInfo &LI,
769                               const DominatorTree &DT) {
770   Value *V = nullptr;
771   for (unsigned i = 0; i < PHI->getNumIncomingValues(); i++) {
772     BasicBlock *BB = PHI->getIncomingBlock(i);
773     if (!isErrorBlock(*BB, *R, LI, DT)) {
774       if (V)
775         return nullptr;
776       V = PHI->getIncomingValue(i);
777     }
778   }
779 
780   return V;
781 }
782 } // namespace polly
783