[Alignment][NFC] Value::getPointerAlignment returns MaybeAlign
[llvm-core.git] / lib / Analysis / ScalarEvolution.cpp
blob8d4c7c5a55f166ef4fc700911fd751f38f841c28
1 //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the implementation of the scalar evolution analysis
10 // engine, which is used primarily to analyze expressions involving induction
11 // variables in loops.
13 // There are several aspects to this library. First is the representation of
14 // scalar expressions, which are represented as subclasses of the SCEV class.
15 // These classes are used to represent certain types of subexpressions that we
16 // can handle. We only create one SCEV of a particular shape, so
17 // pointer-comparisons for equality are legal.
19 // One important aspect of the SCEV objects is that they are never cyclic, even
20 // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
21 // the PHI node is one of the idioms that we can represent (e.g., a polynomial
22 // recurrence) then we represent it directly as a recurrence node, otherwise we
23 // represent it as a SCEVUnknown node.
25 // In addition to being able to represent expressions of various types, we also
26 // have folders that are used to build the *canonical* representation for a
27 // particular expression. These folders are capable of using a variety of
28 // rewrite rules to simplify the expressions.
30 // Once the folders are defined, we can implement the more interesting
31 // higher-level code, such as the code that recognizes PHI nodes of various
32 // types, computes the execution count of a loop, etc.
34 // TODO: We should use these routines and value representations to implement
35 // dependence analysis!
37 //===----------------------------------------------------------------------===//
39 // There are several good references for the techniques used in this analysis.
41 // Chains of recurrences -- a method to expedite the evaluation
42 // of closed-form functions
43 // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45 // On computational properties of chains of recurrences
46 // Eugene V. Zima
48 // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
49 // Robert A. van Engelen
51 // Efficient Symbolic Analysis for Optimizing Compilers
52 // Robert A. van Engelen
54 // Using the chains of recurrences algebra for data dependence testing and
55 // induction variable substitution
56 // MS Thesis, Johnie Birch
58 //===----------------------------------------------------------------------===//
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/ADT/APInt.h"
62 #include "llvm/ADT/ArrayRef.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/DepthFirstIterator.h"
65 #include "llvm/ADT/EquivalenceClasses.h"
66 #include "llvm/ADT/FoldingSet.h"
67 #include "llvm/ADT/None.h"
68 #include "llvm/ADT/Optional.h"
69 #include "llvm/ADT/STLExtras.h"
70 #include "llvm/ADT/ScopeExit.h"
71 #include "llvm/ADT/Sequence.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallSet.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/Statistic.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/ConstantFolding.h"
80 #include "llvm/Analysis/InstructionSimplify.h"
81 #include "llvm/Analysis/LoopInfo.h"
82 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
83 #include "llvm/Analysis/TargetLibraryInfo.h"
84 #include "llvm/Analysis/ValueTracking.h"
85 #include "llvm/Config/llvm-config.h"
86 #include "llvm/IR/Argument.h"
87 #include "llvm/IR/BasicBlock.h"
88 #include "llvm/IR/CFG.h"
89 #include "llvm/IR/CallSite.h"
90 #include "llvm/IR/Constant.h"
91 #include "llvm/IR/ConstantRange.h"
92 #include "llvm/IR/Constants.h"
93 #include "llvm/IR/DataLayout.h"
94 #include "llvm/IR/DerivedTypes.h"
95 #include "llvm/IR/Dominators.h"
96 #include "llvm/IR/Function.h"
97 #include "llvm/IR/GlobalAlias.h"
98 #include "llvm/IR/GlobalValue.h"
99 #include "llvm/IR/GlobalVariable.h"
100 #include "llvm/IR/InstIterator.h"
101 #include "llvm/IR/InstrTypes.h"
102 #include "llvm/IR/Instruction.h"
103 #include "llvm/IR/Instructions.h"
104 #include "llvm/IR/IntrinsicInst.h"
105 #include "llvm/IR/Intrinsics.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/Metadata.h"
108 #include "llvm/IR/Operator.h"
109 #include "llvm/IR/PatternMatch.h"
110 #include "llvm/IR/Type.h"
111 #include "llvm/IR/Use.h"
112 #include "llvm/IR/User.h"
113 #include "llvm/IR/Value.h"
114 #include "llvm/IR/Verifier.h"
115 #include "llvm/Pass.h"
116 #include "llvm/Support/Casting.h"
117 #include "llvm/Support/CommandLine.h"
118 #include "llvm/Support/Compiler.h"
119 #include "llvm/Support/Debug.h"
120 #include "llvm/Support/ErrorHandling.h"
121 #include "llvm/Support/KnownBits.h"
122 #include "llvm/Support/SaveAndRestore.h"
123 #include "llvm/Support/raw_ostream.h"
124 #include <algorithm>
125 #include <cassert>
126 #include <climits>
127 #include <cstddef>
128 #include <cstdint>
129 #include <cstdlib>
130 #include <map>
131 #include <memory>
132 #include <tuple>
133 #include <utility>
134 #include <vector>
136 using namespace llvm;
138 #define DEBUG_TYPE "scalar-evolution"
140 STATISTIC(NumArrayLenItCounts,
141 "Number of trip counts computed with array length");
142 STATISTIC(NumTripCountsComputed,
143 "Number of loops with predictable loop counts");
144 STATISTIC(NumTripCountsNotComputed,
145 "Number of loops without predictable loop counts");
146 STATISTIC(NumBruteForceTripCountsComputed,
147 "Number of loops with trip counts computed by force");
149 static cl::opt<unsigned>
150 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
151 cl::ZeroOrMore,
152 cl::desc("Maximum number of iterations SCEV will "
153 "symbolically execute a constant "
154 "derived loop"),
155 cl::init(100));
157 // FIXME: Enable this with EXPENSIVE_CHECKS when the test suite is clean.
158 static cl::opt<bool> VerifySCEV(
159 "verify-scev", cl::Hidden,
160 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
161 static cl::opt<bool> VerifySCEVStrict(
162 "verify-scev-strict", cl::Hidden,
163 cl::desc("Enable stricter verification with -verify-scev is passed"));
164 static cl::opt<bool>
165 VerifySCEVMap("verify-scev-maps", cl::Hidden,
166 cl::desc("Verify no dangling value in ScalarEvolution's "
167 "ExprValueMap (slow)"));
169 static cl::opt<bool> VerifyIR(
170 "scev-verify-ir", cl::Hidden,
171 cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
172 cl::init(false));
174 static cl::opt<unsigned> MulOpsInlineThreshold(
175 "scev-mulops-inline-threshold", cl::Hidden,
176 cl::desc("Threshold for inlining multiplication operands into a SCEV"),
177 cl::init(32));
179 static cl::opt<unsigned> AddOpsInlineThreshold(
180 "scev-addops-inline-threshold", cl::Hidden,
181 cl::desc("Threshold for inlining addition operands into a SCEV"),
182 cl::init(500));
184 static cl::opt<unsigned> MaxSCEVCompareDepth(
185 "scalar-evolution-max-scev-compare-depth", cl::Hidden,
186 cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
187 cl::init(32));
189 static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
190 "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
191 cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
192 cl::init(2));
194 static cl::opt<unsigned> MaxValueCompareDepth(
195 "scalar-evolution-max-value-compare-depth", cl::Hidden,
196 cl::desc("Maximum depth of recursive value complexity comparisons"),
197 cl::init(2));
199 static cl::opt<unsigned>
200 MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
201 cl::desc("Maximum depth of recursive arithmetics"),
202 cl::init(32));
204 static cl::opt<unsigned> MaxConstantEvolvingDepth(
205 "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
206 cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
208 static cl::opt<unsigned>
209 MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
210 cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
211 cl::init(8));
213 static cl::opt<unsigned>
214 MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
215 cl::desc("Max coefficients in AddRec during evolving"),
216 cl::init(8));
218 static cl::opt<unsigned>
219 HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
220 cl::desc("Size of the expression which is considered huge"),
221 cl::init(4096));
223 //===----------------------------------------------------------------------===//
224 // SCEV class definitions
225 //===----------------------------------------------------------------------===//
227 //===----------------------------------------------------------------------===//
228 // Implementation of the SCEV class.
231 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
232 LLVM_DUMP_METHOD void SCEV::dump() const {
233 print(dbgs());
234 dbgs() << '\n';
236 #endif
238 void SCEV::print(raw_ostream &OS) const {
239 switch (static_cast<SCEVTypes>(getSCEVType())) {
240 case scConstant:
241 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
242 return;
243 case scTruncate: {
244 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
245 const SCEV *Op = Trunc->getOperand();
246 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
247 << *Trunc->getType() << ")";
248 return;
250 case scZeroExtend: {
251 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
252 const SCEV *Op = ZExt->getOperand();
253 OS << "(zext " << *Op->getType() << " " << *Op << " to "
254 << *ZExt->getType() << ")";
255 return;
257 case scSignExtend: {
258 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
259 const SCEV *Op = SExt->getOperand();
260 OS << "(sext " << *Op->getType() << " " << *Op << " to "
261 << *SExt->getType() << ")";
262 return;
264 case scAddRecExpr: {
265 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
266 OS << "{" << *AR->getOperand(0);
267 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
268 OS << ",+," << *AR->getOperand(i);
269 OS << "}<";
270 if (AR->hasNoUnsignedWrap())
271 OS << "nuw><";
272 if (AR->hasNoSignedWrap())
273 OS << "nsw><";
274 if (AR->hasNoSelfWrap() &&
275 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
276 OS << "nw><";
277 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
278 OS << ">";
279 return;
281 case scAddExpr:
282 case scMulExpr:
283 case scUMaxExpr:
284 case scSMaxExpr:
285 case scUMinExpr:
286 case scSMinExpr: {
287 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
288 const char *OpStr = nullptr;
289 switch (NAry->getSCEVType()) {
290 case scAddExpr: OpStr = " + "; break;
291 case scMulExpr: OpStr = " * "; break;
292 case scUMaxExpr: OpStr = " umax "; break;
293 case scSMaxExpr: OpStr = " smax "; break;
294 case scUMinExpr:
295 OpStr = " umin ";
296 break;
297 case scSMinExpr:
298 OpStr = " smin ";
299 break;
301 OS << "(";
302 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
303 I != E; ++I) {
304 OS << **I;
305 if (std::next(I) != E)
306 OS << OpStr;
308 OS << ")";
309 switch (NAry->getSCEVType()) {
310 case scAddExpr:
311 case scMulExpr:
312 if (NAry->hasNoUnsignedWrap())
313 OS << "<nuw>";
314 if (NAry->hasNoSignedWrap())
315 OS << "<nsw>";
317 return;
319 case scUDivExpr: {
320 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
321 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
322 return;
324 case scUnknown: {
325 const SCEVUnknown *U = cast<SCEVUnknown>(this);
326 Type *AllocTy;
327 if (U->isSizeOf(AllocTy)) {
328 OS << "sizeof(" << *AllocTy << ")";
329 return;
331 if (U->isAlignOf(AllocTy)) {
332 OS << "alignof(" << *AllocTy << ")";
333 return;
336 Type *CTy;
337 Constant *FieldNo;
338 if (U->isOffsetOf(CTy, FieldNo)) {
339 OS << "offsetof(" << *CTy << ", ";
340 FieldNo->printAsOperand(OS, false);
341 OS << ")";
342 return;
345 // Otherwise just print it normally.
346 U->getValue()->printAsOperand(OS, false);
347 return;
349 case scCouldNotCompute:
350 OS << "***COULDNOTCOMPUTE***";
351 return;
353 llvm_unreachable("Unknown SCEV kind!");
356 Type *SCEV::getType() const {
357 switch (static_cast<SCEVTypes>(getSCEVType())) {
358 case scConstant:
359 return cast<SCEVConstant>(this)->getType();
360 case scTruncate:
361 case scZeroExtend:
362 case scSignExtend:
363 return cast<SCEVCastExpr>(this)->getType();
364 case scAddRecExpr:
365 case scMulExpr:
366 case scUMaxExpr:
367 case scSMaxExpr:
368 case scUMinExpr:
369 case scSMinExpr:
370 return cast<SCEVNAryExpr>(this)->getType();
371 case scAddExpr:
372 return cast<SCEVAddExpr>(this)->getType();
373 case scUDivExpr:
374 return cast<SCEVUDivExpr>(this)->getType();
375 case scUnknown:
376 return cast<SCEVUnknown>(this)->getType();
377 case scCouldNotCompute:
378 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
380 llvm_unreachable("Unknown SCEV kind!");
383 bool SCEV::isZero() const {
384 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
385 return SC->getValue()->isZero();
386 return false;
389 bool SCEV::isOne() const {
390 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
391 return SC->getValue()->isOne();
392 return false;
395 bool SCEV::isAllOnesValue() const {
396 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
397 return SC->getValue()->isMinusOne();
398 return false;
401 bool SCEV::isNonConstantNegative() const {
402 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
403 if (!Mul) return false;
405 // If there is a constant factor, it will be first.
406 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
407 if (!SC) return false;
409 // Return true if the value is negative, this matches things like (-42 * V).
410 return SC->getAPInt().isNegative();
413 SCEVCouldNotCompute::SCEVCouldNotCompute() :
414 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
416 bool SCEVCouldNotCompute::classof(const SCEV *S) {
417 return S->getSCEVType() == scCouldNotCompute;
420 const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
421 FoldingSetNodeID ID;
422 ID.AddInteger(scConstant);
423 ID.AddPointer(V);
424 void *IP = nullptr;
425 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
426 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
427 UniqueSCEVs.InsertNode(S, IP);
428 return S;
431 const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
432 return getConstant(ConstantInt::get(getContext(), Val));
435 const SCEV *
436 ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
437 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
438 return getConstant(ConstantInt::get(ITy, V, isSigned));
441 SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
442 unsigned SCEVTy, const SCEV *op, Type *ty)
443 : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
445 SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
446 const SCEV *op, Type *ty)
447 : SCEVCastExpr(ID, scTruncate, op, ty) {
448 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
449 "Cannot truncate non-integer value!");
452 SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
453 const SCEV *op, Type *ty)
454 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
455 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
456 "Cannot zero extend non-integer value!");
459 SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
460 const SCEV *op, Type *ty)
461 : SCEVCastExpr(ID, scSignExtend, op, ty) {
462 assert(Op->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
463 "Cannot sign extend non-integer value!");
466 void SCEVUnknown::deleted() {
467 // Clear this SCEVUnknown from various maps.
468 SE->forgetMemoizedResults(this);
470 // Remove this SCEVUnknown from the uniquing map.
471 SE->UniqueSCEVs.RemoveNode(this);
473 // Release the value.
474 setValPtr(nullptr);
477 void SCEVUnknown::allUsesReplacedWith(Value *New) {
478 // Remove this SCEVUnknown from the uniquing map.
479 SE->UniqueSCEVs.RemoveNode(this);
481 // Update this SCEVUnknown to point to the new value. This is needed
482 // because there may still be outstanding SCEVs which still point to
483 // this SCEVUnknown.
484 setValPtr(New);
487 bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
488 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
489 if (VCE->getOpcode() == Instruction::PtrToInt)
490 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
491 if (CE->getOpcode() == Instruction::GetElementPtr &&
492 CE->getOperand(0)->isNullValue() &&
493 CE->getNumOperands() == 2)
494 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
495 if (CI->isOne()) {
496 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
497 ->getElementType();
498 return true;
501 return false;
504 bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
505 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
506 if (VCE->getOpcode() == Instruction::PtrToInt)
507 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
508 if (CE->getOpcode() == Instruction::GetElementPtr &&
509 CE->getOperand(0)->isNullValue()) {
510 Type *Ty =
511 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
512 if (StructType *STy = dyn_cast<StructType>(Ty))
513 if (!STy->isPacked() &&
514 CE->getNumOperands() == 3 &&
515 CE->getOperand(1)->isNullValue()) {
516 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
517 if (CI->isOne() &&
518 STy->getNumElements() == 2 &&
519 STy->getElementType(0)->isIntegerTy(1)) {
520 AllocTy = STy->getElementType(1);
521 return true;
526 return false;
529 bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
530 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
531 if (VCE->getOpcode() == Instruction::PtrToInt)
532 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
533 if (CE->getOpcode() == Instruction::GetElementPtr &&
534 CE->getNumOperands() == 3 &&
535 CE->getOperand(0)->isNullValue() &&
536 CE->getOperand(1)->isNullValue()) {
537 Type *Ty =
538 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
539 // Ignore vector types here so that ScalarEvolutionExpander doesn't
540 // emit getelementptrs that index into vectors.
541 if (Ty->isStructTy() || Ty->isArrayTy()) {
542 CTy = Ty;
543 FieldNo = CE->getOperand(2);
544 return true;
548 return false;
551 //===----------------------------------------------------------------------===//
552 // SCEV Utilities
553 //===----------------------------------------------------------------------===//
555 /// Compare the two values \p LV and \p RV in terms of their "complexity" where
556 /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
557 /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
558 /// have been previously deemed to be "equally complex" by this routine. It is
559 /// intended to avoid exponential time complexity in cases like:
561 /// %a = f(%x, %y)
562 /// %b = f(%a, %a)
563 /// %c = f(%b, %b)
565 /// %d = f(%x, %y)
566 /// %e = f(%d, %d)
567 /// %f = f(%e, %e)
569 /// CompareValueComplexity(%f, %c)
571 /// Since we do not continue running this routine on expression trees once we
572 /// have seen unequal values, there is no need to track them in the cache.
573 static int
574 CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
575 const LoopInfo *const LI, Value *LV, Value *RV,
576 unsigned Depth) {
577 if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
578 return 0;
580 // Order pointer values after integer values. This helps SCEVExpander form
581 // GEPs.
582 bool LIsPointer = LV->getType()->isPointerTy(),
583 RIsPointer = RV->getType()->isPointerTy();
584 if (LIsPointer != RIsPointer)
585 return (int)LIsPointer - (int)RIsPointer;
587 // Compare getValueID values.
588 unsigned LID = LV->getValueID(), RID = RV->getValueID();
589 if (LID != RID)
590 return (int)LID - (int)RID;
592 // Sort arguments by their position.
593 if (const auto *LA = dyn_cast<Argument>(LV)) {
594 const auto *RA = cast<Argument>(RV);
595 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
596 return (int)LArgNo - (int)RArgNo;
599 if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
600 const auto *RGV = cast<GlobalValue>(RV);
602 const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
603 auto LT = GV->getLinkage();
604 return !(GlobalValue::isPrivateLinkage(LT) ||
605 GlobalValue::isInternalLinkage(LT));
608 // Use the names to distinguish the two values, but only if the
609 // names are semantically important.
610 if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
611 return LGV->getName().compare(RGV->getName());
614 // For instructions, compare their loop depth, and their operand count. This
615 // is pretty loose.
616 if (const auto *LInst = dyn_cast<Instruction>(LV)) {
617 const auto *RInst = cast<Instruction>(RV);
619 // Compare loop depths.
620 const BasicBlock *LParent = LInst->getParent(),
621 *RParent = RInst->getParent();
622 if (LParent != RParent) {
623 unsigned LDepth = LI->getLoopDepth(LParent),
624 RDepth = LI->getLoopDepth(RParent);
625 if (LDepth != RDepth)
626 return (int)LDepth - (int)RDepth;
629 // Compare the number of operands.
630 unsigned LNumOps = LInst->getNumOperands(),
631 RNumOps = RInst->getNumOperands();
632 if (LNumOps != RNumOps)
633 return (int)LNumOps - (int)RNumOps;
635 for (unsigned Idx : seq(0u, LNumOps)) {
636 int Result =
637 CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
638 RInst->getOperand(Idx), Depth + 1);
639 if (Result != 0)
640 return Result;
644 EqCacheValue.unionSets(LV, RV);
645 return 0;
648 // Return negative, zero, or positive, if LHS is less than, equal to, or greater
649 // than RHS, respectively. A three-way result allows recursive comparisons to be
650 // more efficient.
651 static int CompareSCEVComplexity(
652 EquivalenceClasses<const SCEV *> &EqCacheSCEV,
653 EquivalenceClasses<const Value *> &EqCacheValue,
654 const LoopInfo *const LI, const SCEV *LHS, const SCEV *RHS,
655 DominatorTree &DT, unsigned Depth = 0) {
656 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
657 if (LHS == RHS)
658 return 0;
660 // Primarily, sort the SCEVs by their getSCEVType().
661 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
662 if (LType != RType)
663 return (int)LType - (int)RType;
665 if (Depth > MaxSCEVCompareDepth || EqCacheSCEV.isEquivalent(LHS, RHS))
666 return 0;
667 // Aside from the getSCEVType() ordering, the particular ordering
668 // isn't very important except that it's beneficial to be consistent,
669 // so that (a + b) and (b + a) don't end up as different expressions.
670 switch (static_cast<SCEVTypes>(LType)) {
671 case scUnknown: {
672 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
673 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
675 int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
676 RU->getValue(), Depth + 1);
677 if (X == 0)
678 EqCacheSCEV.unionSets(LHS, RHS);
679 return X;
682 case scConstant: {
683 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
684 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
686 // Compare constant values.
687 const APInt &LA = LC->getAPInt();
688 const APInt &RA = RC->getAPInt();
689 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
690 if (LBitWidth != RBitWidth)
691 return (int)LBitWidth - (int)RBitWidth;
692 return LA.ult(RA) ? -1 : 1;
695 case scAddRecExpr: {
696 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
697 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
699 // There is always a dominance between two recs that are used by one SCEV,
700 // so we can safely sort recs by loop header dominance. We require such
701 // order in getAddExpr.
702 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
703 if (LLoop != RLoop) {
704 const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
705 assert(LHead != RHead && "Two loops share the same header?");
706 if (DT.dominates(LHead, RHead))
707 return 1;
708 else
709 assert(DT.dominates(RHead, LHead) &&
710 "No dominance between recurrences used by one SCEV?");
711 return -1;
714 // Addrec complexity grows with operand count.
715 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
716 if (LNumOps != RNumOps)
717 return (int)LNumOps - (int)RNumOps;
719 // Lexicographically compare.
720 for (unsigned i = 0; i != LNumOps; ++i) {
721 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
722 LA->getOperand(i), RA->getOperand(i), DT,
723 Depth + 1);
724 if (X != 0)
725 return X;
727 EqCacheSCEV.unionSets(LHS, RHS);
728 return 0;
731 case scAddExpr:
732 case scMulExpr:
733 case scSMaxExpr:
734 case scUMaxExpr:
735 case scSMinExpr:
736 case scUMinExpr: {
737 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
738 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
740 // Lexicographically compare n-ary expressions.
741 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
742 if (LNumOps != RNumOps)
743 return (int)LNumOps - (int)RNumOps;
745 for (unsigned i = 0; i != LNumOps; ++i) {
746 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
747 LC->getOperand(i), RC->getOperand(i), DT,
748 Depth + 1);
749 if (X != 0)
750 return X;
752 EqCacheSCEV.unionSets(LHS, RHS);
753 return 0;
756 case scUDivExpr: {
757 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
758 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
760 // Lexicographically compare udiv expressions.
761 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getLHS(),
762 RC->getLHS(), DT, Depth + 1);
763 if (X != 0)
764 return X;
765 X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LC->getRHS(),
766 RC->getRHS(), DT, Depth + 1);
767 if (X == 0)
768 EqCacheSCEV.unionSets(LHS, RHS);
769 return X;
772 case scTruncate:
773 case scZeroExtend:
774 case scSignExtend: {
775 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
776 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
778 // Compare cast expressions by operand.
779 int X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI,
780 LC->getOperand(), RC->getOperand(), DT,
781 Depth + 1);
782 if (X == 0)
783 EqCacheSCEV.unionSets(LHS, RHS);
784 return X;
787 case scCouldNotCompute:
788 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
790 llvm_unreachable("Unknown SCEV kind!");
793 /// Given a list of SCEV objects, order them by their complexity, and group
794 /// objects of the same complexity together by value. When this routine is
795 /// finished, we know that any duplicates in the vector are consecutive and that
796 /// complexity is monotonically increasing.
798 /// Note that we go take special precautions to ensure that we get deterministic
799 /// results from this routine. In other words, we don't want the results of
800 /// this to depend on where the addresses of various SCEV objects happened to
801 /// land in memory.
802 static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
803 LoopInfo *LI, DominatorTree &DT) {
804 if (Ops.size() < 2) return; // Noop
806 EquivalenceClasses<const SCEV *> EqCacheSCEV;
807 EquivalenceClasses<const Value *> EqCacheValue;
808 if (Ops.size() == 2) {
809 // This is the common case, which also happens to be trivially simple.
810 // Special case it.
811 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
812 if (CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, RHS, LHS, DT) < 0)
813 std::swap(LHS, RHS);
814 return;
817 // Do the rough sort by complexity.
818 llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
819 return CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT) <
823 // Now that we are sorted by complexity, group elements of the same
824 // complexity. Note that this is, at worst, N^2, but the vector is likely to
825 // be extremely short in practice. Note that we take this approach because we
826 // do not want to depend on the addresses of the objects we are grouping.
827 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
828 const SCEV *S = Ops[i];
829 unsigned Complexity = S->getSCEVType();
831 // If there are any objects of the same complexity and same value as this
832 // one, group them.
833 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
834 if (Ops[j] == S) { // Found a duplicate.
835 // Move it to immediately after i'th element.
836 std::swap(Ops[i+1], Ops[j]);
837 ++i; // no need to rescan it.
838 if (i == e-2) return; // Done!
844 // Returns the size of the SCEV S.
845 static inline int sizeOfSCEV(const SCEV *S) {
846 struct FindSCEVSize {
847 int Size = 0;
849 FindSCEVSize() = default;
851 bool follow(const SCEV *S) {
852 ++Size;
853 // Keep looking at all operands of S.
854 return true;
857 bool isDone() const {
858 return false;
862 FindSCEVSize F;
863 SCEVTraversal<FindSCEVSize> ST(F);
864 ST.visitAll(S);
865 return F.Size;
868 /// Returns true if the subtree of \p S contains at least HugeExprThreshold
869 /// nodes.
870 static bool isHugeExpression(const SCEV *S) {
871 return S->getExpressionSize() >= HugeExprThreshold;
874 /// Returns true of \p Ops contains a huge SCEV (see definition above).
875 static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
876 return any_of(Ops, isHugeExpression);
879 namespace {
881 struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
882 public:
883 // Computes the Quotient and Remainder of the division of Numerator by
884 // Denominator.
885 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
886 const SCEV *Denominator, const SCEV **Quotient,
887 const SCEV **Remainder) {
888 assert(Numerator && Denominator && "Uninitialized SCEV");
890 SCEVDivision D(SE, Numerator, Denominator);
892 // Check for the trivial case here to avoid having to check for it in the
893 // rest of the code.
894 if (Numerator == Denominator) {
895 *Quotient = D.One;
896 *Remainder = D.Zero;
897 return;
900 if (Numerator->isZero()) {
901 *Quotient = D.Zero;
902 *Remainder = D.Zero;
903 return;
906 // A simple case when N/1. The quotient is N.
907 if (Denominator->isOne()) {
908 *Quotient = Numerator;
909 *Remainder = D.Zero;
910 return;
913 // Split the Denominator when it is a product.
914 if (const SCEVMulExpr *T = dyn_cast<SCEVMulExpr>(Denominator)) {
915 const SCEV *Q, *R;
916 *Quotient = Numerator;
917 for (const SCEV *Op : T->operands()) {
918 divide(SE, *Quotient, Op, &Q, &R);
919 *Quotient = Q;
921 // Bail out when the Numerator is not divisible by one of the terms of
922 // the Denominator.
923 if (!R->isZero()) {
924 *Quotient = D.Zero;
925 *Remainder = Numerator;
926 return;
929 *Remainder = D.Zero;
930 return;
933 D.visit(Numerator);
934 *Quotient = D.Quotient;
935 *Remainder = D.Remainder;
938 // Except in the trivial case described above, we do not know how to divide
939 // Expr by Denominator for the following functions with empty implementation.
940 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
941 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
942 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
943 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
944 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
945 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
946 void visitSMinExpr(const SCEVSMinExpr *Numerator) {}
947 void visitUMinExpr(const SCEVUMinExpr *Numerator) {}
948 void visitUnknown(const SCEVUnknown *Numerator) {}
949 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
951 void visitConstant(const SCEVConstant *Numerator) {
952 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
953 APInt NumeratorVal = Numerator->getAPInt();
954 APInt DenominatorVal = D->getAPInt();
955 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
956 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
958 if (NumeratorBW > DenominatorBW)
959 DenominatorVal = DenominatorVal.sext(NumeratorBW);
960 else if (NumeratorBW < DenominatorBW)
961 NumeratorVal = NumeratorVal.sext(DenominatorBW);
963 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
964 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
965 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
966 Quotient = SE.getConstant(QuotientVal);
967 Remainder = SE.getConstant(RemainderVal);
968 return;
972 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
973 const SCEV *StartQ, *StartR, *StepQ, *StepR;
974 if (!Numerator->isAffine())
975 return cannotDivide(Numerator);
976 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
977 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
978 // Bail out if the types do not match.
979 Type *Ty = Denominator->getType();
980 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
981 Ty != StepQ->getType() || Ty != StepR->getType())
982 return cannotDivide(Numerator);
983 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
984 Numerator->getNoWrapFlags());
985 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
986 Numerator->getNoWrapFlags());
989 void visitAddExpr(const SCEVAddExpr *Numerator) {
990 SmallVector<const SCEV *, 2> Qs, Rs;
991 Type *Ty = Denominator->getType();
993 for (const SCEV *Op : Numerator->operands()) {
994 const SCEV *Q, *R;
995 divide(SE, Op, Denominator, &Q, &R);
997 // Bail out if types do not match.
998 if (Ty != Q->getType() || Ty != R->getType())
999 return cannotDivide(Numerator);
1001 Qs.push_back(Q);
1002 Rs.push_back(R);
1005 if (Qs.size() == 1) {
1006 Quotient = Qs[0];
1007 Remainder = Rs[0];
1008 return;
1011 Quotient = SE.getAddExpr(Qs);
1012 Remainder = SE.getAddExpr(Rs);
1015 void visitMulExpr(const SCEVMulExpr *Numerator) {
1016 SmallVector<const SCEV *, 2> Qs;
1017 Type *Ty = Denominator->getType();
1019 bool FoundDenominatorTerm = false;
1020 for (const SCEV *Op : Numerator->operands()) {
1021 // Bail out if types do not match.
1022 if (Ty != Op->getType())
1023 return cannotDivide(Numerator);
1025 if (FoundDenominatorTerm) {
1026 Qs.push_back(Op);
1027 continue;
1030 // Check whether Denominator divides one of the product operands.
1031 const SCEV *Q, *R;
1032 divide(SE, Op, Denominator, &Q, &R);
1033 if (!R->isZero()) {
1034 Qs.push_back(Op);
1035 continue;
1038 // Bail out if types do not match.
1039 if (Ty != Q->getType())
1040 return cannotDivide(Numerator);
1042 FoundDenominatorTerm = true;
1043 Qs.push_back(Q);
1046 if (FoundDenominatorTerm) {
1047 Remainder = Zero;
1048 if (Qs.size() == 1)
1049 Quotient = Qs[0];
1050 else
1051 Quotient = SE.getMulExpr(Qs);
1052 return;
1055 if (!isa<SCEVUnknown>(Denominator))
1056 return cannotDivide(Numerator);
1058 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
1059 ValueToValueMap RewriteMap;
1060 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1061 cast<SCEVConstant>(Zero)->getValue();
1062 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1064 if (Remainder->isZero()) {
1065 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
1066 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
1067 cast<SCEVConstant>(One)->getValue();
1068 Quotient =
1069 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
1070 return;
1073 // Quotient is (Numerator - Remainder) divided by Denominator.
1074 const SCEV *Q, *R;
1075 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
1076 // This SCEV does not seem to simplify: fail the division here.
1077 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
1078 return cannotDivide(Numerator);
1079 divide(SE, Diff, Denominator, &Q, &R);
1080 if (R != Zero)
1081 return cannotDivide(Numerator);
1082 Quotient = Q;
1085 private:
1086 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
1087 const SCEV *Denominator)
1088 : SE(S), Denominator(Denominator) {
1089 Zero = SE.getZero(Denominator->getType());
1090 One = SE.getOne(Denominator->getType());
1092 // We generally do not know how to divide Expr by Denominator. We
1093 // initialize the division to a "cannot divide" state to simplify the rest
1094 // of the code.
1095 cannotDivide(Numerator);
1098 // Convenience function for giving up on the division. We set the quotient to
1099 // be equal to zero and the remainder to be equal to the numerator.
1100 void cannotDivide(const SCEV *Numerator) {
1101 Quotient = Zero;
1102 Remainder = Numerator;
1105 ScalarEvolution &SE;
1106 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
1109 } // end anonymous namespace
1111 //===----------------------------------------------------------------------===//
1112 // Simple SCEV method implementations
1113 //===----------------------------------------------------------------------===//
1115 /// Compute BC(It, K). The result has width W. Assume, K > 0.
1116 static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
1117 ScalarEvolution &SE,
1118 Type *ResultTy) {
1119 // Handle the simplest case efficiently.
1120 if (K == 1)
1121 return SE.getTruncateOrZeroExtend(It, ResultTy);
1123 // We are using the following formula for BC(It, K):
1125 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
1127 // Suppose, W is the bitwidth of the return value. We must be prepared for
1128 // overflow. Hence, we must assure that the result of our computation is
1129 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
1130 // safe in modular arithmetic.
1132 // However, this code doesn't use exactly that formula; the formula it uses
1133 // is something like the following, where T is the number of factors of 2 in
1134 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
1135 // exponentiation:
1137 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
1139 // This formula is trivially equivalent to the previous formula. However,
1140 // this formula can be implemented much more efficiently. The trick is that
1141 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
1142 // arithmetic. To do exact division in modular arithmetic, all we have
1143 // to do is multiply by the inverse. Therefore, this step can be done at
1144 // width W.
1146 // The next issue is how to safely do the division by 2^T. The way this
1147 // is done is by doing the multiplication step at a width of at least W + T
1148 // bits. This way, the bottom W+T bits of the product are accurate. Then,
1149 // when we perform the division by 2^T (which is equivalent to a right shift
1150 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
1151 // truncated out after the division by 2^T.
1153 // In comparison to just directly using the first formula, this technique
1154 // is much more efficient; using the first formula requires W * K bits,
1155 // but this formula less than W + K bits. Also, the first formula requires
1156 // a division step, whereas this formula only requires multiplies and shifts.
1158 // It doesn't matter whether the subtraction step is done in the calculation
1159 // width or the input iteration count's width; if the subtraction overflows,
1160 // the result must be zero anyway. We prefer here to do it in the width of
1161 // the induction variable because it helps a lot for certain cases; CodeGen
1162 // isn't smart enough to ignore the overflow, which leads to much less
1163 // efficient code if the width of the subtraction is wider than the native
1164 // register width.
1166 // (It's possible to not widen at all by pulling out factors of 2 before
1167 // the multiplication; for example, K=2 can be calculated as
1168 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1169 // extra arithmetic, so it's not an obvious win, and it gets
1170 // much more complicated for K > 3.)
1172 // Protection from insane SCEVs; this bound is conservative,
1173 // but it probably doesn't matter.
1174 if (K > 1000)
1175 return SE.getCouldNotCompute();
1177 unsigned W = SE.getTypeSizeInBits(ResultTy);
1179 // Calculate K! / 2^T and T; we divide out the factors of two before
1180 // multiplying for calculating K! / 2^T to avoid overflow.
1181 // Other overflow doesn't matter because we only care about the bottom
1182 // W bits of the result.
1183 APInt OddFactorial(W, 1);
1184 unsigned T = 1;
1185 for (unsigned i = 3; i <= K; ++i) {
1186 APInt Mult(W, i);
1187 unsigned TwoFactors = Mult.countTrailingZeros();
1188 T += TwoFactors;
1189 Mult.lshrInPlace(TwoFactors);
1190 OddFactorial *= Mult;
1193 // We need at least W + T bits for the multiplication step
1194 unsigned CalculationBits = W + T;
1196 // Calculate 2^T, at width T+W.
1197 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
1199 // Calculate the multiplicative inverse of K! / 2^T;
1200 // this multiplication factor will perform the exact division by
1201 // K! / 2^T.
1202 APInt Mod = APInt::getSignedMinValue(W+1);
1203 APInt MultiplyFactor = OddFactorial.zext(W+1);
1204 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1205 MultiplyFactor = MultiplyFactor.trunc(W);
1207 // Calculate the product, at width T+W
1208 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
1209 CalculationBits);
1210 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
1211 for (unsigned i = 1; i != K; ++i) {
1212 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
1213 Dividend = SE.getMulExpr(Dividend,
1214 SE.getTruncateOrZeroExtend(S, CalculationTy));
1217 // Divide by 2^T
1218 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
1220 // Truncate the result, and divide by K! / 2^T.
1222 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1223 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
1226 /// Return the value of this chain of recurrences at the specified iteration
1227 /// number. We can evaluate this recurrence by multiplying each element in the
1228 /// chain by the binomial coefficient corresponding to it. In other words, we
1229 /// can evaluate {A,+,B,+,C,+,D} as:
1231 /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
1233 /// where BC(It, k) stands for binomial coefficient.
1234 const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
1235 ScalarEvolution &SE) const {
1236 const SCEV *Result = getStart();
1237 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1238 // The computation is correct in the face of overflow provided that the
1239 // multiplication is performed _after_ the evaluation of the binomial
1240 // coefficient.
1241 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
1242 if (isa<SCEVCouldNotCompute>(Coeff))
1243 return Coeff;
1245 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
1247 return Result;
1250 //===----------------------------------------------------------------------===//
1251 // SCEV Expression folder implementations
1252 //===----------------------------------------------------------------------===//
1254 const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
1255 unsigned Depth) {
1256 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
1257 "This is not a truncating conversion!");
1258 assert(isSCEVable(Ty) &&
1259 "This is not a conversion to a SCEVable type!");
1260 Ty = getEffectiveSCEVType(Ty);
1262 FoldingSetNodeID ID;
1263 ID.AddInteger(scTruncate);
1264 ID.AddPointer(Op);
1265 ID.AddPointer(Ty);
1266 void *IP = nullptr;
1267 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1269 // Fold if the operand is constant.
1270 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1271 return getConstant(
1272 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
1274 // trunc(trunc(x)) --> trunc(x)
1275 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
1276 return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
1278 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
1279 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1280 return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
1282 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
1283 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1284 return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
1286 if (Depth > MaxCastDepth) {
1287 SCEV *S =
1288 new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
1289 UniqueSCEVs.InsertNode(S, IP);
1290 addToLoopUseLists(S);
1291 return S;
1294 // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
1295 // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
1296 // if after transforming we have at most one truncate, not counting truncates
1297 // that replace other casts.
1298 if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
1299 auto *CommOp = cast<SCEVCommutativeExpr>(Op);
1300 SmallVector<const SCEV *, 4> Operands;
1301 unsigned numTruncs = 0;
1302 for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
1303 ++i) {
1304 const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
1305 if (!isa<SCEVCastExpr>(CommOp->getOperand(i)) && isa<SCEVTruncateExpr>(S))
1306 numTruncs++;
1307 Operands.push_back(S);
1309 if (numTruncs < 2) {
1310 if (isa<SCEVAddExpr>(Op))
1311 return getAddExpr(Operands);
1312 else if (isa<SCEVMulExpr>(Op))
1313 return getMulExpr(Operands);
1314 else
1315 llvm_unreachable("Unexpected SCEV type for Op.");
1317 // Although we checked in the beginning that ID is not in the cache, it is
1318 // possible that during recursion and different modification ID was inserted
1319 // into the cache. So if we find it, just return it.
1320 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
1321 return S;
1324 // If the input value is a chrec scev, truncate the chrec's operands.
1325 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
1326 SmallVector<const SCEV *, 4> Operands;
1327 for (const SCEV *Op : AddRec->operands())
1328 Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
1329 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
1332 // The cast wasn't folded; create an explicit cast node. We can reuse
1333 // the existing insert position since if we get here, we won't have
1334 // made any changes which would invalidate it.
1335 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1336 Op, Ty);
1337 UniqueSCEVs.InsertNode(S, IP);
1338 addToLoopUseLists(S);
1339 return S;
1342 // Get the limit of a recurrence such that incrementing by Step cannot cause
1343 // signed overflow as long as the value of the recurrence within the
1344 // loop does not exceed this limit before incrementing.
1345 static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1346 ICmpInst::Predicate *Pred,
1347 ScalarEvolution *SE) {
1348 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1349 if (SE->isKnownPositive(Step)) {
1350 *Pred = ICmpInst::ICMP_SLT;
1351 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1352 SE->getSignedRangeMax(Step));
1354 if (SE->isKnownNegative(Step)) {
1355 *Pred = ICmpInst::ICMP_SGT;
1356 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1357 SE->getSignedRangeMin(Step));
1359 return nullptr;
1362 // Get the limit of a recurrence such that incrementing by Step cannot cause
1363 // unsigned overflow as long as the value of the recurrence within the loop does
1364 // not exceed this limit before incrementing.
1365 static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1366 ICmpInst::Predicate *Pred,
1367 ScalarEvolution *SE) {
1368 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1369 *Pred = ICmpInst::ICMP_ULT;
1371 return SE->getConstant(APInt::getMinValue(BitWidth) -
1372 SE->getUnsignedRangeMax(Step));
1375 namespace {
1377 struct ExtendOpTraitsBase {
1378 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
1379 unsigned);
1382 // Used to make code generic over signed and unsigned overflow.
1383 template <typename ExtendOp> struct ExtendOpTraits {
1384 // Members present:
1386 // static const SCEV::NoWrapFlags WrapType;
1388 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1390 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1391 // ICmpInst::Predicate *Pred,
1392 // ScalarEvolution *SE);
1395 template <>
1396 struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1397 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1399 static const GetExtendExprTy GetExtendExpr;
1401 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1402 ICmpInst::Predicate *Pred,
1403 ScalarEvolution *SE) {
1404 return getSignedOverflowLimitForStep(Step, Pred, SE);
1408 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1409 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1411 template <>
1412 struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1413 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1415 static const GetExtendExprTy GetExtendExpr;
1417 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1418 ICmpInst::Predicate *Pred,
1419 ScalarEvolution *SE) {
1420 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1424 const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
1425 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
1427 } // end anonymous namespace
1429 // The recurrence AR has been shown to have no signed/unsigned wrap or something
1430 // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1431 // easily prove NSW/NUW for its preincrement or postincrement sibling. This
1432 // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1433 // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1434 // expression "Step + sext/zext(PreIncAR)" is congruent with
1435 // "sext/zext(PostIncAR)"
1436 template <typename ExtendOpTy>
1437 static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1438 ScalarEvolution *SE, unsigned Depth) {
1439 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1440 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1442 const Loop *L = AR->getLoop();
1443 const SCEV *Start = AR->getStart();
1444 const SCEV *Step = AR->getStepRecurrence(*SE);
1446 // Check for a simple looking step prior to loop entry.
1447 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1448 if (!SA)
1449 return nullptr;
1451 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1452 // subtraction is expensive. For this purpose, perform a quick and dirty
1453 // difference, by checking for Step in the operand list.
1454 SmallVector<const SCEV *, 4> DiffOps;
1455 for (const SCEV *Op : SA->operands())
1456 if (Op != Step)
1457 DiffOps.push_back(Op);
1459 if (DiffOps.size() == SA->getNumOperands())
1460 return nullptr;
1462 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1463 // `Step`:
1465 // 1. NSW/NUW flags on the step increment.
1466 auto PreStartFlags =
1467 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1468 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
1469 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1470 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1472 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1473 // "S+X does not sign/unsign-overflow".
1476 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1477 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1478 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
1479 return PreStart;
1481 // 2. Direct overflow check on the step operation's expression.
1482 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1483 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1484 const SCEV *OperandExtendedStart =
1485 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
1486 (SE->*GetExtendExpr)(Step, WideTy, Depth));
1487 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
1488 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1489 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1490 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1491 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1492 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1494 return PreStart;
1497 // 3. Loop precondition.
1498 ICmpInst::Predicate Pred;
1499 const SCEV *OverflowLimit =
1500 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1502 if (OverflowLimit &&
1503 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
1504 return PreStart;
1506 return nullptr;
1509 // Get the normalized zero or sign extended expression for this AddRec's Start.
1510 template <typename ExtendOpTy>
1511 static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1512 ScalarEvolution *SE,
1513 unsigned Depth) {
1514 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1516 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
1517 if (!PreStart)
1518 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
1520 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
1521 Depth),
1522 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
1525 // Try to prove away overflow by looking at "nearby" add recurrences. A
1526 // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1527 // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1529 // Formally:
1531 // {S,+,X} == {S-T,+,X} + T
1532 // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1534 // If ({S-T,+,X} + T) does not overflow ... (1)
1536 // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1538 // If {S-T,+,X} does not overflow ... (2)
1540 // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1541 // == {Ext(S-T)+Ext(T),+,Ext(X)}
1543 // If (S-T)+T does not overflow ... (3)
1545 // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1546 // == {Ext(S),+,Ext(X)} == LHS
1548 // Thus, if (1), (2) and (3) are true for some T, then
1549 // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1551 // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1552 // does not overflow" restricted to the 0th iteration. Therefore we only need
1553 // to check for (1) and (2).
1555 // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1556 // is `Delta` (defined below).
1557 template <typename ExtendOpTy>
1558 bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1559 const SCEV *Step,
1560 const Loop *L) {
1561 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1563 // We restrict `Start` to a constant to prevent SCEV from spending too much
1564 // time here. It is correct (but more expensive) to continue with a
1565 // non-constant `Start` and do a general SCEV subtraction to compute
1566 // `PreStart` below.
1567 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1568 if (!StartC)
1569 return false;
1571 APInt StartAI = StartC->getAPInt();
1573 for (unsigned Delta : {-2, -1, 1, 2}) {
1574 const SCEV *PreStart = getConstant(StartAI - Delta);
1576 FoldingSetNodeID ID;
1577 ID.AddInteger(scAddRecExpr);
1578 ID.AddPointer(PreStart);
1579 ID.AddPointer(Step);
1580 ID.AddPointer(L);
1581 void *IP = nullptr;
1582 const auto *PreAR =
1583 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1585 // Give up if we don't already have the add recurrence we need because
1586 // actually constructing an add recurrence is relatively expensive.
1587 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1588 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1589 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1590 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1591 DeltaS, &Pred, this);
1592 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1593 return true;
1597 return false;
1600 // Finds an integer D for an expression (C + x + y + ...) such that the top
1601 // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
1602 // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
1603 // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
1604 // the (C + x + y + ...) expression is \p WholeAddExpr.
1605 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1606 const SCEVConstant *ConstantTerm,
1607 const SCEVAddExpr *WholeAddExpr) {
1608 const APInt C = ConstantTerm->getAPInt();
1609 const unsigned BitWidth = C.getBitWidth();
1610 // Find number of trailing zeros of (x + y + ...) w/o the C first:
1611 uint32_t TZ = BitWidth;
1612 for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
1613 TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
1614 if (TZ) {
1615 // Set D to be as many least significant bits of C as possible while still
1616 // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
1617 return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
1619 return APInt(BitWidth, 0);
1622 // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
1623 // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
1624 // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
1625 // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
1626 static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
1627 const APInt &ConstantStart,
1628 const SCEV *Step) {
1629 const unsigned BitWidth = ConstantStart.getBitWidth();
1630 const uint32_t TZ = SE.GetMinTrailingZeros(Step);
1631 if (TZ)
1632 return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
1633 : ConstantStart;
1634 return APInt(BitWidth, 0);
1637 const SCEV *
1638 ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1639 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1640 "This is not an extending conversion!");
1641 assert(isSCEVable(Ty) &&
1642 "This is not a conversion to a SCEVable type!");
1643 Ty = getEffectiveSCEVType(Ty);
1645 // Fold if the operand is constant.
1646 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1647 return getConstant(
1648 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
1650 // zext(zext(x)) --> zext(x)
1651 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1652 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1654 // Before doing any expensive analysis, check to see if we've already
1655 // computed a SCEV for this Op and Ty.
1656 FoldingSetNodeID ID;
1657 ID.AddInteger(scZeroExtend);
1658 ID.AddPointer(Op);
1659 ID.AddPointer(Ty);
1660 void *IP = nullptr;
1661 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1662 if (Depth > MaxCastDepth) {
1663 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1664 Op, Ty);
1665 UniqueSCEVs.InsertNode(S, IP);
1666 addToLoopUseLists(S);
1667 return S;
1670 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1671 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1672 // It's possible the bits taken off by the truncate were all zero bits. If
1673 // so, we should be able to simplify this further.
1674 const SCEV *X = ST->getOperand();
1675 ConstantRange CR = getUnsignedRange(X);
1676 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1677 unsigned NewBits = getTypeSizeInBits(Ty);
1678 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
1679 CR.zextOrTrunc(NewBits)))
1680 return getTruncateOrZeroExtend(X, Ty, Depth);
1683 // If the input value is a chrec scev, and we can prove that the value
1684 // did not overflow the old, smaller, value, we can zero extend all of the
1685 // operands (often constants). This allows analysis of something like
1686 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
1687 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
1688 if (AR->isAffine()) {
1689 const SCEV *Start = AR->getStart();
1690 const SCEV *Step = AR->getStepRecurrence(*this);
1691 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1692 const Loop *L = AR->getLoop();
1694 if (!AR->hasNoUnsignedWrap()) {
1695 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1696 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1699 // If we have special knowledge that this addrec won't overflow,
1700 // we don't need to do any further analysis.
1701 if (AR->hasNoUnsignedWrap())
1702 return getAddRecExpr(
1703 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1704 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1706 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1707 // Note that this serves two purposes: It filters out loops that are
1708 // simply not analyzable, and it covers the case where this code is
1709 // being called from within backedge-taken count analysis, such that
1710 // attempting to ask for the backedge-taken count would likely result
1711 // in infinite recursion. In the later case, the analysis code will
1712 // cope with a conservative value, and it will take care to purge
1713 // that value once it has finished.
1714 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
1715 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
1716 // Manually compute the final value for AR, checking for
1717 // overflow.
1719 // Check whether the backedge-taken count can be losslessly casted to
1720 // the addrec's type. The count is always unsigned.
1721 const SCEV *CastedMaxBECount =
1722 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
1723 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
1724 CastedMaxBECount, MaxBECount->getType(), Depth);
1725 if (MaxBECount == RecastedMaxBECount) {
1726 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
1727 // Check whether Start+Step*MaxBECount has no unsigned overflow.
1728 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
1729 SCEV::FlagAnyWrap, Depth + 1);
1730 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
1731 SCEV::FlagAnyWrap,
1732 Depth + 1),
1733 WideTy, Depth + 1);
1734 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
1735 const SCEV *WideMaxBECount =
1736 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
1737 const SCEV *OperandExtendedAdd =
1738 getAddExpr(WideStart,
1739 getMulExpr(WideMaxBECount,
1740 getZeroExtendExpr(Step, WideTy, Depth + 1),
1741 SCEV::FlagAnyWrap, Depth + 1),
1742 SCEV::FlagAnyWrap, Depth + 1);
1743 if (ZAdd == OperandExtendedAdd) {
1744 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1745 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1746 // Return the expression with the addrec on the outside.
1747 return getAddRecExpr(
1748 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1749 Depth + 1),
1750 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1751 AR->getNoWrapFlags());
1753 // Similar to above, only this time treat the step value as signed.
1754 // This covers loops that count down.
1755 OperandExtendedAdd =
1756 getAddExpr(WideStart,
1757 getMulExpr(WideMaxBECount,
1758 getSignExtendExpr(Step, WideTy, Depth + 1),
1759 SCEV::FlagAnyWrap, Depth + 1),
1760 SCEV::FlagAnyWrap, Depth + 1);
1761 if (ZAdd == OperandExtendedAdd) {
1762 // Cache knowledge of AR NW, which is propagated to this AddRec.
1763 // Negative step causes unsigned wrap, but it still can't self-wrap.
1764 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1765 // Return the expression with the addrec on the outside.
1766 return getAddRecExpr(
1767 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1768 Depth + 1),
1769 getSignExtendExpr(Step, Ty, Depth + 1), L,
1770 AR->getNoWrapFlags());
1775 // Normally, in the cases we can prove no-overflow via a
1776 // backedge guarding condition, we can also compute a backedge
1777 // taken count for the loop. The exceptions are assumptions and
1778 // guards present in the loop -- SCEV is not great at exploiting
1779 // these to compute max backedge taken counts, but can still use
1780 // these to prove lack of overflow. Use this fact to avoid
1781 // doing extra work that may not pay off.
1782 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
1783 !AC.assumptions().empty()) {
1784 // If the backedge is guarded by a comparison with the pre-inc
1785 // value the addrec is safe. Also, if the entry is guarded by
1786 // a comparison with the start value and the backedge is
1787 // guarded by a comparison with the post-inc value, the addrec
1788 // is safe.
1789 if (isKnownPositive(Step)) {
1790 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1791 getUnsignedRangeMax(Step));
1792 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
1793 isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
1794 // Cache knowledge of AR NUW, which is propagated to this
1795 // AddRec.
1796 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1797 // Return the expression with the addrec on the outside.
1798 return getAddRecExpr(
1799 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1800 Depth + 1),
1801 getZeroExtendExpr(Step, Ty, Depth + 1), L,
1802 AR->getNoWrapFlags());
1804 } else if (isKnownNegative(Step)) {
1805 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1806 getSignedRangeMin(Step));
1807 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1808 isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
1809 // Cache knowledge of AR NW, which is propagated to this
1810 // AddRec. Negative step causes unsigned wrap, but it
1811 // still can't self-wrap.
1812 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1813 // Return the expression with the addrec on the outside.
1814 return getAddRecExpr(
1815 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
1816 Depth + 1),
1817 getSignExtendExpr(Step, Ty, Depth + 1), L,
1818 AR->getNoWrapFlags());
1823 // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
1824 // if D + (C - D + Step * n) could be proven to not unsigned wrap
1825 // where D maximizes the number of trailing zeros of (C - D + Step * n)
1826 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
1827 const APInt &C = SC->getAPInt();
1828 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
1829 if (D != 0) {
1830 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1831 const SCEV *SResidual =
1832 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
1833 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1834 return getAddExpr(SZExtD, SZExtR,
1835 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1836 Depth + 1);
1840 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1841 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1842 return getAddRecExpr(
1843 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1),
1844 getZeroExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
1848 // zext(A % B) --> zext(A) % zext(B)
1850 const SCEV *LHS;
1851 const SCEV *RHS;
1852 if (matchURem(Op, LHS, RHS))
1853 return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
1854 getZeroExtendExpr(RHS, Ty, Depth + 1));
1857 // zext(A / B) --> zext(A) / zext(B).
1858 if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
1859 return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
1860 getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
1862 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1863 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
1864 if (SA->hasNoUnsignedWrap()) {
1865 // If the addition does not unsign overflow then we can, by definition,
1866 // commute the zero extension with the addition operation.
1867 SmallVector<const SCEV *, 4> Ops;
1868 for (const auto *Op : SA->operands())
1869 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1870 return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
1873 // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
1874 // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
1875 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
1877 // Often address arithmetics contain expressions like
1878 // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
1879 // This transformation is useful while proving that such expressions are
1880 // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
1881 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
1882 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
1883 if (D != 0) {
1884 const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
1885 const SCEV *SResidual =
1886 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
1887 const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
1888 return getAddExpr(SZExtD, SZExtR,
1889 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
1890 Depth + 1);
1895 if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
1896 // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
1897 if (SM->hasNoUnsignedWrap()) {
1898 // If the multiply does not unsign overflow then we can, by definition,
1899 // commute the zero extension with the multiply operation.
1900 SmallVector<const SCEV *, 4> Ops;
1901 for (const auto *Op : SM->operands())
1902 Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
1903 return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
1906 // zext(2^K * (trunc X to iN)) to iM ->
1907 // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
1909 // Proof:
1911 // zext(2^K * (trunc X to iN)) to iM
1912 // = zext((trunc X to iN) << K) to iM
1913 // = zext((trunc X to i{N-K}) << K)<nuw> to iM
1914 // (because shl removes the top K bits)
1915 // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
1916 // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
1918 if (SM->getNumOperands() == 2)
1919 if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
1920 if (MulLHS->getAPInt().isPowerOf2())
1921 if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
1922 int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
1923 MulLHS->getAPInt().logBase2();
1924 Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
1925 return getMulExpr(
1926 getZeroExtendExpr(MulLHS, Ty),
1927 getZeroExtendExpr(
1928 getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
1929 SCEV::FlagNUW, Depth + 1);
1933 // The cast wasn't folded; create an explicit cast node.
1934 // Recompute the insert position, as it may have been invalidated.
1935 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1936 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1937 Op, Ty);
1938 UniqueSCEVs.InsertNode(S, IP);
1939 addToLoopUseLists(S);
1940 return S;
1943 const SCEV *
1944 ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
1945 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1946 "This is not an extending conversion!");
1947 assert(isSCEVable(Ty) &&
1948 "This is not a conversion to a SCEVable type!");
1949 Ty = getEffectiveSCEVType(Ty);
1951 // Fold if the operand is constant.
1952 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1953 return getConstant(
1954 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
1956 // sext(sext(x)) --> sext(x)
1957 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
1958 return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
1960 // sext(zext(x)) --> zext(x)
1961 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1962 return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
1964 // Before doing any expensive analysis, check to see if we've already
1965 // computed a SCEV for this Op and Ty.
1966 FoldingSetNodeID ID;
1967 ID.AddInteger(scSignExtend);
1968 ID.AddPointer(Op);
1969 ID.AddPointer(Ty);
1970 void *IP = nullptr;
1971 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1972 // Limit recursion depth.
1973 if (Depth > MaxCastDepth) {
1974 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1975 Op, Ty);
1976 UniqueSCEVs.InsertNode(S, IP);
1977 addToLoopUseLists(S);
1978 return S;
1981 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1982 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1983 // It's possible the bits taken off by the truncate were all sign bits. If
1984 // so, we should be able to simplify this further.
1985 const SCEV *X = ST->getOperand();
1986 ConstantRange CR = getSignedRange(X);
1987 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1988 unsigned NewBits = getTypeSizeInBits(Ty);
1989 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
1990 CR.sextOrTrunc(NewBits)))
1991 return getTruncateOrSignExtend(X, Ty, Depth);
1994 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1995 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
1996 if (SA->hasNoSignedWrap()) {
1997 // If the addition does not sign overflow then we can, by definition,
1998 // commute the sign extension with the addition operation.
1999 SmallVector<const SCEV *, 4> Ops;
2000 for (const auto *Op : SA->operands())
2001 Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
2002 return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
2005 // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
2006 // if D + (C - D + x + y + ...) could be proven to not signed wrap
2007 // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
2009 // For instance, this will bring two seemingly different expressions:
2010 // 1 + sext(5 + 20 * %x + 24 * %y) and
2011 // sext(6 + 20 * %x + 24 * %y)
2012 // to the same form:
2013 // 2 + sext(4 + 20 * %x + 24 * %y)
2014 if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
2015 const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
2016 if (D != 0) {
2017 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2018 const SCEV *SResidual =
2019 getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
2020 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2021 return getAddExpr(SSExtD, SSExtR,
2022 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2023 Depth + 1);
2027 // If the input value is a chrec scev, and we can prove that the value
2028 // did not overflow the old, smaller, value, we can sign extend all of the
2029 // operands (often constants). This allows analysis of something like
2030 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
2031 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
2032 if (AR->isAffine()) {
2033 const SCEV *Start = AR->getStart();
2034 const SCEV *Step = AR->getStepRecurrence(*this);
2035 unsigned BitWidth = getTypeSizeInBits(AR->getType());
2036 const Loop *L = AR->getLoop();
2038 if (!AR->hasNoSignedWrap()) {
2039 auto NewFlags = proveNoWrapViaConstantRanges(AR);
2040 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
2043 // If we have special knowledge that this addrec won't overflow,
2044 // we don't need to do any further analysis.
2045 if (AR->hasNoSignedWrap())
2046 return getAddRecExpr(
2047 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2048 getSignExtendExpr(Step, Ty, Depth + 1), L, SCEV::FlagNSW);
2050 // Check whether the backedge-taken count is SCEVCouldNotCompute.
2051 // Note that this serves two purposes: It filters out loops that are
2052 // simply not analyzable, and it covers the case where this code is
2053 // being called from within backedge-taken count analysis, such that
2054 // attempting to ask for the backedge-taken count would likely result
2055 // in infinite recursion. In the later case, the analysis code will
2056 // cope with a conservative value, and it will take care to purge
2057 // that value once it has finished.
2058 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
2059 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
2060 // Manually compute the final value for AR, checking for
2061 // overflow.
2063 // Check whether the backedge-taken count can be losslessly casted to
2064 // the addrec's type. The count is always unsigned.
2065 const SCEV *CastedMaxBECount =
2066 getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
2067 const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
2068 CastedMaxBECount, MaxBECount->getType(), Depth);
2069 if (MaxBECount == RecastedMaxBECount) {
2070 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
2071 // Check whether Start+Step*MaxBECount has no signed overflow.
2072 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
2073 SCEV::FlagAnyWrap, Depth + 1);
2074 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
2075 SCEV::FlagAnyWrap,
2076 Depth + 1),
2077 WideTy, Depth + 1);
2078 const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
2079 const SCEV *WideMaxBECount =
2080 getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
2081 const SCEV *OperandExtendedAdd =
2082 getAddExpr(WideStart,
2083 getMulExpr(WideMaxBECount,
2084 getSignExtendExpr(Step, WideTy, Depth + 1),
2085 SCEV::FlagAnyWrap, Depth + 1),
2086 SCEV::FlagAnyWrap, Depth + 1);
2087 if (SAdd == OperandExtendedAdd) {
2088 // Cache knowledge of AR NSW, which is propagated to this AddRec.
2089 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2090 // Return the expression with the addrec on the outside.
2091 return getAddRecExpr(
2092 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2093 Depth + 1),
2094 getSignExtendExpr(Step, Ty, Depth + 1), L,
2095 AR->getNoWrapFlags());
2097 // Similar to above, only this time treat the step value as unsigned.
2098 // This covers loops that count up with an unsigned step.
2099 OperandExtendedAdd =
2100 getAddExpr(WideStart,
2101 getMulExpr(WideMaxBECount,
2102 getZeroExtendExpr(Step, WideTy, Depth + 1),
2103 SCEV::FlagAnyWrap, Depth + 1),
2104 SCEV::FlagAnyWrap, Depth + 1);
2105 if (SAdd == OperandExtendedAdd) {
2106 // If AR wraps around then
2108 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
2109 // => SAdd != OperandExtendedAdd
2111 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
2112 // (SAdd == OperandExtendedAdd => AR is NW)
2114 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
2116 // Return the expression with the addrec on the outside.
2117 return getAddRecExpr(
2118 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
2119 Depth + 1),
2120 getZeroExtendExpr(Step, Ty, Depth + 1), L,
2121 AR->getNoWrapFlags());
2126 // Normally, in the cases we can prove no-overflow via a
2127 // backedge guarding condition, we can also compute a backedge
2128 // taken count for the loop. The exceptions are assumptions and
2129 // guards present in the loop -- SCEV is not great at exploiting
2130 // these to compute max backedge taken counts, but can still use
2131 // these to prove lack of overflow. Use this fact to avoid
2132 // doing extra work that may not pay off.
2134 if (!isa<SCEVCouldNotCompute>(MaxBECount) || HasGuards ||
2135 !AC.assumptions().empty()) {
2136 // If the backedge is guarded by a comparison with the pre-inc
2137 // value the addrec is safe. Also, if the entry is guarded by
2138 // a comparison with the start value and the backedge is
2139 // guarded by a comparison with the post-inc value, the addrec
2140 // is safe.
2141 ICmpInst::Predicate Pred;
2142 const SCEV *OverflowLimit =
2143 getSignedOverflowLimitForStep(Step, &Pred, this);
2144 if (OverflowLimit &&
2145 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
2146 isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
2147 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
2148 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2149 return getAddRecExpr(
2150 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2151 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2155 // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
2156 // if D + (C - D + Step * n) could be proven to not signed wrap
2157 // where D maximizes the number of trailing zeros of (C - D + Step * n)
2158 if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
2159 const APInt &C = SC->getAPInt();
2160 const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
2161 if (D != 0) {
2162 const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
2163 const SCEV *SResidual =
2164 getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
2165 const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
2166 return getAddExpr(SSExtD, SSExtR,
2167 (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
2168 Depth + 1);
2172 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
2173 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
2174 return getAddRecExpr(
2175 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1),
2176 getSignExtendExpr(Step, Ty, Depth + 1), L, AR->getNoWrapFlags());
2180 // If the input value is provably positive and we could not simplify
2181 // away the sext build a zext instead.
2182 if (isKnownNonNegative(Op))
2183 return getZeroExtendExpr(Op, Ty, Depth + 1);
2185 // The cast wasn't folded; create an explicit cast node.
2186 // Recompute the insert position, as it may have been invalidated.
2187 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2188 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
2189 Op, Ty);
2190 UniqueSCEVs.InsertNode(S, IP);
2191 addToLoopUseLists(S);
2192 return S;
2195 /// getAnyExtendExpr - Return a SCEV for the given operand extended with
2196 /// unspecified bits out to the given type.
2197 const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
2198 Type *Ty) {
2199 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
2200 "This is not an extending conversion!");
2201 assert(isSCEVable(Ty) &&
2202 "This is not a conversion to a SCEVable type!");
2203 Ty = getEffectiveSCEVType(Ty);
2205 // Sign-extend negative constants.
2206 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
2207 if (SC->getAPInt().isNegative())
2208 return getSignExtendExpr(Op, Ty);
2210 // Peel off a truncate cast.
2211 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
2212 const SCEV *NewOp = T->getOperand();
2213 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
2214 return getAnyExtendExpr(NewOp, Ty);
2215 return getTruncateOrNoop(NewOp, Ty);
2218 // Next try a zext cast. If the cast is folded, use it.
2219 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
2220 if (!isa<SCEVZeroExtendExpr>(ZExt))
2221 return ZExt;
2223 // Next try a sext cast. If the cast is folded, use it.
2224 const SCEV *SExt = getSignExtendExpr(Op, Ty);
2225 if (!isa<SCEVSignExtendExpr>(SExt))
2226 return SExt;
2228 // Force the cast to be folded into the operands of an addrec.
2229 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
2230 SmallVector<const SCEV *, 4> Ops;
2231 for (const SCEV *Op : AR->operands())
2232 Ops.push_back(getAnyExtendExpr(Op, Ty));
2233 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
2236 // If the expression is obviously signed, use the sext cast value.
2237 if (isa<SCEVSMaxExpr>(Op))
2238 return SExt;
2240 // Absent any other information, use the zext cast value.
2241 return ZExt;
2244 /// Process the given Ops list, which is a list of operands to be added under
2245 /// the given scale, update the given map. This is a helper function for
2246 /// getAddRecExpr. As an example of what it does, given a sequence of operands
2247 /// that would form an add expression like this:
2249 /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
2251 /// where A and B are constants, update the map with these values:
2253 /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
2255 /// and add 13 + A*B*29 to AccumulatedConstant.
2256 /// This will allow getAddRecExpr to produce this:
2258 /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
2260 /// This form often exposes folding opportunities that are hidden in
2261 /// the original operand list.
2263 /// Return true iff it appears that any interesting folding opportunities
2264 /// may be exposed. This helps getAddRecExpr short-circuit extra work in
2265 /// the common case where no interesting opportunities are present, and
2266 /// is also used as a check to avoid infinite recursion.
2267 static bool
2268 CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
2269 SmallVectorImpl<const SCEV *> &NewOps,
2270 APInt &AccumulatedConstant,
2271 const SCEV *const *Ops, size_t NumOperands,
2272 const APInt &Scale,
2273 ScalarEvolution &SE) {
2274 bool Interesting = false;
2276 // Iterate over the add operands. They are sorted, with constants first.
2277 unsigned i = 0;
2278 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2279 ++i;
2280 // Pull a buried constant out to the outside.
2281 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
2282 Interesting = true;
2283 AccumulatedConstant += Scale * C->getAPInt();
2286 // Next comes everything else. We're especially interested in multiplies
2287 // here, but they're in the middle, so just visit the rest with one loop.
2288 for (; i != NumOperands; ++i) {
2289 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
2290 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
2291 APInt NewScale =
2292 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
2293 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
2294 // A multiplication of a constant with another add; recurse.
2295 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
2296 Interesting |=
2297 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2298 Add->op_begin(), Add->getNumOperands(),
2299 NewScale, SE);
2300 } else {
2301 // A multiplication of a constant with some other value. Update
2302 // the map.
2303 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
2304 const SCEV *Key = SE.getMulExpr(MulOps);
2305 auto Pair = M.insert({Key, NewScale});
2306 if (Pair.second) {
2307 NewOps.push_back(Pair.first->first);
2308 } else {
2309 Pair.first->second += NewScale;
2310 // The map already had an entry for this value, which may indicate
2311 // a folding opportunity.
2312 Interesting = true;
2315 } else {
2316 // An ordinary operand. Update the map.
2317 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
2318 M.insert({Ops[i], Scale});
2319 if (Pair.second) {
2320 NewOps.push_back(Pair.first->first);
2321 } else {
2322 Pair.first->second += Scale;
2323 // The map already had an entry for this value, which may indicate
2324 // a folding opportunity.
2325 Interesting = true;
2330 return Interesting;
2333 // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
2334 // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
2335 // can't-overflow flags for the operation if possible.
2336 static SCEV::NoWrapFlags
2337 StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
2338 const ArrayRef<const SCEV *> Ops,
2339 SCEV::NoWrapFlags Flags) {
2340 using namespace std::placeholders;
2342 using OBO = OverflowingBinaryOperator;
2344 bool CanAnalyze =
2345 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
2346 (void)CanAnalyze;
2347 assert(CanAnalyze && "don't call from other places!");
2349 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2350 SCEV::NoWrapFlags SignOrUnsignWrap =
2351 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2353 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
2354 auto IsKnownNonNegative = [&](const SCEV *S) {
2355 return SE->isKnownNonNegative(S);
2358 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
2359 Flags =
2360 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
2362 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
2364 if (SignOrUnsignWrap != SignOrUnsignMask &&
2365 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
2366 isa<SCEVConstant>(Ops[0])) {
2368 auto Opcode = [&] {
2369 switch (Type) {
2370 case scAddExpr:
2371 return Instruction::Add;
2372 case scMulExpr:
2373 return Instruction::Mul;
2374 default:
2375 llvm_unreachable("Unexpected SCEV op.");
2377 }();
2379 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
2381 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
2382 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
2383 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2384 Opcode, C, OBO::NoSignedWrap);
2385 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
2386 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
2389 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
2390 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
2391 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
2392 Opcode, C, OBO::NoUnsignedWrap);
2393 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
2394 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
2398 return Flags;
2401 bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
2402 return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
2405 /// Get a canonical add expression, or something simpler if possible.
2406 const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
2407 SCEV::NoWrapFlags Flags,
2408 unsigned Depth) {
2409 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2410 "only nuw or nsw allowed");
2411 assert(!Ops.empty() && "Cannot get empty add!");
2412 if (Ops.size() == 1) return Ops[0];
2413 #ifndef NDEBUG
2414 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2415 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2416 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2417 "SCEVAddExpr operand types don't match!");
2418 #endif
2420 // Sort by complexity, this groups all similar expression types together.
2421 GroupByComplexity(Ops, &LI, DT);
2423 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2425 // If there are any constants, fold them together.
2426 unsigned Idx = 0;
2427 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2428 ++Idx;
2429 assert(Idx < Ops.size());
2430 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2431 // We found two constants, fold them together!
2432 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
2433 if (Ops.size() == 2) return Ops[0];
2434 Ops.erase(Ops.begin()+1); // Erase the folded element
2435 LHSC = cast<SCEVConstant>(Ops[0]);
2438 // If we are left with a constant zero being added, strip it off.
2439 if (LHSC->getValue()->isZero()) {
2440 Ops.erase(Ops.begin());
2441 --Idx;
2444 if (Ops.size() == 1) return Ops[0];
2447 // Limit recursion calls depth.
2448 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2449 return getOrCreateAddExpr(Ops, Flags);
2451 // Okay, check to see if the same value occurs in the operand list more than
2452 // once. If so, merge them together into an multiply expression. Since we
2453 // sorted the list, these values are required to be adjacent.
2454 Type *Ty = Ops[0]->getType();
2455 bool FoundMatch = false;
2456 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
2457 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
2458 // Scan ahead to count how many equal operands there are.
2459 unsigned Count = 2;
2460 while (i+Count != e && Ops[i+Count] == Ops[i])
2461 ++Count;
2462 // Merge the values into a multiply.
2463 const SCEV *Scale = getConstant(Ty, Count);
2464 const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
2465 if (Ops.size() == Count)
2466 return Mul;
2467 Ops[i] = Mul;
2468 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
2469 --i; e -= Count - 1;
2470 FoundMatch = true;
2472 if (FoundMatch)
2473 return getAddExpr(Ops, Flags, Depth + 1);
2475 // Check for truncates. If all the operands are truncated from the same
2476 // type, see if factoring out the truncate would permit the result to be
2477 // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
2478 // if the contents of the resulting outer trunc fold to something simple.
2479 auto FindTruncSrcType = [&]() -> Type * {
2480 // We're ultimately looking to fold an addrec of truncs and muls of only
2481 // constants and truncs, so if we find any other types of SCEV
2482 // as operands of the addrec then we bail and return nullptr here.
2483 // Otherwise, we return the type of the operand of a trunc that we find.
2484 if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
2485 return T->getOperand()->getType();
2486 if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
2487 const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
2488 if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
2489 return T->getOperand()->getType();
2491 return nullptr;
2493 if (auto *SrcType = FindTruncSrcType()) {
2494 SmallVector<const SCEV *, 8> LargeOps;
2495 bool Ok = true;
2496 // Check all the operands to see if they can be represented in the
2497 // source type of the truncate.
2498 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2499 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2500 if (T->getOperand()->getType() != SrcType) {
2501 Ok = false;
2502 break;
2504 LargeOps.push_back(T->getOperand());
2505 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
2506 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
2507 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
2508 SmallVector<const SCEV *, 8> LargeMulOps;
2509 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2510 if (const SCEVTruncateExpr *T =
2511 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2512 if (T->getOperand()->getType() != SrcType) {
2513 Ok = false;
2514 break;
2516 LargeMulOps.push_back(T->getOperand());
2517 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
2518 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
2519 } else {
2520 Ok = false;
2521 break;
2524 if (Ok)
2525 LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
2526 } else {
2527 Ok = false;
2528 break;
2531 if (Ok) {
2532 // Evaluate the expression in the larger type.
2533 const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
2534 // If it folds to something simple, use it. Otherwise, don't.
2535 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2536 return getTruncateExpr(Fold, Ty);
2540 // Skip past any other cast SCEVs.
2541 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2542 ++Idx;
2544 // If there are add operands they would be next.
2545 if (Idx < Ops.size()) {
2546 bool DeletedAdd = false;
2547 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
2548 if (Ops.size() > AddOpsInlineThreshold ||
2549 Add->getNumOperands() > AddOpsInlineThreshold)
2550 break;
2551 // If we have an add, expand the add operands onto the end of the operands
2552 // list.
2553 Ops.erase(Ops.begin()+Idx);
2554 Ops.append(Add->op_begin(), Add->op_end());
2555 DeletedAdd = true;
2558 // If we deleted at least one add, we added operands to the end of the list,
2559 // and they are not necessarily sorted. Recurse to resort and resimplify
2560 // any operands we just acquired.
2561 if (DeletedAdd)
2562 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2565 // Skip over the add expression until we get to a multiply.
2566 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2567 ++Idx;
2569 // Check to see if there are any folding opportunities present with
2570 // operands multiplied by constant values.
2571 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2572 uint64_t BitWidth = getTypeSizeInBits(Ty);
2573 DenseMap<const SCEV *, APInt> M;
2574 SmallVector<const SCEV *, 8> NewOps;
2575 APInt AccumulatedConstant(BitWidth, 0);
2576 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
2577 Ops.data(), Ops.size(),
2578 APInt(BitWidth, 1), *this)) {
2579 struct APIntCompare {
2580 bool operator()(const APInt &LHS, const APInt &RHS) const {
2581 return LHS.ult(RHS);
2585 // Some interesting folding opportunity is present, so its worthwhile to
2586 // re-generate the operands list. Group the operands by constant scale,
2587 // to avoid multiplying by the same constant scale multiple times.
2588 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
2589 for (const SCEV *NewOp : NewOps)
2590 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
2591 // Re-generate the operands list.
2592 Ops.clear();
2593 if (AccumulatedConstant != 0)
2594 Ops.push_back(getConstant(AccumulatedConstant));
2595 for (auto &MulOp : MulOpLists)
2596 if (MulOp.first != 0)
2597 Ops.push_back(getMulExpr(
2598 getConstant(MulOp.first),
2599 getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
2600 SCEV::FlagAnyWrap, Depth + 1));
2601 if (Ops.empty())
2602 return getZero(Ty);
2603 if (Ops.size() == 1)
2604 return Ops[0];
2605 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2609 // If we are adding something to a multiply expression, make sure the
2610 // something is not already an operand of the multiply. If so, merge it into
2611 // the multiply.
2612 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
2613 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
2614 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
2615 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
2616 if (isa<SCEVConstant>(MulOpSCEV))
2617 continue;
2618 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
2619 if (MulOpSCEV == Ops[AddOp]) {
2620 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
2621 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
2622 if (Mul->getNumOperands() != 2) {
2623 // If the multiply has more than two operands, we must get the
2624 // Y*Z term.
2625 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2626 Mul->op_begin()+MulOp);
2627 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2628 InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2630 SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
2631 const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2632 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
2633 SCEV::FlagAnyWrap, Depth + 1);
2634 if (Ops.size() == 2) return OuterMul;
2635 if (AddOp < Idx) {
2636 Ops.erase(Ops.begin()+AddOp);
2637 Ops.erase(Ops.begin()+Idx-1);
2638 } else {
2639 Ops.erase(Ops.begin()+Idx);
2640 Ops.erase(Ops.begin()+AddOp-1);
2642 Ops.push_back(OuterMul);
2643 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2646 // Check this multiply against other multiplies being added together.
2647 for (unsigned OtherMulIdx = Idx+1;
2648 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2649 ++OtherMulIdx) {
2650 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
2651 // If MulOp occurs in OtherMul, we can fold the two multiplies
2652 // together.
2653 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2654 OMulOp != e; ++OMulOp)
2655 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2656 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
2657 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
2658 if (Mul->getNumOperands() != 2) {
2659 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2660 Mul->op_begin()+MulOp);
2661 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
2662 InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2664 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
2665 if (OtherMul->getNumOperands() != 2) {
2666 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
2667 OtherMul->op_begin()+OMulOp);
2668 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
2669 InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
2671 SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
2672 const SCEV *InnerMulSum =
2673 getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2674 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
2675 SCEV::FlagAnyWrap, Depth + 1);
2676 if (Ops.size() == 2) return OuterMul;
2677 Ops.erase(Ops.begin()+Idx);
2678 Ops.erase(Ops.begin()+OtherMulIdx-1);
2679 Ops.push_back(OuterMul);
2680 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2686 // If there are any add recurrences in the operands list, see if any other
2687 // added values are loop invariant. If so, we can fold them into the
2688 // recurrence.
2689 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2690 ++Idx;
2692 // Scan over all recurrences, trying to fold loop invariants into them.
2693 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2694 // Scan all of the other operands to this add and add them to the vector if
2695 // they are loop invariant w.r.t. the recurrence.
2696 SmallVector<const SCEV *, 8> LIOps;
2697 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
2698 const Loop *AddRecLoop = AddRec->getLoop();
2699 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2700 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
2701 LIOps.push_back(Ops[i]);
2702 Ops.erase(Ops.begin()+i);
2703 --i; --e;
2706 // If we found some loop invariants, fold them into the recurrence.
2707 if (!LIOps.empty()) {
2708 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
2709 LIOps.push_back(AddRec->getStart());
2711 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2712 AddRec->op_end());
2713 // This follows from the fact that the no-wrap flags on the outer add
2714 // expression are applicable on the 0th iteration, when the add recurrence
2715 // will be equal to its start value.
2716 AddRecOps[0] = getAddExpr(LIOps, Flags, Depth + 1);
2718 // Build the new addrec. Propagate the NUW and NSW flags if both the
2719 // outer add and the inner addrec are guaranteed to have no overflow.
2720 // Always propagate NW.
2721 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
2722 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
2724 // If all of the other operands were loop invariant, we are done.
2725 if (Ops.size() == 1) return NewRec;
2727 // Otherwise, add the folded AddRec by the non-invariant parts.
2728 for (unsigned i = 0;; ++i)
2729 if (Ops[i] == AddRec) {
2730 Ops[i] = NewRec;
2731 break;
2733 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2736 // Okay, if there weren't any loop invariants to be folded, check to see if
2737 // there are multiple AddRec's with the same loop induction variable being
2738 // added together. If so, we can fold them.
2739 for (unsigned OtherIdx = Idx+1;
2740 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2741 ++OtherIdx) {
2742 // We expect the AddRecExpr's to be sorted in reverse dominance order,
2743 // so that the 1st found AddRecExpr is dominated by all others.
2744 assert(DT.dominates(
2745 cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
2746 AddRec->getLoop()->getHeader()) &&
2747 "AddRecExprs are not sorted in reverse dominance order?");
2748 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2749 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2750 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2751 AddRec->op_end());
2752 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2753 ++OtherIdx) {
2754 const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2755 if (OtherAddRec->getLoop() == AddRecLoop) {
2756 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2757 i != e; ++i) {
2758 if (i >= AddRecOps.size()) {
2759 AddRecOps.append(OtherAddRec->op_begin()+i,
2760 OtherAddRec->op_end());
2761 break;
2763 SmallVector<const SCEV *, 2> TwoOps = {
2764 AddRecOps[i], OtherAddRec->getOperand(i)};
2765 AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
2767 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2770 // Step size has changed, so we cannot guarantee no self-wraparound.
2771 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
2772 return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
2776 // Otherwise couldn't fold anything into this recurrence. Move onto the
2777 // next one.
2780 // Okay, it looks like we really DO need an add expr. Check to see if we
2781 // already have one, otherwise create a new one.
2782 return getOrCreateAddExpr(Ops, Flags);
2785 const SCEV *
2786 ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
2787 SCEV::NoWrapFlags Flags) {
2788 FoldingSetNodeID ID;
2789 ID.AddInteger(scAddExpr);
2790 for (const SCEV *Op : Ops)
2791 ID.AddPointer(Op);
2792 void *IP = nullptr;
2793 SCEVAddExpr *S =
2794 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2795 if (!S) {
2796 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2797 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2798 S = new (SCEVAllocator)
2799 SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
2800 UniqueSCEVs.InsertNode(S, IP);
2801 addToLoopUseLists(S);
2803 S->setNoWrapFlags(Flags);
2804 return S;
2807 const SCEV *
2808 ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
2809 const Loop *L, SCEV::NoWrapFlags Flags) {
2810 FoldingSetNodeID ID;
2811 ID.AddInteger(scAddRecExpr);
2812 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2813 ID.AddPointer(Ops[i]);
2814 ID.AddPointer(L);
2815 void *IP = nullptr;
2816 SCEVAddRecExpr *S =
2817 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2818 if (!S) {
2819 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2820 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2821 S = new (SCEVAllocator)
2822 SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
2823 UniqueSCEVs.InsertNode(S, IP);
2824 addToLoopUseLists(S);
2826 S->setNoWrapFlags(Flags);
2827 return S;
2830 const SCEV *
2831 ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
2832 SCEV::NoWrapFlags Flags) {
2833 FoldingSetNodeID ID;
2834 ID.AddInteger(scMulExpr);
2835 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2836 ID.AddPointer(Ops[i]);
2837 void *IP = nullptr;
2838 SCEVMulExpr *S =
2839 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2840 if (!S) {
2841 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2842 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
2843 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2844 O, Ops.size());
2845 UniqueSCEVs.InsertNode(S, IP);
2846 addToLoopUseLists(S);
2848 S->setNoWrapFlags(Flags);
2849 return S;
2852 static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2853 uint64_t k = i*j;
2854 if (j > 1 && k / j != i) Overflow = true;
2855 return k;
2858 /// Compute the result of "n choose k", the binomial coefficient. If an
2859 /// intermediate computation overflows, Overflow will be set and the return will
2860 /// be garbage. Overflow is not cleared on absence of overflow.
2861 static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2862 // We use the multiplicative formula:
2863 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2864 // At each iteration, we take the n-th term of the numeral and divide by the
2865 // (k-n)th term of the denominator. This division will always produce an
2866 // integral result, and helps reduce the chance of overflow in the
2867 // intermediate computations. However, we can still overflow even when the
2868 // final result would fit.
2870 if (n == 0 || n == k) return 1;
2871 if (k > n) return 0;
2873 if (k > n/2)
2874 k = n-k;
2876 uint64_t r = 1;
2877 for (uint64_t i = 1; i <= k; ++i) {
2878 r = umul_ov(r, n-(i-1), Overflow);
2879 r /= i;
2881 return r;
2884 /// Determine if any of the operands in this SCEV are a constant or if
2885 /// any of the add or multiply expressions in this SCEV contain a constant.
2886 static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
2887 struct FindConstantInAddMulChain {
2888 bool FoundConstant = false;
2890 bool follow(const SCEV *S) {
2891 FoundConstant |= isa<SCEVConstant>(S);
2892 return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
2895 bool isDone() const {
2896 return FoundConstant;
2900 FindConstantInAddMulChain F;
2901 SCEVTraversal<FindConstantInAddMulChain> ST(F);
2902 ST.visitAll(StartExpr);
2903 return F.FoundConstant;
2906 /// Get a canonical multiply expression, or something simpler if possible.
2907 const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
2908 SCEV::NoWrapFlags Flags,
2909 unsigned Depth) {
2910 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2911 "only nuw or nsw allowed");
2912 assert(!Ops.empty() && "Cannot get empty mul!");
2913 if (Ops.size() == 1) return Ops[0];
2914 #ifndef NDEBUG
2915 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
2916 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2917 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
2918 "SCEVMulExpr operand types don't match!");
2919 #endif
2921 // Sort by complexity, this groups all similar expression types together.
2922 GroupByComplexity(Ops, &LI, DT);
2924 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2926 // Limit recursion calls depth.
2927 if (Depth > MaxArithDepth || hasHugeExpression(Ops))
2928 return getOrCreateMulExpr(Ops, Flags);
2930 // If there are any constants, fold them together.
2931 unsigned Idx = 0;
2932 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
2934 if (Ops.size() == 2)
2935 // C1*(C2+V) -> C1*C2 + C1*V
2936 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2937 // If any of Add's ops are Adds or Muls with a constant, apply this
2938 // transformation as well.
2940 // TODO: There are some cases where this transformation is not
2941 // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
2942 // this transformation should be narrowed down.
2943 if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add))
2944 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0),
2945 SCEV::FlagAnyWrap, Depth + 1),
2946 getMulExpr(LHSC, Add->getOperand(1),
2947 SCEV::FlagAnyWrap, Depth + 1),
2948 SCEV::FlagAnyWrap, Depth + 1);
2950 ++Idx;
2951 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
2952 // We found two constants, fold them together!
2953 ConstantInt *Fold =
2954 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
2955 Ops[0] = getConstant(Fold);
2956 Ops.erase(Ops.begin()+1); // Erase the folded element
2957 if (Ops.size() == 1) return Ops[0];
2958 LHSC = cast<SCEVConstant>(Ops[0]);
2961 // If we are left with a constant one being multiplied, strip it off.
2962 if (cast<SCEVConstant>(Ops[0])->getValue()->isOne()) {
2963 Ops.erase(Ops.begin());
2964 --Idx;
2965 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
2966 // If we have a multiply of zero, it will always be zero.
2967 return Ops[0];
2968 } else if (Ops[0]->isAllOnesValue()) {
2969 // If we have a mul by -1 of an add, try distributing the -1 among the
2970 // add operands.
2971 if (Ops.size() == 2) {
2972 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2973 SmallVector<const SCEV *, 4> NewOps;
2974 bool AnyFolded = false;
2975 for (const SCEV *AddOp : Add->operands()) {
2976 const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
2977 Depth + 1);
2978 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2979 NewOps.push_back(Mul);
2981 if (AnyFolded)
2982 return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
2983 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2984 // Negation preserves a recurrence's no self-wrap property.
2985 SmallVector<const SCEV *, 4> Operands;
2986 for (const SCEV *AddRecOp : AddRec->operands())
2987 Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
2988 Depth + 1));
2990 return getAddRecExpr(Operands, AddRec->getLoop(),
2991 AddRec->getNoWrapFlags(SCEV::FlagNW));
2996 if (Ops.size() == 1)
2997 return Ops[0];
3000 // Skip over the add expression until we get to a multiply.
3001 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
3002 ++Idx;
3004 // If there are mul operands inline them all into this expression.
3005 if (Idx < Ops.size()) {
3006 bool DeletedMul = false;
3007 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
3008 if (Ops.size() > MulOpsInlineThreshold)
3009 break;
3010 // If we have an mul, expand the mul operands onto the end of the
3011 // operands list.
3012 Ops.erase(Ops.begin()+Idx);
3013 Ops.append(Mul->op_begin(), Mul->op_end());
3014 DeletedMul = true;
3017 // If we deleted at least one mul, we added operands to the end of the
3018 // list, and they are not necessarily sorted. Recurse to resort and
3019 // resimplify any operands we just acquired.
3020 if (DeletedMul)
3021 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3024 // If there are any add recurrences in the operands list, see if any other
3025 // added values are loop invariant. If so, we can fold them into the
3026 // recurrence.
3027 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
3028 ++Idx;
3030 // Scan over all recurrences, trying to fold loop invariants into them.
3031 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
3032 // Scan all of the other operands to this mul and add them to the vector
3033 // if they are loop invariant w.r.t. the recurrence.
3034 SmallVector<const SCEV *, 8> LIOps;
3035 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
3036 const Loop *AddRecLoop = AddRec->getLoop();
3037 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3038 if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
3039 LIOps.push_back(Ops[i]);
3040 Ops.erase(Ops.begin()+i);
3041 --i; --e;
3044 // If we found some loop invariants, fold them into the recurrence.
3045 if (!LIOps.empty()) {
3046 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
3047 SmallVector<const SCEV *, 4> NewOps;
3048 NewOps.reserve(AddRec->getNumOperands());
3049 const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
3050 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
3051 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
3052 SCEV::FlagAnyWrap, Depth + 1));
3054 // Build the new addrec. Propagate the NUW and NSW flags if both the
3055 // outer mul and the inner addrec are guaranteed to have no overflow.
3057 // No self-wrap cannot be guaranteed after changing the step size, but
3058 // will be inferred if either NUW or NSW is true.
3059 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
3060 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
3062 // If all of the other operands were loop invariant, we are done.
3063 if (Ops.size() == 1) return NewRec;
3065 // Otherwise, multiply the folded AddRec by the non-invariant parts.
3066 for (unsigned i = 0;; ++i)
3067 if (Ops[i] == AddRec) {
3068 Ops[i] = NewRec;
3069 break;
3071 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3074 // Okay, if there weren't any loop invariants to be folded, check to see
3075 // if there are multiple AddRec's with the same loop induction variable
3076 // being multiplied together. If so, we can fold them.
3078 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
3079 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
3080 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
3081 // ]]],+,...up to x=2n}.
3082 // Note that the arguments to choose() are always integers with values
3083 // known at compile time, never SCEV objects.
3085 // The implementation avoids pointless extra computations when the two
3086 // addrec's are of different length (mathematically, it's equivalent to
3087 // an infinite stream of zeros on the right).
3088 bool OpsModified = false;
3089 for (unsigned OtherIdx = Idx+1;
3090 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
3091 ++OtherIdx) {
3092 const SCEVAddRecExpr *OtherAddRec =
3093 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
3094 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
3095 continue;
3097 // Limit max number of arguments to avoid creation of unreasonably big
3098 // SCEVAddRecs with very complex operands.
3099 if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
3100 MaxAddRecSize || isHugeExpression(AddRec) ||
3101 isHugeExpression(OtherAddRec))
3102 continue;
3104 bool Overflow = false;
3105 Type *Ty = AddRec->getType();
3106 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
3107 SmallVector<const SCEV*, 7> AddRecOps;
3108 for (int x = 0, xe = AddRec->getNumOperands() +
3109 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
3110 SmallVector <const SCEV *, 7> SumOps;
3111 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
3112 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
3113 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
3114 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
3115 z < ze && !Overflow; ++z) {
3116 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
3117 uint64_t Coeff;
3118 if (LargerThan64Bits)
3119 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
3120 else
3121 Coeff = Coeff1*Coeff2;
3122 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
3123 const SCEV *Term1 = AddRec->getOperand(y-z);
3124 const SCEV *Term2 = OtherAddRec->getOperand(z);
3125 SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
3126 SCEV::FlagAnyWrap, Depth + 1));
3129 if (SumOps.empty())
3130 SumOps.push_back(getZero(Ty));
3131 AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
3133 if (!Overflow) {
3134 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
3135 SCEV::FlagAnyWrap);
3136 if (Ops.size() == 2) return NewAddRec;
3137 Ops[Idx] = NewAddRec;
3138 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
3139 OpsModified = true;
3140 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
3141 if (!AddRec)
3142 break;
3145 if (OpsModified)
3146 return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
3148 // Otherwise couldn't fold anything into this recurrence. Move onto the
3149 // next one.
3152 // Okay, it looks like we really DO need an mul expr. Check to see if we
3153 // already have one, otherwise create a new one.
3154 return getOrCreateMulExpr(Ops, Flags);
3157 /// Represents an unsigned remainder expression based on unsigned division.
3158 const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
3159 const SCEV *RHS) {
3160 assert(getEffectiveSCEVType(LHS->getType()) ==
3161 getEffectiveSCEVType(RHS->getType()) &&
3162 "SCEVURemExpr operand types don't match!");
3164 // Short-circuit easy cases
3165 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3166 // If constant is one, the result is trivial
3167 if (RHSC->getValue()->isOne())
3168 return getZero(LHS->getType()); // X urem 1 --> 0
3170 // If constant is a power of two, fold into a zext(trunc(LHS)).
3171 if (RHSC->getAPInt().isPowerOf2()) {
3172 Type *FullTy = LHS->getType();
3173 Type *TruncTy =
3174 IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
3175 return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
3179 // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
3180 const SCEV *UDiv = getUDivExpr(LHS, RHS);
3181 const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
3182 return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
3185 /// Get a canonical unsigned division expression, or something simpler if
3186 /// possible.
3187 const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
3188 const SCEV *RHS) {
3189 assert(getEffectiveSCEVType(LHS->getType()) ==
3190 getEffectiveSCEVType(RHS->getType()) &&
3191 "SCEVUDivExpr operand types don't match!");
3193 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
3194 if (RHSC->getValue()->isOne())
3195 return LHS; // X udiv 1 --> x
3196 // If the denominator is zero, the result of the udiv is undefined. Don't
3197 // try to analyze it, because the resolution chosen here may differ from
3198 // the resolution chosen in other parts of the compiler.
3199 if (!RHSC->getValue()->isZero()) {
3200 // Determine if the division can be folded into the operands of
3201 // its operands.
3202 // TODO: Generalize this to non-constants by using known-bits information.
3203 Type *Ty = LHS->getType();
3204 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
3205 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
3206 // For non-power-of-two values, effectively round the value up to the
3207 // nearest power of two.
3208 if (!RHSC->getAPInt().isPowerOf2())
3209 ++MaxShiftAmt;
3210 IntegerType *ExtTy =
3211 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
3212 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
3213 if (const SCEVConstant *Step =
3214 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
3215 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
3216 const APInt &StepInt = Step->getAPInt();
3217 const APInt &DivInt = RHSC->getAPInt();
3218 if (!StepInt.urem(DivInt) &&
3219 getZeroExtendExpr(AR, ExtTy) ==
3220 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3221 getZeroExtendExpr(Step, ExtTy),
3222 AR->getLoop(), SCEV::FlagAnyWrap)) {
3223 SmallVector<const SCEV *, 4> Operands;
3224 for (const SCEV *Op : AR->operands())
3225 Operands.push_back(getUDivExpr(Op, RHS));
3226 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
3228 /// Get a canonical UDivExpr for a recurrence.
3229 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
3230 // We can currently only fold X%N if X is constant.
3231 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
3232 if (StartC && !DivInt.urem(StepInt) &&
3233 getZeroExtendExpr(AR, ExtTy) ==
3234 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
3235 getZeroExtendExpr(Step, ExtTy),
3236 AR->getLoop(), SCEV::FlagAnyWrap)) {
3237 const APInt &StartInt = StartC->getAPInt();
3238 const APInt &StartRem = StartInt.urem(StepInt);
3239 if (StartRem != 0)
3240 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
3241 AR->getLoop(), SCEV::FlagNW);
3244 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
3245 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
3246 SmallVector<const SCEV *, 4> Operands;
3247 for (const SCEV *Op : M->operands())
3248 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3249 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
3250 // Find an operand that's safely divisible.
3251 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
3252 const SCEV *Op = M->getOperand(i);
3253 const SCEV *Div = getUDivExpr(Op, RHSC);
3254 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
3255 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
3256 M->op_end());
3257 Operands[i] = Div;
3258 return getMulExpr(Operands);
3263 // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
3264 if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
3265 if (auto *DivisorConstant =
3266 dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
3267 bool Overflow = false;
3268 APInt NewRHS =
3269 DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
3270 if (Overflow) {
3271 return getConstant(RHSC->getType(), 0, false);
3273 return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
3277 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
3278 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
3279 SmallVector<const SCEV *, 4> Operands;
3280 for (const SCEV *Op : A->operands())
3281 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
3282 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
3283 Operands.clear();
3284 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
3285 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
3286 if (isa<SCEVUDivExpr>(Op) ||
3287 getMulExpr(Op, RHS) != A->getOperand(i))
3288 break;
3289 Operands.push_back(Op);
3291 if (Operands.size() == A->getNumOperands())
3292 return getAddExpr(Operands);
3296 // Fold if both operands are constant.
3297 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
3298 Constant *LHSCV = LHSC->getValue();
3299 Constant *RHSCV = RHSC->getValue();
3300 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
3301 RHSCV)));
3306 FoldingSetNodeID ID;
3307 ID.AddInteger(scUDivExpr);
3308 ID.AddPointer(LHS);
3309 ID.AddPointer(RHS);
3310 void *IP = nullptr;
3311 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
3312 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
3313 LHS, RHS);
3314 UniqueSCEVs.InsertNode(S, IP);
3315 addToLoopUseLists(S);
3316 return S;
3319 static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
3320 APInt A = C1->getAPInt().abs();
3321 APInt B = C2->getAPInt().abs();
3322 uint32_t ABW = A.getBitWidth();
3323 uint32_t BBW = B.getBitWidth();
3325 if (ABW > BBW)
3326 B = B.zext(ABW);
3327 else if (ABW < BBW)
3328 A = A.zext(BBW);
3330 return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
3333 /// Get a canonical unsigned division expression, or something simpler if
3334 /// possible. There is no representation for an exact udiv in SCEV IR, but we
3335 /// can attempt to remove factors from the LHS and RHS. We can't do this when
3336 /// it's not exact because the udiv may be clearing bits.
3337 const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
3338 const SCEV *RHS) {
3339 // TODO: we could try to find factors in all sorts of things, but for now we
3340 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
3341 // end of this file for inspiration.
3343 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
3344 if (!Mul || !Mul->hasNoUnsignedWrap())
3345 return getUDivExpr(LHS, RHS);
3347 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
3348 // If the mulexpr multiplies by a constant, then that constant must be the
3349 // first element of the mulexpr.
3350 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3351 if (LHSCst == RHSCst) {
3352 SmallVector<const SCEV *, 2> Operands;
3353 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3354 return getMulExpr(Operands);
3357 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
3358 // that there's a factor provided by one of the other terms. We need to
3359 // check.
3360 APInt Factor = gcd(LHSCst, RHSCst);
3361 if (!Factor.isIntN(1)) {
3362 LHSCst =
3363 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
3364 RHSCst =
3365 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
3366 SmallVector<const SCEV *, 2> Operands;
3367 Operands.push_back(LHSCst);
3368 Operands.append(Mul->op_begin() + 1, Mul->op_end());
3369 LHS = getMulExpr(Operands);
3370 RHS = RHSCst;
3371 Mul = dyn_cast<SCEVMulExpr>(LHS);
3372 if (!Mul)
3373 return getUDivExactExpr(LHS, RHS);
3378 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
3379 if (Mul->getOperand(i) == RHS) {
3380 SmallVector<const SCEV *, 2> Operands;
3381 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
3382 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
3383 return getMulExpr(Operands);
3387 return getUDivExpr(LHS, RHS);
3390 /// Get an add recurrence expression for the specified loop. Simplify the
3391 /// expression as much as possible.
3392 const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
3393 const Loop *L,
3394 SCEV::NoWrapFlags Flags) {
3395 SmallVector<const SCEV *, 4> Operands;
3396 Operands.push_back(Start);
3397 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
3398 if (StepChrec->getLoop() == L) {
3399 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
3400 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
3403 Operands.push_back(Step);
3404 return getAddRecExpr(Operands, L, Flags);
3407 /// Get an add recurrence expression for the specified loop. Simplify the
3408 /// expression as much as possible.
3409 const SCEV *
3410 ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
3411 const Loop *L, SCEV::NoWrapFlags Flags) {
3412 if (Operands.size() == 1) return Operands[0];
3413 #ifndef NDEBUG
3414 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
3415 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
3416 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
3417 "SCEVAddRecExpr operand types don't match!");
3418 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
3419 assert(isLoopInvariant(Operands[i], L) &&
3420 "SCEVAddRecExpr operand is not loop-invariant!");
3421 #endif
3423 if (Operands.back()->isZero()) {
3424 Operands.pop_back();
3425 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
3428 // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
3429 // use that information to infer NUW and NSW flags. However, computing a
3430 // BE count requires calling getAddRecExpr, so we may not yet have a
3431 // meaningful BE count at this point (and if we don't, we'd be stuck
3432 // with a SCEVCouldNotCompute as the cached BE count).
3434 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
3436 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
3437 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
3438 const Loop *NestedLoop = NestedAR->getLoop();
3439 if (L->contains(NestedLoop)
3440 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
3441 : (!NestedLoop->contains(L) &&
3442 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
3443 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
3444 NestedAR->op_end());
3445 Operands[0] = NestedAR->getStart();
3446 // AddRecs require their operands be loop-invariant with respect to their
3447 // loops. Don't perform this transformation if it would break this
3448 // requirement.
3449 bool AllInvariant = all_of(
3450 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
3452 if (AllInvariant) {
3453 // Create a recurrence for the outer loop with the same step size.
3455 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
3456 // inner recurrence has the same property.
3457 SCEV::NoWrapFlags OuterFlags =
3458 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
3460 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
3461 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
3462 return isLoopInvariant(Op, NestedLoop);
3465 if (AllInvariant) {
3466 // Ok, both add recurrences are valid after the transformation.
3468 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
3469 // the outer recurrence has the same property.
3470 SCEV::NoWrapFlags InnerFlags =
3471 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
3472 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
3475 // Reset Operands to its original state.
3476 Operands[0] = NestedAR;
3480 // Okay, it looks like we really DO need an addrec expr. Check to see if we
3481 // already have one, otherwise create a new one.
3482 return getOrCreateAddRecExpr(Operands, L, Flags);
3485 const SCEV *
3486 ScalarEvolution::getGEPExpr(GEPOperator *GEP,
3487 const SmallVectorImpl<const SCEV *> &IndexExprs) {
3488 const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
3489 // getSCEV(Base)->getType() has the same address space as Base->getType()
3490 // because SCEV::getType() preserves the address space.
3491 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
3492 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
3493 // instruction to its SCEV, because the Instruction may be guarded by control
3494 // flow and the no-overflow bits may not be valid for the expression in any
3495 // context. This can be fixed similarly to how these flags are handled for
3496 // adds.
3497 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW
3498 : SCEV::FlagAnyWrap;
3500 const SCEV *TotalOffset = getZero(IntPtrTy);
3501 // The array size is unimportant. The first thing we do on CurTy is getting
3502 // its element type.
3503 Type *CurTy = ArrayType::get(GEP->getSourceElementType(), 0);
3504 for (const SCEV *IndexExpr : IndexExprs) {
3505 // Compute the (potentially symbolic) offset in bytes for this index.
3506 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
3507 // For a struct, add the member offset.
3508 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
3509 unsigned FieldNo = Index->getZExtValue();
3510 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
3512 // Add the field offset to the running total offset.
3513 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
3515 // Update CurTy to the type of the field at Index.
3516 CurTy = STy->getTypeAtIndex(Index);
3517 } else {
3518 // Update CurTy to its element type.
3519 CurTy = cast<SequentialType>(CurTy)->getElementType();
3520 // For an array, add the element offset, explicitly scaled.
3521 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
3522 // Getelementptr indices are signed.
3523 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
3525 // Multiply the index by the element size to compute the element offset.
3526 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
3528 // Add the element offset to the running total offset.
3529 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
3533 // Add the total offset from all the GEP indices to the base.
3534 return getAddExpr(BaseExpr, TotalOffset, Wrap);
3537 std::tuple<const SCEV *, FoldingSetNodeID, void *>
3538 ScalarEvolution::findExistingSCEVInCache(int SCEVType,
3539 ArrayRef<const SCEV *> Ops) {
3540 FoldingSetNodeID ID;
3541 void *IP = nullptr;
3542 ID.AddInteger(SCEVType);
3543 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3544 ID.AddPointer(Ops[i]);
3545 return std::tuple<const SCEV *, FoldingSetNodeID, void *>(
3546 UniqueSCEVs.FindNodeOrInsertPos(ID, IP), std::move(ID), IP);
3549 const SCEV *ScalarEvolution::getMinMaxExpr(unsigned Kind,
3550 SmallVectorImpl<const SCEV *> &Ops) {
3551 assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
3552 if (Ops.size() == 1) return Ops[0];
3553 #ifndef NDEBUG
3554 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
3555 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
3556 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
3557 "Operand types don't match!");
3558 #endif
3560 bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
3561 bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
3563 // Sort by complexity, this groups all similar expression types together.
3564 GroupByComplexity(Ops, &LI, DT);
3566 // Check if we have created the same expression before.
3567 if (const SCEV *S = std::get<0>(findExistingSCEVInCache(Kind, Ops))) {
3568 return S;
3571 // If there are any constants, fold them together.
3572 unsigned Idx = 0;
3573 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
3574 ++Idx;
3575 assert(Idx < Ops.size());
3576 auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
3577 if (Kind == scSMaxExpr)
3578 return APIntOps::smax(LHS, RHS);
3579 else if (Kind == scSMinExpr)
3580 return APIntOps::smin(LHS, RHS);
3581 else if (Kind == scUMaxExpr)
3582 return APIntOps::umax(LHS, RHS);
3583 else if (Kind == scUMinExpr)
3584 return APIntOps::umin(LHS, RHS);
3585 llvm_unreachable("Unknown SCEV min/max opcode");
3588 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
3589 // We found two constants, fold them together!
3590 ConstantInt *Fold = ConstantInt::get(
3591 getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
3592 Ops[0] = getConstant(Fold);
3593 Ops.erase(Ops.begin()+1); // Erase the folded element
3594 if (Ops.size() == 1) return Ops[0];
3595 LHSC = cast<SCEVConstant>(Ops[0]);
3598 bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
3599 bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
3601 if (IsMax ? IsMinV : IsMaxV) {
3602 // If we are left with a constant minimum(/maximum)-int, strip it off.
3603 Ops.erase(Ops.begin());
3604 --Idx;
3605 } else if (IsMax ? IsMaxV : IsMinV) {
3606 // If we have a max(/min) with a constant maximum(/minimum)-int,
3607 // it will always be the extremum.
3608 return LHSC;
3611 if (Ops.size() == 1) return Ops[0];
3614 // Find the first operation of the same kind
3615 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
3616 ++Idx;
3618 // Check to see if one of the operands is of the same kind. If so, expand its
3619 // operands onto our operand list, and recurse to simplify.
3620 if (Idx < Ops.size()) {
3621 bool DeletedAny = false;
3622 while (Ops[Idx]->getSCEVType() == Kind) {
3623 const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
3624 Ops.erase(Ops.begin()+Idx);
3625 Ops.append(SMME->op_begin(), SMME->op_end());
3626 DeletedAny = true;
3629 if (DeletedAny)
3630 return getMinMaxExpr(Kind, Ops);
3633 // Okay, check to see if the same value occurs in the operand list twice. If
3634 // so, delete one. Since we sorted the list, these values are required to
3635 // be adjacent.
3636 llvm::CmpInst::Predicate GEPred =
3637 IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
3638 llvm::CmpInst::Predicate LEPred =
3639 IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
3640 llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
3641 llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
3642 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
3643 if (Ops[i] == Ops[i + 1] ||
3644 isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
3645 // X op Y op Y --> X op Y
3646 // X op Y --> X, if we know X, Y are ordered appropriately
3647 Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
3648 --i;
3649 --e;
3650 } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
3651 Ops[i + 1])) {
3652 // X op Y --> Y, if we know X, Y are ordered appropriately
3653 Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
3654 --i;
3655 --e;
3659 if (Ops.size() == 1) return Ops[0];
3661 assert(!Ops.empty() && "Reduced smax down to nothing!");
3663 // Okay, it looks like we really DO need an expr. Check to see if we
3664 // already have one, otherwise create a new one.
3665 const SCEV *ExistingSCEV;
3666 FoldingSetNodeID ID;
3667 void *IP;
3668 std::tie(ExistingSCEV, ID, IP) = findExistingSCEVInCache(Kind, Ops);
3669 if (ExistingSCEV)
3670 return ExistingSCEV;
3671 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3672 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
3673 SCEV *S = new (SCEVAllocator) SCEVMinMaxExpr(
3674 ID.Intern(SCEVAllocator), static_cast<SCEVTypes>(Kind), O, Ops.size());
3676 UniqueSCEVs.InsertNode(S, IP);
3677 addToLoopUseLists(S);
3678 return S;
3681 const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3682 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3683 return getSMaxExpr(Ops);
3686 const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3687 return getMinMaxExpr(scSMaxExpr, Ops);
3690 const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
3691 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
3692 return getUMaxExpr(Ops);
3695 const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
3696 return getMinMaxExpr(scUMaxExpr, Ops);
3699 const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3700 const SCEV *RHS) {
3701 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3702 return getSMinExpr(Ops);
3705 const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3706 return getMinMaxExpr(scSMinExpr, Ops);
3709 const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3710 const SCEV *RHS) {
3711 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
3712 return getUMinExpr(Ops);
3715 const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
3716 return getMinMaxExpr(scUMinExpr, Ops);
3719 const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
3720 // We can bypass creating a target-independent
3721 // constant expression and then folding it back into a ConstantInt.
3722 // This is just a compile-time optimization.
3723 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
3726 const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3727 StructType *STy,
3728 unsigned FieldNo) {
3729 // We can bypass creating a target-independent
3730 // constant expression and then folding it back into a ConstantInt.
3731 // This is just a compile-time optimization.
3732 return getConstant(
3733 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
3736 const SCEV *ScalarEvolution::getUnknown(Value *V) {
3737 // Don't attempt to do anything other than create a SCEVUnknown object
3738 // here. createSCEV only calls getUnknown after checking for all other
3739 // interesting possibilities, and any other code that calls getUnknown
3740 // is doing so in order to hide a value from SCEV canonicalization.
3742 FoldingSetNodeID ID;
3743 ID.AddInteger(scUnknown);
3744 ID.AddPointer(V);
3745 void *IP = nullptr;
3746 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3747 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3748 "Stale SCEVUnknown in uniquing map!");
3749 return S;
3751 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3752 FirstUnknown);
3753 FirstUnknown = cast<SCEVUnknown>(S);
3754 UniqueSCEVs.InsertNode(S, IP);
3755 return S;
3758 //===----------------------------------------------------------------------===//
3759 // Basic SCEV Analysis and PHI Idiom Recognition Code
3762 /// Test if values of the given type are analyzable within the SCEV
3763 /// framework. This primarily includes integer types, and it can optionally
3764 /// include pointer types if the ScalarEvolution class has access to
3765 /// target-specific information.
3766 bool ScalarEvolution::isSCEVable(Type *Ty) const {
3767 // Integers and pointers are always SCEVable.
3768 return Ty->isIntOrPtrTy();
3771 /// Return the size in bits of the specified type, for which isSCEVable must
3772 /// return true.
3773 uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
3774 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3775 if (Ty->isPointerTy())
3776 return getDataLayout().getIndexTypeSizeInBits(Ty);
3777 return getDataLayout().getTypeSizeInBits(Ty);
3780 /// Return a type with the same bitwidth as the given type and which represents
3781 /// how SCEV will treat the given type, for which isSCEVable must return
3782 /// true. For pointer types, this is the pointer-sized integer type.
3783 Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
3784 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3786 if (Ty->isIntegerTy())
3787 return Ty;
3789 // The only other support type is pointer.
3790 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
3791 return getDataLayout().getIntPtrType(Ty);
3794 Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
3795 return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
3798 const SCEV *ScalarEvolution::getCouldNotCompute() {
3799 return CouldNotCompute.get();
3802 bool ScalarEvolution::checkValidity(const SCEV *S) const {
3803 bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
3804 auto *SU = dyn_cast<SCEVUnknown>(S);
3805 return SU && SU->getValue() == nullptr;
3808 return !ContainsNulls;
3811 bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3812 HasRecMapType::iterator I = HasRecMap.find(S);
3813 if (I != HasRecMap.end())
3814 return I->second;
3816 bool FoundAddRec = SCEVExprContains(S, isa<SCEVAddRecExpr, const SCEV *>);
3817 HasRecMap.insert({S, FoundAddRec});
3818 return FoundAddRec;
3821 /// Try to split a SCEVAddExpr into a pair of {SCEV, ConstantInt}.
3822 /// If \p S is a SCEVAddExpr and is composed of a sub SCEV S' and an
3823 /// offset I, then return {S', I}, else return {\p S, nullptr}.
3824 static std::pair<const SCEV *, ConstantInt *> splitAddExpr(const SCEV *S) {
3825 const auto *Add = dyn_cast<SCEVAddExpr>(S);
3826 if (!Add)
3827 return {S, nullptr};
3829 if (Add->getNumOperands() != 2)
3830 return {S, nullptr};
3832 auto *ConstOp = dyn_cast<SCEVConstant>(Add->getOperand(0));
3833 if (!ConstOp)
3834 return {S, nullptr};
3836 return {Add->getOperand(1), ConstOp->getValue()};
3839 /// Return the ValueOffsetPair set for \p S. \p S can be represented
3840 /// by the value and offset from any ValueOffsetPair in the set.
3841 SetVector<ScalarEvolution::ValueOffsetPair> *
3842 ScalarEvolution::getSCEVValues(const SCEV *S) {
3843 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3844 if (SI == ExprValueMap.end())
3845 return nullptr;
3846 #ifndef NDEBUG
3847 if (VerifySCEVMap) {
3848 // Check there is no dangling Value in the set returned.
3849 for (const auto &VE : SI->second)
3850 assert(ValueExprMap.count(VE.first));
3852 #endif
3853 return &SI->second;
3856 /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
3857 /// cannot be used separately. eraseValueFromMap should be used to remove
3858 /// V from ValueExprMap and ExprValueMap at the same time.
3859 void ScalarEvolution::eraseValueFromMap(Value *V) {
3860 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3861 if (I != ValueExprMap.end()) {
3862 const SCEV *S = I->second;
3863 // Remove {V, 0} from the set of ExprValueMap[S]
3864 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(S))
3865 SV->remove({V, nullptr});
3867 // Remove {V, Offset} from the set of ExprValueMap[Stripped]
3868 const SCEV *Stripped;
3869 ConstantInt *Offset;
3870 std::tie(Stripped, Offset) = splitAddExpr(S);
3871 if (Offset != nullptr) {
3872 if (SetVector<ValueOffsetPair> *SV = getSCEVValues(Stripped))
3873 SV->remove({V, Offset});
3875 ValueExprMap.erase(V);
3879 /// Check whether value has nuw/nsw/exact set but SCEV does not.
3880 /// TODO: In reality it is better to check the poison recursively
3881 /// but this is better than nothing.
3882 static bool SCEVLostPoisonFlags(const SCEV *S, const Value *V) {
3883 if (auto *I = dyn_cast<Instruction>(V)) {
3884 if (isa<OverflowingBinaryOperator>(I)) {
3885 if (auto *NS = dyn_cast<SCEVNAryExpr>(S)) {
3886 if (I->hasNoSignedWrap() && !NS->hasNoSignedWrap())
3887 return true;
3888 if (I->hasNoUnsignedWrap() && !NS->hasNoUnsignedWrap())
3889 return true;
3891 } else if (isa<PossiblyExactOperator>(I) && I->isExact())
3892 return true;
3894 return false;
3897 /// Return an existing SCEV if it exists, otherwise analyze the expression and
3898 /// create a new one.
3899 const SCEV *ScalarEvolution::getSCEV(Value *V) {
3900 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3902 const SCEV *S = getExistingSCEV(V);
3903 if (S == nullptr) {
3904 S = createSCEV(V);
3905 // During PHI resolution, it is possible to create two SCEVs for the same
3906 // V, so it is needed to double check whether V->S is inserted into
3907 // ValueExprMap before insert S->{V, 0} into ExprValueMap.
3908 std::pair<ValueExprMapType::iterator, bool> Pair =
3909 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
3910 if (Pair.second && !SCEVLostPoisonFlags(S, V)) {
3911 ExprValueMap[S].insert({V, nullptr});
3913 // If S == Stripped + Offset, add Stripped -> {V, Offset} into
3914 // ExprValueMap.
3915 const SCEV *Stripped = S;
3916 ConstantInt *Offset = nullptr;
3917 std::tie(Stripped, Offset) = splitAddExpr(S);
3918 // If stripped is SCEVUnknown, don't bother to save
3919 // Stripped -> {V, offset}. It doesn't simplify and sometimes even
3920 // increase the complexity of the expansion code.
3921 // If V is GetElementPtrInst, don't save Stripped -> {V, offset}
3922 // because it may generate add/sub instead of GEP in SCEV expansion.
3923 if (Offset != nullptr && !isa<SCEVUnknown>(Stripped) &&
3924 !isa<GetElementPtrInst>(V))
3925 ExprValueMap[Stripped].insert({V, Offset});
3928 return S;
3931 const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3932 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3934 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3935 if (I != ValueExprMap.end()) {
3936 const SCEV *S = I->second;
3937 if (checkValidity(S))
3938 return S;
3939 eraseValueFromMap(V);
3940 forgetMemoizedResults(S);
3942 return nullptr;
3945 /// Return a SCEV corresponding to -V = -1*V
3946 const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3947 SCEV::NoWrapFlags Flags) {
3948 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3949 return getConstant(
3950 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
3952 Type *Ty = V->getType();
3953 Ty = getEffectiveSCEVType(Ty);
3954 return getMulExpr(
3955 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
3958 /// If Expr computes ~A, return A else return nullptr
3959 static const SCEV *MatchNotExpr(const SCEV *Expr) {
3960 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
3961 if (!Add || Add->getNumOperands() != 2 ||
3962 !Add->getOperand(0)->isAllOnesValue())
3963 return nullptr;
3965 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
3966 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
3967 !AddRHS->getOperand(0)->isAllOnesValue())
3968 return nullptr;
3970 return AddRHS->getOperand(1);
3973 /// Return a SCEV corresponding to ~V = -1-V
3974 const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
3975 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
3976 return getConstant(
3977 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
3979 // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
3980 if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
3981 auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
3982 SmallVector<const SCEV *, 2> MatchedOperands;
3983 for (const SCEV *Operand : MME->operands()) {
3984 const SCEV *Matched = MatchNotExpr(Operand);
3985 if (!Matched)
3986 return (const SCEV *)nullptr;
3987 MatchedOperands.push_back(Matched);
3989 return getMinMaxExpr(
3990 SCEVMinMaxExpr::negate(static_cast<SCEVTypes>(MME->getSCEVType())),
3991 MatchedOperands);
3993 if (const SCEV *Replaced = MatchMinMaxNegation(MME))
3994 return Replaced;
3997 Type *Ty = V->getType();
3998 Ty = getEffectiveSCEVType(Ty);
3999 const SCEV *AllOnes =
4000 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
4001 return getMinusSCEV(AllOnes, V);
4004 const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
4005 SCEV::NoWrapFlags Flags,
4006 unsigned Depth) {
4007 // Fast path: X - X --> 0.
4008 if (LHS == RHS)
4009 return getZero(LHS->getType());
4011 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
4012 // makes it so that we cannot make much use of NUW.
4013 auto AddFlags = SCEV::FlagAnyWrap;
4014 const bool RHSIsNotMinSigned =
4015 !getSignedRangeMin(RHS).isMinSignedValue();
4016 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
4017 // Let M be the minimum representable signed value. Then (-1)*RHS
4018 // signed-wraps if and only if RHS is M. That can happen even for
4019 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
4020 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
4021 // (-1)*RHS, we need to prove that RHS != M.
4023 // If LHS is non-negative and we know that LHS - RHS does not
4024 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
4025 // either by proving that RHS > M or that LHS >= 0.
4026 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
4027 AddFlags = SCEV::FlagNSW;
4031 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
4032 // RHS is NSW and LHS >= 0.
4034 // The difficulty here is that the NSW flag may have been proven
4035 // relative to a loop that is to be found in a recurrence in LHS and
4036 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
4037 // larger scope than intended.
4038 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
4040 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
4043 const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
4044 unsigned Depth) {
4045 Type *SrcTy = V->getType();
4046 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4047 "Cannot truncate or zero extend with non-integer arguments!");
4048 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4049 return V; // No conversion
4050 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4051 return getTruncateExpr(V, Ty, Depth);
4052 return getZeroExtendExpr(V, Ty, Depth);
4055 const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
4056 unsigned Depth) {
4057 Type *SrcTy = V->getType();
4058 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4059 "Cannot truncate or zero extend with non-integer arguments!");
4060 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4061 return V; // No conversion
4062 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
4063 return getTruncateExpr(V, Ty, Depth);
4064 return getSignExtendExpr(V, Ty, Depth);
4067 const SCEV *
4068 ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
4069 Type *SrcTy = V->getType();
4070 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4071 "Cannot noop or zero extend with non-integer arguments!");
4072 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4073 "getNoopOrZeroExtend cannot truncate!");
4074 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4075 return V; // No conversion
4076 return getZeroExtendExpr(V, Ty);
4079 const SCEV *
4080 ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
4081 Type *SrcTy = V->getType();
4082 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4083 "Cannot noop or sign extend with non-integer arguments!");
4084 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4085 "getNoopOrSignExtend cannot truncate!");
4086 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4087 return V; // No conversion
4088 return getSignExtendExpr(V, Ty);
4091 const SCEV *
4092 ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
4093 Type *SrcTy = V->getType();
4094 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4095 "Cannot noop or any extend with non-integer arguments!");
4096 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
4097 "getNoopOrAnyExtend cannot truncate!");
4098 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4099 return V; // No conversion
4100 return getAnyExtendExpr(V, Ty);
4103 const SCEV *
4104 ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
4105 Type *SrcTy = V->getType();
4106 assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
4107 "Cannot truncate or noop with non-integer arguments!");
4108 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
4109 "getTruncateOrNoop cannot extend!");
4110 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
4111 return V; // No conversion
4112 return getTruncateExpr(V, Ty);
4115 const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
4116 const SCEV *RHS) {
4117 const SCEV *PromotedLHS = LHS;
4118 const SCEV *PromotedRHS = RHS;
4120 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
4121 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
4122 else
4123 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
4125 return getUMaxExpr(PromotedLHS, PromotedRHS);
4128 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
4129 const SCEV *RHS) {
4130 SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
4131 return getUMinFromMismatchedTypes(Ops);
4134 const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(
4135 SmallVectorImpl<const SCEV *> &Ops) {
4136 assert(!Ops.empty() && "At least one operand must be!");
4137 // Trivial case.
4138 if (Ops.size() == 1)
4139 return Ops[0];
4141 // Find the max type first.
4142 Type *MaxType = nullptr;
4143 for (auto *S : Ops)
4144 if (MaxType)
4145 MaxType = getWiderType(MaxType, S->getType());
4146 else
4147 MaxType = S->getType();
4149 // Extend all ops to max type.
4150 SmallVector<const SCEV *, 2> PromotedOps;
4151 for (auto *S : Ops)
4152 PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
4154 // Generate umin.
4155 return getUMinExpr(PromotedOps);
4158 const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
4159 // A pointer operand may evaluate to a nonpointer expression, such as null.
4160 if (!V->getType()->isPointerTy())
4161 return V;
4163 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
4164 return getPointerBase(Cast->getOperand());
4165 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
4166 const SCEV *PtrOp = nullptr;
4167 for (const SCEV *NAryOp : NAry->operands()) {
4168 if (NAryOp->getType()->isPointerTy()) {
4169 // Cannot find the base of an expression with multiple pointer operands.
4170 if (PtrOp)
4171 return V;
4172 PtrOp = NAryOp;
4175 if (!PtrOp)
4176 return V;
4177 return getPointerBase(PtrOp);
4179 return V;
4182 /// Push users of the given Instruction onto the given Worklist.
4183 static void
4184 PushDefUseChildren(Instruction *I,
4185 SmallVectorImpl<Instruction *> &Worklist) {
4186 // Push the def-use children onto the Worklist stack.
4187 for (User *U : I->users())
4188 Worklist.push_back(cast<Instruction>(U));
4191 void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
4192 SmallVector<Instruction *, 16> Worklist;
4193 PushDefUseChildren(PN, Worklist);
4195 SmallPtrSet<Instruction *, 8> Visited;
4196 Visited.insert(PN);
4197 while (!Worklist.empty()) {
4198 Instruction *I = Worklist.pop_back_val();
4199 if (!Visited.insert(I).second)
4200 continue;
4202 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
4203 if (It != ValueExprMap.end()) {
4204 const SCEV *Old = It->second;
4206 // Short-circuit the def-use traversal if the symbolic name
4207 // ceases to appear in expressions.
4208 if (Old != SymName && !hasOperand(Old, SymName))
4209 continue;
4211 // SCEVUnknown for a PHI either means that it has an unrecognized
4212 // structure, it's a PHI that's in the progress of being computed
4213 // by createNodeForPHI, or it's a single-value PHI. In the first case,
4214 // additional loop trip count information isn't going to change anything.
4215 // In the second case, createNodeForPHI will perform the necessary
4216 // updates on its own when it gets to that point. In the third, we do
4217 // want to forget the SCEVUnknown.
4218 if (!isa<PHINode>(I) ||
4219 !isa<SCEVUnknown>(Old) ||
4220 (I != PN && Old == SymName)) {
4221 eraseValueFromMap(It->first);
4222 forgetMemoizedResults(Old);
4226 PushDefUseChildren(I, Worklist);
4230 namespace {
4232 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
4233 /// expression in case its Loop is L. If it is not L then
4234 /// if IgnoreOtherLoops is true then use AddRec itself
4235 /// otherwise rewrite cannot be done.
4236 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4237 class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
4238 public:
4239 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
4240 bool IgnoreOtherLoops = true) {
4241 SCEVInitRewriter Rewriter(L, SE);
4242 const SCEV *Result = Rewriter.visit(S);
4243 if (Rewriter.hasSeenLoopVariantSCEVUnknown())
4244 return SE.getCouldNotCompute();
4245 return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
4246 ? SE.getCouldNotCompute()
4247 : Result;
4250 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4251 if (!SE.isLoopInvariant(Expr, L))
4252 SeenLoopVariantSCEVUnknown = true;
4253 return Expr;
4256 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4257 // Only re-write AddRecExprs for this loop.
4258 if (Expr->getLoop() == L)
4259 return Expr->getStart();
4260 SeenOtherLoops = true;
4261 return Expr;
4264 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4266 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4268 private:
4269 explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
4270 : SCEVRewriteVisitor(SE), L(L) {}
4272 const Loop *L;
4273 bool SeenLoopVariantSCEVUnknown = false;
4274 bool SeenOtherLoops = false;
4277 /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
4278 /// increment expression in case its Loop is L. If it is not L then
4279 /// use AddRec itself.
4280 /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
4281 class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
4282 public:
4283 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
4284 SCEVPostIncRewriter Rewriter(L, SE);
4285 const SCEV *Result = Rewriter.visit(S);
4286 return Rewriter.hasSeenLoopVariantSCEVUnknown()
4287 ? SE.getCouldNotCompute()
4288 : Result;
4291 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4292 if (!SE.isLoopInvariant(Expr, L))
4293 SeenLoopVariantSCEVUnknown = true;
4294 return Expr;
4297 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4298 // Only re-write AddRecExprs for this loop.
4299 if (Expr->getLoop() == L)
4300 return Expr->getPostIncExpr(SE);
4301 SeenOtherLoops = true;
4302 return Expr;
4305 bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
4307 bool hasSeenOtherLoops() { return SeenOtherLoops; }
4309 private:
4310 explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
4311 : SCEVRewriteVisitor(SE), L(L) {}
4313 const Loop *L;
4314 bool SeenLoopVariantSCEVUnknown = false;
4315 bool SeenOtherLoops = false;
4318 /// This class evaluates the compare condition by matching it against the
4319 /// condition of loop latch. If there is a match we assume a true value
4320 /// for the condition while building SCEV nodes.
4321 class SCEVBackedgeConditionFolder
4322 : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
4323 public:
4324 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4325 ScalarEvolution &SE) {
4326 bool IsPosBECond = false;
4327 Value *BECond = nullptr;
4328 if (BasicBlock *Latch = L->getLoopLatch()) {
4329 BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
4330 if (BI && BI->isConditional()) {
4331 assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
4332 "Both outgoing branches should not target same header!");
4333 BECond = BI->getCondition();
4334 IsPosBECond = BI->getSuccessor(0) == L->getHeader();
4335 } else {
4336 return S;
4339 SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
4340 return Rewriter.visit(S);
4343 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4344 const SCEV *Result = Expr;
4345 bool InvariantF = SE.isLoopInvariant(Expr, L);
4347 if (!InvariantF) {
4348 Instruction *I = cast<Instruction>(Expr->getValue());
4349 switch (I->getOpcode()) {
4350 case Instruction::Select: {
4351 SelectInst *SI = cast<SelectInst>(I);
4352 Optional<const SCEV *> Res =
4353 compareWithBackedgeCondition(SI->getCondition());
4354 if (Res.hasValue()) {
4355 bool IsOne = cast<SCEVConstant>(Res.getValue())->getValue()->isOne();
4356 Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
4358 break;
4360 default: {
4361 Optional<const SCEV *> Res = compareWithBackedgeCondition(I);
4362 if (Res.hasValue())
4363 Result = Res.getValue();
4364 break;
4368 return Result;
4371 private:
4372 explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
4373 bool IsPosBECond, ScalarEvolution &SE)
4374 : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
4375 IsPositiveBECond(IsPosBECond) {}
4377 Optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
4379 const Loop *L;
4380 /// Loop back condition.
4381 Value *BackedgeCond = nullptr;
4382 /// Set to true if loop back is on positive branch condition.
4383 bool IsPositiveBECond;
4386 Optional<const SCEV *>
4387 SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
4389 // If value matches the backedge condition for loop latch,
4390 // then return a constant evolution node based on loopback
4391 // branch taken.
4392 if (BackedgeCond == IC)
4393 return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
4394 : SE.getZero(Type::getInt1Ty(SE.getContext()));
4395 return None;
4398 class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
4399 public:
4400 static const SCEV *rewrite(const SCEV *S, const Loop *L,
4401 ScalarEvolution &SE) {
4402 SCEVShiftRewriter Rewriter(L, SE);
4403 const SCEV *Result = Rewriter.visit(S);
4404 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
4407 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
4408 // Only allow AddRecExprs for this loop.
4409 if (!SE.isLoopInvariant(Expr, L))
4410 Valid = false;
4411 return Expr;
4414 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
4415 if (Expr->getLoop() == L && Expr->isAffine())
4416 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
4417 Valid = false;
4418 return Expr;
4421 bool isValid() { return Valid; }
4423 private:
4424 explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
4425 : SCEVRewriteVisitor(SE), L(L) {}
4427 const Loop *L;
4428 bool Valid = true;
4431 } // end anonymous namespace
4433 SCEV::NoWrapFlags
4434 ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
4435 if (!AR->isAffine())
4436 return SCEV::FlagAnyWrap;
4438 using OBO = OverflowingBinaryOperator;
4440 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
4442 if (!AR->hasNoSignedWrap()) {
4443 ConstantRange AddRecRange = getSignedRange(AR);
4444 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
4446 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4447 Instruction::Add, IncRange, OBO::NoSignedWrap);
4448 if (NSWRegion.contains(AddRecRange))
4449 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
4452 if (!AR->hasNoUnsignedWrap()) {
4453 ConstantRange AddRecRange = getUnsignedRange(AR);
4454 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
4456 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
4457 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
4458 if (NUWRegion.contains(AddRecRange))
4459 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
4462 return Result;
4465 namespace {
4467 /// Represents an abstract binary operation. This may exist as a
4468 /// normal instruction or constant expression, or may have been
4469 /// derived from an expression tree.
4470 struct BinaryOp {
4471 unsigned Opcode;
4472 Value *LHS;
4473 Value *RHS;
4474 bool IsNSW = false;
4475 bool IsNUW = false;
4477 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
4478 /// constant expression.
4479 Operator *Op = nullptr;
4481 explicit BinaryOp(Operator *Op)
4482 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
4483 Op(Op) {
4484 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
4485 IsNSW = OBO->hasNoSignedWrap();
4486 IsNUW = OBO->hasNoUnsignedWrap();
4490 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
4491 bool IsNUW = false)
4492 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
4495 } // end anonymous namespace
4497 /// Try to map \p V into a BinaryOp, and return \c None on failure.
4498 static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
4499 auto *Op = dyn_cast<Operator>(V);
4500 if (!Op)
4501 return None;
4503 // Implementation detail: all the cleverness here should happen without
4504 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
4505 // SCEV expressions when possible, and we should not break that.
4507 switch (Op->getOpcode()) {
4508 case Instruction::Add:
4509 case Instruction::Sub:
4510 case Instruction::Mul:
4511 case Instruction::UDiv:
4512 case Instruction::URem:
4513 case Instruction::And:
4514 case Instruction::Or:
4515 case Instruction::AShr:
4516 case Instruction::Shl:
4517 return BinaryOp(Op);
4519 case Instruction::Xor:
4520 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
4521 // If the RHS of the xor is a signmask, then this is just an add.
4522 // Instcombine turns add of signmask into xor as a strength reduction step.
4523 if (RHSC->getValue().isSignMask())
4524 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
4525 return BinaryOp(Op);
4527 case Instruction::LShr:
4528 // Turn logical shift right of a constant into a unsigned divide.
4529 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
4530 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
4532 // If the shift count is not less than the bitwidth, the result of
4533 // the shift is undefined. Don't try to analyze it, because the
4534 // resolution chosen here may differ from the resolution chosen in
4535 // other parts of the compiler.
4536 if (SA->getValue().ult(BitWidth)) {
4537 Constant *X =
4538 ConstantInt::get(SA->getContext(),
4539 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
4540 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
4543 return BinaryOp(Op);
4545 case Instruction::ExtractValue: {
4546 auto *EVI = cast<ExtractValueInst>(Op);
4547 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
4548 break;
4550 auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
4551 if (!WO)
4552 break;
4554 Instruction::BinaryOps BinOp = WO->getBinaryOp();
4555 bool Signed = WO->isSigned();
4556 // TODO: Should add nuw/nsw flags for mul as well.
4557 if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
4558 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
4560 // Now that we know that all uses of the arithmetic-result component of
4561 // CI are guarded by the overflow check, we can go ahead and pretend
4562 // that the arithmetic is non-overflowing.
4563 return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
4564 /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
4567 default:
4568 break;
4571 return None;
4574 /// Helper function to createAddRecFromPHIWithCasts. We have a phi
4575 /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
4576 /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
4577 /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
4578 /// follows one of the following patterns:
4579 /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4580 /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
4581 /// If the SCEV expression of \p Op conforms with one of the expected patterns
4582 /// we return the type of the truncation operation, and indicate whether the
4583 /// truncated type should be treated as signed/unsigned by setting
4584 /// \p Signed to true/false, respectively.
4585 static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
4586 bool &Signed, ScalarEvolution &SE) {
4587 // The case where Op == SymbolicPHI (that is, with no type conversions on
4588 // the way) is handled by the regular add recurrence creating logic and
4589 // would have already been triggered in createAddRecForPHI. Reaching it here
4590 // means that createAddRecFromPHI had failed for this PHI before (e.g.,
4591 // because one of the other operands of the SCEVAddExpr updating this PHI is
4592 // not invariant).
4594 // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
4595 // this case predicates that allow us to prove that Op == SymbolicPHI will
4596 // be added.
4597 if (Op == SymbolicPHI)
4598 return nullptr;
4600 unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
4601 unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
4602 if (SourceBits != NewBits)
4603 return nullptr;
4605 const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
4606 const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
4607 if (!SExt && !ZExt)
4608 return nullptr;
4609 const SCEVTruncateExpr *Trunc =
4610 SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
4611 : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
4612 if (!Trunc)
4613 return nullptr;
4614 const SCEV *X = Trunc->getOperand();
4615 if (X != SymbolicPHI)
4616 return nullptr;
4617 Signed = SExt != nullptr;
4618 return Trunc->getType();
4621 static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
4622 if (!PN->getType()->isIntegerTy())
4623 return nullptr;
4624 const Loop *L = LI.getLoopFor(PN->getParent());
4625 if (!L || L->getHeader() != PN->getParent())
4626 return nullptr;
4627 return L;
4630 // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
4631 // computation that updates the phi follows the following pattern:
4632 // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
4633 // which correspond to a phi->trunc->sext/zext->add->phi update chain.
4634 // If so, try to see if it can be rewritten as an AddRecExpr under some
4635 // Predicates. If successful, return them as a pair. Also cache the results
4636 // of the analysis.
4638 // Example usage scenario:
4639 // Say the Rewriter is called for the following SCEV:
4640 // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4641 // where:
4642 // %X = phi i64 (%Start, %BEValue)
4643 // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
4644 // and call this function with %SymbolicPHI = %X.
4646 // The analysis will find that the value coming around the backedge has
4647 // the following SCEV:
4648 // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
4649 // Upon concluding that this matches the desired pattern, the function
4650 // will return the pair {NewAddRec, SmallPredsVec} where:
4651 // NewAddRec = {%Start,+,%Step}
4652 // SmallPredsVec = {P1, P2, P3} as follows:
4653 // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
4654 // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
4655 // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
4656 // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
4657 // under the predicates {P1,P2,P3}.
4658 // This predicated rewrite will be cached in PredicatedSCEVRewrites:
4659 // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
4661 // TODO's:
4663 // 1) Extend the Induction descriptor to also support inductions that involve
4664 // casts: When needed (namely, when we are called in the context of the
4665 // vectorizer induction analysis), a Set of cast instructions will be
4666 // populated by this method, and provided back to isInductionPHI. This is
4667 // needed to allow the vectorizer to properly record them to be ignored by
4668 // the cost model and to avoid vectorizing them (otherwise these casts,
4669 // which are redundant under the runtime overflow checks, will be
4670 // vectorized, which can be costly).
4672 // 2) Support additional induction/PHISCEV patterns: We also want to support
4673 // inductions where the sext-trunc / zext-trunc operations (partly) occur
4674 // after the induction update operation (the induction increment):
4676 // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
4677 // which correspond to a phi->add->trunc->sext/zext->phi update chain.
4679 // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
4680 // which correspond to a phi->trunc->add->sext/zext->phi update chain.
4682 // 3) Outline common code with createAddRecFromPHI to avoid duplication.
4683 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4684 ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
4685 SmallVector<const SCEVPredicate *, 3> Predicates;
4687 // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
4688 // return an AddRec expression under some predicate.
4690 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4691 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4692 assert(L && "Expecting an integer loop header phi");
4694 // The loop may have multiple entrances or multiple exits; we can analyze
4695 // this phi as an addrec if it has a unique entry value and a unique
4696 // backedge value.
4697 Value *BEValueV = nullptr, *StartValueV = nullptr;
4698 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4699 Value *V = PN->getIncomingValue(i);
4700 if (L->contains(PN->getIncomingBlock(i))) {
4701 if (!BEValueV) {
4702 BEValueV = V;
4703 } else if (BEValueV != V) {
4704 BEValueV = nullptr;
4705 break;
4707 } else if (!StartValueV) {
4708 StartValueV = V;
4709 } else if (StartValueV != V) {
4710 StartValueV = nullptr;
4711 break;
4714 if (!BEValueV || !StartValueV)
4715 return None;
4717 const SCEV *BEValue = getSCEV(BEValueV);
4719 // If the value coming around the backedge is an add with the symbolic
4720 // value we just inserted, possibly with casts that we can ignore under
4721 // an appropriate runtime guard, then we found a simple induction variable!
4722 const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
4723 if (!Add)
4724 return None;
4726 // If there is a single occurrence of the symbolic value, possibly
4727 // casted, replace it with a recurrence.
4728 unsigned FoundIndex = Add->getNumOperands();
4729 Type *TruncTy = nullptr;
4730 bool Signed;
4731 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4732 if ((TruncTy =
4733 isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
4734 if (FoundIndex == e) {
4735 FoundIndex = i;
4736 break;
4739 if (FoundIndex == Add->getNumOperands())
4740 return None;
4742 // Create an add with everything but the specified operand.
4743 SmallVector<const SCEV *, 8> Ops;
4744 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
4745 if (i != FoundIndex)
4746 Ops.push_back(Add->getOperand(i));
4747 const SCEV *Accum = getAddExpr(Ops);
4749 // The runtime checks will not be valid if the step amount is
4750 // varying inside the loop.
4751 if (!isLoopInvariant(Accum, L))
4752 return None;
4754 // *** Part2: Create the predicates
4756 // Analysis was successful: we have a phi-with-cast pattern for which we
4757 // can return an AddRec expression under the following predicates:
4759 // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
4760 // fits within the truncated type (does not overflow) for i = 0 to n-1.
4761 // P2: An Equal predicate that guarantees that
4762 // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
4763 // P3: An Equal predicate that guarantees that
4764 // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
4766 // As we next prove, the above predicates guarantee that:
4767 // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
4770 // More formally, we want to prove that:
4771 // Expr(i+1) = Start + (i+1) * Accum
4772 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4774 // Given that:
4775 // 1) Expr(0) = Start
4776 // 2) Expr(1) = Start + Accum
4777 // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
4778 // 3) Induction hypothesis (step i):
4779 // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
4781 // Proof:
4782 // Expr(i+1) =
4783 // = Start + (i+1)*Accum
4784 // = (Start + i*Accum) + Accum
4785 // = Expr(i) + Accum
4786 // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
4787 // :: from step i
4789 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
4791 // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
4792 // + (Ext ix (Trunc iy (Accum) to ix) to iy)
4793 // + Accum :: from P3
4795 // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
4796 // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
4798 // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
4799 // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
4801 // By induction, the same applies to all iterations 1<=i<n:
4804 // Create a truncated addrec for which we will add a no overflow check (P1).
4805 const SCEV *StartVal = getSCEV(StartValueV);
4806 const SCEV *PHISCEV =
4807 getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
4808 getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
4810 // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
4811 // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
4812 // will be constant.
4814 // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
4815 // add P1.
4816 if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
4817 SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
4818 Signed ? SCEVWrapPredicate::IncrementNSSW
4819 : SCEVWrapPredicate::IncrementNUSW;
4820 const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
4821 Predicates.push_back(AddRecPred);
4824 // Create the Equal Predicates P2,P3:
4826 // It is possible that the predicates P2 and/or P3 are computable at
4827 // compile time due to StartVal and/or Accum being constants.
4828 // If either one is, then we can check that now and escape if either P2
4829 // or P3 is false.
4831 // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
4832 // for each of StartVal and Accum
4833 auto getExtendedExpr = [&](const SCEV *Expr,
4834 bool CreateSignExtend) -> const SCEV * {
4835 assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
4836 const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
4837 const SCEV *ExtendedExpr =
4838 CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
4839 : getZeroExtendExpr(TruncatedExpr, Expr->getType());
4840 return ExtendedExpr;
4843 // Given:
4844 // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
4845 // = getExtendedExpr(Expr)
4846 // Determine whether the predicate P: Expr == ExtendedExpr
4847 // is known to be false at compile time
4848 auto PredIsKnownFalse = [&](const SCEV *Expr,
4849 const SCEV *ExtendedExpr) -> bool {
4850 return Expr != ExtendedExpr &&
4851 isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
4854 const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
4855 if (PredIsKnownFalse(StartVal, StartExtended)) {
4856 LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
4857 return None;
4860 // The Step is always Signed (because the overflow checks are either
4861 // NSSW or NUSW)
4862 const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
4863 if (PredIsKnownFalse(Accum, AccumExtended)) {
4864 LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
4865 return None;
4868 auto AppendPredicate = [&](const SCEV *Expr,
4869 const SCEV *ExtendedExpr) -> void {
4870 if (Expr != ExtendedExpr &&
4871 !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
4872 const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
4873 LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
4874 Predicates.push_back(Pred);
4878 AppendPredicate(StartVal, StartExtended);
4879 AppendPredicate(Accum, AccumExtended);
4881 // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
4882 // which the casts had been folded away. The caller can rewrite SymbolicPHI
4883 // into NewAR if it will also add the runtime overflow checks specified in
4884 // Predicates.
4885 auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
4887 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
4888 std::make_pair(NewAR, Predicates);
4889 // Remember the result of the analysis for this SCEV at this locayyytion.
4890 PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
4891 return PredRewrite;
4894 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4895 ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
4896 auto *PN = cast<PHINode>(SymbolicPHI->getValue());
4897 const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
4898 if (!L)
4899 return None;
4901 // Check to see if we already analyzed this PHI.
4902 auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
4903 if (I != PredicatedSCEVRewrites.end()) {
4904 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
4905 I->second;
4906 // Analysis was done before and failed to create an AddRec:
4907 if (Rewrite.first == SymbolicPHI)
4908 return None;
4909 // Analysis was done before and succeeded to create an AddRec under
4910 // a predicate:
4911 assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
4912 assert(!(Rewrite.second).empty() && "Expected to find Predicates");
4913 return Rewrite;
4916 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
4917 Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
4919 // Record in the cache that the analysis failed
4920 if (!Rewrite) {
4921 SmallVector<const SCEVPredicate *, 3> Predicates;
4922 PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
4923 return None;
4926 return Rewrite;
4929 // FIXME: This utility is currently required because the Rewriter currently
4930 // does not rewrite this expression:
4931 // {0, +, (sext ix (trunc iy to ix) to iy)}
4932 // into {0, +, %step},
4933 // even when the following Equal predicate exists:
4934 // "%step == (sext ix (trunc iy to ix) to iy)".
4935 bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
4936 const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
4937 if (AR1 == AR2)
4938 return true;
4940 auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
4941 if (Expr1 != Expr2 && !Preds.implies(SE.getEqualPredicate(Expr1, Expr2)) &&
4942 !Preds.implies(SE.getEqualPredicate(Expr2, Expr1)))
4943 return false;
4944 return true;
4947 if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
4948 !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
4949 return false;
4950 return true;
4953 /// A helper function for createAddRecFromPHI to handle simple cases.
4955 /// This function tries to find an AddRec expression for the simplest (yet most
4956 /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
4957 /// If it fails, createAddRecFromPHI will use a more general, but slow,
4958 /// technique for finding the AddRec expression.
4959 const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
4960 Value *BEValueV,
4961 Value *StartValueV) {
4962 const Loop *L = LI.getLoopFor(PN->getParent());
4963 assert(L && L->getHeader() == PN->getParent());
4964 assert(BEValueV && StartValueV);
4966 auto BO = MatchBinaryOp(BEValueV, DT);
4967 if (!BO)
4968 return nullptr;
4970 if (BO->Opcode != Instruction::Add)
4971 return nullptr;
4973 const SCEV *Accum = nullptr;
4974 if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
4975 Accum = getSCEV(BO->RHS);
4976 else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
4977 Accum = getSCEV(BO->LHS);
4979 if (!Accum)
4980 return nullptr;
4982 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4983 if (BO->IsNUW)
4984 Flags = setFlags(Flags, SCEV::FlagNUW);
4985 if (BO->IsNSW)
4986 Flags = setFlags(Flags, SCEV::FlagNSW);
4988 const SCEV *StartVal = getSCEV(StartValueV);
4989 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4991 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4993 // We can add Flags to the post-inc expression only if we
4994 // know that it is *undefined behavior* for BEValueV to
4995 // overflow.
4996 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
4997 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
4998 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5000 return PHISCEV;
5003 const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
5004 const Loop *L = LI.getLoopFor(PN->getParent());
5005 if (!L || L->getHeader() != PN->getParent())
5006 return nullptr;
5008 // The loop may have multiple entrances or multiple exits; we can analyze
5009 // this phi as an addrec if it has a unique entry value and a unique
5010 // backedge value.
5011 Value *BEValueV = nullptr, *StartValueV = nullptr;
5012 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5013 Value *V = PN->getIncomingValue(i);
5014 if (L->contains(PN->getIncomingBlock(i))) {
5015 if (!BEValueV) {
5016 BEValueV = V;
5017 } else if (BEValueV != V) {
5018 BEValueV = nullptr;
5019 break;
5021 } else if (!StartValueV) {
5022 StartValueV = V;
5023 } else if (StartValueV != V) {
5024 StartValueV = nullptr;
5025 break;
5028 if (!BEValueV || !StartValueV)
5029 return nullptr;
5031 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
5032 "PHI node already processed?");
5034 // First, try to find AddRec expression without creating a fictituos symbolic
5035 // value for PN.
5036 if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
5037 return S;
5039 // Handle PHI node value symbolically.
5040 const SCEV *SymbolicName = getUnknown(PN);
5041 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
5043 // Using this symbolic name for the PHI, analyze the value coming around
5044 // the back-edge.
5045 const SCEV *BEValue = getSCEV(BEValueV);
5047 // NOTE: If BEValue is loop invariant, we know that the PHI node just
5048 // has a special value for the first iteration of the loop.
5050 // If the value coming around the backedge is an add with the symbolic
5051 // value we just inserted, then we found a simple induction variable!
5052 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
5053 // If there is a single occurrence of the symbolic value, replace it
5054 // with a recurrence.
5055 unsigned FoundIndex = Add->getNumOperands();
5056 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5057 if (Add->getOperand(i) == SymbolicName)
5058 if (FoundIndex == e) {
5059 FoundIndex = i;
5060 break;
5063 if (FoundIndex != Add->getNumOperands()) {
5064 // Create an add with everything but the specified operand.
5065 SmallVector<const SCEV *, 8> Ops;
5066 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
5067 if (i != FoundIndex)
5068 Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
5069 L, *this));
5070 const SCEV *Accum = getAddExpr(Ops);
5072 // This is not a valid addrec if the step amount is varying each
5073 // loop iteration, but is not itself an addrec in this loop.
5074 if (isLoopInvariant(Accum, L) ||
5075 (isa<SCEVAddRecExpr>(Accum) &&
5076 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
5077 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5079 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
5080 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
5081 if (BO->IsNUW)
5082 Flags = setFlags(Flags, SCEV::FlagNUW);
5083 if (BO->IsNSW)
5084 Flags = setFlags(Flags, SCEV::FlagNSW);
5086 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
5087 // If the increment is an inbounds GEP, then we know the address
5088 // space cannot be wrapped around. We cannot make any guarantee
5089 // about signed or unsigned overflow because pointers are
5090 // unsigned but we may have a negative index from the base
5091 // pointer. We can guarantee that no unsigned wrap occurs if the
5092 // indices form a positive value.
5093 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
5094 Flags = setFlags(Flags, SCEV::FlagNW);
5096 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
5097 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
5098 Flags = setFlags(Flags, SCEV::FlagNUW);
5101 // We cannot transfer nuw and nsw flags from subtraction
5102 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
5103 // for instance.
5106 const SCEV *StartVal = getSCEV(StartValueV);
5107 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
5109 // Okay, for the entire analysis of this edge we assumed the PHI
5110 // to be symbolic. We now need to go back and purge all of the
5111 // entries for the scalars that use the symbolic expression.
5112 forgetSymbolicName(PN, SymbolicName);
5113 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
5115 // We can add Flags to the post-inc expression only if we
5116 // know that it is *undefined behavior* for BEValueV to
5117 // overflow.
5118 if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
5119 if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
5120 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
5122 return PHISCEV;
5125 } else {
5126 // Otherwise, this could be a loop like this:
5127 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
5128 // In this case, j = {1,+,1} and BEValue is j.
5129 // Because the other in-value of i (0) fits the evolution of BEValue
5130 // i really is an addrec evolution.
5132 // We can generalize this saying that i is the shifted value of BEValue
5133 // by one iteration:
5134 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
5135 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
5136 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
5137 if (Shifted != getCouldNotCompute() &&
5138 Start != getCouldNotCompute()) {
5139 const SCEV *StartVal = getSCEV(StartValueV);
5140 if (Start == StartVal) {
5141 // Okay, for the entire analysis of this edge we assumed the PHI
5142 // to be symbolic. We now need to go back and purge all of the
5143 // entries for the scalars that use the symbolic expression.
5144 forgetSymbolicName(PN, SymbolicName);
5145 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
5146 return Shifted;
5151 // Remove the temporary PHI node SCEV that has been inserted while intending
5152 // to create an AddRecExpr for this PHI node. We can not keep this temporary
5153 // as it will prevent later (possibly simpler) SCEV expressions to be added
5154 // to the ValueExprMap.
5155 eraseValueFromMap(PN);
5157 return nullptr;
5160 // Checks if the SCEV S is available at BB. S is considered available at BB
5161 // if S can be materialized at BB without introducing a fault.
5162 static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
5163 BasicBlock *BB) {
5164 struct CheckAvailable {
5165 bool TraversalDone = false;
5166 bool Available = true;
5168 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
5169 BasicBlock *BB = nullptr;
5170 DominatorTree &DT;
5172 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
5173 : L(L), BB(BB), DT(DT) {}
5175 bool setUnavailable() {
5176 TraversalDone = true;
5177 Available = false;
5178 return false;
5181 bool follow(const SCEV *S) {
5182 switch (S->getSCEVType()) {
5183 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
5184 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
5185 case scUMinExpr:
5186 case scSMinExpr:
5187 // These expressions are available if their operand(s) is/are.
5188 return true;
5190 case scAddRecExpr: {
5191 // We allow add recurrences that are on the loop BB is in, or some
5192 // outer loop. This guarantees availability because the value of the
5193 // add recurrence at BB is simply the "current" value of the induction
5194 // variable. We can relax this in the future; for instance an add
5195 // recurrence on a sibling dominating loop is also available at BB.
5196 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
5197 if (L && (ARLoop == L || ARLoop->contains(L)))
5198 return true;
5200 return setUnavailable();
5203 case scUnknown: {
5204 // For SCEVUnknown, we check for simple dominance.
5205 const auto *SU = cast<SCEVUnknown>(S);
5206 Value *V = SU->getValue();
5208 if (isa<Argument>(V))
5209 return false;
5211 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
5212 return false;
5214 return setUnavailable();
5217 case scUDivExpr:
5218 case scCouldNotCompute:
5219 // We do not try to smart about these at all.
5220 return setUnavailable();
5222 llvm_unreachable("switch should be fully covered!");
5225 bool isDone() { return TraversalDone; }
5228 CheckAvailable CA(L, BB, DT);
5229 SCEVTraversal<CheckAvailable> ST(CA);
5231 ST.visitAll(S);
5232 return CA.Available;
5235 // Try to match a control flow sequence that branches out at BI and merges back
5236 // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
5237 // match.
5238 static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
5239 Value *&C, Value *&LHS, Value *&RHS) {
5240 C = BI->getCondition();
5242 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
5243 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
5245 if (!LeftEdge.isSingleEdge())
5246 return false;
5248 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
5250 Use &LeftUse = Merge->getOperandUse(0);
5251 Use &RightUse = Merge->getOperandUse(1);
5253 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
5254 LHS = LeftUse;
5255 RHS = RightUse;
5256 return true;
5259 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
5260 LHS = RightUse;
5261 RHS = LeftUse;
5262 return true;
5265 return false;
5268 const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
5269 auto IsReachable =
5270 [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
5271 if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
5272 const Loop *L = LI.getLoopFor(PN->getParent());
5274 // We don't want to break LCSSA, even in a SCEV expression tree.
5275 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5276 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
5277 return nullptr;
5279 // Try to match
5281 // br %cond, label %left, label %right
5282 // left:
5283 // br label %merge
5284 // right:
5285 // br label %merge
5286 // merge:
5287 // V = phi [ %x, %left ], [ %y, %right ]
5289 // as "select %cond, %x, %y"
5291 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
5292 assert(IDom && "At least the entry block should dominate PN");
5294 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
5295 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
5297 if (BI && BI->isConditional() &&
5298 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
5299 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
5300 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
5301 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
5304 return nullptr;
5307 const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
5308 if (const SCEV *S = createAddRecFromPHI(PN))
5309 return S;
5311 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
5312 return S;
5314 // If the PHI has a single incoming value, follow that value, unless the
5315 // PHI's incoming blocks are in a different loop, in which case doing so
5316 // risks breaking LCSSA form. Instcombine would normally zap these, but
5317 // it doesn't have DominatorTree information, so it may miss cases.
5318 if (Value *V = SimplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
5319 if (LI.replacementPreservesLCSSAForm(PN, V))
5320 return getSCEV(V);
5322 // If it's not a loop phi, we can't handle it yet.
5323 return getUnknown(PN);
5326 const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
5327 Value *Cond,
5328 Value *TrueVal,
5329 Value *FalseVal) {
5330 // Handle "constant" branch or select. This can occur for instance when a
5331 // loop pass transforms an inner loop and moves on to process the outer loop.
5332 if (auto *CI = dyn_cast<ConstantInt>(Cond))
5333 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
5335 // Try to match some simple smax or umax patterns.
5336 auto *ICI = dyn_cast<ICmpInst>(Cond);
5337 if (!ICI)
5338 return getUnknown(I);
5340 Value *LHS = ICI->getOperand(0);
5341 Value *RHS = ICI->getOperand(1);
5343 switch (ICI->getPredicate()) {
5344 case ICmpInst::ICMP_SLT:
5345 case ICmpInst::ICMP_SLE:
5346 std::swap(LHS, RHS);
5347 LLVM_FALLTHROUGH;
5348 case ICmpInst::ICMP_SGT:
5349 case ICmpInst::ICMP_SGE:
5350 // a >s b ? a+x : b+x -> smax(a, b)+x
5351 // a >s b ? b+x : a+x -> smin(a, b)+x
5352 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5353 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
5354 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
5355 const SCEV *LA = getSCEV(TrueVal);
5356 const SCEV *RA = getSCEV(FalseVal);
5357 const SCEV *LDiff = getMinusSCEV(LA, LS);
5358 const SCEV *RDiff = getMinusSCEV(RA, RS);
5359 if (LDiff == RDiff)
5360 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
5361 LDiff = getMinusSCEV(LA, RS);
5362 RDiff = getMinusSCEV(RA, LS);
5363 if (LDiff == RDiff)
5364 return getAddExpr(getSMinExpr(LS, RS), LDiff);
5366 break;
5367 case ICmpInst::ICMP_ULT:
5368 case ICmpInst::ICMP_ULE:
5369 std::swap(LHS, RHS);
5370 LLVM_FALLTHROUGH;
5371 case ICmpInst::ICMP_UGT:
5372 case ICmpInst::ICMP_UGE:
5373 // a >u b ? a+x : b+x -> umax(a, b)+x
5374 // a >u b ? b+x : a+x -> umin(a, b)+x
5375 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
5376 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5377 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
5378 const SCEV *LA = getSCEV(TrueVal);
5379 const SCEV *RA = getSCEV(FalseVal);
5380 const SCEV *LDiff = getMinusSCEV(LA, LS);
5381 const SCEV *RDiff = getMinusSCEV(RA, RS);
5382 if (LDiff == RDiff)
5383 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
5384 LDiff = getMinusSCEV(LA, RS);
5385 RDiff = getMinusSCEV(RA, LS);
5386 if (LDiff == RDiff)
5387 return getAddExpr(getUMinExpr(LS, RS), LDiff);
5389 break;
5390 case ICmpInst::ICMP_NE:
5391 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
5392 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5393 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5394 const SCEV *One = getOne(I->getType());
5395 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5396 const SCEV *LA = getSCEV(TrueVal);
5397 const SCEV *RA = getSCEV(FalseVal);
5398 const SCEV *LDiff = getMinusSCEV(LA, LS);
5399 const SCEV *RDiff = getMinusSCEV(RA, One);
5400 if (LDiff == RDiff)
5401 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5403 break;
5404 case ICmpInst::ICMP_EQ:
5405 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
5406 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
5407 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
5408 const SCEV *One = getOne(I->getType());
5409 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
5410 const SCEV *LA = getSCEV(TrueVal);
5411 const SCEV *RA = getSCEV(FalseVal);
5412 const SCEV *LDiff = getMinusSCEV(LA, One);
5413 const SCEV *RDiff = getMinusSCEV(RA, LS);
5414 if (LDiff == RDiff)
5415 return getAddExpr(getUMaxExpr(One, LS), LDiff);
5417 break;
5418 default:
5419 break;
5422 return getUnknown(I);
5425 /// Expand GEP instructions into add and multiply operations. This allows them
5426 /// to be analyzed by regular SCEV code.
5427 const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
5428 // Don't attempt to analyze GEPs over unsized objects.
5429 if (!GEP->getSourceElementType()->isSized())
5430 return getUnknown(GEP);
5432 SmallVector<const SCEV *, 4> IndexExprs;
5433 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
5434 IndexExprs.push_back(getSCEV(*Index));
5435 return getGEPExpr(GEP, IndexExprs);
5438 uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
5439 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5440 return C->getAPInt().countTrailingZeros();
5442 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
5443 return std::min(GetMinTrailingZeros(T->getOperand()),
5444 (uint32_t)getTypeSizeInBits(T->getType()));
5446 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
5447 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5448 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5449 ? getTypeSizeInBits(E->getType())
5450 : OpRes;
5453 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
5454 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
5455 return OpRes == getTypeSizeInBits(E->getOperand()->getType())
5456 ? getTypeSizeInBits(E->getType())
5457 : OpRes;
5460 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
5461 // The result is the min of all operands results.
5462 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5463 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5464 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5465 return MinOpRes;
5468 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
5469 // The result is the sum of all operands results.
5470 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
5471 uint32_t BitWidth = getTypeSizeInBits(M->getType());
5472 for (unsigned i = 1, e = M->getNumOperands();
5473 SumOpRes != BitWidth && i != e; ++i)
5474 SumOpRes =
5475 std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
5476 return SumOpRes;
5479 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
5480 // The result is the min of all operands results.
5481 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
5482 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
5483 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
5484 return MinOpRes;
5487 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
5488 // The result is the min of all operands results.
5489 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5490 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5491 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5492 return MinOpRes;
5495 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
5496 // The result is the min of all operands results.
5497 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
5498 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
5499 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
5500 return MinOpRes;
5503 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5504 // For a SCEVUnknown, ask ValueTracking.
5505 KnownBits Known = computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
5506 return Known.countMinTrailingZeros();
5509 // SCEVUDivExpr
5510 return 0;
5513 uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
5514 auto I = MinTrailingZerosCache.find(S);
5515 if (I != MinTrailingZerosCache.end())
5516 return I->second;
5518 uint32_t Result = GetMinTrailingZerosImpl(S);
5519 auto InsertPair = MinTrailingZerosCache.insert({S, Result});
5520 assert(InsertPair.second && "Should insert a new key");
5521 return InsertPair.first->second;
5524 /// Helper method to assign a range to V from metadata present in the IR.
5525 static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
5526 if (Instruction *I = dyn_cast<Instruction>(V))
5527 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
5528 return getConstantRangeFromMetadata(*MD);
5530 return None;
5533 /// Determine the range for a particular SCEV. If SignHint is
5534 /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
5535 /// with a "cleaner" unsigned (resp. signed) representation.
5536 const ConstantRange &
5537 ScalarEvolution::getRangeRef(const SCEV *S,
5538 ScalarEvolution::RangeSignHint SignHint) {
5539 DenseMap<const SCEV *, ConstantRange> &Cache =
5540 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
5541 : SignedRanges;
5542 ConstantRange::PreferredRangeType RangeType =
5543 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED
5544 ? ConstantRange::Unsigned : ConstantRange::Signed;
5546 // See if we've computed this range already.
5547 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
5548 if (I != Cache.end())
5549 return I->second;
5551 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
5552 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
5554 unsigned BitWidth = getTypeSizeInBits(S->getType());
5555 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
5557 // If the value has known zeros, the maximum value will have those known zeros
5558 // as well.
5559 uint32_t TZ = GetMinTrailingZeros(S);
5560 if (TZ != 0) {
5561 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
5562 ConservativeResult =
5563 ConstantRange(APInt::getMinValue(BitWidth),
5564 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
5565 else
5566 ConservativeResult = ConstantRange(
5567 APInt::getSignedMinValue(BitWidth),
5568 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
5571 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
5572 ConstantRange X = getRangeRef(Add->getOperand(0), SignHint);
5573 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
5574 X = X.add(getRangeRef(Add->getOperand(i), SignHint));
5575 return setRange(Add, SignHint,
5576 ConservativeResult.intersectWith(X, RangeType));
5579 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
5580 ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint);
5581 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
5582 X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint));
5583 return setRange(Mul, SignHint,
5584 ConservativeResult.intersectWith(X, RangeType));
5587 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
5588 ConstantRange X = getRangeRef(SMax->getOperand(0), SignHint);
5589 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
5590 X = X.smax(getRangeRef(SMax->getOperand(i), SignHint));
5591 return setRange(SMax, SignHint,
5592 ConservativeResult.intersectWith(X, RangeType));
5595 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
5596 ConstantRange X = getRangeRef(UMax->getOperand(0), SignHint);
5597 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
5598 X = X.umax(getRangeRef(UMax->getOperand(i), SignHint));
5599 return setRange(UMax, SignHint,
5600 ConservativeResult.intersectWith(X, RangeType));
5603 if (const SCEVSMinExpr *SMin = dyn_cast<SCEVSMinExpr>(S)) {
5604 ConstantRange X = getRangeRef(SMin->getOperand(0), SignHint);
5605 for (unsigned i = 1, e = SMin->getNumOperands(); i != e; ++i)
5606 X = X.smin(getRangeRef(SMin->getOperand(i), SignHint));
5607 return setRange(SMin, SignHint,
5608 ConservativeResult.intersectWith(X, RangeType));
5611 if (const SCEVUMinExpr *UMin = dyn_cast<SCEVUMinExpr>(S)) {
5612 ConstantRange X = getRangeRef(UMin->getOperand(0), SignHint);
5613 for (unsigned i = 1, e = UMin->getNumOperands(); i != e; ++i)
5614 X = X.umin(getRangeRef(UMin->getOperand(i), SignHint));
5615 return setRange(UMin, SignHint,
5616 ConservativeResult.intersectWith(X, RangeType));
5619 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
5620 ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint);
5621 ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint);
5622 return setRange(UDiv, SignHint,
5623 ConservativeResult.intersectWith(X.udiv(Y), RangeType));
5626 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
5627 ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint);
5628 return setRange(ZExt, SignHint,
5629 ConservativeResult.intersectWith(X.zeroExtend(BitWidth),
5630 RangeType));
5633 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
5634 ConstantRange X = getRangeRef(SExt->getOperand(), SignHint);
5635 return setRange(SExt, SignHint,
5636 ConservativeResult.intersectWith(X.signExtend(BitWidth),
5637 RangeType));
5640 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
5641 ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint);
5642 return setRange(Trunc, SignHint,
5643 ConservativeResult.intersectWith(X.truncate(BitWidth),
5644 RangeType));
5647 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
5648 // If there's no unsigned wrap, the value will never be less than its
5649 // initial value.
5650 if (AddRec->hasNoUnsignedWrap())
5651 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
5652 if (!C->getValue()->isZero())
5653 ConservativeResult = ConservativeResult.intersectWith(
5654 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)), RangeType);
5656 // If there's no signed wrap, and all the operands have the same sign or
5657 // zero, the value won't ever change sign.
5658 if (AddRec->hasNoSignedWrap()) {
5659 bool AllNonNeg = true;
5660 bool AllNonPos = true;
5661 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5662 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
5663 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
5665 if (AllNonNeg)
5666 ConservativeResult = ConservativeResult.intersectWith(
5667 ConstantRange(APInt(BitWidth, 0),
5668 APInt::getSignedMinValue(BitWidth)), RangeType);
5669 else if (AllNonPos)
5670 ConservativeResult = ConservativeResult.intersectWith(
5671 ConstantRange(APInt::getSignedMinValue(BitWidth),
5672 APInt(BitWidth, 1)), RangeType);
5675 // TODO: non-affine addrec
5676 if (AddRec->isAffine()) {
5677 const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(AddRec->getLoop());
5678 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
5679 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
5680 auto RangeFromAffine = getRangeForAffineAR(
5681 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5682 BitWidth);
5683 if (!RangeFromAffine.isFullSet())
5684 ConservativeResult =
5685 ConservativeResult.intersectWith(RangeFromAffine, RangeType);
5687 auto RangeFromFactoring = getRangeViaFactoring(
5688 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
5689 BitWidth);
5690 if (!RangeFromFactoring.isFullSet())
5691 ConservativeResult =
5692 ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
5696 return setRange(AddRec, SignHint, std::move(ConservativeResult));
5699 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
5700 // Check if the IR explicitly contains !range metadata.
5701 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
5702 if (MDRange.hasValue())
5703 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue(),
5704 RangeType);
5706 // Split here to avoid paying the compile-time cost of calling both
5707 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
5708 // if needed.
5709 const DataLayout &DL = getDataLayout();
5710 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
5711 // For a SCEVUnknown, ask ValueTracking.
5712 KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5713 if (Known.One != ~Known.Zero + 1)
5714 ConservativeResult =
5715 ConservativeResult.intersectWith(
5716 ConstantRange(Known.One, ~Known.Zero + 1), RangeType);
5717 } else {
5718 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
5719 "generalize as needed!");
5720 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
5721 if (NS > 1)
5722 ConservativeResult = ConservativeResult.intersectWith(
5723 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
5724 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
5725 RangeType);
5728 // A range of Phi is a subset of union of all ranges of its input.
5729 if (const PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
5730 // Make sure that we do not run over cycled Phis.
5731 if (PendingPhiRanges.insert(Phi).second) {
5732 ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
5733 for (auto &Op : Phi->operands()) {
5734 auto OpRange = getRangeRef(getSCEV(Op), SignHint);
5735 RangeFromOps = RangeFromOps.unionWith(OpRange);
5736 // No point to continue if we already have a full set.
5737 if (RangeFromOps.isFullSet())
5738 break;
5740 ConservativeResult =
5741 ConservativeResult.intersectWith(RangeFromOps, RangeType);
5742 bool Erased = PendingPhiRanges.erase(Phi);
5743 assert(Erased && "Failed to erase Phi properly?");
5744 (void) Erased;
5748 return setRange(U, SignHint, std::move(ConservativeResult));
5751 return setRange(S, SignHint, std::move(ConservativeResult));
5754 // Given a StartRange, Step and MaxBECount for an expression compute a range of
5755 // values that the expression can take. Initially, the expression has a value
5756 // from StartRange and then is changed by Step up to MaxBECount times. Signed
5757 // argument defines if we treat Step as signed or unsigned.
5758 static ConstantRange getRangeForAffineARHelper(APInt Step,
5759 const ConstantRange &StartRange,
5760 const APInt &MaxBECount,
5761 unsigned BitWidth, bool Signed) {
5762 // If either Step or MaxBECount is 0, then the expression won't change, and we
5763 // just need to return the initial range.
5764 if (Step == 0 || MaxBECount == 0)
5765 return StartRange;
5767 // If we don't know anything about the initial value (i.e. StartRange is
5768 // FullRange), then we don't know anything about the final range either.
5769 // Return FullRange.
5770 if (StartRange.isFullSet())
5771 return ConstantRange::getFull(BitWidth);
5773 // If Step is signed and negative, then we use its absolute value, but we also
5774 // note that we're moving in the opposite direction.
5775 bool Descending = Signed && Step.isNegative();
5777 if (Signed)
5778 // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
5779 // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
5780 // This equations hold true due to the well-defined wrap-around behavior of
5781 // APInt.
5782 Step = Step.abs();
5784 // Check if Offset is more than full span of BitWidth. If it is, the
5785 // expression is guaranteed to overflow.
5786 if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
5787 return ConstantRange::getFull(BitWidth);
5789 // Offset is by how much the expression can change. Checks above guarantee no
5790 // overflow here.
5791 APInt Offset = Step * MaxBECount;
5793 // Minimum value of the final range will match the minimal value of StartRange
5794 // if the expression is increasing and will be decreased by Offset otherwise.
5795 // Maximum value of the final range will match the maximal value of StartRange
5796 // if the expression is decreasing and will be increased by Offset otherwise.
5797 APInt StartLower = StartRange.getLower();
5798 APInt StartUpper = StartRange.getUpper() - 1;
5799 APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
5800 : (StartUpper + std::move(Offset));
5802 // It's possible that the new minimum/maximum value will fall into the initial
5803 // range (due to wrap around). This means that the expression can take any
5804 // value in this bitwidth, and we have to return full range.
5805 if (StartRange.contains(MovedBoundary))
5806 return ConstantRange::getFull(BitWidth);
5808 APInt NewLower =
5809 Descending ? std::move(MovedBoundary) : std::move(StartLower);
5810 APInt NewUpper =
5811 Descending ? std::move(StartUpper) : std::move(MovedBoundary);
5812 NewUpper += 1;
5814 // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
5815 return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
5818 ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
5819 const SCEV *Step,
5820 const SCEV *MaxBECount,
5821 unsigned BitWidth) {
5822 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
5823 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
5824 "Precondition!");
5826 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
5827 APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
5829 // First, consider step signed.
5830 ConstantRange StartSRange = getSignedRange(Start);
5831 ConstantRange StepSRange = getSignedRange(Step);
5833 // If Step can be both positive and negative, we need to find ranges for the
5834 // maximum absolute step values in both directions and union them.
5835 ConstantRange SR =
5836 getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
5837 MaxBECountValue, BitWidth, /* Signed = */ true);
5838 SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
5839 StartSRange, MaxBECountValue,
5840 BitWidth, /* Signed = */ true));
5842 // Next, consider step unsigned.
5843 ConstantRange UR = getRangeForAffineARHelper(
5844 getUnsignedRangeMax(Step), getUnsignedRange(Start),
5845 MaxBECountValue, BitWidth, /* Signed = */ false);
5847 // Finally, intersect signed and unsigned ranges.
5848 return SR.intersectWith(UR, ConstantRange::Smallest);
5851 ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
5852 const SCEV *Step,
5853 const SCEV *MaxBECount,
5854 unsigned BitWidth) {
5855 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
5856 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
5858 struct SelectPattern {
5859 Value *Condition = nullptr;
5860 APInt TrueValue;
5861 APInt FalseValue;
5863 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
5864 const SCEV *S) {
5865 Optional<unsigned> CastOp;
5866 APInt Offset(BitWidth, 0);
5868 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
5869 "Should be!");
5871 // Peel off a constant offset:
5872 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
5873 // In the future we could consider being smarter here and handle
5874 // {Start+Step,+,Step} too.
5875 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
5876 return;
5878 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
5879 S = SA->getOperand(1);
5882 // Peel off a cast operation
5883 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
5884 CastOp = SCast->getSCEVType();
5885 S = SCast->getOperand();
5888 using namespace llvm::PatternMatch;
5890 auto *SU = dyn_cast<SCEVUnknown>(S);
5891 const APInt *TrueVal, *FalseVal;
5892 if (!SU ||
5893 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
5894 m_APInt(FalseVal)))) {
5895 Condition = nullptr;
5896 return;
5899 TrueValue = *TrueVal;
5900 FalseValue = *FalseVal;
5902 // Re-apply the cast we peeled off earlier
5903 if (CastOp.hasValue())
5904 switch (*CastOp) {
5905 default:
5906 llvm_unreachable("Unknown SCEV cast type!");
5908 case scTruncate:
5909 TrueValue = TrueValue.trunc(BitWidth);
5910 FalseValue = FalseValue.trunc(BitWidth);
5911 break;
5912 case scZeroExtend:
5913 TrueValue = TrueValue.zext(BitWidth);
5914 FalseValue = FalseValue.zext(BitWidth);
5915 break;
5916 case scSignExtend:
5917 TrueValue = TrueValue.sext(BitWidth);
5918 FalseValue = FalseValue.sext(BitWidth);
5919 break;
5922 // Re-apply the constant offset we peeled off earlier
5923 TrueValue += Offset;
5924 FalseValue += Offset;
5927 bool isRecognized() { return Condition != nullptr; }
5930 SelectPattern StartPattern(*this, BitWidth, Start);
5931 if (!StartPattern.isRecognized())
5932 return ConstantRange::getFull(BitWidth);
5934 SelectPattern StepPattern(*this, BitWidth, Step);
5935 if (!StepPattern.isRecognized())
5936 return ConstantRange::getFull(BitWidth);
5938 if (StartPattern.Condition != StepPattern.Condition) {
5939 // We don't handle this case today; but we could, by considering four
5940 // possibilities below instead of two. I'm not sure if there are cases where
5941 // that will help over what getRange already does, though.
5942 return ConstantRange::getFull(BitWidth);
5945 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
5946 // construct arbitrary general SCEV expressions here. This function is called
5947 // from deep in the call stack, and calling getSCEV (on a sext instruction,
5948 // say) can end up caching a suboptimal value.
5950 // FIXME: without the explicit `this` receiver below, MSVC errors out with
5951 // C2352 and C2512 (otherwise it isn't needed).
5953 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
5954 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
5955 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
5956 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
5958 ConstantRange TrueRange =
5959 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
5960 ConstantRange FalseRange =
5961 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
5963 return TrueRange.unionWith(FalseRange);
5966 SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
5967 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
5968 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
5970 // Return early if there are no flags to propagate to the SCEV.
5971 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
5972 if (BinOp->hasNoUnsignedWrap())
5973 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
5974 if (BinOp->hasNoSignedWrap())
5975 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
5976 if (Flags == SCEV::FlagAnyWrap)
5977 return SCEV::FlagAnyWrap;
5979 return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
5982 bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
5983 // Here we check that I is in the header of the innermost loop containing I,
5984 // since we only deal with instructions in the loop header. The actual loop we
5985 // need to check later will come from an add recurrence, but getting that
5986 // requires computing the SCEV of the operands, which can be expensive. This
5987 // check we can do cheaply to rule out some cases early.
5988 Loop *InnermostContainingLoop = LI.getLoopFor(I->getParent());
5989 if (InnermostContainingLoop == nullptr ||
5990 InnermostContainingLoop->getHeader() != I->getParent())
5991 return false;
5993 // Only proceed if we can prove that I does not yield poison.
5994 if (!programUndefinedIfFullPoison(I))
5995 return false;
5997 // At this point we know that if I is executed, then it does not wrap
5998 // according to at least one of NSW or NUW. If I is not executed, then we do
5999 // not know if the calculation that I represents would wrap. Multiple
6000 // instructions can map to the same SCEV. If we apply NSW or NUW from I to
6001 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
6002 // derived from other instructions that map to the same SCEV. We cannot make
6003 // that guarantee for cases where I is not executed. So we need to find the
6004 // loop that I is considered in relation to and prove that I is executed for
6005 // every iteration of that loop. That implies that the value that I
6006 // calculates does not wrap anywhere in the loop, so then we can apply the
6007 // flags to the SCEV.
6009 // We check isLoopInvariant to disambiguate in case we are adding recurrences
6010 // from different loops, so that we know which loop to prove that I is
6011 // executed in.
6012 for (unsigned OpIndex = 0; OpIndex < I->getNumOperands(); ++OpIndex) {
6013 // I could be an extractvalue from a call to an overflow intrinsic.
6014 // TODO: We can do better here in some cases.
6015 if (!isSCEVable(I->getOperand(OpIndex)->getType()))
6016 return false;
6017 const SCEV *Op = getSCEV(I->getOperand(OpIndex));
6018 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
6019 bool AllOtherOpsLoopInvariant = true;
6020 for (unsigned OtherOpIndex = 0; OtherOpIndex < I->getNumOperands();
6021 ++OtherOpIndex) {
6022 if (OtherOpIndex != OpIndex) {
6023 const SCEV *OtherOp = getSCEV(I->getOperand(OtherOpIndex));
6024 if (!isLoopInvariant(OtherOp, AddRec->getLoop())) {
6025 AllOtherOpsLoopInvariant = false;
6026 break;
6030 if (AllOtherOpsLoopInvariant &&
6031 isGuaranteedToExecuteForEveryIteration(I, AddRec->getLoop()))
6032 return true;
6035 return false;
6038 bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
6039 // If we know that \c I can never be poison period, then that's enough.
6040 if (isSCEVExprNeverPoison(I))
6041 return true;
6043 // For an add recurrence specifically, we assume that infinite loops without
6044 // side effects are undefined behavior, and then reason as follows:
6046 // If the add recurrence is poison in any iteration, it is poison on all
6047 // future iterations (since incrementing poison yields poison). If the result
6048 // of the add recurrence is fed into the loop latch condition and the loop
6049 // does not contain any throws or exiting blocks other than the latch, we now
6050 // have the ability to "choose" whether the backedge is taken or not (by
6051 // choosing a sufficiently evil value for the poison feeding into the branch)
6052 // for every iteration including and after the one in which \p I first became
6053 // poison. There are two possibilities (let's call the iteration in which \p
6054 // I first became poison as K):
6056 // 1. In the set of iterations including and after K, the loop body executes
6057 // no side effects. In this case executing the backege an infinte number
6058 // of times will yield undefined behavior.
6060 // 2. In the set of iterations including and after K, the loop body executes
6061 // at least one side effect. In this case, that specific instance of side
6062 // effect is control dependent on poison, which also yields undefined
6063 // behavior.
6065 auto *ExitingBB = L->getExitingBlock();
6066 auto *LatchBB = L->getLoopLatch();
6067 if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
6068 return false;
6070 SmallPtrSet<const Instruction *, 16> Pushed;
6071 SmallVector<const Instruction *, 8> PoisonStack;
6073 // We start by assuming \c I, the post-inc add recurrence, is poison. Only
6074 // things that are known to be fully poison under that assumption go on the
6075 // PoisonStack.
6076 Pushed.insert(I);
6077 PoisonStack.push_back(I);
6079 bool LatchControlDependentOnPoison = false;
6080 while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
6081 const Instruction *Poison = PoisonStack.pop_back_val();
6083 for (auto *PoisonUser : Poison->users()) {
6084 if (propagatesFullPoison(cast<Instruction>(PoisonUser))) {
6085 if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
6086 PoisonStack.push_back(cast<Instruction>(PoisonUser));
6087 } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
6088 assert(BI->isConditional() && "Only possibility!");
6089 if (BI->getParent() == LatchBB) {
6090 LatchControlDependentOnPoison = true;
6091 break;
6097 return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
6100 ScalarEvolution::LoopProperties
6101 ScalarEvolution::getLoopProperties(const Loop *L) {
6102 using LoopProperties = ScalarEvolution::LoopProperties;
6104 auto Itr = LoopPropertiesCache.find(L);
6105 if (Itr == LoopPropertiesCache.end()) {
6106 auto HasSideEffects = [](Instruction *I) {
6107 if (auto *SI = dyn_cast<StoreInst>(I))
6108 return !SI->isSimple();
6110 return I->mayHaveSideEffects();
6113 LoopProperties LP = {/* HasNoAbnormalExits */ true,
6114 /*HasNoSideEffects*/ true};
6116 for (auto *BB : L->getBlocks())
6117 for (auto &I : *BB) {
6118 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
6119 LP.HasNoAbnormalExits = false;
6120 if (HasSideEffects(&I))
6121 LP.HasNoSideEffects = false;
6122 if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
6123 break; // We're already as pessimistic as we can get.
6126 auto InsertPair = LoopPropertiesCache.insert({L, LP});
6127 assert(InsertPair.second && "We just checked!");
6128 Itr = InsertPair.first;
6131 return Itr->second;
6134 const SCEV *ScalarEvolution::createSCEV(Value *V) {
6135 if (!isSCEVable(V->getType()))
6136 return getUnknown(V);
6138 if (Instruction *I = dyn_cast<Instruction>(V)) {
6139 // Don't attempt to analyze instructions in blocks that aren't
6140 // reachable. Such instructions don't matter, and they aren't required
6141 // to obey basic rules for definitions dominating uses which this
6142 // analysis depends on.
6143 if (!DT.isReachableFromEntry(I->getParent()))
6144 return getUnknown(UndefValue::get(V->getType()));
6145 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
6146 return getConstant(CI);
6147 else if (isa<ConstantPointerNull>(V))
6148 return getZero(V->getType());
6149 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
6150 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
6151 else if (!isa<ConstantExpr>(V))
6152 return getUnknown(V);
6154 Operator *U = cast<Operator>(V);
6155 if (auto BO = MatchBinaryOp(U, DT)) {
6156 switch (BO->Opcode) {
6157 case Instruction::Add: {
6158 // The simple thing to do would be to just call getSCEV on both operands
6159 // and call getAddExpr with the result. However if we're looking at a
6160 // bunch of things all added together, this can be quite inefficient,
6161 // because it leads to N-1 getAddExpr calls for N ultimate operands.
6162 // Instead, gather up all the operands and make a single getAddExpr call.
6163 // LLVM IR canonical form means we need only traverse the left operands.
6164 SmallVector<const SCEV *, 4> AddOps;
6165 do {
6166 if (BO->Op) {
6167 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6168 AddOps.push_back(OpSCEV);
6169 break;
6172 // If a NUW or NSW flag can be applied to the SCEV for this
6173 // addition, then compute the SCEV for this addition by itself
6174 // with a separate call to getAddExpr. We need to do that
6175 // instead of pushing the operands of the addition onto AddOps,
6176 // since the flags are only known to apply to this particular
6177 // addition - they may not apply to other additions that can be
6178 // formed with operands from AddOps.
6179 const SCEV *RHS = getSCEV(BO->RHS);
6180 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6181 if (Flags != SCEV::FlagAnyWrap) {
6182 const SCEV *LHS = getSCEV(BO->LHS);
6183 if (BO->Opcode == Instruction::Sub)
6184 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
6185 else
6186 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
6187 break;
6191 if (BO->Opcode == Instruction::Sub)
6192 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
6193 else
6194 AddOps.push_back(getSCEV(BO->RHS));
6196 auto NewBO = MatchBinaryOp(BO->LHS, DT);
6197 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
6198 NewBO->Opcode != Instruction::Sub)) {
6199 AddOps.push_back(getSCEV(BO->LHS));
6200 break;
6202 BO = NewBO;
6203 } while (true);
6205 return getAddExpr(AddOps);
6208 case Instruction::Mul: {
6209 SmallVector<const SCEV *, 4> MulOps;
6210 do {
6211 if (BO->Op) {
6212 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
6213 MulOps.push_back(OpSCEV);
6214 break;
6217 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
6218 if (Flags != SCEV::FlagAnyWrap) {
6219 MulOps.push_back(
6220 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
6221 break;
6225 MulOps.push_back(getSCEV(BO->RHS));
6226 auto NewBO = MatchBinaryOp(BO->LHS, DT);
6227 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
6228 MulOps.push_back(getSCEV(BO->LHS));
6229 break;
6231 BO = NewBO;
6232 } while (true);
6234 return getMulExpr(MulOps);
6236 case Instruction::UDiv:
6237 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6238 case Instruction::URem:
6239 return getURemExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
6240 case Instruction::Sub: {
6241 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
6242 if (BO->Op)
6243 Flags = getNoWrapFlagsFromUB(BO->Op);
6244 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
6246 case Instruction::And:
6247 // For an expression like x&255 that merely masks off the high bits,
6248 // use zext(trunc(x)) as the SCEV expression.
6249 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6250 if (CI->isZero())
6251 return getSCEV(BO->RHS);
6252 if (CI->isMinusOne())
6253 return getSCEV(BO->LHS);
6254 const APInt &A = CI->getValue();
6256 // Instcombine's ShrinkDemandedConstant may strip bits out of
6257 // constants, obscuring what would otherwise be a low-bits mask.
6258 // Use computeKnownBits to compute what ShrinkDemandedConstant
6259 // knew about to reconstruct a low-bits mask value.
6260 unsigned LZ = A.countLeadingZeros();
6261 unsigned TZ = A.countTrailingZeros();
6262 unsigned BitWidth = A.getBitWidth();
6263 KnownBits Known(BitWidth);
6264 computeKnownBits(BO->LHS, Known, getDataLayout(),
6265 0, &AC, nullptr, &DT);
6267 APInt EffectiveMask =
6268 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
6269 if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
6270 const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
6271 const SCEV *LHS = getSCEV(BO->LHS);
6272 const SCEV *ShiftedLHS = nullptr;
6273 if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
6274 if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
6275 // For an expression like (x * 8) & 8, simplify the multiply.
6276 unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
6277 unsigned GCD = std::min(MulZeros, TZ);
6278 APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
6279 SmallVector<const SCEV*, 4> MulOps;
6280 MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
6281 MulOps.append(LHSMul->op_begin() + 1, LHSMul->op_end());
6282 auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
6283 ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
6286 if (!ShiftedLHS)
6287 ShiftedLHS = getUDivExpr(LHS, MulCount);
6288 return getMulExpr(
6289 getZeroExtendExpr(
6290 getTruncateExpr(ShiftedLHS,
6291 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
6292 BO->LHS->getType()),
6293 MulCount);
6296 break;
6298 case Instruction::Or:
6299 // If the RHS of the Or is a constant, we may have something like:
6300 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
6301 // optimizations will transparently handle this case.
6303 // In order for this transformation to be safe, the LHS must be of the
6304 // form X*(2^n) and the Or constant must be less than 2^n.
6305 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6306 const SCEV *LHS = getSCEV(BO->LHS);
6307 const APInt &CIVal = CI->getValue();
6308 if (GetMinTrailingZeros(LHS) >=
6309 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
6310 // Build a plain add SCEV.
6311 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
6312 // If the LHS of the add was an addrec and it has no-wrap flags,
6313 // transfer the no-wrap flags, since an or won't introduce a wrap.
6314 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
6315 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
6316 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
6317 OldAR->getNoWrapFlags());
6319 return S;
6322 break;
6324 case Instruction::Xor:
6325 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
6326 // If the RHS of xor is -1, then this is a not operation.
6327 if (CI->isMinusOne())
6328 return getNotSCEV(getSCEV(BO->LHS));
6330 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
6331 // This is a variant of the check for xor with -1, and it handles
6332 // the case where instcombine has trimmed non-demanded bits out
6333 // of an xor with -1.
6334 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
6335 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
6336 if (LBO->getOpcode() == Instruction::And &&
6337 LCI->getValue() == CI->getValue())
6338 if (const SCEVZeroExtendExpr *Z =
6339 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
6340 Type *UTy = BO->LHS->getType();
6341 const SCEV *Z0 = Z->getOperand();
6342 Type *Z0Ty = Z0->getType();
6343 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
6345 // If C is a low-bits mask, the zero extend is serving to
6346 // mask off the high bits. Complement the operand and
6347 // re-apply the zext.
6348 if (CI->getValue().isMask(Z0TySize))
6349 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
6351 // If C is a single bit, it may be in the sign-bit position
6352 // before the zero-extend. In this case, represent the xor
6353 // using an add, which is equivalent, and re-apply the zext.
6354 APInt Trunc = CI->getValue().trunc(Z0TySize);
6355 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
6356 Trunc.isSignMask())
6357 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
6358 UTy);
6361 break;
6363 case Instruction::Shl:
6364 // Turn shift left of a constant amount into a multiply.
6365 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
6366 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
6368 // If the shift count is not less than the bitwidth, the result of
6369 // the shift is undefined. Don't try to analyze it, because the
6370 // resolution chosen here may differ from the resolution chosen in
6371 // other parts of the compiler.
6372 if (SA->getValue().uge(BitWidth))
6373 break;
6375 // It is currently not resolved how to interpret NSW for left
6376 // shift by BitWidth - 1, so we avoid applying flags in that
6377 // case. Remove this check (or this comment) once the situation
6378 // is resolved. See
6379 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
6380 // and http://reviews.llvm.org/D8890 .
6381 auto Flags = SCEV::FlagAnyWrap;
6382 if (BO->Op && SA->getValue().ult(BitWidth - 1))
6383 Flags = getNoWrapFlagsFromUB(BO->Op);
6385 Constant *X = ConstantInt::get(
6386 getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
6387 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
6389 break;
6391 case Instruction::AShr: {
6392 // AShr X, C, where C is a constant.
6393 ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
6394 if (!CI)
6395 break;
6397 Type *OuterTy = BO->LHS->getType();
6398 uint64_t BitWidth = getTypeSizeInBits(OuterTy);
6399 // If the shift count is not less than the bitwidth, the result of
6400 // the shift is undefined. Don't try to analyze it, because the
6401 // resolution chosen here may differ from the resolution chosen in
6402 // other parts of the compiler.
6403 if (CI->getValue().uge(BitWidth))
6404 break;
6406 if (CI->isZero())
6407 return getSCEV(BO->LHS); // shift by zero --> noop
6409 uint64_t AShrAmt = CI->getZExtValue();
6410 Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
6412 Operator *L = dyn_cast<Operator>(BO->LHS);
6413 if (L && L->getOpcode() == Instruction::Shl) {
6414 // X = Shl A, n
6415 // Y = AShr X, m
6416 // Both n and m are constant.
6418 const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
6419 if (L->getOperand(1) == BO->RHS)
6420 // For a two-shift sext-inreg, i.e. n = m,
6421 // use sext(trunc(x)) as the SCEV expression.
6422 return getSignExtendExpr(
6423 getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
6425 ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
6426 if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
6427 uint64_t ShlAmt = ShlAmtCI->getZExtValue();
6428 if (ShlAmt > AShrAmt) {
6429 // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
6430 // expression. We already checked that ShlAmt < BitWidth, so
6431 // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
6432 // ShlAmt - AShrAmt < Amt.
6433 APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
6434 ShlAmt - AShrAmt);
6435 return getSignExtendExpr(
6436 getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
6437 getConstant(Mul)), OuterTy);
6441 break;
6446 switch (U->getOpcode()) {
6447 case Instruction::Trunc:
6448 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
6450 case Instruction::ZExt:
6451 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6453 case Instruction::SExt:
6454 if (auto BO = MatchBinaryOp(U->getOperand(0), DT)) {
6455 // The NSW flag of a subtract does not always survive the conversion to
6456 // A + (-1)*B. By pushing sign extension onto its operands we are much
6457 // more likely to preserve NSW and allow later AddRec optimisations.
6459 // NOTE: This is effectively duplicating this logic from getSignExtend:
6460 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
6461 // but by that point the NSW information has potentially been lost.
6462 if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
6463 Type *Ty = U->getType();
6464 auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
6465 auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
6466 return getMinusSCEV(V1, V2, SCEV::FlagNSW);
6469 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
6471 case Instruction::BitCast:
6472 // BitCasts are no-op casts so we just eliminate the cast.
6473 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
6474 return getSCEV(U->getOperand(0));
6475 break;
6477 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
6478 // lead to pointer expressions which cannot safely be expanded to GEPs,
6479 // because ScalarEvolution doesn't respect the GEP aliasing rules when
6480 // simplifying integer expressions.
6482 case Instruction::GetElementPtr:
6483 return createNodeForGEP(cast<GEPOperator>(U));
6485 case Instruction::PHI:
6486 return createNodeForPHI(cast<PHINode>(U));
6488 case Instruction::Select:
6489 // U can also be a select constant expr, which let fall through. Since
6490 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
6491 // constant expressions cannot have instructions as operands, we'd have
6492 // returned getUnknown for a select constant expressions anyway.
6493 if (isa<Instruction>(U))
6494 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
6495 U->getOperand(1), U->getOperand(2));
6496 break;
6498 case Instruction::Call:
6499 case Instruction::Invoke:
6500 if (Value *RV = CallSite(U).getReturnedArgOperand())
6501 return getSCEV(RV);
6502 break;
6505 return getUnknown(V);
6508 //===----------------------------------------------------------------------===//
6509 // Iteration Count Computation Code
6512 static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
6513 if (!ExitCount)
6514 return 0;
6516 ConstantInt *ExitConst = ExitCount->getValue();
6518 // Guard against huge trip counts.
6519 if (ExitConst->getValue().getActiveBits() > 32)
6520 return 0;
6522 // In case of integer overflow, this returns 0, which is correct.
6523 return ((unsigned)ExitConst->getZExtValue()) + 1;
6526 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
6527 if (BasicBlock *ExitingBB = L->getExitingBlock())
6528 return getSmallConstantTripCount(L, ExitingBB);
6530 // No trip count information for multiple exits.
6531 return 0;
6534 unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L,
6535 BasicBlock *ExitingBlock) {
6536 assert(ExitingBlock && "Must pass a non-null exiting block!");
6537 assert(L->isLoopExiting(ExitingBlock) &&
6538 "Exiting block must actually branch out of the loop!");
6539 const SCEVConstant *ExitCount =
6540 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
6541 return getConstantTripCount(ExitCount);
6544 unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
6545 const auto *MaxExitCount =
6546 dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
6547 return getConstantTripCount(MaxExitCount);
6550 unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
6551 if (BasicBlock *ExitingBB = L->getExitingBlock())
6552 return getSmallConstantTripMultiple(L, ExitingBB);
6554 // No trip multiple information for multiple exits.
6555 return 0;
6558 /// Returns the largest constant divisor of the trip count of this loop as a
6559 /// normal unsigned value, if possible. This means that the actual trip count is
6560 /// always a multiple of the returned value (don't forget the trip count could
6561 /// very well be zero as well!).
6563 /// Returns 1 if the trip count is unknown or not guaranteed to be the
6564 /// multiple of a constant (which is also the case if the trip count is simply
6565 /// constant, use getSmallConstantTripCount for that case), Will also return 1
6566 /// if the trip count is very large (>= 2^32).
6568 /// As explained in the comments for getSmallConstantTripCount, this assumes
6569 /// that control exits the loop via ExitingBlock.
6570 unsigned
6571 ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
6572 BasicBlock *ExitingBlock) {
6573 assert(ExitingBlock && "Must pass a non-null exiting block!");
6574 assert(L->isLoopExiting(ExitingBlock) &&
6575 "Exiting block must actually branch out of the loop!");
6576 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
6577 if (ExitCount == getCouldNotCompute())
6578 return 1;
6580 // Get the trip count from the BE count by adding 1.
6581 const SCEV *TCExpr = getAddExpr(ExitCount, getOne(ExitCount->getType()));
6583 const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
6584 if (!TC)
6585 // Attempt to factor more general cases. Returns the greatest power of
6586 // two divisor. If overflow happens, the trip count expression is still
6587 // divisible by the greatest power of 2 divisor returned.
6588 return 1U << std::min((uint32_t)31, GetMinTrailingZeros(TCExpr));
6590 ConstantInt *Result = TC->getValue();
6592 // Guard against huge trip counts (this requires checking
6593 // for zero to handle the case where the trip count == -1 and the
6594 // addition wraps).
6595 if (!Result || Result->getValue().getActiveBits() > 32 ||
6596 Result->getValue().getActiveBits() == 0)
6597 return 1;
6599 return (unsigned)Result->getZExtValue();
6602 /// Get the expression for the number of loop iterations for which this loop is
6603 /// guaranteed not to exit via ExitingBlock. Otherwise return
6604 /// SCEVCouldNotCompute.
6605 const SCEV *ScalarEvolution::getExitCount(const Loop *L,
6606 BasicBlock *ExitingBlock) {
6607 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
6610 const SCEV *
6611 ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
6612 SCEVUnionPredicate &Preds) {
6613 return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
6616 const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
6617 return getBackedgeTakenInfo(L).getExact(L, this);
6620 /// Similar to getBackedgeTakenCount, except return the least SCEV value that is
6621 /// known never to be less than the actual backedge taken count.
6622 const SCEV *ScalarEvolution::getConstantMaxBackedgeTakenCount(const Loop *L) {
6623 return getBackedgeTakenInfo(L).getMax(this);
6626 bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
6627 return getBackedgeTakenInfo(L).isMaxOrZero(this);
6630 /// Push PHI nodes in the header of the given loop onto the given Worklist.
6631 static void
6632 PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
6633 BasicBlock *Header = L->getHeader();
6635 // Push all Loop-header PHIs onto the Worklist stack.
6636 for (PHINode &PN : Header->phis())
6637 Worklist.push_back(&PN);
6640 const ScalarEvolution::BackedgeTakenInfo &
6641 ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
6642 auto &BTI = getBackedgeTakenInfo(L);
6643 if (BTI.hasFullInfo())
6644 return BTI;
6646 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6648 if (!Pair.second)
6649 return Pair.first->second;
6651 BackedgeTakenInfo Result =
6652 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
6654 return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
6657 const ScalarEvolution::BackedgeTakenInfo &
6658 ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
6659 // Initially insert an invalid entry for this loop. If the insertion
6660 // succeeds, proceed to actually compute a backedge-taken count and
6661 // update the value. The temporary CouldNotCompute value tells SCEV
6662 // code elsewhere that it shouldn't attempt to request a new
6663 // backedge-taken count, which could result in infinite recursion.
6664 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
6665 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
6666 if (!Pair.second)
6667 return Pair.first->second;
6669 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
6670 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
6671 // must be cleared in this scope.
6672 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
6674 // In product build, there are no usage of statistic.
6675 (void)NumTripCountsComputed;
6676 (void)NumTripCountsNotComputed;
6677 #if LLVM_ENABLE_STATS || !defined(NDEBUG)
6678 const SCEV *BEExact = Result.getExact(L, this);
6679 if (BEExact != getCouldNotCompute()) {
6680 assert(isLoopInvariant(BEExact, L) &&
6681 isLoopInvariant(Result.getMax(this), L) &&
6682 "Computed backedge-taken count isn't loop invariant for loop!");
6683 ++NumTripCountsComputed;
6685 else if (Result.getMax(this) == getCouldNotCompute() &&
6686 isa<PHINode>(L->getHeader()->begin())) {
6687 // Only count loops that have phi nodes as not being computable.
6688 ++NumTripCountsNotComputed;
6690 #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
6692 // Now that we know more about the trip count for this loop, forget any
6693 // existing SCEV values for PHI nodes in this loop since they are only
6694 // conservative estimates made without the benefit of trip count
6695 // information. This is similar to the code in forgetLoop, except that
6696 // it handles SCEVUnknown PHI nodes specially.
6697 if (Result.hasAnyInfo()) {
6698 SmallVector<Instruction *, 16> Worklist;
6699 PushLoopPHIs(L, Worklist);
6701 SmallPtrSet<Instruction *, 8> Discovered;
6702 while (!Worklist.empty()) {
6703 Instruction *I = Worklist.pop_back_val();
6705 ValueExprMapType::iterator It =
6706 ValueExprMap.find_as(static_cast<Value *>(I));
6707 if (It != ValueExprMap.end()) {
6708 const SCEV *Old = It->second;
6710 // SCEVUnknown for a PHI either means that it has an unrecognized
6711 // structure, or it's a PHI that's in the progress of being computed
6712 // by createNodeForPHI. In the former case, additional loop trip
6713 // count information isn't going to change anything. In the later
6714 // case, createNodeForPHI will perform the necessary updates on its
6715 // own when it gets to that point.
6716 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
6717 eraseValueFromMap(It->first);
6718 forgetMemoizedResults(Old);
6720 if (PHINode *PN = dyn_cast<PHINode>(I))
6721 ConstantEvolutionLoopExitValue.erase(PN);
6724 // Since we don't need to invalidate anything for correctness and we're
6725 // only invalidating to make SCEV's results more precise, we get to stop
6726 // early to avoid invalidating too much. This is especially important in
6727 // cases like:
6729 // %v = f(pn0, pn1) // pn0 and pn1 used through some other phi node
6730 // loop0:
6731 // %pn0 = phi
6732 // ...
6733 // loop1:
6734 // %pn1 = phi
6735 // ...
6737 // where both loop0 and loop1's backedge taken count uses the SCEV
6738 // expression for %v. If we don't have the early stop below then in cases
6739 // like the above, getBackedgeTakenInfo(loop1) will clear out the trip
6740 // count for loop0 and getBackedgeTakenInfo(loop0) will clear out the trip
6741 // count for loop1, effectively nullifying SCEV's trip count cache.
6742 for (auto *U : I->users())
6743 if (auto *I = dyn_cast<Instruction>(U)) {
6744 auto *LoopForUser = LI.getLoopFor(I->getParent());
6745 if (LoopForUser && L->contains(LoopForUser) &&
6746 Discovered.insert(I).second)
6747 Worklist.push_back(I);
6752 // Re-lookup the insert position, since the call to
6753 // computeBackedgeTakenCount above could result in a
6754 // recusive call to getBackedgeTakenInfo (on a different
6755 // loop), which would invalidate the iterator computed
6756 // earlier.
6757 return BackedgeTakenCounts.find(L)->second = std::move(Result);
6760 void ScalarEvolution::forgetAllLoops() {
6761 // This method is intended to forget all info about loops. It should
6762 // invalidate caches as if the following happened:
6763 // - The trip counts of all loops have changed arbitrarily
6764 // - Every llvm::Value has been updated in place to produce a different
6765 // result.
6766 BackedgeTakenCounts.clear();
6767 PredicatedBackedgeTakenCounts.clear();
6768 LoopPropertiesCache.clear();
6769 ConstantEvolutionLoopExitValue.clear();
6770 ValueExprMap.clear();
6771 ValuesAtScopes.clear();
6772 LoopDispositions.clear();
6773 BlockDispositions.clear();
6774 UnsignedRanges.clear();
6775 SignedRanges.clear();
6776 ExprValueMap.clear();
6777 HasRecMap.clear();
6778 MinTrailingZerosCache.clear();
6779 PredicatedSCEVRewrites.clear();
6782 void ScalarEvolution::forgetLoop(const Loop *L) {
6783 // Drop any stored trip count value.
6784 auto RemoveLoopFromBackedgeMap =
6785 [](DenseMap<const Loop *, BackedgeTakenInfo> &Map, const Loop *L) {
6786 auto BTCPos = Map.find(L);
6787 if (BTCPos != Map.end()) {
6788 BTCPos->second.clear();
6789 Map.erase(BTCPos);
6793 SmallVector<const Loop *, 16> LoopWorklist(1, L);
6794 SmallVector<Instruction *, 32> Worklist;
6795 SmallPtrSet<Instruction *, 16> Visited;
6797 // Iterate over all the loops and sub-loops to drop SCEV information.
6798 while (!LoopWorklist.empty()) {
6799 auto *CurrL = LoopWorklist.pop_back_val();
6801 RemoveLoopFromBackedgeMap(BackedgeTakenCounts, CurrL);
6802 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts, CurrL);
6804 // Drop information about predicated SCEV rewrites for this loop.
6805 for (auto I = PredicatedSCEVRewrites.begin();
6806 I != PredicatedSCEVRewrites.end();) {
6807 std::pair<const SCEV *, const Loop *> Entry = I->first;
6808 if (Entry.second == CurrL)
6809 PredicatedSCEVRewrites.erase(I++);
6810 else
6811 ++I;
6814 auto LoopUsersItr = LoopUsers.find(CurrL);
6815 if (LoopUsersItr != LoopUsers.end()) {
6816 for (auto *S : LoopUsersItr->second)
6817 forgetMemoizedResults(S);
6818 LoopUsers.erase(LoopUsersItr);
6821 // Drop information about expressions based on loop-header PHIs.
6822 PushLoopPHIs(CurrL, Worklist);
6824 while (!Worklist.empty()) {
6825 Instruction *I = Worklist.pop_back_val();
6826 if (!Visited.insert(I).second)
6827 continue;
6829 ValueExprMapType::iterator It =
6830 ValueExprMap.find_as(static_cast<Value *>(I));
6831 if (It != ValueExprMap.end()) {
6832 eraseValueFromMap(It->first);
6833 forgetMemoizedResults(It->second);
6834 if (PHINode *PN = dyn_cast<PHINode>(I))
6835 ConstantEvolutionLoopExitValue.erase(PN);
6838 PushDefUseChildren(I, Worklist);
6841 LoopPropertiesCache.erase(CurrL);
6842 // Forget all contained loops too, to avoid dangling entries in the
6843 // ValuesAtScopes map.
6844 LoopWorklist.append(CurrL->begin(), CurrL->end());
6848 void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
6849 while (Loop *Parent = L->getParentLoop())
6850 L = Parent;
6851 forgetLoop(L);
6854 void ScalarEvolution::forgetValue(Value *V) {
6855 Instruction *I = dyn_cast<Instruction>(V);
6856 if (!I) return;
6858 // Drop information about expressions based on loop-header PHIs.
6859 SmallVector<Instruction *, 16> Worklist;
6860 Worklist.push_back(I);
6862 SmallPtrSet<Instruction *, 8> Visited;
6863 while (!Worklist.empty()) {
6864 I = Worklist.pop_back_val();
6865 if (!Visited.insert(I).second)
6866 continue;
6868 ValueExprMapType::iterator It =
6869 ValueExprMap.find_as(static_cast<Value *>(I));
6870 if (It != ValueExprMap.end()) {
6871 eraseValueFromMap(It->first);
6872 forgetMemoizedResults(It->second);
6873 if (PHINode *PN = dyn_cast<PHINode>(I))
6874 ConstantEvolutionLoopExitValue.erase(PN);
6877 PushDefUseChildren(I, Worklist);
6881 /// Get the exact loop backedge taken count considering all loop exits. A
6882 /// computable result can only be returned for loops with all exiting blocks
6883 /// dominating the latch. howFarToZero assumes that the limit of each loop test
6884 /// is never skipped. This is a valid assumption as long as the loop exits via
6885 /// that test. For precise results, it is the caller's responsibility to specify
6886 /// the relevant loop exiting block using getExact(ExitingBlock, SE).
6887 const SCEV *
6888 ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
6889 SCEVUnionPredicate *Preds) const {
6890 // If any exits were not computable, the loop is not computable.
6891 if (!isComplete() || ExitNotTaken.empty())
6892 return SE->getCouldNotCompute();
6894 const BasicBlock *Latch = L->getLoopLatch();
6895 // All exiting blocks we have collected must dominate the only backedge.
6896 if (!Latch)
6897 return SE->getCouldNotCompute();
6899 // All exiting blocks we have gathered dominate loop's latch, so exact trip
6900 // count is simply a minimum out of all these calculated exit counts.
6901 SmallVector<const SCEV *, 2> Ops;
6902 for (auto &ENT : ExitNotTaken) {
6903 const SCEV *BECount = ENT.ExactNotTaken;
6904 assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
6905 assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
6906 "We should only have known counts for exiting blocks that dominate "
6907 "latch!");
6909 Ops.push_back(BECount);
6911 if (Preds && !ENT.hasAlwaysTruePredicate())
6912 Preds->add(ENT.Predicate.get());
6914 assert((Preds || ENT.hasAlwaysTruePredicate()) &&
6915 "Predicate should be always true!");
6918 return SE->getUMinFromMismatchedTypes(Ops);
6921 /// Get the exact not taken count for this loop exit.
6922 const SCEV *
6923 ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
6924 ScalarEvolution *SE) const {
6925 for (auto &ENT : ExitNotTaken)
6926 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
6927 return ENT.ExactNotTaken;
6929 return SE->getCouldNotCompute();
6932 /// getMax - Get the max backedge taken count for the loop.
6933 const SCEV *
6934 ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
6935 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6936 return !ENT.hasAlwaysTruePredicate();
6939 if (any_of(ExitNotTaken, PredicateNotAlwaysTrue) || !getMax())
6940 return SE->getCouldNotCompute();
6942 assert((isa<SCEVCouldNotCompute>(getMax()) || isa<SCEVConstant>(getMax())) &&
6943 "No point in having a non-constant max backedge taken count!");
6944 return getMax();
6947 bool ScalarEvolution::BackedgeTakenInfo::isMaxOrZero(ScalarEvolution *SE) const {
6948 auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
6949 return !ENT.hasAlwaysTruePredicate();
6951 return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
6954 bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
6955 ScalarEvolution *SE) const {
6956 if (getMax() && getMax() != SE->getCouldNotCompute() &&
6957 SE->hasOperand(getMax(), S))
6958 return true;
6960 for (auto &ENT : ExitNotTaken)
6961 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
6962 SE->hasOperand(ENT.ExactNotTaken, S))
6963 return true;
6965 return false;
6968 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
6969 : ExactNotTaken(E), MaxNotTaken(E) {
6970 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6971 isa<SCEVConstant>(MaxNotTaken)) &&
6972 "No point in having a non-constant max backedge taken count!");
6975 ScalarEvolution::ExitLimit::ExitLimit(
6976 const SCEV *E, const SCEV *M, bool MaxOrZero,
6977 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
6978 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
6979 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
6980 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
6981 "Exact is not allowed to be less precise than Max");
6982 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6983 isa<SCEVConstant>(MaxNotTaken)) &&
6984 "No point in having a non-constant max backedge taken count!");
6985 for (auto *PredSet : PredSetList)
6986 for (auto *P : *PredSet)
6987 addPredicate(P);
6990 ScalarEvolution::ExitLimit::ExitLimit(
6991 const SCEV *E, const SCEV *M, bool MaxOrZero,
6992 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
6993 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {
6994 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
6995 isa<SCEVConstant>(MaxNotTaken)) &&
6996 "No point in having a non-constant max backedge taken count!");
6999 ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E, const SCEV *M,
7000 bool MaxOrZero)
7001 : ExitLimit(E, M, MaxOrZero, None) {
7002 assert((isa<SCEVCouldNotCompute>(MaxNotTaken) ||
7003 isa<SCEVConstant>(MaxNotTaken)) &&
7004 "No point in having a non-constant max backedge taken count!");
7007 /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
7008 /// computable exit into a persistent ExitNotTakenInfo array.
7009 ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
7010 ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo>
7011 ExitCounts,
7012 bool Complete, const SCEV *MaxCount, bool MaxOrZero)
7013 : MaxAndComplete(MaxCount, Complete), MaxOrZero(MaxOrZero) {
7014 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7016 ExitNotTaken.reserve(ExitCounts.size());
7017 std::transform(
7018 ExitCounts.begin(), ExitCounts.end(), std::back_inserter(ExitNotTaken),
7019 [&](const EdgeExitInfo &EEI) {
7020 BasicBlock *ExitBB = EEI.first;
7021 const ExitLimit &EL = EEI.second;
7022 if (EL.Predicates.empty())
7023 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, nullptr);
7025 std::unique_ptr<SCEVUnionPredicate> Predicate(new SCEVUnionPredicate);
7026 for (auto *Pred : EL.Predicates)
7027 Predicate->add(Pred);
7029 return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken, std::move(Predicate));
7031 assert((isa<SCEVCouldNotCompute>(MaxCount) || isa<SCEVConstant>(MaxCount)) &&
7032 "No point in having a non-constant max backedge taken count!");
7035 /// Invalidate this result and free the ExitNotTakenInfo array.
7036 void ScalarEvolution::BackedgeTakenInfo::clear() {
7037 ExitNotTaken.clear();
7040 /// Compute the number of times the backedge of the specified loop will execute.
7041 ScalarEvolution::BackedgeTakenInfo
7042 ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
7043 bool AllowPredicates) {
7044 SmallVector<BasicBlock *, 8> ExitingBlocks;
7045 L->getExitingBlocks(ExitingBlocks);
7047 using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
7049 SmallVector<EdgeExitInfo, 4> ExitCounts;
7050 bool CouldComputeBECount = true;
7051 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
7052 const SCEV *MustExitMaxBECount = nullptr;
7053 const SCEV *MayExitMaxBECount = nullptr;
7054 bool MustExitMaxOrZero = false;
7056 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
7057 // and compute maxBECount.
7058 // Do a union of all the predicates here.
7059 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
7060 BasicBlock *ExitBB = ExitingBlocks[i];
7061 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
7063 assert((AllowPredicates || EL.Predicates.empty()) &&
7064 "Predicated exit limit when predicates are not allowed!");
7066 // 1. For each exit that can be computed, add an entry to ExitCounts.
7067 // CouldComputeBECount is true only if all exits can be computed.
7068 if (EL.ExactNotTaken == getCouldNotCompute())
7069 // We couldn't compute an exact value for this exit, so
7070 // we won't be able to compute an exact value for the loop.
7071 CouldComputeBECount = false;
7072 else
7073 ExitCounts.emplace_back(ExitBB, EL);
7075 // 2. Derive the loop's MaxBECount from each exit's max number of
7076 // non-exiting iterations. Partition the loop exits into two kinds:
7077 // LoopMustExits and LoopMayExits.
7079 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
7080 // is a LoopMayExit. If any computable LoopMustExit is found, then
7081 // MaxBECount is the minimum EL.MaxNotTaken of computable
7082 // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
7083 // EL.MaxNotTaken, where CouldNotCompute is considered greater than any
7084 // computable EL.MaxNotTaken.
7085 if (EL.MaxNotTaken != getCouldNotCompute() && Latch &&
7086 DT.dominates(ExitBB, Latch)) {
7087 if (!MustExitMaxBECount) {
7088 MustExitMaxBECount = EL.MaxNotTaken;
7089 MustExitMaxOrZero = EL.MaxOrZero;
7090 } else {
7091 MustExitMaxBECount =
7092 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.MaxNotTaken);
7094 } else if (MayExitMaxBECount != getCouldNotCompute()) {
7095 if (!MayExitMaxBECount || EL.MaxNotTaken == getCouldNotCompute())
7096 MayExitMaxBECount = EL.MaxNotTaken;
7097 else {
7098 MayExitMaxBECount =
7099 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.MaxNotTaken);
7103 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
7104 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
7105 // The loop backedge will be taken the maximum or zero times if there's
7106 // a single exit that must be taken the maximum or zero times.
7107 bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
7108 return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
7109 MaxBECount, MaxOrZero);
7112 ScalarEvolution::ExitLimit
7113 ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
7114 bool AllowPredicates) {
7115 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
7116 // If our exiting block does not dominate the latch, then its connection with
7117 // loop's exit limit may be far from trivial.
7118 const BasicBlock *Latch = L->getLoopLatch();
7119 if (!Latch || !DT.dominates(ExitingBlock, Latch))
7120 return getCouldNotCompute();
7122 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
7123 Instruction *Term = ExitingBlock->getTerminator();
7124 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
7125 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
7126 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
7127 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
7128 "It should have one successor in loop and one exit block!");
7129 // Proceed to the next level to examine the exit condition expression.
7130 return computeExitLimitFromCond(
7131 L, BI->getCondition(), ExitIfTrue,
7132 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
7135 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
7136 // For switch, make sure that there is a single exit from the loop.
7137 BasicBlock *Exit = nullptr;
7138 for (auto *SBB : successors(ExitingBlock))
7139 if (!L->contains(SBB)) {
7140 if (Exit) // Multiple exit successors.
7141 return getCouldNotCompute();
7142 Exit = SBB;
7144 assert(Exit && "Exiting block must have at least one exit");
7145 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
7146 /*ControlsExit=*/IsOnlyExit);
7149 return getCouldNotCompute();
7152 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
7153 const Loop *L, Value *ExitCond, bool ExitIfTrue,
7154 bool ControlsExit, bool AllowPredicates) {
7155 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
7156 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
7157 ControlsExit, AllowPredicates);
7160 Optional<ScalarEvolution::ExitLimit>
7161 ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
7162 bool ExitIfTrue, bool ControlsExit,
7163 bool AllowPredicates) {
7164 (void)this->L;
7165 (void)this->ExitIfTrue;
7166 (void)this->AllowPredicates;
7168 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7169 this->AllowPredicates == AllowPredicates &&
7170 "Variance in assumed invariant key components!");
7171 auto Itr = TripCountMap.find({ExitCond, ControlsExit});
7172 if (Itr == TripCountMap.end())
7173 return None;
7174 return Itr->second;
7177 void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
7178 bool ExitIfTrue,
7179 bool ControlsExit,
7180 bool AllowPredicates,
7181 const ExitLimit &EL) {
7182 assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
7183 this->AllowPredicates == AllowPredicates &&
7184 "Variance in assumed invariant key components!");
7186 auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
7187 assert(InsertResult.second && "Expected successful insertion!");
7188 (void)InsertResult;
7189 (void)ExitIfTrue;
7192 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
7193 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7194 bool ControlsExit, bool AllowPredicates) {
7196 if (auto MaybeEL =
7197 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
7198 return *MaybeEL;
7200 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
7201 ControlsExit, AllowPredicates);
7202 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
7203 return EL;
7206 ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
7207 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
7208 bool ControlsExit, bool AllowPredicates) {
7209 // Check if the controlling expression for this loop is an And or Or.
7210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
7211 if (BO->getOpcode() == Instruction::And) {
7212 // Recurse on the operands of the and.
7213 bool EitherMayExit = !ExitIfTrue;
7214 ExitLimit EL0 = computeExitLimitFromCondCached(
7215 Cache, L, BO->getOperand(0), ExitIfTrue,
7216 ControlsExit && !EitherMayExit, AllowPredicates);
7217 ExitLimit EL1 = computeExitLimitFromCondCached(
7218 Cache, L, BO->getOperand(1), ExitIfTrue,
7219 ControlsExit && !EitherMayExit, AllowPredicates);
7220 const SCEV *BECount = getCouldNotCompute();
7221 const SCEV *MaxBECount = getCouldNotCompute();
7222 if (EitherMayExit) {
7223 // Both conditions must be true for the loop to continue executing.
7224 // Choose the less conservative count.
7225 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7226 EL1.ExactNotTaken == getCouldNotCompute())
7227 BECount = getCouldNotCompute();
7228 else
7229 BECount =
7230 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7231 if (EL0.MaxNotTaken == getCouldNotCompute())
7232 MaxBECount = EL1.MaxNotTaken;
7233 else if (EL1.MaxNotTaken == getCouldNotCompute())
7234 MaxBECount = EL0.MaxNotTaken;
7235 else
7236 MaxBECount =
7237 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7238 } else {
7239 // Both conditions must be true at the same time for the loop to exit.
7240 // For now, be conservative.
7241 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7242 MaxBECount = EL0.MaxNotTaken;
7243 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7244 BECount = EL0.ExactNotTaken;
7247 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7248 // to be more aggressive when computing BECount than when computing
7249 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7250 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7251 // to not.
7252 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7253 !isa<SCEVCouldNotCompute>(BECount))
7254 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7256 return ExitLimit(BECount, MaxBECount, false,
7257 {&EL0.Predicates, &EL1.Predicates});
7259 if (BO->getOpcode() == Instruction::Or) {
7260 // Recurse on the operands of the or.
7261 bool EitherMayExit = ExitIfTrue;
7262 ExitLimit EL0 = computeExitLimitFromCondCached(
7263 Cache, L, BO->getOperand(0), ExitIfTrue,
7264 ControlsExit && !EitherMayExit, AllowPredicates);
7265 ExitLimit EL1 = computeExitLimitFromCondCached(
7266 Cache, L, BO->getOperand(1), ExitIfTrue,
7267 ControlsExit && !EitherMayExit, AllowPredicates);
7268 const SCEV *BECount = getCouldNotCompute();
7269 const SCEV *MaxBECount = getCouldNotCompute();
7270 if (EitherMayExit) {
7271 // Both conditions must be false for the loop to continue executing.
7272 // Choose the less conservative count.
7273 if (EL0.ExactNotTaken == getCouldNotCompute() ||
7274 EL1.ExactNotTaken == getCouldNotCompute())
7275 BECount = getCouldNotCompute();
7276 else
7277 BECount =
7278 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
7279 if (EL0.MaxNotTaken == getCouldNotCompute())
7280 MaxBECount = EL1.MaxNotTaken;
7281 else if (EL1.MaxNotTaken == getCouldNotCompute())
7282 MaxBECount = EL0.MaxNotTaken;
7283 else
7284 MaxBECount =
7285 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
7286 } else {
7287 // Both conditions must be false at the same time for the loop to exit.
7288 // For now, be conservative.
7289 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
7290 MaxBECount = EL0.MaxNotTaken;
7291 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
7292 BECount = EL0.ExactNotTaken;
7294 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
7295 // to be more aggressive when computing BECount than when computing
7296 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
7297 // EL1.ExactNotTaken to match, but for EL0.MaxNotTaken and EL1.MaxNotTaken
7298 // to not.
7299 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
7300 !isa<SCEVCouldNotCompute>(BECount))
7301 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
7303 return ExitLimit(BECount, MaxBECount, false,
7304 {&EL0.Predicates, &EL1.Predicates});
7308 // With an icmp, it may be feasible to compute an exact backedge-taken count.
7309 // Proceed to the next level to examine the icmp.
7310 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
7311 ExitLimit EL =
7312 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
7313 if (EL.hasFullInfo() || !AllowPredicates)
7314 return EL;
7316 // Try again, but use SCEV predicates this time.
7317 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
7318 /*AllowPredicates=*/true);
7321 // Check for a constant condition. These are normally stripped out by
7322 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
7323 // preserve the CFG and is temporarily leaving constant conditions
7324 // in place.
7325 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
7326 if (ExitIfTrue == !CI->getZExtValue())
7327 // The backedge is always taken.
7328 return getCouldNotCompute();
7329 else
7330 // The backedge is never taken.
7331 return getZero(CI->getType());
7334 // If it's not an integer or pointer comparison then compute it the hard way.
7335 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7338 ScalarEvolution::ExitLimit
7339 ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
7340 ICmpInst *ExitCond,
7341 bool ExitIfTrue,
7342 bool ControlsExit,
7343 bool AllowPredicates) {
7344 // If the condition was exit on true, convert the condition to exit on false
7345 ICmpInst::Predicate Pred;
7346 if (!ExitIfTrue)
7347 Pred = ExitCond->getPredicate();
7348 else
7349 Pred = ExitCond->getInversePredicate();
7350 const ICmpInst::Predicate OriginalPred = Pred;
7352 // Handle common loops like: for (X = "string"; *X; ++X)
7353 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
7354 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
7355 ExitLimit ItCnt =
7356 computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
7357 if (ItCnt.hasAnyInfo())
7358 return ItCnt;
7361 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
7362 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
7364 // Try to evaluate any dependencies out of the loop.
7365 LHS = getSCEVAtScope(LHS, L);
7366 RHS = getSCEVAtScope(RHS, L);
7368 // At this point, we would like to compute how many iterations of the
7369 // loop the predicate will return true for these inputs.
7370 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
7371 // If there is a loop-invariant, force it into the RHS.
7372 std::swap(LHS, RHS);
7373 Pred = ICmpInst::getSwappedPredicate(Pred);
7376 // Simplify the operands before analyzing them.
7377 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7379 // If we have a comparison of a chrec against a constant, try to use value
7380 // ranges to answer this query.
7381 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
7382 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
7383 if (AddRec->getLoop() == L) {
7384 // Form the constant range.
7385 ConstantRange CompRange =
7386 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
7388 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
7389 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
7392 switch (Pred) {
7393 case ICmpInst::ICMP_NE: { // while (X != Y)
7394 // Convert to: while (X-Y != 0)
7395 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
7396 AllowPredicates);
7397 if (EL.hasAnyInfo()) return EL;
7398 break;
7400 case ICmpInst::ICMP_EQ: { // while (X == Y)
7401 // Convert to: while (X-Y == 0)
7402 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
7403 if (EL.hasAnyInfo()) return EL;
7404 break;
7406 case ICmpInst::ICMP_SLT:
7407 case ICmpInst::ICMP_ULT: { // while (X < Y)
7408 bool IsSigned = Pred == ICmpInst::ICMP_SLT;
7409 ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
7410 AllowPredicates);
7411 if (EL.hasAnyInfo()) return EL;
7412 break;
7414 case ICmpInst::ICMP_SGT:
7415 case ICmpInst::ICMP_UGT: { // while (X > Y)
7416 bool IsSigned = Pred == ICmpInst::ICMP_SGT;
7417 ExitLimit EL =
7418 howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
7419 AllowPredicates);
7420 if (EL.hasAnyInfo()) return EL;
7421 break;
7423 default:
7424 break;
7427 auto *ExhaustiveCount =
7428 computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
7430 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
7431 return ExhaustiveCount;
7433 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
7434 ExitCond->getOperand(1), L, OriginalPred);
7437 ScalarEvolution::ExitLimit
7438 ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
7439 SwitchInst *Switch,
7440 BasicBlock *ExitingBlock,
7441 bool ControlsExit) {
7442 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
7444 // Give up if the exit is the default dest of a switch.
7445 if (Switch->getDefaultDest() == ExitingBlock)
7446 return getCouldNotCompute();
7448 assert(L->contains(Switch->getDefaultDest()) &&
7449 "Default case must not exit the loop!");
7450 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
7451 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
7453 // while (X != Y) --> while (X-Y != 0)
7454 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
7455 if (EL.hasAnyInfo())
7456 return EL;
7458 return getCouldNotCompute();
7461 static ConstantInt *
7462 EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
7463 ScalarEvolution &SE) {
7464 const SCEV *InVal = SE.getConstant(C);
7465 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
7466 assert(isa<SCEVConstant>(Val) &&
7467 "Evaluation of SCEV at constant didn't fold correctly?");
7468 return cast<SCEVConstant>(Val)->getValue();
7471 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
7472 /// compute the backedge execution count.
7473 ScalarEvolution::ExitLimit
7474 ScalarEvolution::computeLoadConstantCompareExitLimit(
7475 LoadInst *LI,
7476 Constant *RHS,
7477 const Loop *L,
7478 ICmpInst::Predicate predicate) {
7479 if (LI->isVolatile()) return getCouldNotCompute();
7481 // Check to see if the loaded pointer is a getelementptr of a global.
7482 // TODO: Use SCEV instead of manually grubbing with GEPs.
7483 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
7484 if (!GEP) return getCouldNotCompute();
7486 // Make sure that it is really a constant global we are gepping, with an
7487 // initializer, and make sure the first IDX is really 0.
7488 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
7489 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
7490 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
7491 !cast<Constant>(GEP->getOperand(1))->isNullValue())
7492 return getCouldNotCompute();
7494 // Okay, we allow one non-constant index into the GEP instruction.
7495 Value *VarIdx = nullptr;
7496 std::vector<Constant*> Indexes;
7497 unsigned VarIdxNum = 0;
7498 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
7499 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
7500 Indexes.push_back(CI);
7501 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
7502 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
7503 VarIdx = GEP->getOperand(i);
7504 VarIdxNum = i-2;
7505 Indexes.push_back(nullptr);
7508 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
7509 if (!VarIdx)
7510 return getCouldNotCompute();
7512 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
7513 // Check to see if X is a loop variant variable value now.
7514 const SCEV *Idx = getSCEV(VarIdx);
7515 Idx = getSCEVAtScope(Idx, L);
7517 // We can only recognize very limited forms of loop index expressions, in
7518 // particular, only affine AddRec's like {C1,+,C2}.
7519 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
7520 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
7521 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
7522 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
7523 return getCouldNotCompute();
7525 unsigned MaxSteps = MaxBruteForceIterations;
7526 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
7527 ConstantInt *ItCst = ConstantInt::get(
7528 cast<IntegerType>(IdxExpr->getType()), IterationNum);
7529 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
7531 // Form the GEP offset.
7532 Indexes[VarIdxNum] = Val;
7534 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
7535 Indexes);
7536 if (!Result) break; // Cannot compute!
7538 // Evaluate the condition for this iteration.
7539 Result = ConstantExpr::getICmp(predicate, Result, RHS);
7540 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
7541 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
7542 ++NumArrayLenItCounts;
7543 return getConstant(ItCst); // Found terminating iteration!
7546 return getCouldNotCompute();
7549 ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
7550 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
7551 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
7552 if (!RHS)
7553 return getCouldNotCompute();
7555 const BasicBlock *Latch = L->getLoopLatch();
7556 if (!Latch)
7557 return getCouldNotCompute();
7559 const BasicBlock *Predecessor = L->getLoopPredecessor();
7560 if (!Predecessor)
7561 return getCouldNotCompute();
7563 // Return true if V is of the form "LHS `shift_op` <positive constant>".
7564 // Return LHS in OutLHS and shift_opt in OutOpCode.
7565 auto MatchPositiveShift =
7566 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
7568 using namespace PatternMatch;
7570 ConstantInt *ShiftAmt;
7571 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7572 OutOpCode = Instruction::LShr;
7573 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7574 OutOpCode = Instruction::AShr;
7575 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
7576 OutOpCode = Instruction::Shl;
7577 else
7578 return false;
7580 return ShiftAmt->getValue().isStrictlyPositive();
7583 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
7585 // loop:
7586 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
7587 // %iv.shifted = lshr i32 %iv, <positive constant>
7589 // Return true on a successful match. Return the corresponding PHI node (%iv
7590 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
7591 auto MatchShiftRecurrence =
7592 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
7593 Optional<Instruction::BinaryOps> PostShiftOpCode;
7596 Instruction::BinaryOps OpC;
7597 Value *V;
7599 // If we encounter a shift instruction, "peel off" the shift operation,
7600 // and remember that we did so. Later when we inspect %iv's backedge
7601 // value, we will make sure that the backedge value uses the same
7602 // operation.
7604 // Note: the peeled shift operation does not have to be the same
7605 // instruction as the one feeding into the PHI's backedge value. We only
7606 // really care about it being the same *kind* of shift instruction --
7607 // that's all that is required for our later inferences to hold.
7608 if (MatchPositiveShift(LHS, V, OpC)) {
7609 PostShiftOpCode = OpC;
7610 LHS = V;
7614 PNOut = dyn_cast<PHINode>(LHS);
7615 if (!PNOut || PNOut->getParent() != L->getHeader())
7616 return false;
7618 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
7619 Value *OpLHS;
7621 return
7622 // The backedge value for the PHI node must be a shift by a positive
7623 // amount
7624 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
7626 // of the PHI node itself
7627 OpLHS == PNOut &&
7629 // and the kind of shift should be match the kind of shift we peeled
7630 // off, if any.
7631 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
7634 PHINode *PN;
7635 Instruction::BinaryOps OpCode;
7636 if (!MatchShiftRecurrence(LHS, PN, OpCode))
7637 return getCouldNotCompute();
7639 const DataLayout &DL = getDataLayout();
7641 // The key rationale for this optimization is that for some kinds of shift
7642 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
7643 // within a finite number of iterations. If the condition guarding the
7644 // backedge (in the sense that the backedge is taken if the condition is true)
7645 // is false for the value the shift recurrence stabilizes to, then we know
7646 // that the backedge is taken only a finite number of times.
7648 ConstantInt *StableValue = nullptr;
7649 switch (OpCode) {
7650 default:
7651 llvm_unreachable("Impossible case!");
7653 case Instruction::AShr: {
7654 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
7655 // bitwidth(K) iterations.
7656 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
7657 KnownBits Known = computeKnownBits(FirstValue, DL, 0, nullptr,
7658 Predecessor->getTerminator(), &DT);
7659 auto *Ty = cast<IntegerType>(RHS->getType());
7660 if (Known.isNonNegative())
7661 StableValue = ConstantInt::get(Ty, 0);
7662 else if (Known.isNegative())
7663 StableValue = ConstantInt::get(Ty, -1, true);
7664 else
7665 return getCouldNotCompute();
7667 break;
7669 case Instruction::LShr:
7670 case Instruction::Shl:
7671 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
7672 // stabilize to 0 in at most bitwidth(K) iterations.
7673 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
7674 break;
7677 auto *Result =
7678 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
7679 assert(Result->getType()->isIntegerTy(1) &&
7680 "Otherwise cannot be an operand to a branch instruction");
7682 if (Result->isZeroValue()) {
7683 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
7684 const SCEV *UpperBound =
7685 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
7686 return ExitLimit(getCouldNotCompute(), UpperBound, false);
7689 return getCouldNotCompute();
7692 /// Return true if we can constant fold an instruction of the specified type,
7693 /// assuming that all operands were constants.
7694 static bool CanConstantFold(const Instruction *I) {
7695 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
7696 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7697 isa<LoadInst>(I) || isa<ExtractValueInst>(I))
7698 return true;
7700 if (const CallInst *CI = dyn_cast<CallInst>(I))
7701 if (const Function *F = CI->getCalledFunction())
7702 return canConstantFoldCallTo(CI, F);
7703 return false;
7706 /// Determine whether this instruction can constant evolve within this loop
7707 /// assuming its operands can all constant evolve.
7708 static bool canConstantEvolve(Instruction *I, const Loop *L) {
7709 // An instruction outside of the loop can't be derived from a loop PHI.
7710 if (!L->contains(I)) return false;
7712 if (isa<PHINode>(I)) {
7713 // We don't currently keep track of the control flow needed to evaluate
7714 // PHIs, so we cannot handle PHIs inside of loops.
7715 return L->getHeader() == I->getParent();
7718 // If we won't be able to constant fold this expression even if the operands
7719 // are constants, bail early.
7720 return CanConstantFold(I);
7723 /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
7724 /// recursing through each instruction operand until reaching a loop header phi.
7725 static PHINode *
7726 getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
7727 DenseMap<Instruction *, PHINode *> &PHIMap,
7728 unsigned Depth) {
7729 if (Depth > MaxConstantEvolvingDepth)
7730 return nullptr;
7732 // Otherwise, we can evaluate this instruction if all of its operands are
7733 // constant or derived from a PHI node themselves.
7734 PHINode *PHI = nullptr;
7735 for (Value *Op : UseInst->operands()) {
7736 if (isa<Constant>(Op)) continue;
7738 Instruction *OpInst = dyn_cast<Instruction>(Op);
7739 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
7741 PHINode *P = dyn_cast<PHINode>(OpInst);
7742 if (!P)
7743 // If this operand is already visited, reuse the prior result.
7744 // We may have P != PHI if this is the deepest point at which the
7745 // inconsistent paths meet.
7746 P = PHIMap.lookup(OpInst);
7747 if (!P) {
7748 // Recurse and memoize the results, whether a phi is found or not.
7749 // This recursive call invalidates pointers into PHIMap.
7750 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
7751 PHIMap[OpInst] = P;
7753 if (!P)
7754 return nullptr; // Not evolving from PHI
7755 if (PHI && PHI != P)
7756 return nullptr; // Evolving from multiple different PHIs.
7757 PHI = P;
7759 // This is a expression evolving from a constant PHI!
7760 return PHI;
7763 /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
7764 /// in the loop that V is derived from. We allow arbitrary operations along the
7765 /// way, but the operands of an operation must either be constants or a value
7766 /// derived from a constant PHI. If this expression does not fit with these
7767 /// constraints, return null.
7768 static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
7769 Instruction *I = dyn_cast<Instruction>(V);
7770 if (!I || !canConstantEvolve(I, L)) return nullptr;
7772 if (PHINode *PN = dyn_cast<PHINode>(I))
7773 return PN;
7775 // Record non-constant instructions contained by the loop.
7776 DenseMap<Instruction *, PHINode *> PHIMap;
7777 return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
7780 /// EvaluateExpression - Given an expression that passes the
7781 /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
7782 /// in the loop has the value PHIVal. If we can't fold this expression for some
7783 /// reason, return null.
7784 static Constant *EvaluateExpression(Value *V, const Loop *L,
7785 DenseMap<Instruction *, Constant *> &Vals,
7786 const DataLayout &DL,
7787 const TargetLibraryInfo *TLI) {
7788 // Convenient constant check, but redundant for recursive calls.
7789 if (Constant *C = dyn_cast<Constant>(V)) return C;
7790 Instruction *I = dyn_cast<Instruction>(V);
7791 if (!I) return nullptr;
7793 if (Constant *C = Vals.lookup(I)) return C;
7795 // An instruction inside the loop depends on a value outside the loop that we
7796 // weren't given a mapping for, or a value such as a call inside the loop.
7797 if (!canConstantEvolve(I, L)) return nullptr;
7799 // An unmapped PHI can be due to a branch or another loop inside this loop,
7800 // or due to this not being the initial iteration through a loop where we
7801 // couldn't compute the evolution of this particular PHI last time.
7802 if (isa<PHINode>(I)) return nullptr;
7804 std::vector<Constant*> Operands(I->getNumOperands());
7806 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
7807 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
7808 if (!Operand) {
7809 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
7810 if (!Operands[i]) return nullptr;
7811 continue;
7813 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
7814 Vals[Operand] = C;
7815 if (!C) return nullptr;
7816 Operands[i] = C;
7819 if (CmpInst *CI = dyn_cast<CmpInst>(I))
7820 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
7821 Operands[1], DL, TLI);
7822 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7823 if (!LI->isVolatile())
7824 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
7826 return ConstantFoldInstOperands(I, Operands, DL, TLI);
7830 // If every incoming value to PN except the one for BB is a specific Constant,
7831 // return that, else return nullptr.
7832 static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
7833 Constant *IncomingVal = nullptr;
7835 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7836 if (PN->getIncomingBlock(i) == BB)
7837 continue;
7839 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
7840 if (!CurrentVal)
7841 return nullptr;
7843 if (IncomingVal != CurrentVal) {
7844 if (IncomingVal)
7845 return nullptr;
7846 IncomingVal = CurrentVal;
7850 return IncomingVal;
7853 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
7854 /// in the header of its containing loop, we know the loop executes a
7855 /// constant number of times, and the PHI node is just a recurrence
7856 /// involving constants, fold it.
7857 Constant *
7858 ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
7859 const APInt &BEs,
7860 const Loop *L) {
7861 auto I = ConstantEvolutionLoopExitValue.find(PN);
7862 if (I != ConstantEvolutionLoopExitValue.end())
7863 return I->second;
7865 if (BEs.ugt(MaxBruteForceIterations))
7866 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
7868 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
7870 DenseMap<Instruction *, Constant *> CurrentIterVals;
7871 BasicBlock *Header = L->getHeader();
7872 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7874 BasicBlock *Latch = L->getLoopLatch();
7875 if (!Latch)
7876 return nullptr;
7878 for (PHINode &PHI : Header->phis()) {
7879 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7880 CurrentIterVals[&PHI] = StartCST;
7882 if (!CurrentIterVals.count(PN))
7883 return RetVal = nullptr;
7885 Value *BEValue = PN->getIncomingValueForBlock(Latch);
7887 // Execute the loop symbolically to determine the exit value.
7888 assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
7889 "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
7891 unsigned NumIterations = BEs.getZExtValue(); // must be in range
7892 unsigned IterationNum = 0;
7893 const DataLayout &DL = getDataLayout();
7894 for (; ; ++IterationNum) {
7895 if (IterationNum == NumIterations)
7896 return RetVal = CurrentIterVals[PN]; // Got exit value!
7898 // Compute the value of the PHIs for the next iteration.
7899 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
7900 DenseMap<Instruction *, Constant *> NextIterVals;
7901 Constant *NextPHI =
7902 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7903 if (!NextPHI)
7904 return nullptr; // Couldn't evaluate!
7905 NextIterVals[PN] = NextPHI;
7907 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
7909 // Also evaluate the other PHI nodes. However, we don't get to stop if we
7910 // cease to be able to evaluate one of them or if they stop evolving,
7911 // because that doesn't necessarily prevent us from computing PN.
7912 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
7913 for (const auto &I : CurrentIterVals) {
7914 PHINode *PHI = dyn_cast<PHINode>(I.first);
7915 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
7916 PHIsToCompute.emplace_back(PHI, I.second);
7918 // We use two distinct loops because EvaluateExpression may invalidate any
7919 // iterators into CurrentIterVals.
7920 for (const auto &I : PHIsToCompute) {
7921 PHINode *PHI = I.first;
7922 Constant *&NextPHI = NextIterVals[PHI];
7923 if (!NextPHI) { // Not already computed.
7924 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7925 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
7927 if (NextPHI != I.second)
7928 StoppedEvolving = false;
7931 // If all entries in CurrentIterVals == NextIterVals then we can stop
7932 // iterating, the loop can't continue to change.
7933 if (StoppedEvolving)
7934 return RetVal = CurrentIterVals[PN];
7936 CurrentIterVals.swap(NextIterVals);
7940 const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
7941 Value *Cond,
7942 bool ExitWhen) {
7943 PHINode *PN = getConstantEvolvingPHI(Cond, L);
7944 if (!PN) return getCouldNotCompute();
7946 // If the loop is canonicalized, the PHI will have exactly two entries.
7947 // That's the only form we support here.
7948 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
7950 DenseMap<Instruction *, Constant *> CurrentIterVals;
7951 BasicBlock *Header = L->getHeader();
7952 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
7954 BasicBlock *Latch = L->getLoopLatch();
7955 assert(Latch && "Should follow from NumIncomingValues == 2!");
7957 for (PHINode &PHI : Header->phis()) {
7958 if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
7959 CurrentIterVals[&PHI] = StartCST;
7961 if (!CurrentIterVals.count(PN))
7962 return getCouldNotCompute();
7964 // Okay, we find a PHI node that defines the trip count of this loop. Execute
7965 // the loop symbolically to determine when the condition gets a value of
7966 // "ExitWhen".
7967 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
7968 const DataLayout &DL = getDataLayout();
7969 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
7970 auto *CondVal = dyn_cast_or_null<ConstantInt>(
7971 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
7973 // Couldn't symbolically evaluate.
7974 if (!CondVal) return getCouldNotCompute();
7976 if (CondVal->getValue() == uint64_t(ExitWhen)) {
7977 ++NumBruteForceTripCountsComputed;
7978 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
7981 // Update all the PHI nodes for the next iteration.
7982 DenseMap<Instruction *, Constant *> NextIterVals;
7984 // Create a list of which PHIs we need to compute. We want to do this before
7985 // calling EvaluateExpression on them because that may invalidate iterators
7986 // into CurrentIterVals.
7987 SmallVector<PHINode *, 8> PHIsToCompute;
7988 for (const auto &I : CurrentIterVals) {
7989 PHINode *PHI = dyn_cast<PHINode>(I.first);
7990 if (!PHI || PHI->getParent() != Header) continue;
7991 PHIsToCompute.push_back(PHI);
7993 for (PHINode *PHI : PHIsToCompute) {
7994 Constant *&NextPHI = NextIterVals[PHI];
7995 if (NextPHI) continue; // Already computed!
7997 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
7998 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
8000 CurrentIterVals.swap(NextIterVals);
8003 // Too many iterations were needed to evaluate.
8004 return getCouldNotCompute();
8007 const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
8008 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
8009 ValuesAtScopes[V];
8010 // Check to see if we've folded this expression at this loop before.
8011 for (auto &LS : Values)
8012 if (LS.first == L)
8013 return LS.second ? LS.second : V;
8015 Values.emplace_back(L, nullptr);
8017 // Otherwise compute it.
8018 const SCEV *C = computeSCEVAtScope(V, L);
8019 for (auto &LS : reverse(ValuesAtScopes[V]))
8020 if (LS.first == L) {
8021 LS.second = C;
8022 break;
8024 return C;
8027 /// This builds up a Constant using the ConstantExpr interface. That way, we
8028 /// will return Constants for objects which aren't represented by a
8029 /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
8030 /// Returns NULL if the SCEV isn't representable as a Constant.
8031 static Constant *BuildConstantFromSCEV(const SCEV *V) {
8032 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
8033 case scCouldNotCompute:
8034 case scAddRecExpr:
8035 break;
8036 case scConstant:
8037 return cast<SCEVConstant>(V)->getValue();
8038 case scUnknown:
8039 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
8040 case scSignExtend: {
8041 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
8042 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
8043 return ConstantExpr::getSExt(CastOp, SS->getType());
8044 break;
8046 case scZeroExtend: {
8047 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
8048 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
8049 return ConstantExpr::getZExt(CastOp, SZ->getType());
8050 break;
8052 case scTruncate: {
8053 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
8054 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
8055 return ConstantExpr::getTrunc(CastOp, ST->getType());
8056 break;
8058 case scAddExpr: {
8059 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
8060 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
8061 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8062 unsigned AS = PTy->getAddressSpace();
8063 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8064 C = ConstantExpr::getBitCast(C, DestPtrTy);
8066 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
8067 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
8068 if (!C2) return nullptr;
8070 // First pointer!
8071 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
8072 unsigned AS = C2->getType()->getPointerAddressSpace();
8073 std::swap(C, C2);
8074 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
8075 // The offsets have been converted to bytes. We can add bytes to an
8076 // i8* by GEP with the byte count in the first index.
8077 C = ConstantExpr::getBitCast(C, DestPtrTy);
8080 // Don't bother trying to sum two pointers. We probably can't
8081 // statically compute a load that results from it anyway.
8082 if (C2->getType()->isPointerTy())
8083 return nullptr;
8085 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
8086 if (PTy->getElementType()->isStructTy())
8087 C2 = ConstantExpr::getIntegerCast(
8088 C2, Type::getInt32Ty(C->getContext()), true);
8089 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
8090 } else
8091 C = ConstantExpr::getAdd(C, C2);
8093 return C;
8095 break;
8097 case scMulExpr: {
8098 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
8099 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
8100 // Don't bother with pointers at all.
8101 if (C->getType()->isPointerTy()) return nullptr;
8102 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
8103 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
8104 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
8105 C = ConstantExpr::getMul(C, C2);
8107 return C;
8109 break;
8111 case scUDivExpr: {
8112 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
8113 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
8114 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
8115 if (LHS->getType() == RHS->getType())
8116 return ConstantExpr::getUDiv(LHS, RHS);
8117 break;
8119 case scSMaxExpr:
8120 case scUMaxExpr:
8121 case scSMinExpr:
8122 case scUMinExpr:
8123 break; // TODO: smax, umax, smin, umax.
8125 return nullptr;
8128 const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
8129 if (isa<SCEVConstant>(V)) return V;
8131 // If this instruction is evolved from a constant-evolving PHI, compute the
8132 // exit value from the loop without using SCEVs.
8133 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
8134 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
8135 if (PHINode *PN = dyn_cast<PHINode>(I)) {
8136 const Loop *LI = this->LI[I->getParent()];
8137 // Looking for loop exit value.
8138 if (LI && LI->getParentLoop() == L &&
8139 PN->getParent() == LI->getHeader()) {
8140 // Okay, there is no closed form solution for the PHI node. Check
8141 // to see if the loop that contains it has a known backedge-taken
8142 // count. If so, we may be able to force computation of the exit
8143 // value.
8144 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
8145 // This trivial case can show up in some degenerate cases where
8146 // the incoming IR has not yet been fully simplified.
8147 if (BackedgeTakenCount->isZero()) {
8148 Value *InitValue = nullptr;
8149 bool MultipleInitValues = false;
8150 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
8151 if (!LI->contains(PN->getIncomingBlock(i))) {
8152 if (!InitValue)
8153 InitValue = PN->getIncomingValue(i);
8154 else if (InitValue != PN->getIncomingValue(i)) {
8155 MultipleInitValues = true;
8156 break;
8160 if (!MultipleInitValues && InitValue)
8161 return getSCEV(InitValue);
8163 // Do we have a loop invariant value flowing around the backedge
8164 // for a loop which must execute the backedge?
8165 if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
8166 isKnownPositive(BackedgeTakenCount) &&
8167 PN->getNumIncomingValues() == 2) {
8168 unsigned InLoopPred = LI->contains(PN->getIncomingBlock(0)) ? 0 : 1;
8169 const SCEV *OnBackedge = getSCEV(PN->getIncomingValue(InLoopPred));
8170 if (IsAvailableOnEntry(LI, DT, OnBackedge, PN->getParent()))
8171 return OnBackedge;
8173 if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
8174 // Okay, we know how many times the containing loop executes. If
8175 // this is a constant evolving PHI node, get the final value at
8176 // the specified iteration number.
8177 Constant *RV =
8178 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
8179 if (RV) return getSCEV(RV);
8183 // If there is a single-input Phi, evaluate it at our scope. If we can
8184 // prove that this replacement does not break LCSSA form, use new value.
8185 if (PN->getNumOperands() == 1) {
8186 const SCEV *Input = getSCEV(PN->getOperand(0));
8187 const SCEV *InputAtScope = getSCEVAtScope(Input, L);
8188 // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
8189 // for the simplest case just support constants.
8190 if (isa<SCEVConstant>(InputAtScope)) return InputAtScope;
8194 // Okay, this is an expression that we cannot symbolically evaluate
8195 // into a SCEV. Check to see if it's possible to symbolically evaluate
8196 // the arguments into constants, and if so, try to constant propagate the
8197 // result. This is particularly useful for computing loop exit values.
8198 if (CanConstantFold(I)) {
8199 SmallVector<Constant *, 4> Operands;
8200 bool MadeImprovement = false;
8201 for (Value *Op : I->operands()) {
8202 if (Constant *C = dyn_cast<Constant>(Op)) {
8203 Operands.push_back(C);
8204 continue;
8207 // If any of the operands is non-constant and if they are
8208 // non-integer and non-pointer, don't even try to analyze them
8209 // with scev techniques.
8210 if (!isSCEVable(Op->getType()))
8211 return V;
8213 const SCEV *OrigV = getSCEV(Op);
8214 const SCEV *OpV = getSCEVAtScope(OrigV, L);
8215 MadeImprovement |= OrigV != OpV;
8217 Constant *C = BuildConstantFromSCEV(OpV);
8218 if (!C) return V;
8219 if (C->getType() != Op->getType())
8220 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
8221 Op->getType(),
8222 false),
8223 C, Op->getType());
8224 Operands.push_back(C);
8227 // Check to see if getSCEVAtScope actually made an improvement.
8228 if (MadeImprovement) {
8229 Constant *C = nullptr;
8230 const DataLayout &DL = getDataLayout();
8231 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
8232 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
8233 Operands[1], DL, &TLI);
8234 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
8235 if (!LI->isVolatile())
8236 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
8237 } else
8238 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
8239 if (!C) return V;
8240 return getSCEV(C);
8245 // This is some other type of SCEVUnknown, just return it.
8246 return V;
8249 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
8250 // Avoid performing the look-up in the common case where the specified
8251 // expression has no loop-variant portions.
8252 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
8253 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8254 if (OpAtScope != Comm->getOperand(i)) {
8255 // Okay, at least one of these operands is loop variant but might be
8256 // foldable. Build a new instance of the folded commutative expression.
8257 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
8258 Comm->op_begin()+i);
8259 NewOps.push_back(OpAtScope);
8261 for (++i; i != e; ++i) {
8262 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
8263 NewOps.push_back(OpAtScope);
8265 if (isa<SCEVAddExpr>(Comm))
8266 return getAddExpr(NewOps, Comm->getNoWrapFlags());
8267 if (isa<SCEVMulExpr>(Comm))
8268 return getMulExpr(NewOps, Comm->getNoWrapFlags());
8269 if (isa<SCEVMinMaxExpr>(Comm))
8270 return getMinMaxExpr(Comm->getSCEVType(), NewOps);
8271 llvm_unreachable("Unknown commutative SCEV type!");
8274 // If we got here, all operands are loop invariant.
8275 return Comm;
8278 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
8279 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
8280 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
8281 if (LHS == Div->getLHS() && RHS == Div->getRHS())
8282 return Div; // must be loop invariant
8283 return getUDivExpr(LHS, RHS);
8286 // If this is a loop recurrence for a loop that does not contain L, then we
8287 // are dealing with the final value computed by the loop.
8288 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
8289 // First, attempt to evaluate each operand.
8290 // Avoid performing the look-up in the common case where the specified
8291 // expression has no loop-variant portions.
8292 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
8293 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
8294 if (OpAtScope == AddRec->getOperand(i))
8295 continue;
8297 // Okay, at least one of these operands is loop variant but might be
8298 // foldable. Build a new instance of the folded commutative expression.
8299 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
8300 AddRec->op_begin()+i);
8301 NewOps.push_back(OpAtScope);
8302 for (++i; i != e; ++i)
8303 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
8305 const SCEV *FoldedRec =
8306 getAddRecExpr(NewOps, AddRec->getLoop(),
8307 AddRec->getNoWrapFlags(SCEV::FlagNW));
8308 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
8309 // The addrec may be folded to a nonrecurrence, for example, if the
8310 // induction variable is multiplied by zero after constant folding. Go
8311 // ahead and return the folded value.
8312 if (!AddRec)
8313 return FoldedRec;
8314 break;
8317 // If the scope is outside the addrec's loop, evaluate it by using the
8318 // loop exit value of the addrec.
8319 if (!AddRec->getLoop()->contains(L)) {
8320 // To evaluate this recurrence, we need to know how many times the AddRec
8321 // loop iterates. Compute this now.
8322 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
8323 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
8325 // Then, evaluate the AddRec.
8326 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
8329 return AddRec;
8332 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
8333 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8334 if (Op == Cast->getOperand())
8335 return Cast; // must be loop invariant
8336 return getZeroExtendExpr(Op, Cast->getType());
8339 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
8340 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8341 if (Op == Cast->getOperand())
8342 return Cast; // must be loop invariant
8343 return getSignExtendExpr(Op, Cast->getType());
8346 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
8347 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
8348 if (Op == Cast->getOperand())
8349 return Cast; // must be loop invariant
8350 return getTruncateExpr(Op, Cast->getType());
8353 llvm_unreachable("Unknown SCEV type!");
8356 const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
8357 return getSCEVAtScope(getSCEV(V), L);
8360 const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
8361 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
8362 return stripInjectiveFunctions(ZExt->getOperand());
8363 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
8364 return stripInjectiveFunctions(SExt->getOperand());
8365 return S;
8368 /// Finds the minimum unsigned root of the following equation:
8370 /// A * X = B (mod N)
8372 /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
8373 /// A and B isn't important.
8375 /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
8376 static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
8377 ScalarEvolution &SE) {
8378 uint32_t BW = A.getBitWidth();
8379 assert(BW == SE.getTypeSizeInBits(B->getType()));
8380 assert(A != 0 && "A must be non-zero.");
8382 // 1. D = gcd(A, N)
8384 // The gcd of A and N may have only one prime factor: 2. The number of
8385 // trailing zeros in A is its multiplicity
8386 uint32_t Mult2 = A.countTrailingZeros();
8387 // D = 2^Mult2
8389 // 2. Check if B is divisible by D.
8391 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
8392 // is not less than multiplicity of this prime factor for D.
8393 if (SE.GetMinTrailingZeros(B) < Mult2)
8394 return SE.getCouldNotCompute();
8396 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
8397 // modulo (N / D).
8399 // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
8400 // (N / D) in general. The inverse itself always fits into BW bits, though,
8401 // so we immediately truncate it.
8402 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
8403 APInt Mod(BW + 1, 0);
8404 Mod.setBit(BW - Mult2); // Mod = N / D
8405 APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
8407 // 4. Compute the minimum unsigned root of the equation:
8408 // I * (B / D) mod (N / D)
8409 // To simplify the computation, we factor out the divide by D:
8410 // (I * B mod N) / D
8411 const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
8412 return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
8415 /// For a given quadratic addrec, generate coefficients of the corresponding
8416 /// quadratic equation, multiplied by a common value to ensure that they are
8417 /// integers.
8418 /// The returned value is a tuple { A, B, C, M, BitWidth }, where
8419 /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
8420 /// were multiplied by, and BitWidth is the bit width of the original addrec
8421 /// coefficients.
8422 /// This function returns None if the addrec coefficients are not compile-
8423 /// time constants.
8424 static Optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
8425 GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
8426 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
8427 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
8428 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
8429 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
8430 LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
8431 << *AddRec << '\n');
8433 // We currently can only solve this if the coefficients are constants.
8434 if (!LC || !MC || !NC) {
8435 LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
8436 return None;
8439 APInt L = LC->getAPInt();
8440 APInt M = MC->getAPInt();
8441 APInt N = NC->getAPInt();
8442 assert(!N.isNullValue() && "This is not a quadratic addrec");
8444 unsigned BitWidth = LC->getAPInt().getBitWidth();
8445 unsigned NewWidth = BitWidth + 1;
8446 LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
8447 << BitWidth << '\n');
8448 // The sign-extension (as opposed to a zero-extension) here matches the
8449 // extension used in SolveQuadraticEquationWrap (with the same motivation).
8450 N = N.sext(NewWidth);
8451 M = M.sext(NewWidth);
8452 L = L.sext(NewWidth);
8454 // The increments are M, M+N, M+2N, ..., so the accumulated values are
8455 // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
8456 // L+M, L+2M+N, L+3M+3N, ...
8457 // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
8459 // The equation Acc = 0 is then
8460 // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
8461 // In a quadratic form it becomes:
8462 // N n^2 + (2M-N) n + 2L = 0.
8464 APInt A = N;
8465 APInt B = 2 * M - A;
8466 APInt C = 2 * L;
8467 APInt T = APInt(NewWidth, 2);
8468 LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
8469 << "x + " << C << ", coeff bw: " << NewWidth
8470 << ", multiplied by " << T << '\n');
8471 return std::make_tuple(A, B, C, T, BitWidth);
8474 /// Helper function to compare optional APInts:
8475 /// (a) if X and Y both exist, return min(X, Y),
8476 /// (b) if neither X nor Y exist, return None,
8477 /// (c) if exactly one of X and Y exists, return that value.
8478 static Optional<APInt> MinOptional(Optional<APInt> X, Optional<APInt> Y) {
8479 if (X.hasValue() && Y.hasValue()) {
8480 unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
8481 APInt XW = X->sextOrSelf(W);
8482 APInt YW = Y->sextOrSelf(W);
8483 return XW.slt(YW) ? *X : *Y;
8485 if (!X.hasValue() && !Y.hasValue())
8486 return None;
8487 return X.hasValue() ? *X : *Y;
8490 /// Helper function to truncate an optional APInt to a given BitWidth.
8491 /// When solving addrec-related equations, it is preferable to return a value
8492 /// that has the same bit width as the original addrec's coefficients. If the
8493 /// solution fits in the original bit width, truncate it (except for i1).
8494 /// Returning a value of a different bit width may inhibit some optimizations.
8496 /// In general, a solution to a quadratic equation generated from an addrec
8497 /// may require BW+1 bits, where BW is the bit width of the addrec's
8498 /// coefficients. The reason is that the coefficients of the quadratic
8499 /// equation are BW+1 bits wide (to avoid truncation when converting from
8500 /// the addrec to the equation).
8501 static Optional<APInt> TruncIfPossible(Optional<APInt> X, unsigned BitWidth) {
8502 if (!X.hasValue())
8503 return None;
8504 unsigned W = X->getBitWidth();
8505 if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
8506 return X->trunc(BitWidth);
8507 return X;
8510 /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
8511 /// iterations. The values L, M, N are assumed to be signed, and they
8512 /// should all have the same bit widths.
8513 /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
8514 /// where BW is the bit width of the addrec's coefficients.
8515 /// If the calculated value is a BW-bit integer (for BW > 1), it will be
8516 /// returned as such, otherwise the bit width of the returned value may
8517 /// be greater than BW.
8519 /// This function returns None if
8520 /// (a) the addrec coefficients are not constant, or
8521 /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
8522 /// like x^2 = 5, no integer solutions exist, in other cases an integer
8523 /// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
8524 static Optional<APInt>
8525 SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
8526 APInt A, B, C, M;
8527 unsigned BitWidth;
8528 auto T = GetQuadraticEquation(AddRec);
8529 if (!T.hasValue())
8530 return None;
8532 std::tie(A, B, C, M, BitWidth) = *T;
8533 LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
8534 Optional<APInt> X = APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth+1);
8535 if (!X.hasValue())
8536 return None;
8538 ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
8539 ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
8540 if (!V->isZero())
8541 return None;
8543 return TruncIfPossible(X, BitWidth);
8546 /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
8547 /// iterations. The values M, N are assumed to be signed, and they
8548 /// should all have the same bit widths.
8549 /// Find the least n such that c(n) does not belong to the given range,
8550 /// while c(n-1) does.
8552 /// This function returns None if
8553 /// (a) the addrec coefficients are not constant, or
8554 /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
8555 /// bounds of the range.
8556 static Optional<APInt>
8557 SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
8558 const ConstantRange &Range, ScalarEvolution &SE) {
8559 assert(AddRec->getOperand(0)->isZero() &&
8560 "Starting value of addrec should be 0");
8561 LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
8562 << Range << ", addrec " << *AddRec << '\n');
8563 // This case is handled in getNumIterationsInRange. Here we can assume that
8564 // we start in the range.
8565 assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
8566 "Addrec's initial value should be in range");
8568 APInt A, B, C, M;
8569 unsigned BitWidth;
8570 auto T = GetQuadraticEquation(AddRec);
8571 if (!T.hasValue())
8572 return None;
8574 // Be careful about the return value: there can be two reasons for not
8575 // returning an actual number. First, if no solutions to the equations
8576 // were found, and second, if the solutions don't leave the given range.
8577 // The first case means that the actual solution is "unknown", the second
8578 // means that it's known, but not valid. If the solution is unknown, we
8579 // cannot make any conclusions.
8580 // Return a pair: the optional solution and a flag indicating if the
8581 // solution was found.
8582 auto SolveForBoundary = [&](APInt Bound) -> std::pair<Optional<APInt>,bool> {
8583 // Solve for signed overflow and unsigned overflow, pick the lower
8584 // solution.
8585 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
8586 << Bound << " (before multiplying by " << M << ")\n");
8587 Bound *= M; // The quadratic equation multiplier.
8589 Optional<APInt> SO = None;
8590 if (BitWidth > 1) {
8591 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8592 "signed overflow\n");
8593 SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
8595 LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
8596 "unsigned overflow\n");
8597 Optional<APInt> UO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound,
8598 BitWidth+1);
8600 auto LeavesRange = [&] (const APInt &X) {
8601 ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
8602 ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
8603 if (Range.contains(V0->getValue()))
8604 return false;
8605 // X should be at least 1, so X-1 is non-negative.
8606 ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
8607 ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
8608 if (Range.contains(V1->getValue()))
8609 return true;
8610 return false;
8613 // If SolveQuadraticEquationWrap returns None, it means that there can
8614 // be a solution, but the function failed to find it. We cannot treat it
8615 // as "no solution".
8616 if (!SO.hasValue() || !UO.hasValue())
8617 return { None, false };
8619 // Check the smaller value first to see if it leaves the range.
8620 // At this point, both SO and UO must have values.
8621 Optional<APInt> Min = MinOptional(SO, UO);
8622 if (LeavesRange(*Min))
8623 return { Min, true };
8624 Optional<APInt> Max = Min == SO ? UO : SO;
8625 if (LeavesRange(*Max))
8626 return { Max, true };
8628 // Solutions were found, but were eliminated, hence the "true".
8629 return { None, true };
8632 std::tie(A, B, C, M, BitWidth) = *T;
8633 // Lower bound is inclusive, subtract 1 to represent the exiting value.
8634 APInt Lower = Range.getLower().sextOrSelf(A.getBitWidth()) - 1;
8635 APInt Upper = Range.getUpper().sextOrSelf(A.getBitWidth());
8636 auto SL = SolveForBoundary(Lower);
8637 auto SU = SolveForBoundary(Upper);
8638 // If any of the solutions was unknown, no meaninigful conclusions can
8639 // be made.
8640 if (!SL.second || !SU.second)
8641 return None;
8643 // Claim: The correct solution is not some value between Min and Max.
8645 // Justification: Assuming that Min and Max are different values, one of
8646 // them is when the first signed overflow happens, the other is when the
8647 // first unsigned overflow happens. Crossing the range boundary is only
8648 // possible via an overflow (treating 0 as a special case of it, modeling
8649 // an overflow as crossing k*2^W for some k).
8651 // The interesting case here is when Min was eliminated as an invalid
8652 // solution, but Max was not. The argument is that if there was another
8653 // overflow between Min and Max, it would also have been eliminated if
8654 // it was considered.
8656 // For a given boundary, it is possible to have two overflows of the same
8657 // type (signed/unsigned) without having the other type in between: this
8658 // can happen when the vertex of the parabola is between the iterations
8659 // corresponding to the overflows. This is only possible when the two
8660 // overflows cross k*2^W for the same k. In such case, if the second one
8661 // left the range (and was the first one to do so), the first overflow
8662 // would have to enter the range, which would mean that either we had left
8663 // the range before or that we started outside of it. Both of these cases
8664 // are contradictions.
8666 // Claim: In the case where SolveForBoundary returns None, the correct
8667 // solution is not some value between the Max for this boundary and the
8668 // Min of the other boundary.
8670 // Justification: Assume that we had such Max_A and Min_B corresponding
8671 // to range boundaries A and B and such that Max_A < Min_B. If there was
8672 // a solution between Max_A and Min_B, it would have to be caused by an
8673 // overflow corresponding to either A or B. It cannot correspond to B,
8674 // since Min_B is the first occurrence of such an overflow. If it
8675 // corresponded to A, it would have to be either a signed or an unsigned
8676 // overflow that is larger than both eliminated overflows for A. But
8677 // between the eliminated overflows and this overflow, the values would
8678 // cover the entire value space, thus crossing the other boundary, which
8679 // is a contradiction.
8681 return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
8684 ScalarEvolution::ExitLimit
8685 ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
8686 bool AllowPredicates) {
8688 // This is only used for loops with a "x != y" exit test. The exit condition
8689 // is now expressed as a single expression, V = x-y. So the exit test is
8690 // effectively V != 0. We know and take advantage of the fact that this
8691 // expression only being used in a comparison by zero context.
8693 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
8694 // If the value is a constant
8695 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8696 // If the value is already zero, the branch will execute zero times.
8697 if (C->getValue()->isZero()) return C;
8698 return getCouldNotCompute(); // Otherwise it will loop infinitely.
8701 const SCEVAddRecExpr *AddRec =
8702 dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
8704 if (!AddRec && AllowPredicates)
8705 // Try to make this an AddRec using runtime tests, in the first X
8706 // iterations of this loop, where X is the SCEV expression found by the
8707 // algorithm below.
8708 AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
8710 if (!AddRec || AddRec->getLoop() != L)
8711 return getCouldNotCompute();
8713 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
8714 // the quadratic equation to solve it.
8715 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
8716 // We can only use this value if the chrec ends up with an exact zero
8717 // value at this index. When solving for "X*X != 5", for example, we
8718 // should not accept a root of 2.
8719 if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
8720 const auto *R = cast<SCEVConstant>(getConstant(S.getValue()));
8721 return ExitLimit(R, R, false, Predicates);
8723 return getCouldNotCompute();
8726 // Otherwise we can only handle this if it is affine.
8727 if (!AddRec->isAffine())
8728 return getCouldNotCompute();
8730 // If this is an affine expression, the execution count of this branch is
8731 // the minimum unsigned root of the following equation:
8733 // Start + Step*N = 0 (mod 2^BW)
8735 // equivalent to:
8737 // Step*N = -Start (mod 2^BW)
8739 // where BW is the common bit width of Start and Step.
8741 // Get the initial value for the loop.
8742 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
8743 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
8745 // For now we handle only constant steps.
8747 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
8748 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
8749 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
8750 // We have not yet seen any such cases.
8751 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
8752 if (!StepC || StepC->getValue()->isZero())
8753 return getCouldNotCompute();
8755 // For positive steps (counting up until unsigned overflow):
8756 // N = -Start/Step (as unsigned)
8757 // For negative steps (counting down to zero):
8758 // N = Start/-Step
8759 // First compute the unsigned distance from zero in the direction of Step.
8760 bool CountDown = StepC->getAPInt().isNegative();
8761 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
8763 // Handle unitary steps, which cannot wraparound.
8764 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
8765 // N = Distance (as unsigned)
8766 if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
8767 APInt MaxBECount = getUnsignedRangeMax(Distance);
8769 // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
8770 // we end up with a loop whose backedge-taken count is n - 1. Detect this
8771 // case, and see if we can improve the bound.
8773 // Explicitly handling this here is necessary because getUnsignedRange
8774 // isn't context-sensitive; it doesn't know that we only care about the
8775 // range inside the loop.
8776 const SCEV *Zero = getZero(Distance->getType());
8777 const SCEV *One = getOne(Distance->getType());
8778 const SCEV *DistancePlusOne = getAddExpr(Distance, One);
8779 if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
8780 // If Distance + 1 doesn't overflow, we can compute the maximum distance
8781 // as "unsigned_max(Distance + 1) - 1".
8782 ConstantRange CR = getUnsignedRange(DistancePlusOne);
8783 MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
8785 return ExitLimit(Distance, getConstant(MaxBECount), false, Predicates);
8788 // If the condition controls loop exit (the loop exits only if the expression
8789 // is true) and the addition is no-wrap we can use unsigned divide to
8790 // compute the backedge count. In this case, the step may not divide the
8791 // distance, but we don't care because if the condition is "missed" the loop
8792 // will have undefined behavior due to wrapping.
8793 if (ControlsExit && AddRec->hasNoSelfWrap() &&
8794 loopHasNoAbnormalExits(AddRec->getLoop())) {
8795 const SCEV *Exact =
8796 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
8797 const SCEV *Max =
8798 Exact == getCouldNotCompute()
8799 ? Exact
8800 : getConstant(getUnsignedRangeMax(Exact));
8801 return ExitLimit(Exact, Max, false, Predicates);
8804 // Solve the general equation.
8805 const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
8806 getNegativeSCEV(Start), *this);
8807 const SCEV *M = E == getCouldNotCompute()
8809 : getConstant(getUnsignedRangeMax(E));
8810 return ExitLimit(E, M, false, Predicates);
8813 ScalarEvolution::ExitLimit
8814 ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
8815 // Loops that look like: while (X == 0) are very strange indeed. We don't
8816 // handle them yet except for the trivial case. This could be expanded in the
8817 // future as needed.
8819 // If the value is a constant, check to see if it is known to be non-zero
8820 // already. If so, the backedge will execute zero times.
8821 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
8822 if (!C->getValue()->isZero())
8823 return getZero(C->getType());
8824 return getCouldNotCompute(); // Otherwise it will loop infinitely.
8827 // We could implement others, but I really doubt anyone writes loops like
8828 // this, and if they did, they would already be constant folded.
8829 return getCouldNotCompute();
8832 std::pair<BasicBlock *, BasicBlock *>
8833 ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
8834 // If the block has a unique predecessor, then there is no path from the
8835 // predecessor to the block that does not go through the direct edge
8836 // from the predecessor to the block.
8837 if (BasicBlock *Pred = BB->getSinglePredecessor())
8838 return {Pred, BB};
8840 // A loop's header is defined to be a block that dominates the loop.
8841 // If the header has a unique predecessor outside the loop, it must be
8842 // a block that has exactly one successor that can reach the loop.
8843 if (Loop *L = LI.getLoopFor(BB))
8844 return {L->getLoopPredecessor(), L->getHeader()};
8846 return {nullptr, nullptr};
8849 /// SCEV structural equivalence is usually sufficient for testing whether two
8850 /// expressions are equal, however for the purposes of looking for a condition
8851 /// guarding a loop, it can be useful to be a little more general, since a
8852 /// front-end may have replicated the controlling expression.
8853 static bool HasSameValue(const SCEV *A, const SCEV *B) {
8854 // Quick check to see if they are the same SCEV.
8855 if (A == B) return true;
8857 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
8858 // Not all instructions that are "identical" compute the same value. For
8859 // instance, two distinct alloca instructions allocating the same type are
8860 // identical and do not read memory; but compute distinct values.
8861 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
8864 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
8865 // two different instructions with the same value. Check for this case.
8866 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
8867 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
8868 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
8869 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
8870 if (ComputesEqualValues(AI, BI))
8871 return true;
8873 // Otherwise assume they may have a different value.
8874 return false;
8877 bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
8878 const SCEV *&LHS, const SCEV *&RHS,
8879 unsigned Depth) {
8880 bool Changed = false;
8881 // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
8882 // '0 != 0'.
8883 auto TrivialCase = [&](bool TriviallyTrue) {
8884 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
8885 Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
8886 return true;
8888 // If we hit the max recursion limit bail out.
8889 if (Depth >= 3)
8890 return false;
8892 // Canonicalize a constant to the right side.
8893 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
8894 // Check for both operands constant.
8895 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
8896 if (ConstantExpr::getICmp(Pred,
8897 LHSC->getValue(),
8898 RHSC->getValue())->isNullValue())
8899 return TrivialCase(false);
8900 else
8901 return TrivialCase(true);
8903 // Otherwise swap the operands to put the constant on the right.
8904 std::swap(LHS, RHS);
8905 Pred = ICmpInst::getSwappedPredicate(Pred);
8906 Changed = true;
8909 // If we're comparing an addrec with a value which is loop-invariant in the
8910 // addrec's loop, put the addrec on the left. Also make a dominance check,
8911 // as both operands could be addrecs loop-invariant in each other's loop.
8912 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
8913 const Loop *L = AR->getLoop();
8914 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
8915 std::swap(LHS, RHS);
8916 Pred = ICmpInst::getSwappedPredicate(Pred);
8917 Changed = true;
8921 // If there's a constant operand, canonicalize comparisons with boundary
8922 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
8923 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
8924 const APInt &RA = RC->getAPInt();
8926 bool SimplifiedByConstantRange = false;
8928 if (!ICmpInst::isEquality(Pred)) {
8929 ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
8930 if (ExactCR.isFullSet())
8931 return TrivialCase(true);
8932 else if (ExactCR.isEmptySet())
8933 return TrivialCase(false);
8935 APInt NewRHS;
8936 CmpInst::Predicate NewPred;
8937 if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
8938 ICmpInst::isEquality(NewPred)) {
8939 // We were able to convert an inequality to an equality.
8940 Pred = NewPred;
8941 RHS = getConstant(NewRHS);
8942 Changed = SimplifiedByConstantRange = true;
8946 if (!SimplifiedByConstantRange) {
8947 switch (Pred) {
8948 default:
8949 break;
8950 case ICmpInst::ICMP_EQ:
8951 case ICmpInst::ICMP_NE:
8952 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
8953 if (!RA)
8954 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
8955 if (const SCEVMulExpr *ME =
8956 dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
8957 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
8958 ME->getOperand(0)->isAllOnesValue()) {
8959 RHS = AE->getOperand(1);
8960 LHS = ME->getOperand(1);
8961 Changed = true;
8963 break;
8966 // The "Should have been caught earlier!" messages refer to the fact
8967 // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
8968 // should have fired on the corresponding cases, and canonicalized the
8969 // check to trivial case.
8971 case ICmpInst::ICMP_UGE:
8972 assert(!RA.isMinValue() && "Should have been caught earlier!");
8973 Pred = ICmpInst::ICMP_UGT;
8974 RHS = getConstant(RA - 1);
8975 Changed = true;
8976 break;
8977 case ICmpInst::ICMP_ULE:
8978 assert(!RA.isMaxValue() && "Should have been caught earlier!");
8979 Pred = ICmpInst::ICMP_ULT;
8980 RHS = getConstant(RA + 1);
8981 Changed = true;
8982 break;
8983 case ICmpInst::ICMP_SGE:
8984 assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
8985 Pred = ICmpInst::ICMP_SGT;
8986 RHS = getConstant(RA - 1);
8987 Changed = true;
8988 break;
8989 case ICmpInst::ICMP_SLE:
8990 assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
8991 Pred = ICmpInst::ICMP_SLT;
8992 RHS = getConstant(RA + 1);
8993 Changed = true;
8994 break;
8999 // Check for obvious equality.
9000 if (HasSameValue(LHS, RHS)) {
9001 if (ICmpInst::isTrueWhenEqual(Pred))
9002 return TrivialCase(true);
9003 if (ICmpInst::isFalseWhenEqual(Pred))
9004 return TrivialCase(false);
9007 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
9008 // adding or subtracting 1 from one of the operands.
9009 switch (Pred) {
9010 case ICmpInst::ICMP_SLE:
9011 if (!getSignedRangeMax(RHS).isMaxSignedValue()) {
9012 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9013 SCEV::FlagNSW);
9014 Pred = ICmpInst::ICMP_SLT;
9015 Changed = true;
9016 } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
9017 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
9018 SCEV::FlagNSW);
9019 Pred = ICmpInst::ICMP_SLT;
9020 Changed = true;
9022 break;
9023 case ICmpInst::ICMP_SGE:
9024 if (!getSignedRangeMin(RHS).isMinSignedValue()) {
9025 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
9026 SCEV::FlagNSW);
9027 Pred = ICmpInst::ICMP_SGT;
9028 Changed = true;
9029 } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
9030 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9031 SCEV::FlagNSW);
9032 Pred = ICmpInst::ICMP_SGT;
9033 Changed = true;
9035 break;
9036 case ICmpInst::ICMP_ULE:
9037 if (!getUnsignedRangeMax(RHS).isMaxValue()) {
9038 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
9039 SCEV::FlagNUW);
9040 Pred = ICmpInst::ICMP_ULT;
9041 Changed = true;
9042 } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
9043 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
9044 Pred = ICmpInst::ICMP_ULT;
9045 Changed = true;
9047 break;
9048 case ICmpInst::ICMP_UGE:
9049 if (!getUnsignedRangeMin(RHS).isMinValue()) {
9050 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
9051 Pred = ICmpInst::ICMP_UGT;
9052 Changed = true;
9053 } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
9054 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
9055 SCEV::FlagNUW);
9056 Pred = ICmpInst::ICMP_UGT;
9057 Changed = true;
9059 break;
9060 default:
9061 break;
9064 // TODO: More simplifications are possible here.
9066 // Recursively simplify until we either hit a recursion limit or nothing
9067 // changes.
9068 if (Changed)
9069 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
9071 return Changed;
9074 bool ScalarEvolution::isKnownNegative(const SCEV *S) {
9075 return getSignedRangeMax(S).isNegative();
9078 bool ScalarEvolution::isKnownPositive(const SCEV *S) {
9079 return getSignedRangeMin(S).isStrictlyPositive();
9082 bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
9083 return !getSignedRangeMin(S).isNegative();
9086 bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
9087 return !getSignedRangeMax(S).isStrictlyPositive();
9090 bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
9091 return isKnownNegative(S) || isKnownPositive(S);
9094 std::pair<const SCEV *, const SCEV *>
9095 ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
9096 // Compute SCEV on entry of loop L.
9097 const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
9098 if (Start == getCouldNotCompute())
9099 return { Start, Start };
9100 // Compute post increment SCEV for loop L.
9101 const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
9102 assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
9103 return { Start, PostInc };
9106 bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
9107 const SCEV *LHS, const SCEV *RHS) {
9108 // First collect all loops.
9109 SmallPtrSet<const Loop *, 8> LoopsUsed;
9110 getUsedLoops(LHS, LoopsUsed);
9111 getUsedLoops(RHS, LoopsUsed);
9113 if (LoopsUsed.empty())
9114 return false;
9116 // Domination relationship must be a linear order on collected loops.
9117 #ifndef NDEBUG
9118 for (auto *L1 : LoopsUsed)
9119 for (auto *L2 : LoopsUsed)
9120 assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
9121 DT.dominates(L2->getHeader(), L1->getHeader())) &&
9122 "Domination relationship is not a linear order");
9123 #endif
9125 const Loop *MDL =
9126 *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
9127 [&](const Loop *L1, const Loop *L2) {
9128 return DT.properlyDominates(L1->getHeader(), L2->getHeader());
9131 // Get init and post increment value for LHS.
9132 auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
9133 // if LHS contains unknown non-invariant SCEV then bail out.
9134 if (SplitLHS.first == getCouldNotCompute())
9135 return false;
9136 assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
9137 // Get init and post increment value for RHS.
9138 auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
9139 // if RHS contains unknown non-invariant SCEV then bail out.
9140 if (SplitRHS.first == getCouldNotCompute())
9141 return false;
9142 assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
9143 // It is possible that init SCEV contains an invariant load but it does
9144 // not dominate MDL and is not available at MDL loop entry, so we should
9145 // check it here.
9146 if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
9147 !isAvailableAtLoopEntry(SplitRHS.first, MDL))
9148 return false;
9150 return isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first) &&
9151 isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
9152 SplitRHS.second);
9155 bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
9156 const SCEV *LHS, const SCEV *RHS) {
9157 // Canonicalize the inputs first.
9158 (void)SimplifyICmpOperands(Pred, LHS, RHS);
9160 if (isKnownViaInduction(Pred, LHS, RHS))
9161 return true;
9163 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
9164 return true;
9166 // Otherwise see what can be done with some simple reasoning.
9167 return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
9170 bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
9171 const SCEVAddRecExpr *LHS,
9172 const SCEV *RHS) {
9173 const Loop *L = LHS->getLoop();
9174 return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
9175 isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
9178 bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
9179 ICmpInst::Predicate Pred,
9180 bool &Increasing) {
9181 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
9183 #ifndef NDEBUG
9184 // Verify an invariant: inverting the predicate should turn a monotonically
9185 // increasing change to a monotonically decreasing one, and vice versa.
9186 bool IncreasingSwapped;
9187 bool ResultSwapped = isMonotonicPredicateImpl(
9188 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
9190 assert(Result == ResultSwapped && "should be able to analyze both!");
9191 if (ResultSwapped)
9192 assert(Increasing == !IncreasingSwapped &&
9193 "monotonicity should flip as we flip the predicate");
9194 #endif
9196 return Result;
9199 bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
9200 ICmpInst::Predicate Pred,
9201 bool &Increasing) {
9203 // A zero step value for LHS means the induction variable is essentially a
9204 // loop invariant value. We don't really depend on the predicate actually
9205 // flipping from false to true (for increasing predicates, and the other way
9206 // around for decreasing predicates), all we care about is that *if* the
9207 // predicate changes then it only changes from false to true.
9209 // A zero step value in itself is not very useful, but there may be places
9210 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
9211 // as general as possible.
9213 switch (Pred) {
9214 default:
9215 return false; // Conservative answer
9217 case ICmpInst::ICMP_UGT:
9218 case ICmpInst::ICMP_UGE:
9219 case ICmpInst::ICMP_ULT:
9220 case ICmpInst::ICMP_ULE:
9221 if (!LHS->hasNoUnsignedWrap())
9222 return false;
9224 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
9225 return true;
9227 case ICmpInst::ICMP_SGT:
9228 case ICmpInst::ICMP_SGE:
9229 case ICmpInst::ICMP_SLT:
9230 case ICmpInst::ICMP_SLE: {
9231 if (!LHS->hasNoSignedWrap())
9232 return false;
9234 const SCEV *Step = LHS->getStepRecurrence(*this);
9236 if (isKnownNonNegative(Step)) {
9237 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
9238 return true;
9241 if (isKnownNonPositive(Step)) {
9242 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
9243 return true;
9246 return false;
9251 llvm_unreachable("switch has default clause!");
9254 bool ScalarEvolution::isLoopInvariantPredicate(
9255 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
9256 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
9257 const SCEV *&InvariantRHS) {
9259 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
9260 if (!isLoopInvariant(RHS, L)) {
9261 if (!isLoopInvariant(LHS, L))
9262 return false;
9264 std::swap(LHS, RHS);
9265 Pred = ICmpInst::getSwappedPredicate(Pred);
9268 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9269 if (!ArLHS || ArLHS->getLoop() != L)
9270 return false;
9272 bool Increasing;
9273 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
9274 return false;
9276 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
9277 // true as the loop iterates, and the backedge is control dependent on
9278 // "ArLHS `Pred` RHS" == true then we can reason as follows:
9280 // * if the predicate was false in the first iteration then the predicate
9281 // is never evaluated again, since the loop exits without taking the
9282 // backedge.
9283 // * if the predicate was true in the first iteration then it will
9284 // continue to be true for all future iterations since it is
9285 // monotonically increasing.
9287 // For both the above possibilities, we can replace the loop varying
9288 // predicate with its value on the first iteration of the loop (which is
9289 // loop invariant).
9291 // A similar reasoning applies for a monotonically decreasing predicate, by
9292 // replacing true with false and false with true in the above two bullets.
9294 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
9296 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
9297 return false;
9299 InvariantPred = Pred;
9300 InvariantLHS = ArLHS->getStart();
9301 InvariantRHS = RHS;
9302 return true;
9305 bool ScalarEvolution::isKnownPredicateViaConstantRanges(
9306 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
9307 if (HasSameValue(LHS, RHS))
9308 return ICmpInst::isTrueWhenEqual(Pred);
9310 // This code is split out from isKnownPredicate because it is called from
9311 // within isLoopEntryGuardedByCond.
9313 auto CheckRanges =
9314 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
9315 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
9316 .contains(RangeLHS);
9319 // The check at the top of the function catches the case where the values are
9320 // known to be equal.
9321 if (Pred == CmpInst::ICMP_EQ)
9322 return false;
9324 if (Pred == CmpInst::ICMP_NE)
9325 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
9326 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
9327 isKnownNonZero(getMinusSCEV(LHS, RHS));
9329 if (CmpInst::isSigned(Pred))
9330 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
9332 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
9335 bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
9336 const SCEV *LHS,
9337 const SCEV *RHS) {
9338 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
9339 // Return Y via OutY.
9340 auto MatchBinaryAddToConst =
9341 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
9342 SCEV::NoWrapFlags ExpectedFlags) {
9343 const SCEV *NonConstOp, *ConstOp;
9344 SCEV::NoWrapFlags FlagsPresent;
9346 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
9347 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
9348 return false;
9350 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
9351 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
9354 APInt C;
9356 switch (Pred) {
9357 default:
9358 break;
9360 case ICmpInst::ICMP_SGE:
9361 std::swap(LHS, RHS);
9362 LLVM_FALLTHROUGH;
9363 case ICmpInst::ICMP_SLE:
9364 // X s<= (X + C)<nsw> if C >= 0
9365 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
9366 return true;
9368 // (X + C)<nsw> s<= X if C <= 0
9369 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
9370 !C.isStrictlyPositive())
9371 return true;
9372 break;
9374 case ICmpInst::ICMP_SGT:
9375 std::swap(LHS, RHS);
9376 LLVM_FALLTHROUGH;
9377 case ICmpInst::ICMP_SLT:
9378 // X s< (X + C)<nsw> if C > 0
9379 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
9380 C.isStrictlyPositive())
9381 return true;
9383 // (X + C)<nsw> s< X if C < 0
9384 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
9385 return true;
9386 break;
9389 return false;
9392 bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
9393 const SCEV *LHS,
9394 const SCEV *RHS) {
9395 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
9396 return false;
9398 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
9399 // the stack can result in exponential time complexity.
9400 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
9402 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
9404 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
9405 // isKnownPredicate. isKnownPredicate is more powerful, but also more
9406 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
9407 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
9408 // use isKnownPredicate later if needed.
9409 return isKnownNonNegative(RHS) &&
9410 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
9411 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
9414 bool ScalarEvolution::isImpliedViaGuard(BasicBlock *BB,
9415 ICmpInst::Predicate Pred,
9416 const SCEV *LHS, const SCEV *RHS) {
9417 // No need to even try if we know the module has no guards.
9418 if (!HasGuards)
9419 return false;
9421 return any_of(*BB, [&](Instruction &I) {
9422 using namespace llvm::PatternMatch;
9424 Value *Condition;
9425 return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
9426 m_Value(Condition))) &&
9427 isImpliedCond(Pred, LHS, RHS, Condition, false);
9431 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
9432 /// protected by a conditional between LHS and RHS. This is used to
9433 /// to eliminate casts.
9434 bool
9435 ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
9436 ICmpInst::Predicate Pred,
9437 const SCEV *LHS, const SCEV *RHS) {
9438 // Interpret a null as meaning no loop, where there is obviously no guard
9439 // (interprocedural conditions notwithstanding).
9440 if (!L) return true;
9442 if (VerifyIR)
9443 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9444 "This cannot be done on broken IR!");
9447 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9448 return true;
9450 BasicBlock *Latch = L->getLoopLatch();
9451 if (!Latch)
9452 return false;
9454 BranchInst *LoopContinuePredicate =
9455 dyn_cast<BranchInst>(Latch->getTerminator());
9456 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
9457 isImpliedCond(Pred, LHS, RHS,
9458 LoopContinuePredicate->getCondition(),
9459 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
9460 return true;
9462 // We don't want more than one activation of the following loops on the stack
9463 // -- that can lead to O(n!) time complexity.
9464 if (WalkingBEDominatingConds)
9465 return false;
9467 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
9469 // See if we can exploit a trip count to prove the predicate.
9470 const auto &BETakenInfo = getBackedgeTakenInfo(L);
9471 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
9472 if (LatchBECount != getCouldNotCompute()) {
9473 // We know that Latch branches back to the loop header exactly
9474 // LatchBECount times. This means the backdege condition at Latch is
9475 // equivalent to "{0,+,1} u< LatchBECount".
9476 Type *Ty = LatchBECount->getType();
9477 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
9478 const SCEV *LoopCounter =
9479 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
9480 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
9481 LatchBECount))
9482 return true;
9485 // Check conditions due to any @llvm.assume intrinsics.
9486 for (auto &AssumeVH : AC.assumptions()) {
9487 if (!AssumeVH)
9488 continue;
9489 auto *CI = cast<CallInst>(AssumeVH);
9490 if (!DT.dominates(CI, Latch->getTerminator()))
9491 continue;
9493 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
9494 return true;
9497 // If the loop is not reachable from the entry block, we risk running into an
9498 // infinite loop as we walk up into the dom tree. These loops do not matter
9499 // anyway, so we just return a conservative answer when we see them.
9500 if (!DT.isReachableFromEntry(L->getHeader()))
9501 return false;
9503 if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
9504 return true;
9506 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
9507 DTN != HeaderDTN; DTN = DTN->getIDom()) {
9508 assert(DTN && "should reach the loop header before reaching the root!");
9510 BasicBlock *BB = DTN->getBlock();
9511 if (isImpliedViaGuard(BB, Pred, LHS, RHS))
9512 return true;
9514 BasicBlock *PBB = BB->getSinglePredecessor();
9515 if (!PBB)
9516 continue;
9518 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
9519 if (!ContinuePredicate || !ContinuePredicate->isConditional())
9520 continue;
9522 Value *Condition = ContinuePredicate->getCondition();
9524 // If we have an edge `E` within the loop body that dominates the only
9525 // latch, the condition guarding `E` also guards the backedge. This
9526 // reasoning works only for loops with a single latch.
9528 BasicBlockEdge DominatingEdge(PBB, BB);
9529 if (DominatingEdge.isSingleEdge()) {
9530 // We're constructively (and conservatively) enumerating edges within the
9531 // loop body that dominate the latch. The dominator tree better agree
9532 // with us on this:
9533 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
9535 if (isImpliedCond(Pred, LHS, RHS, Condition,
9536 BB != ContinuePredicate->getSuccessor(0)))
9537 return true;
9541 return false;
9544 bool
9545 ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
9546 ICmpInst::Predicate Pred,
9547 const SCEV *LHS, const SCEV *RHS) {
9548 // Interpret a null as meaning no loop, where there is obviously no guard
9549 // (interprocedural conditions notwithstanding).
9550 if (!L) return false;
9552 if (VerifyIR)
9553 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
9554 "This cannot be done on broken IR!");
9556 // Both LHS and RHS must be available at loop entry.
9557 assert(isAvailableAtLoopEntry(LHS, L) &&
9558 "LHS is not available at Loop Entry");
9559 assert(isAvailableAtLoopEntry(RHS, L) &&
9560 "RHS is not available at Loop Entry");
9562 if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
9563 return true;
9565 // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
9566 // the facts (a >= b && a != b) separately. A typical situation is when the
9567 // non-strict comparison is known from ranges and non-equality is known from
9568 // dominating predicates. If we are proving strict comparison, we always try
9569 // to prove non-equality and non-strict comparison separately.
9570 auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
9571 const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
9572 bool ProvedNonStrictComparison = false;
9573 bool ProvedNonEquality = false;
9575 if (ProvingStrictComparison) {
9576 ProvedNonStrictComparison =
9577 isKnownViaNonRecursiveReasoning(NonStrictPredicate, LHS, RHS);
9578 ProvedNonEquality =
9579 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, LHS, RHS);
9580 if (ProvedNonStrictComparison && ProvedNonEquality)
9581 return true;
9584 // Try to prove (Pred, LHS, RHS) using isImpliedViaGuard.
9585 auto ProveViaGuard = [&](BasicBlock *Block) {
9586 if (isImpliedViaGuard(Block, Pred, LHS, RHS))
9587 return true;
9588 if (ProvingStrictComparison) {
9589 if (!ProvedNonStrictComparison)
9590 ProvedNonStrictComparison =
9591 isImpliedViaGuard(Block, NonStrictPredicate, LHS, RHS);
9592 if (!ProvedNonEquality)
9593 ProvedNonEquality =
9594 isImpliedViaGuard(Block, ICmpInst::ICMP_NE, LHS, RHS);
9595 if (ProvedNonStrictComparison && ProvedNonEquality)
9596 return true;
9598 return false;
9601 // Try to prove (Pred, LHS, RHS) using isImpliedCond.
9602 auto ProveViaCond = [&](Value *Condition, bool Inverse) {
9603 if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse))
9604 return true;
9605 if (ProvingStrictComparison) {
9606 if (!ProvedNonStrictComparison)
9607 ProvedNonStrictComparison =
9608 isImpliedCond(NonStrictPredicate, LHS, RHS, Condition, Inverse);
9609 if (!ProvedNonEquality)
9610 ProvedNonEquality =
9611 isImpliedCond(ICmpInst::ICMP_NE, LHS, RHS, Condition, Inverse);
9612 if (ProvedNonStrictComparison && ProvedNonEquality)
9613 return true;
9615 return false;
9618 // Starting at the loop predecessor, climb up the predecessor chain, as long
9619 // as there are predecessors that can be found that have unique successors
9620 // leading to the original header.
9621 for (std::pair<BasicBlock *, BasicBlock *>
9622 Pair(L->getLoopPredecessor(), L->getHeader());
9623 Pair.first;
9624 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
9626 if (ProveViaGuard(Pair.first))
9627 return true;
9629 BranchInst *LoopEntryPredicate =
9630 dyn_cast<BranchInst>(Pair.first->getTerminator());
9631 if (!LoopEntryPredicate ||
9632 LoopEntryPredicate->isUnconditional())
9633 continue;
9635 if (ProveViaCond(LoopEntryPredicate->getCondition(),
9636 LoopEntryPredicate->getSuccessor(0) != Pair.second))
9637 return true;
9640 // Check conditions due to any @llvm.assume intrinsics.
9641 for (auto &AssumeVH : AC.assumptions()) {
9642 if (!AssumeVH)
9643 continue;
9644 auto *CI = cast<CallInst>(AssumeVH);
9645 if (!DT.dominates(CI, L->getHeader()))
9646 continue;
9648 if (ProveViaCond(CI->getArgOperand(0), false))
9649 return true;
9652 return false;
9655 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
9656 const SCEV *LHS, const SCEV *RHS,
9657 Value *FoundCondValue,
9658 bool Inverse) {
9659 if (!PendingLoopPredicates.insert(FoundCondValue).second)
9660 return false;
9662 auto ClearOnExit =
9663 make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
9665 // Recursively handle And and Or conditions.
9666 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
9667 if (BO->getOpcode() == Instruction::And) {
9668 if (!Inverse)
9669 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9670 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9671 } else if (BO->getOpcode() == Instruction::Or) {
9672 if (Inverse)
9673 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
9674 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
9678 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
9679 if (!ICI) return false;
9681 // Now that we found a conditional branch that dominates the loop or controls
9682 // the loop latch. Check to see if it is the comparison we are looking for.
9683 ICmpInst::Predicate FoundPred;
9684 if (Inverse)
9685 FoundPred = ICI->getInversePredicate();
9686 else
9687 FoundPred = ICI->getPredicate();
9689 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
9690 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
9692 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
9695 bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
9696 const SCEV *RHS,
9697 ICmpInst::Predicate FoundPred,
9698 const SCEV *FoundLHS,
9699 const SCEV *FoundRHS) {
9700 // Balance the types.
9701 if (getTypeSizeInBits(LHS->getType()) <
9702 getTypeSizeInBits(FoundLHS->getType())) {
9703 if (CmpInst::isSigned(Pred)) {
9704 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
9705 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
9706 } else {
9707 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
9708 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
9710 } else if (getTypeSizeInBits(LHS->getType()) >
9711 getTypeSizeInBits(FoundLHS->getType())) {
9712 if (CmpInst::isSigned(FoundPred)) {
9713 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
9714 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
9715 } else {
9716 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
9717 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
9721 // Canonicalize the query to match the way instcombine will have
9722 // canonicalized the comparison.
9723 if (SimplifyICmpOperands(Pred, LHS, RHS))
9724 if (LHS == RHS)
9725 return CmpInst::isTrueWhenEqual(Pred);
9726 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
9727 if (FoundLHS == FoundRHS)
9728 return CmpInst::isFalseWhenEqual(FoundPred);
9730 // Check to see if we can make the LHS or RHS match.
9731 if (LHS == FoundRHS || RHS == FoundLHS) {
9732 if (isa<SCEVConstant>(RHS)) {
9733 std::swap(FoundLHS, FoundRHS);
9734 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
9735 } else {
9736 std::swap(LHS, RHS);
9737 Pred = ICmpInst::getSwappedPredicate(Pred);
9741 // Check whether the found predicate is the same as the desired predicate.
9742 if (FoundPred == Pred)
9743 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9745 // Check whether swapping the found predicate makes it the same as the
9746 // desired predicate.
9747 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
9748 if (isa<SCEVConstant>(RHS))
9749 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
9750 else
9751 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
9752 RHS, LHS, FoundLHS, FoundRHS);
9755 // Unsigned comparison is the same as signed comparison when both the operands
9756 // are non-negative.
9757 if (CmpInst::isUnsigned(FoundPred) &&
9758 CmpInst::getSignedPredicate(FoundPred) == Pred &&
9759 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
9760 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
9762 // Check if we can make progress by sharpening ranges.
9763 if (FoundPred == ICmpInst::ICMP_NE &&
9764 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
9766 const SCEVConstant *C = nullptr;
9767 const SCEV *V = nullptr;
9769 if (isa<SCEVConstant>(FoundLHS)) {
9770 C = cast<SCEVConstant>(FoundLHS);
9771 V = FoundRHS;
9772 } else {
9773 C = cast<SCEVConstant>(FoundRHS);
9774 V = FoundLHS;
9777 // The guarding predicate tells us that C != V. If the known range
9778 // of V is [C, t), we can sharpen the range to [C + 1, t). The
9779 // range we consider has to correspond to same signedness as the
9780 // predicate we're interested in folding.
9782 APInt Min = ICmpInst::isSigned(Pred) ?
9783 getSignedRangeMin(V) : getUnsignedRangeMin(V);
9785 if (Min == C->getAPInt()) {
9786 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
9787 // This is true even if (Min + 1) wraps around -- in case of
9788 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
9790 APInt SharperMin = Min + 1;
9792 switch (Pred) {
9793 case ICmpInst::ICMP_SGE:
9794 case ICmpInst::ICMP_UGE:
9795 // We know V `Pred` SharperMin. If this implies LHS `Pred`
9796 // RHS, we're done.
9797 if (isImpliedCondOperands(Pred, LHS, RHS, V,
9798 getConstant(SharperMin)))
9799 return true;
9800 LLVM_FALLTHROUGH;
9802 case ICmpInst::ICMP_SGT:
9803 case ICmpInst::ICMP_UGT:
9804 // We know from the range information that (V `Pred` Min ||
9805 // V == Min). We know from the guarding condition that !(V
9806 // == Min). This gives us
9808 // V `Pred` Min || V == Min && !(V == Min)
9809 // => V `Pred` Min
9811 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
9813 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
9814 return true;
9815 LLVM_FALLTHROUGH;
9817 default:
9818 // No change
9819 break;
9824 // Check whether the actual condition is beyond sufficient.
9825 if (FoundPred == ICmpInst::ICMP_EQ)
9826 if (ICmpInst::isTrueWhenEqual(Pred))
9827 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
9828 return true;
9829 if (Pred == ICmpInst::ICMP_NE)
9830 if (!ICmpInst::isTrueWhenEqual(FoundPred))
9831 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
9832 return true;
9834 // Otherwise assume the worst.
9835 return false;
9838 bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
9839 const SCEV *&L, const SCEV *&R,
9840 SCEV::NoWrapFlags &Flags) {
9841 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
9842 if (!AE || AE->getNumOperands() != 2)
9843 return false;
9845 L = AE->getOperand(0);
9846 R = AE->getOperand(1);
9847 Flags = AE->getNoWrapFlags();
9848 return true;
9851 Optional<APInt> ScalarEvolution::computeConstantDifference(const SCEV *More,
9852 const SCEV *Less) {
9853 // We avoid subtracting expressions here because this function is usually
9854 // fairly deep in the call stack (i.e. is called many times).
9856 // X - X = 0.
9857 if (More == Less)
9858 return APInt(getTypeSizeInBits(More->getType()), 0);
9860 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
9861 const auto *LAR = cast<SCEVAddRecExpr>(Less);
9862 const auto *MAR = cast<SCEVAddRecExpr>(More);
9864 if (LAR->getLoop() != MAR->getLoop())
9865 return None;
9867 // We look at affine expressions only; not for correctness but to keep
9868 // getStepRecurrence cheap.
9869 if (!LAR->isAffine() || !MAR->isAffine())
9870 return None;
9872 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
9873 return None;
9875 Less = LAR->getStart();
9876 More = MAR->getStart();
9878 // fall through
9881 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
9882 const auto &M = cast<SCEVConstant>(More)->getAPInt();
9883 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
9884 return M - L;
9887 SCEV::NoWrapFlags Flags;
9888 const SCEV *LLess = nullptr, *RLess = nullptr;
9889 const SCEV *LMore = nullptr, *RMore = nullptr;
9890 const SCEVConstant *C1 = nullptr, *C2 = nullptr;
9891 // Compare (X + C1) vs X.
9892 if (splitBinaryAdd(Less, LLess, RLess, Flags))
9893 if ((C1 = dyn_cast<SCEVConstant>(LLess)))
9894 if (RLess == More)
9895 return -(C1->getAPInt());
9897 // Compare X vs (X + C2).
9898 if (splitBinaryAdd(More, LMore, RMore, Flags))
9899 if ((C2 = dyn_cast<SCEVConstant>(LMore)))
9900 if (RMore == Less)
9901 return C2->getAPInt();
9903 // Compare (X + C1) vs (X + C2).
9904 if (C1 && C2 && RLess == RMore)
9905 return C2->getAPInt() - C1->getAPInt();
9907 return None;
9910 bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
9911 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
9912 const SCEV *FoundLHS, const SCEV *FoundRHS) {
9913 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
9914 return false;
9916 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
9917 if (!AddRecLHS)
9918 return false;
9920 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
9921 if (!AddRecFoundLHS)
9922 return false;
9924 // We'd like to let SCEV reason about control dependencies, so we constrain
9925 // both the inequalities to be about add recurrences on the same loop. This
9926 // way we can use isLoopEntryGuardedByCond later.
9928 const Loop *L = AddRecFoundLHS->getLoop();
9929 if (L != AddRecLHS->getLoop())
9930 return false;
9932 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
9934 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
9935 // ... (2)
9937 // Informal proof for (2), assuming (1) [*]:
9939 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
9941 // Then
9943 // FoundLHS s< FoundRHS s< INT_MIN - C
9944 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
9945 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
9946 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
9947 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
9948 // <=> FoundLHS + C s< FoundRHS + C
9950 // [*]: (1) can be proved by ruling out overflow.
9952 // [**]: This can be proved by analyzing all the four possibilities:
9953 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
9954 // (A s>= 0, B s>= 0).
9956 // Note:
9957 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
9958 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
9959 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
9960 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
9961 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
9962 // C)".
9964 Optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
9965 Optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
9966 if (!LDiff || !RDiff || *LDiff != *RDiff)
9967 return false;
9969 if (LDiff->isMinValue())
9970 return true;
9972 APInt FoundRHSLimit;
9974 if (Pred == CmpInst::ICMP_ULT) {
9975 FoundRHSLimit = -(*RDiff);
9976 } else {
9977 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
9978 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
9981 // Try to prove (1) or (2), as needed.
9982 return isAvailableAtLoopEntry(FoundRHS, L) &&
9983 isLoopEntryGuardedByCond(L, Pred, FoundRHS,
9984 getConstant(FoundRHSLimit));
9987 bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
9988 const SCEV *LHS, const SCEV *RHS,
9989 const SCEV *FoundLHS,
9990 const SCEV *FoundRHS, unsigned Depth) {
9991 const PHINode *LPhi = nullptr, *RPhi = nullptr;
9993 auto ClearOnExit = make_scope_exit([&]() {
9994 if (LPhi) {
9995 bool Erased = PendingMerges.erase(LPhi);
9996 assert(Erased && "Failed to erase LPhi!");
9997 (void)Erased;
9999 if (RPhi) {
10000 bool Erased = PendingMerges.erase(RPhi);
10001 assert(Erased && "Failed to erase RPhi!");
10002 (void)Erased;
10006 // Find respective Phis and check that they are not being pending.
10007 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
10008 if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
10009 if (!PendingMerges.insert(Phi).second)
10010 return false;
10011 LPhi = Phi;
10013 if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
10014 if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
10015 // If we detect a loop of Phi nodes being processed by this method, for
10016 // example:
10018 // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
10019 // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
10021 // we don't want to deal with a case that complex, so return conservative
10022 // answer false.
10023 if (!PendingMerges.insert(Phi).second)
10024 return false;
10025 RPhi = Phi;
10028 // If none of LHS, RHS is a Phi, nothing to do here.
10029 if (!LPhi && !RPhi)
10030 return false;
10032 // If there is a SCEVUnknown Phi we are interested in, make it left.
10033 if (!LPhi) {
10034 std::swap(LHS, RHS);
10035 std::swap(FoundLHS, FoundRHS);
10036 std::swap(LPhi, RPhi);
10037 Pred = ICmpInst::getSwappedPredicate(Pred);
10040 assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
10041 const BasicBlock *LBB = LPhi->getParent();
10042 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10044 auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
10045 return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
10046 isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
10047 isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
10050 if (RPhi && RPhi->getParent() == LBB) {
10051 // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
10052 // If we compare two Phis from the same block, and for each entry block
10053 // the predicate is true for incoming values from this block, then the
10054 // predicate is also true for the Phis.
10055 for (const BasicBlock *IncBB : predecessors(LBB)) {
10056 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10057 const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
10058 if (!ProvedEasily(L, R))
10059 return false;
10061 } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
10062 // Case two: RHS is also a Phi from the same basic block, and it is an
10063 // AddRec. It means that there is a loop which has both AddRec and Unknown
10064 // PHIs, for it we can compare incoming values of AddRec from above the loop
10065 // and latch with their respective incoming values of LPhi.
10066 // TODO: Generalize to handle loops with many inputs in a header.
10067 if (LPhi->getNumIncomingValues() != 2) return false;
10069 auto *RLoop = RAR->getLoop();
10070 auto *Predecessor = RLoop->getLoopPredecessor();
10071 assert(Predecessor && "Loop with AddRec with no predecessor?");
10072 const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
10073 if (!ProvedEasily(L1, RAR->getStart()))
10074 return false;
10075 auto *Latch = RLoop->getLoopLatch();
10076 assert(Latch && "Loop with AddRec with no latch?");
10077 const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
10078 if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
10079 return false;
10080 } else {
10081 // In all other cases go over inputs of LHS and compare each of them to RHS,
10082 // the predicate is true for (LHS, RHS) if it is true for all such pairs.
10083 // At this point RHS is either a non-Phi, or it is a Phi from some block
10084 // different from LBB.
10085 for (const BasicBlock *IncBB : predecessors(LBB)) {
10086 // Check that RHS is available in this block.
10087 if (!dominates(RHS, IncBB))
10088 return false;
10089 const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
10090 if (!ProvedEasily(L, RHS))
10091 return false;
10094 return true;
10097 bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
10098 const SCEV *LHS, const SCEV *RHS,
10099 const SCEV *FoundLHS,
10100 const SCEV *FoundRHS) {
10101 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
10102 return true;
10104 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
10105 return true;
10107 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
10108 FoundLHS, FoundRHS) ||
10109 // ~x < ~y --> x > y
10110 isImpliedCondOperandsHelper(Pred, LHS, RHS,
10111 getNotSCEV(FoundRHS),
10112 getNotSCEV(FoundLHS));
10115 /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
10116 template <typename MinMaxExprType>
10117 static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
10118 const SCEV *Candidate) {
10119 const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
10120 if (!MinMaxExpr)
10121 return false;
10123 return find(MinMaxExpr->operands(), Candidate) != MinMaxExpr->op_end();
10126 static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
10127 ICmpInst::Predicate Pred,
10128 const SCEV *LHS, const SCEV *RHS) {
10129 // If both sides are affine addrecs for the same loop, with equal
10130 // steps, and we know the recurrences don't wrap, then we only
10131 // need to check the predicate on the starting values.
10133 if (!ICmpInst::isRelational(Pred))
10134 return false;
10136 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
10137 if (!LAR)
10138 return false;
10139 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
10140 if (!RAR)
10141 return false;
10142 if (LAR->getLoop() != RAR->getLoop())
10143 return false;
10144 if (!LAR->isAffine() || !RAR->isAffine())
10145 return false;
10147 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
10148 return false;
10150 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
10151 SCEV::FlagNSW : SCEV::FlagNUW;
10152 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
10153 return false;
10155 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
10158 /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
10159 /// expression?
10160 static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
10161 ICmpInst::Predicate Pred,
10162 const SCEV *LHS, const SCEV *RHS) {
10163 switch (Pred) {
10164 default:
10165 return false;
10167 case ICmpInst::ICMP_SGE:
10168 std::swap(LHS, RHS);
10169 LLVM_FALLTHROUGH;
10170 case ICmpInst::ICMP_SLE:
10171 return
10172 // min(A, ...) <= A
10173 IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
10174 // A <= max(A, ...)
10175 IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
10177 case ICmpInst::ICMP_UGE:
10178 std::swap(LHS, RHS);
10179 LLVM_FALLTHROUGH;
10180 case ICmpInst::ICMP_ULE:
10181 return
10182 // min(A, ...) <= A
10183 IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
10184 // A <= max(A, ...)
10185 IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
10188 llvm_unreachable("covered switch fell through?!");
10191 bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
10192 const SCEV *LHS, const SCEV *RHS,
10193 const SCEV *FoundLHS,
10194 const SCEV *FoundRHS,
10195 unsigned Depth) {
10196 assert(getTypeSizeInBits(LHS->getType()) ==
10197 getTypeSizeInBits(RHS->getType()) &&
10198 "LHS and RHS have different sizes?");
10199 assert(getTypeSizeInBits(FoundLHS->getType()) ==
10200 getTypeSizeInBits(FoundRHS->getType()) &&
10201 "FoundLHS and FoundRHS have different sizes?");
10202 // We want to avoid hurting the compile time with analysis of too big trees.
10203 if (Depth > MaxSCEVOperationsImplicationDepth)
10204 return false;
10205 // We only want to work with ICMP_SGT comparison so far.
10206 // TODO: Extend to ICMP_UGT?
10207 if (Pred == ICmpInst::ICMP_SLT) {
10208 Pred = ICmpInst::ICMP_SGT;
10209 std::swap(LHS, RHS);
10210 std::swap(FoundLHS, FoundRHS);
10212 if (Pred != ICmpInst::ICMP_SGT)
10213 return false;
10215 auto GetOpFromSExt = [&](const SCEV *S) {
10216 if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
10217 return Ext->getOperand();
10218 // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
10219 // the constant in some cases.
10220 return S;
10223 // Acquire values from extensions.
10224 auto *OrigLHS = LHS;
10225 auto *OrigFoundLHS = FoundLHS;
10226 LHS = GetOpFromSExt(LHS);
10227 FoundLHS = GetOpFromSExt(FoundLHS);
10229 // Is the SGT predicate can be proved trivially or using the found context.
10230 auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
10231 return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
10232 isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
10233 FoundRHS, Depth + 1);
10236 if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
10237 // We want to avoid creation of any new non-constant SCEV. Since we are
10238 // going to compare the operands to RHS, we should be certain that we don't
10239 // need any size extensions for this. So let's decline all cases when the
10240 // sizes of types of LHS and RHS do not match.
10241 // TODO: Maybe try to get RHS from sext to catch more cases?
10242 if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
10243 return false;
10245 // Should not overflow.
10246 if (!LHSAddExpr->hasNoSignedWrap())
10247 return false;
10249 auto *LL = LHSAddExpr->getOperand(0);
10250 auto *LR = LHSAddExpr->getOperand(1);
10251 auto *MinusOne = getNegativeSCEV(getOne(RHS->getType()));
10253 // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
10254 auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
10255 return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
10257 // Try to prove the following rule:
10258 // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
10259 // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
10260 if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
10261 return true;
10262 } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
10263 Value *LL, *LR;
10264 // FIXME: Once we have SDiv implemented, we can get rid of this matching.
10266 using namespace llvm::PatternMatch;
10268 if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
10269 // Rules for division.
10270 // We are going to perform some comparisons with Denominator and its
10271 // derivative expressions. In general case, creating a SCEV for it may
10272 // lead to a complex analysis of the entire graph, and in particular it
10273 // can request trip count recalculation for the same loop. This would
10274 // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
10275 // this, we only want to create SCEVs that are constants in this section.
10276 // So we bail if Denominator is not a constant.
10277 if (!isa<ConstantInt>(LR))
10278 return false;
10280 auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
10282 // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
10283 // then a SCEV for the numerator already exists and matches with FoundLHS.
10284 auto *Numerator = getExistingSCEV(LL);
10285 if (!Numerator || Numerator->getType() != FoundLHS->getType())
10286 return false;
10288 // Make sure that the numerator matches with FoundLHS and the denominator
10289 // is positive.
10290 if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
10291 return false;
10293 auto *DTy = Denominator->getType();
10294 auto *FRHSTy = FoundRHS->getType();
10295 if (DTy->isPointerTy() != FRHSTy->isPointerTy())
10296 // One of types is a pointer and another one is not. We cannot extend
10297 // them properly to a wider type, so let us just reject this case.
10298 // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
10299 // to avoid this check.
10300 return false;
10302 // Given that:
10303 // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
10304 auto *WTy = getWiderType(DTy, FRHSTy);
10305 auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
10306 auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
10308 // Try to prove the following rule:
10309 // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
10310 // For example, given that FoundLHS > 2. It means that FoundLHS is at
10311 // least 3. If we divide it by Denominator < 4, we will have at least 1.
10312 auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
10313 if (isKnownNonPositive(RHS) &&
10314 IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
10315 return true;
10317 // Try to prove the following rule:
10318 // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
10319 // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
10320 // If we divide it by Denominator > 2, then:
10321 // 1. If FoundLHS is negative, then the result is 0.
10322 // 2. If FoundLHS is non-negative, then the result is non-negative.
10323 // Anyways, the result is non-negative.
10324 auto *MinusOne = getNegativeSCEV(getOne(WTy));
10325 auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
10326 if (isKnownNegative(RHS) &&
10327 IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
10328 return true;
10332 // If our expression contained SCEVUnknown Phis, and we split it down and now
10333 // need to prove something for them, try to prove the predicate for every
10334 // possible incoming values of those Phis.
10335 if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
10336 return true;
10338 return false;
10341 bool
10342 ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
10343 const SCEV *LHS, const SCEV *RHS) {
10344 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
10345 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
10346 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
10347 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
10350 bool
10351 ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
10352 const SCEV *LHS, const SCEV *RHS,
10353 const SCEV *FoundLHS,
10354 const SCEV *FoundRHS) {
10355 switch (Pred) {
10356 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
10357 case ICmpInst::ICMP_EQ:
10358 case ICmpInst::ICMP_NE:
10359 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
10360 return true;
10361 break;
10362 case ICmpInst::ICMP_SLT:
10363 case ICmpInst::ICMP_SLE:
10364 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
10365 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
10366 return true;
10367 break;
10368 case ICmpInst::ICMP_SGT:
10369 case ICmpInst::ICMP_SGE:
10370 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
10371 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
10372 return true;
10373 break;
10374 case ICmpInst::ICMP_ULT:
10375 case ICmpInst::ICMP_ULE:
10376 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
10377 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
10378 return true;
10379 break;
10380 case ICmpInst::ICMP_UGT:
10381 case ICmpInst::ICMP_UGE:
10382 if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
10383 isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
10384 return true;
10385 break;
10388 // Maybe it can be proved via operations?
10389 if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
10390 return true;
10392 return false;
10395 bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
10396 const SCEV *LHS,
10397 const SCEV *RHS,
10398 const SCEV *FoundLHS,
10399 const SCEV *FoundRHS) {
10400 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
10401 // The restriction on `FoundRHS` be lifted easily -- it exists only to
10402 // reduce the compile time impact of this optimization.
10403 return false;
10405 Optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
10406 if (!Addend)
10407 return false;
10409 const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
10411 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
10412 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
10413 ConstantRange FoundLHSRange =
10414 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
10416 // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
10417 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
10419 // We can also compute the range of values for `LHS` that satisfy the
10420 // consequent, "`LHS` `Pred` `RHS`":
10421 const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
10422 ConstantRange SatisfyingLHSRange =
10423 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
10425 // The antecedent implies the consequent if every value of `LHS` that
10426 // satisfies the antecedent also satisfies the consequent.
10427 return SatisfyingLHSRange.contains(LHSRange);
10430 bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
10431 bool IsSigned, bool NoWrap) {
10432 assert(isKnownPositive(Stride) && "Positive stride expected!");
10434 if (NoWrap) return false;
10436 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10437 const SCEV *One = getOne(Stride->getType());
10439 if (IsSigned) {
10440 APInt MaxRHS = getSignedRangeMax(RHS);
10441 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
10442 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10444 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
10445 return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
10448 APInt MaxRHS = getUnsignedRangeMax(RHS);
10449 APInt MaxValue = APInt::getMaxValue(BitWidth);
10450 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10452 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
10453 return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
10456 bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
10457 bool IsSigned, bool NoWrap) {
10458 if (NoWrap) return false;
10460 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
10461 const SCEV *One = getOne(Stride->getType());
10463 if (IsSigned) {
10464 APInt MinRHS = getSignedRangeMin(RHS);
10465 APInt MinValue = APInt::getSignedMinValue(BitWidth);
10466 APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
10468 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
10469 return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
10472 APInt MinRHS = getUnsignedRangeMin(RHS);
10473 APInt MinValue = APInt::getMinValue(BitWidth);
10474 APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
10476 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
10477 return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
10480 const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
10481 bool Equality) {
10482 const SCEV *One = getOne(Step->getType());
10483 Delta = Equality ? getAddExpr(Delta, Step)
10484 : getAddExpr(Delta, getMinusSCEV(Step, One));
10485 return getUDivExpr(Delta, Step);
10488 const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
10489 const SCEV *Stride,
10490 const SCEV *End,
10491 unsigned BitWidth,
10492 bool IsSigned) {
10494 assert(!isKnownNonPositive(Stride) &&
10495 "Stride is expected strictly positive!");
10496 // Calculate the maximum backedge count based on the range of values
10497 // permitted by Start, End, and Stride.
10498 const SCEV *MaxBECount;
10499 APInt MinStart =
10500 IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
10502 APInt StrideForMaxBECount =
10503 IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
10505 // We already know that the stride is positive, so we paper over conservatism
10506 // in our range computation by forcing StrideForMaxBECount to be at least one.
10507 // In theory this is unnecessary, but we expect MaxBECount to be a
10508 // SCEVConstant, and (udiv <constant> 0) is not constant folded by SCEV (there
10509 // is nothing to constant fold it to).
10510 APInt One(BitWidth, 1, IsSigned);
10511 StrideForMaxBECount = APIntOps::smax(One, StrideForMaxBECount);
10513 APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
10514 : APInt::getMaxValue(BitWidth);
10515 APInt Limit = MaxValue - (StrideForMaxBECount - 1);
10517 // Although End can be a MAX expression we estimate MaxEnd considering only
10518 // the case End = RHS of the loop termination condition. This is safe because
10519 // in the other case (End - Start) is zero, leading to a zero maximum backedge
10520 // taken count.
10521 APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
10522 : APIntOps::umin(getUnsignedRangeMax(End), Limit);
10524 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart) /* Delta */,
10525 getConstant(StrideForMaxBECount) /* Step */,
10526 false /* Equality */);
10528 return MaxBECount;
10531 ScalarEvolution::ExitLimit
10532 ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
10533 const Loop *L, bool IsSigned,
10534 bool ControlsExit, bool AllowPredicates) {
10535 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10537 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10538 bool PredicatedIV = false;
10540 if (!IV && AllowPredicates) {
10541 // Try to make this an AddRec using runtime tests, in the first X
10542 // iterations of this loop, where X is the SCEV expression found by the
10543 // algorithm below.
10544 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10545 PredicatedIV = true;
10548 // Avoid weird loops
10549 if (!IV || IV->getLoop() != L || !IV->isAffine())
10550 return getCouldNotCompute();
10552 bool NoWrap = ControlsExit &&
10553 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10555 const SCEV *Stride = IV->getStepRecurrence(*this);
10557 bool PositiveStride = isKnownPositive(Stride);
10559 // Avoid negative or zero stride values.
10560 if (!PositiveStride) {
10561 // We can compute the correct backedge taken count for loops with unknown
10562 // strides if we can prove that the loop is not an infinite loop with side
10563 // effects. Here's the loop structure we are trying to handle -
10565 // i = start
10566 // do {
10567 // A[i] = i;
10568 // i += s;
10569 // } while (i < end);
10571 // The backedge taken count for such loops is evaluated as -
10572 // (max(end, start + stride) - start - 1) /u stride
10574 // The additional preconditions that we need to check to prove correctness
10575 // of the above formula is as follows -
10577 // a) IV is either nuw or nsw depending upon signedness (indicated by the
10578 // NoWrap flag).
10579 // b) loop is single exit with no side effects.
10582 // Precondition a) implies that if the stride is negative, this is a single
10583 // trip loop. The backedge taken count formula reduces to zero in this case.
10585 // Precondition b) implies that the unknown stride cannot be zero otherwise
10586 // we have UB.
10588 // The positive stride case is the same as isKnownPositive(Stride) returning
10589 // true (original behavior of the function).
10591 // We want to make sure that the stride is truly unknown as there are edge
10592 // cases where ScalarEvolution propagates no wrap flags to the
10593 // post-increment/decrement IV even though the increment/decrement operation
10594 // itself is wrapping. The computed backedge taken count may be wrong in
10595 // such cases. This is prevented by checking that the stride is not known to
10596 // be either positive or non-positive. For example, no wrap flags are
10597 // propagated to the post-increment IV of this loop with a trip count of 2 -
10599 // unsigned char i;
10600 // for(i=127; i<128; i+=129)
10601 // A[i] = i;
10603 if (PredicatedIV || !NoWrap || isKnownNonPositive(Stride) ||
10604 !loopHasNoSideEffects(L))
10605 return getCouldNotCompute();
10606 } else if (!Stride->isOne() &&
10607 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
10608 // Avoid proven overflow cases: this will ensure that the backedge taken
10609 // count will not generate any unsigned overflow. Relaxed no-overflow
10610 // conditions exploit NoWrapFlags, allowing to optimize in presence of
10611 // undefined behaviors like the case of C language.
10612 return getCouldNotCompute();
10614 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
10615 : ICmpInst::ICMP_ULT;
10616 const SCEV *Start = IV->getStart();
10617 const SCEV *End = RHS;
10618 // When the RHS is not invariant, we do not know the end bound of the loop and
10619 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
10620 // calculate the MaxBECount, given the start, stride and max value for the end
10621 // bound of the loop (RHS), and the fact that IV does not overflow (which is
10622 // checked above).
10623 if (!isLoopInvariant(RHS, L)) {
10624 const SCEV *MaxBECount = computeMaxBECountForLT(
10625 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10626 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
10627 false /*MaxOrZero*/, Predicates);
10629 // If the backedge is taken at least once, then it will be taken
10630 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
10631 // is the LHS value of the less-than comparison the first time it is evaluated
10632 // and End is the RHS.
10633 const SCEV *BECountIfBackedgeTaken =
10634 computeBECount(getMinusSCEV(End, Start), Stride, false);
10635 // If the loop entry is guarded by the result of the backedge test of the
10636 // first loop iteration, then we know the backedge will be taken at least
10637 // once and so the backedge taken count is as above. If not then we use the
10638 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
10639 // as if the backedge is taken at least once max(End,Start) is End and so the
10640 // result is as above, and if not max(End,Start) is Start so we get a backedge
10641 // count of zero.
10642 const SCEV *BECount;
10643 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
10644 BECount = BECountIfBackedgeTaken;
10645 else {
10646 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
10647 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
10650 const SCEV *MaxBECount;
10651 bool MaxOrZero = false;
10652 if (isa<SCEVConstant>(BECount))
10653 MaxBECount = BECount;
10654 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
10655 // If we know exactly how many times the backedge will be taken if it's
10656 // taken at least once, then the backedge count will either be that or
10657 // zero.
10658 MaxBECount = BECountIfBackedgeTaken;
10659 MaxOrZero = true;
10660 } else {
10661 MaxBECount = computeMaxBECountForLT(
10662 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
10665 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
10666 !isa<SCEVCouldNotCompute>(BECount))
10667 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
10669 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
10672 ScalarEvolution::ExitLimit
10673 ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
10674 const Loop *L, bool IsSigned,
10675 bool ControlsExit, bool AllowPredicates) {
10676 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
10677 // We handle only IV > Invariant
10678 if (!isLoopInvariant(RHS, L))
10679 return getCouldNotCompute();
10681 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
10682 if (!IV && AllowPredicates)
10683 // Try to make this an AddRec using runtime tests, in the first X
10684 // iterations of this loop, where X is the SCEV expression found by the
10685 // algorithm below.
10686 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
10688 // Avoid weird loops
10689 if (!IV || IV->getLoop() != L || !IV->isAffine())
10690 return getCouldNotCompute();
10692 bool NoWrap = ControlsExit &&
10693 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
10695 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
10697 // Avoid negative or zero stride values
10698 if (!isKnownPositive(Stride))
10699 return getCouldNotCompute();
10701 // Avoid proven overflow cases: this will ensure that the backedge taken count
10702 // will not generate any unsigned overflow. Relaxed no-overflow conditions
10703 // exploit NoWrapFlags, allowing to optimize in presence of undefined
10704 // behaviors like the case of C language.
10705 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
10706 return getCouldNotCompute();
10708 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
10709 : ICmpInst::ICMP_UGT;
10711 const SCEV *Start = IV->getStart();
10712 const SCEV *End = RHS;
10713 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
10714 End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
10716 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
10718 APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
10719 : getUnsignedRangeMax(Start);
10721 APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
10722 : getUnsignedRangeMin(Stride);
10724 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
10725 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
10726 : APInt::getMinValue(BitWidth) + (MinStride - 1);
10728 // Although End can be a MIN expression we estimate MinEnd considering only
10729 // the case End = RHS. This is safe because in the other case (Start - End)
10730 // is zero, leading to a zero maximum backedge taken count.
10731 APInt MinEnd =
10732 IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
10733 : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
10735 const SCEV *MaxBECount = isa<SCEVConstant>(BECount)
10736 ? BECount
10737 : computeBECount(getConstant(MaxStart - MinEnd),
10738 getConstant(MinStride), false);
10740 if (isa<SCEVCouldNotCompute>(MaxBECount))
10741 MaxBECount = BECount;
10743 return ExitLimit(BECount, MaxBECount, false, Predicates);
10746 const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
10747 ScalarEvolution &SE) const {
10748 if (Range.isFullSet()) // Infinite loop.
10749 return SE.getCouldNotCompute();
10751 // If the start is a non-zero constant, shift the range to simplify things.
10752 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
10753 if (!SC->getValue()->isZero()) {
10754 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
10755 Operands[0] = SE.getZero(SC->getType());
10756 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
10757 getNoWrapFlags(FlagNW));
10758 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
10759 return ShiftedAddRec->getNumIterationsInRange(
10760 Range.subtract(SC->getAPInt()), SE);
10761 // This is strange and shouldn't happen.
10762 return SE.getCouldNotCompute();
10765 // The only time we can solve this is when we have all constant indices.
10766 // Otherwise, we cannot determine the overflow conditions.
10767 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
10768 return SE.getCouldNotCompute();
10770 // Okay at this point we know that all elements of the chrec are constants and
10771 // that the start element is zero.
10773 // First check to see if the range contains zero. If not, the first
10774 // iteration exits.
10775 unsigned BitWidth = SE.getTypeSizeInBits(getType());
10776 if (!Range.contains(APInt(BitWidth, 0)))
10777 return SE.getZero(getType());
10779 if (isAffine()) {
10780 // If this is an affine expression then we have this situation:
10781 // Solve {0,+,A} in Range === Ax in Range
10783 // We know that zero is in the range. If A is positive then we know that
10784 // the upper value of the range must be the first possible exit value.
10785 // If A is negative then the lower of the range is the last possible loop
10786 // value. Also note that we already checked for a full range.
10787 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
10788 APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
10790 // The exit value should be (End+A)/A.
10791 APInt ExitVal = (End + A).udiv(A);
10792 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
10794 // Evaluate at the exit value. If we really did fall out of the valid
10795 // range, then we computed our trip count, otherwise wrap around or other
10796 // things must have happened.
10797 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
10798 if (Range.contains(Val->getValue()))
10799 return SE.getCouldNotCompute(); // Something strange happened
10801 // Ensure that the previous value is in the range. This is a sanity check.
10802 assert(Range.contains(
10803 EvaluateConstantChrecAtConstant(this,
10804 ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
10805 "Linear scev computation is off in a bad way!");
10806 return SE.getConstant(ExitValue);
10809 if (isQuadratic()) {
10810 if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
10811 return SE.getConstant(S.getValue());
10814 return SE.getCouldNotCompute();
10817 const SCEVAddRecExpr *
10818 SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
10819 assert(getNumOperands() > 1 && "AddRec with zero step?");
10820 // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
10821 // but in this case we cannot guarantee that the value returned will be an
10822 // AddRec because SCEV does not have a fixed point where it stops
10823 // simplification: it is legal to return ({rec1} + {rec2}). For example, it
10824 // may happen if we reach arithmetic depth limit while simplifying. So we
10825 // construct the returned value explicitly.
10826 SmallVector<const SCEV *, 3> Ops;
10827 // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
10828 // (this + Step) is {A+B,+,B+C,+...,+,N}.
10829 for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
10830 Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
10831 // We know that the last operand is not a constant zero (otherwise it would
10832 // have been popped out earlier). This guarantees us that if the result has
10833 // the same last operand, then it will also not be popped out, meaning that
10834 // the returned value will be an AddRec.
10835 const SCEV *Last = getOperand(getNumOperands() - 1);
10836 assert(!Last->isZero() && "Recurrency with zero step?");
10837 Ops.push_back(Last);
10838 return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
10839 SCEV::FlagAnyWrap));
10842 // Return true when S contains at least an undef value.
10843 static inline bool containsUndefs(const SCEV *S) {
10844 return SCEVExprContains(S, [](const SCEV *S) {
10845 if (const auto *SU = dyn_cast<SCEVUnknown>(S))
10846 return isa<UndefValue>(SU->getValue());
10847 return false;
10851 namespace {
10853 // Collect all steps of SCEV expressions.
10854 struct SCEVCollectStrides {
10855 ScalarEvolution &SE;
10856 SmallVectorImpl<const SCEV *> &Strides;
10858 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
10859 : SE(SE), Strides(S) {}
10861 bool follow(const SCEV *S) {
10862 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
10863 Strides.push_back(AR->getStepRecurrence(SE));
10864 return true;
10867 bool isDone() const { return false; }
10870 // Collect all SCEVUnknown and SCEVMulExpr expressions.
10871 struct SCEVCollectTerms {
10872 SmallVectorImpl<const SCEV *> &Terms;
10874 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T) : Terms(T) {}
10876 bool follow(const SCEV *S) {
10877 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S) ||
10878 isa<SCEVSignExtendExpr>(S)) {
10879 if (!containsUndefs(S))
10880 Terms.push_back(S);
10882 // Stop recursion: once we collected a term, do not walk its operands.
10883 return false;
10886 // Keep looking.
10887 return true;
10890 bool isDone() const { return false; }
10893 // Check if a SCEV contains an AddRecExpr.
10894 struct SCEVHasAddRec {
10895 bool &ContainsAddRec;
10897 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
10898 ContainsAddRec = false;
10901 bool follow(const SCEV *S) {
10902 if (isa<SCEVAddRecExpr>(S)) {
10903 ContainsAddRec = true;
10905 // Stop recursion: once we collected a term, do not walk its operands.
10906 return false;
10909 // Keep looking.
10910 return true;
10913 bool isDone() const { return false; }
10916 // Find factors that are multiplied with an expression that (possibly as a
10917 // subexpression) contains an AddRecExpr. In the expression:
10919 // 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
10921 // "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
10922 // that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
10923 // parameters as they form a product with an induction variable.
10925 // This collector expects all array size parameters to be in the same MulExpr.
10926 // It might be necessary to later add support for collecting parameters that are
10927 // spread over different nested MulExpr.
10928 struct SCEVCollectAddRecMultiplies {
10929 SmallVectorImpl<const SCEV *> &Terms;
10930 ScalarEvolution &SE;
10932 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
10933 : Terms(T), SE(SE) {}
10935 bool follow(const SCEV *S) {
10936 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
10937 bool HasAddRec = false;
10938 SmallVector<const SCEV *, 0> Operands;
10939 for (auto Op : Mul->operands()) {
10940 const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Op);
10941 if (Unknown && !isa<CallInst>(Unknown->getValue())) {
10942 Operands.push_back(Op);
10943 } else if (Unknown) {
10944 HasAddRec = true;
10945 } else {
10946 bool ContainsAddRec;
10947 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
10948 visitAll(Op, ContiansAddRec);
10949 HasAddRec |= ContainsAddRec;
10952 if (Operands.size() == 0)
10953 return true;
10955 if (!HasAddRec)
10956 return false;
10958 Terms.push_back(SE.getMulExpr(Operands));
10959 // Stop recursion: once we collected a term, do not walk its operands.
10960 return false;
10963 // Keep looking.
10964 return true;
10967 bool isDone() const { return false; }
10970 } // end anonymous namespace
10972 /// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
10973 /// two places:
10974 /// 1) The strides of AddRec expressions.
10975 /// 2) Unknowns that are multiplied with AddRec expressions.
10976 void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
10977 SmallVectorImpl<const SCEV *> &Terms) {
10978 SmallVector<const SCEV *, 4> Strides;
10979 SCEVCollectStrides StrideCollector(*this, Strides);
10980 visitAll(Expr, StrideCollector);
10982 LLVM_DEBUG({
10983 dbgs() << "Strides:\n";
10984 for (const SCEV *S : Strides)
10985 dbgs() << *S << "\n";
10988 for (const SCEV *S : Strides) {
10989 SCEVCollectTerms TermCollector(Terms);
10990 visitAll(S, TermCollector);
10993 LLVM_DEBUG({
10994 dbgs() << "Terms:\n";
10995 for (const SCEV *T : Terms)
10996 dbgs() << *T << "\n";
10999 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
11000 visitAll(Expr, MulCollector);
11003 static bool findArrayDimensionsRec(ScalarEvolution &SE,
11004 SmallVectorImpl<const SCEV *> &Terms,
11005 SmallVectorImpl<const SCEV *> &Sizes) {
11006 int Last = Terms.size() - 1;
11007 const SCEV *Step = Terms[Last];
11009 // End of recursion.
11010 if (Last == 0) {
11011 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
11012 SmallVector<const SCEV *, 2> Qs;
11013 for (const SCEV *Op : M->operands())
11014 if (!isa<SCEVConstant>(Op))
11015 Qs.push_back(Op);
11017 Step = SE.getMulExpr(Qs);
11020 Sizes.push_back(Step);
11021 return true;
11024 for (const SCEV *&Term : Terms) {
11025 // Normalize the terms before the next call to findArrayDimensionsRec.
11026 const SCEV *Q, *R;
11027 SCEVDivision::divide(SE, Term, Step, &Q, &R);
11029 // Bail out when GCD does not evenly divide one of the terms.
11030 if (!R->isZero())
11031 return false;
11033 Term = Q;
11036 // Remove all SCEVConstants.
11037 Terms.erase(
11038 remove_if(Terms, [](const SCEV *E) { return isa<SCEVConstant>(E); }),
11039 Terms.end());
11041 if (Terms.size() > 0)
11042 if (!findArrayDimensionsRec(SE, Terms, Sizes))
11043 return false;
11045 Sizes.push_back(Step);
11046 return true;
11049 // Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
11050 static inline bool containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
11051 for (const SCEV *T : Terms)
11052 if (SCEVExprContains(T, isa<SCEVUnknown, const SCEV *>))
11053 return true;
11054 return false;
11057 // Return the number of product terms in S.
11058 static inline int numberOfTerms(const SCEV *S) {
11059 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
11060 return Expr->getNumOperands();
11061 return 1;
11064 static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
11065 if (isa<SCEVConstant>(T))
11066 return nullptr;
11068 if (isa<SCEVUnknown>(T))
11069 return T;
11071 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
11072 SmallVector<const SCEV *, 2> Factors;
11073 for (const SCEV *Op : M->operands())
11074 if (!isa<SCEVConstant>(Op))
11075 Factors.push_back(Op);
11077 return SE.getMulExpr(Factors);
11080 return T;
11083 /// Return the size of an element read or written by Inst.
11084 const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
11085 Type *Ty;
11086 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
11087 Ty = Store->getValueOperand()->getType();
11088 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
11089 Ty = Load->getType();
11090 else
11091 return nullptr;
11093 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
11094 return getSizeOfExpr(ETy, Ty);
11097 void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
11098 SmallVectorImpl<const SCEV *> &Sizes,
11099 const SCEV *ElementSize) {
11100 if (Terms.size() < 1 || !ElementSize)
11101 return;
11103 // Early return when Terms do not contain parameters: we do not delinearize
11104 // non parametric SCEVs.
11105 if (!containsParameters(Terms))
11106 return;
11108 LLVM_DEBUG({
11109 dbgs() << "Terms:\n";
11110 for (const SCEV *T : Terms)
11111 dbgs() << *T << "\n";
11114 // Remove duplicates.
11115 array_pod_sort(Terms.begin(), Terms.end());
11116 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
11118 // Put larger terms first.
11119 llvm::sort(Terms, [](const SCEV *LHS, const SCEV *RHS) {
11120 return numberOfTerms(LHS) > numberOfTerms(RHS);
11123 // Try to divide all terms by the element size. If term is not divisible by
11124 // element size, proceed with the original term.
11125 for (const SCEV *&Term : Terms) {
11126 const SCEV *Q, *R;
11127 SCEVDivision::divide(*this, Term, ElementSize, &Q, &R);
11128 if (!Q->isZero())
11129 Term = Q;
11132 SmallVector<const SCEV *, 4> NewTerms;
11134 // Remove constant factors.
11135 for (const SCEV *T : Terms)
11136 if (const SCEV *NewT = removeConstantFactors(*this, T))
11137 NewTerms.push_back(NewT);
11139 LLVM_DEBUG({
11140 dbgs() << "Terms after sorting:\n";
11141 for (const SCEV *T : NewTerms)
11142 dbgs() << *T << "\n";
11145 if (NewTerms.empty() || !findArrayDimensionsRec(*this, NewTerms, Sizes)) {
11146 Sizes.clear();
11147 return;
11150 // The last element to be pushed into Sizes is the size of an element.
11151 Sizes.push_back(ElementSize);
11153 LLVM_DEBUG({
11154 dbgs() << "Sizes:\n";
11155 for (const SCEV *S : Sizes)
11156 dbgs() << *S << "\n";
11160 void ScalarEvolution::computeAccessFunctions(
11161 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
11162 SmallVectorImpl<const SCEV *> &Sizes) {
11163 // Early exit in case this SCEV is not an affine multivariate function.
11164 if (Sizes.empty())
11165 return;
11167 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
11168 if (!AR->isAffine())
11169 return;
11171 const SCEV *Res = Expr;
11172 int Last = Sizes.size() - 1;
11173 for (int i = Last; i >= 0; i--) {
11174 const SCEV *Q, *R;
11175 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
11177 LLVM_DEBUG({
11178 dbgs() << "Res: " << *Res << "\n";
11179 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
11180 dbgs() << "Res divided by Sizes[i]:\n";
11181 dbgs() << "Quotient: " << *Q << "\n";
11182 dbgs() << "Remainder: " << *R << "\n";
11185 Res = Q;
11187 // Do not record the last subscript corresponding to the size of elements in
11188 // the array.
11189 if (i == Last) {
11191 // Bail out if the remainder is too complex.
11192 if (isa<SCEVAddRecExpr>(R)) {
11193 Subscripts.clear();
11194 Sizes.clear();
11195 return;
11198 continue;
11201 // Record the access function for the current subscript.
11202 Subscripts.push_back(R);
11205 // Also push in last position the remainder of the last division: it will be
11206 // the access function of the innermost dimension.
11207 Subscripts.push_back(Res);
11209 std::reverse(Subscripts.begin(), Subscripts.end());
11211 LLVM_DEBUG({
11212 dbgs() << "Subscripts:\n";
11213 for (const SCEV *S : Subscripts)
11214 dbgs() << *S << "\n";
11218 /// Splits the SCEV into two vectors of SCEVs representing the subscripts and
11219 /// sizes of an array access. Returns the remainder of the delinearization that
11220 /// is the offset start of the array. The SCEV->delinearize algorithm computes
11221 /// the multiples of SCEV coefficients: that is a pattern matching of sub
11222 /// expressions in the stride and base of a SCEV corresponding to the
11223 /// computation of a GCD (greatest common divisor) of base and stride. When
11224 /// SCEV->delinearize fails, it returns the SCEV unchanged.
11226 /// For example: when analyzing the memory access A[i][j][k] in this loop nest
11228 /// void foo(long n, long m, long o, double A[n][m][o]) {
11230 /// for (long i = 0; i < n; i++)
11231 /// for (long j = 0; j < m; j++)
11232 /// for (long k = 0; k < o; k++)
11233 /// A[i][j][k] = 1.0;
11234 /// }
11236 /// the delinearization input is the following AddRec SCEV:
11238 /// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
11240 /// From this SCEV, we are able to say that the base offset of the access is %A
11241 /// because it appears as an offset that does not divide any of the strides in
11242 /// the loops:
11244 /// CHECK: Base offset: %A
11246 /// and then SCEV->delinearize determines the size of some of the dimensions of
11247 /// the array as these are the multiples by which the strides are happening:
11249 /// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
11251 /// Note that the outermost dimension remains of UnknownSize because there are
11252 /// no strides that would help identifying the size of the last dimension: when
11253 /// the array has been statically allocated, one could compute the size of that
11254 /// dimension by dividing the overall size of the array by the size of the known
11255 /// dimensions: %m * %o * 8.
11257 /// Finally delinearize provides the access functions for the array reference
11258 /// that does correspond to A[i][j][k] of the above C testcase:
11260 /// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
11262 /// The testcases are checking the output of a function pass:
11263 /// DelinearizationPass that walks through all loads and stores of a function
11264 /// asking for the SCEV of the memory access with respect to all enclosing
11265 /// loops, calling SCEV->delinearize on that and printing the results.
11266 void ScalarEvolution::delinearize(const SCEV *Expr,
11267 SmallVectorImpl<const SCEV *> &Subscripts,
11268 SmallVectorImpl<const SCEV *> &Sizes,
11269 const SCEV *ElementSize) {
11270 // First step: collect parametric terms.
11271 SmallVector<const SCEV *, 4> Terms;
11272 collectParametricTerms(Expr, Terms);
11274 if (Terms.empty())
11275 return;
11277 // Second step: find subscript sizes.
11278 findArrayDimensions(Terms, Sizes, ElementSize);
11280 if (Sizes.empty())
11281 return;
11283 // Third step: compute the access functions for each subscript.
11284 computeAccessFunctions(Expr, Subscripts, Sizes);
11286 if (Subscripts.empty())
11287 return;
11289 LLVM_DEBUG({
11290 dbgs() << "succeeded to delinearize " << *Expr << "\n";
11291 dbgs() << "ArrayDecl[UnknownSize]";
11292 for (const SCEV *S : Sizes)
11293 dbgs() << "[" << *S << "]";
11295 dbgs() << "\nArrayRef";
11296 for (const SCEV *S : Subscripts)
11297 dbgs() << "[" << *S << "]";
11298 dbgs() << "\n";
11302 //===----------------------------------------------------------------------===//
11303 // SCEVCallbackVH Class Implementation
11304 //===----------------------------------------------------------------------===//
11306 void ScalarEvolution::SCEVCallbackVH::deleted() {
11307 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11308 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
11309 SE->ConstantEvolutionLoopExitValue.erase(PN);
11310 SE->eraseValueFromMap(getValPtr());
11311 // this now dangles!
11314 void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
11315 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
11317 // Forget all the expressions associated with users of the old value,
11318 // so that future queries will recompute the expressions using the new
11319 // value.
11320 Value *Old = getValPtr();
11321 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
11322 SmallPtrSet<User *, 8> Visited;
11323 while (!Worklist.empty()) {
11324 User *U = Worklist.pop_back_val();
11325 // Deleting the Old value will cause this to dangle. Postpone
11326 // that until everything else is done.
11327 if (U == Old)
11328 continue;
11329 if (!Visited.insert(U).second)
11330 continue;
11331 if (PHINode *PN = dyn_cast<PHINode>(U))
11332 SE->ConstantEvolutionLoopExitValue.erase(PN);
11333 SE->eraseValueFromMap(U);
11334 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
11336 // Delete the Old value.
11337 if (PHINode *PN = dyn_cast<PHINode>(Old))
11338 SE->ConstantEvolutionLoopExitValue.erase(PN);
11339 SE->eraseValueFromMap(Old);
11340 // this now dangles!
11343 ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
11344 : CallbackVH(V), SE(se) {}
11346 //===----------------------------------------------------------------------===//
11347 // ScalarEvolution Class Implementation
11348 //===----------------------------------------------------------------------===//
11350 ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
11351 AssumptionCache &AC, DominatorTree &DT,
11352 LoopInfo &LI)
11353 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
11354 CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
11355 LoopDispositions(64), BlockDispositions(64) {
11356 // To use guards for proving predicates, we need to scan every instruction in
11357 // relevant basic blocks, and not just terminators. Doing this is a waste of
11358 // time if the IR does not actually contain any calls to
11359 // @llvm.experimental.guard, so do a quick check and remember this beforehand.
11361 // This pessimizes the case where a pass that preserves ScalarEvolution wants
11362 // to _add_ guards to the module when there weren't any before, and wants
11363 // ScalarEvolution to optimize based on those guards. For now we prefer to be
11364 // efficient in lieu of being smart in that rather obscure case.
11366 auto *GuardDecl = F.getParent()->getFunction(
11367 Intrinsic::getName(Intrinsic::experimental_guard));
11368 HasGuards = GuardDecl && !GuardDecl->use_empty();
11371 ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
11372 : F(Arg.F), HasGuards(Arg.HasGuards), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT),
11373 LI(Arg.LI), CouldNotCompute(std::move(Arg.CouldNotCompute)),
11374 ValueExprMap(std::move(Arg.ValueExprMap)),
11375 PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
11376 PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
11377 PendingMerges(std::move(Arg.PendingMerges)),
11378 MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
11379 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
11380 PredicatedBackedgeTakenCounts(
11381 std::move(Arg.PredicatedBackedgeTakenCounts)),
11382 ConstantEvolutionLoopExitValue(
11383 std::move(Arg.ConstantEvolutionLoopExitValue)),
11384 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
11385 LoopDispositions(std::move(Arg.LoopDispositions)),
11386 LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
11387 BlockDispositions(std::move(Arg.BlockDispositions)),
11388 UnsignedRanges(std::move(Arg.UnsignedRanges)),
11389 SignedRanges(std::move(Arg.SignedRanges)),
11390 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
11391 UniquePreds(std::move(Arg.UniquePreds)),
11392 SCEVAllocator(std::move(Arg.SCEVAllocator)),
11393 LoopUsers(std::move(Arg.LoopUsers)),
11394 PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
11395 FirstUnknown(Arg.FirstUnknown) {
11396 Arg.FirstUnknown = nullptr;
11399 ScalarEvolution::~ScalarEvolution() {
11400 // Iterate through all the SCEVUnknown instances and call their
11401 // destructors, so that they release their references to their values.
11402 for (SCEVUnknown *U = FirstUnknown; U;) {
11403 SCEVUnknown *Tmp = U;
11404 U = U->Next;
11405 Tmp->~SCEVUnknown();
11407 FirstUnknown = nullptr;
11409 ExprValueMap.clear();
11410 ValueExprMap.clear();
11411 HasRecMap.clear();
11413 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
11414 // that a loop had multiple computable exits.
11415 for (auto &BTCI : BackedgeTakenCounts)
11416 BTCI.second.clear();
11417 for (auto &BTCI : PredicatedBackedgeTakenCounts)
11418 BTCI.second.clear();
11420 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
11421 assert(PendingPhiRanges.empty() && "getRangeRef garbage");
11422 assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
11423 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
11424 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
11427 bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
11428 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
11431 static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
11432 const Loop *L) {
11433 // Print all inner loops first
11434 for (Loop *I : *L)
11435 PrintLoopInfo(OS, SE, I);
11437 OS << "Loop ";
11438 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11439 OS << ": ";
11441 SmallVector<BasicBlock *, 8> ExitingBlocks;
11442 L->getExitingBlocks(ExitingBlocks);
11443 if (ExitingBlocks.size() != 1)
11444 OS << "<multiple exits> ";
11446 if (SE->hasLoopInvariantBackedgeTakenCount(L))
11447 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
11448 else
11449 OS << "Unpredictable backedge-taken count.\n";
11451 if (ExitingBlocks.size() > 1)
11452 for (BasicBlock *ExitingBlock : ExitingBlocks) {
11453 OS << " exit count for " << ExitingBlock->getName() << ": "
11454 << *SE->getExitCount(L, ExitingBlock) << "\n";
11457 OS << "Loop ";
11458 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11459 OS << ": ";
11461 if (!isa<SCEVCouldNotCompute>(SE->getConstantMaxBackedgeTakenCount(L))) {
11462 OS << "max backedge-taken count is " << *SE->getConstantMaxBackedgeTakenCount(L);
11463 if (SE->isBackedgeTakenCountMaxOrZero(L))
11464 OS << ", actual taken count either this or zero.";
11465 } else {
11466 OS << "Unpredictable max backedge-taken count. ";
11469 OS << "\n"
11470 "Loop ";
11471 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11472 OS << ": ";
11474 SCEVUnionPredicate Pred;
11475 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
11476 if (!isa<SCEVCouldNotCompute>(PBT)) {
11477 OS << "Predicated backedge-taken count is " << *PBT << "\n";
11478 OS << " Predicates:\n";
11479 Pred.print(OS, 4);
11480 } else {
11481 OS << "Unpredictable predicated backedge-taken count. ";
11483 OS << "\n";
11485 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
11486 OS << "Loop ";
11487 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11488 OS << ": ";
11489 OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
11493 static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
11494 switch (LD) {
11495 case ScalarEvolution::LoopVariant:
11496 return "Variant";
11497 case ScalarEvolution::LoopInvariant:
11498 return "Invariant";
11499 case ScalarEvolution::LoopComputable:
11500 return "Computable";
11502 llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
11505 void ScalarEvolution::print(raw_ostream &OS) const {
11506 // ScalarEvolution's implementation of the print method is to print
11507 // out SCEV values of all instructions that are interesting. Doing
11508 // this potentially causes it to create new SCEV objects though,
11509 // which technically conflicts with the const qualifier. This isn't
11510 // observable from outside the class though, so casting away the
11511 // const isn't dangerous.
11512 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11514 OS << "Classifying expressions for: ";
11515 F.printAsOperand(OS, /*PrintType=*/false);
11516 OS << "\n";
11517 for (Instruction &I : instructions(F))
11518 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
11519 OS << I << '\n';
11520 OS << " --> ";
11521 const SCEV *SV = SE.getSCEV(&I);
11522 SV->print(OS);
11523 if (!isa<SCEVCouldNotCompute>(SV)) {
11524 OS << " U: ";
11525 SE.getUnsignedRange(SV).print(OS);
11526 OS << " S: ";
11527 SE.getSignedRange(SV).print(OS);
11530 const Loop *L = LI.getLoopFor(I.getParent());
11532 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
11533 if (AtUse != SV) {
11534 OS << " --> ";
11535 AtUse->print(OS);
11536 if (!isa<SCEVCouldNotCompute>(AtUse)) {
11537 OS << " U: ";
11538 SE.getUnsignedRange(AtUse).print(OS);
11539 OS << " S: ";
11540 SE.getSignedRange(AtUse).print(OS);
11544 if (L) {
11545 OS << "\t\t" "Exits: ";
11546 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
11547 if (!SE.isLoopInvariant(ExitValue, L)) {
11548 OS << "<<Unknown>>";
11549 } else {
11550 OS << *ExitValue;
11553 bool First = true;
11554 for (auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
11555 if (First) {
11556 OS << "\t\t" "LoopDispositions: { ";
11557 First = false;
11558 } else {
11559 OS << ", ";
11562 Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11563 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
11566 for (auto *InnerL : depth_first(L)) {
11567 if (InnerL == L)
11568 continue;
11569 if (First) {
11570 OS << "\t\t" "LoopDispositions: { ";
11571 First = false;
11572 } else {
11573 OS << ", ";
11576 InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
11577 OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
11580 OS << " }";
11583 OS << "\n";
11586 OS << "Determining loop execution counts for: ";
11587 F.printAsOperand(OS, /*PrintType=*/false);
11588 OS << "\n";
11589 for (Loop *I : LI)
11590 PrintLoopInfo(OS, &SE, I);
11593 ScalarEvolution::LoopDisposition
11594 ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
11595 auto &Values = LoopDispositions[S];
11596 for (auto &V : Values) {
11597 if (V.getPointer() == L)
11598 return V.getInt();
11600 Values.emplace_back(L, LoopVariant);
11601 LoopDisposition D = computeLoopDisposition(S, L);
11602 auto &Values2 = LoopDispositions[S];
11603 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11604 if (V.getPointer() == L) {
11605 V.setInt(D);
11606 break;
11609 return D;
11612 ScalarEvolution::LoopDisposition
11613 ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
11614 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11615 case scConstant:
11616 return LoopInvariant;
11617 case scTruncate:
11618 case scZeroExtend:
11619 case scSignExtend:
11620 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
11621 case scAddRecExpr: {
11622 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11624 // If L is the addrec's loop, it's computable.
11625 if (AR->getLoop() == L)
11626 return LoopComputable;
11628 // Add recurrences are never invariant in the function-body (null loop).
11629 if (!L)
11630 return LoopVariant;
11632 // Everything that is not defined at loop entry is variant.
11633 if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
11634 return LoopVariant;
11635 assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
11636 " dominate the contained loop's header?");
11638 // This recurrence is invariant w.r.t. L if AR's loop contains L.
11639 if (AR->getLoop()->contains(L))
11640 return LoopInvariant;
11642 // This recurrence is variant w.r.t. L if any of its operands
11643 // are variant.
11644 for (auto *Op : AR->operands())
11645 if (!isLoopInvariant(Op, L))
11646 return LoopVariant;
11648 // Otherwise it's loop-invariant.
11649 return LoopInvariant;
11651 case scAddExpr:
11652 case scMulExpr:
11653 case scUMaxExpr:
11654 case scSMaxExpr:
11655 case scUMinExpr:
11656 case scSMinExpr: {
11657 bool HasVarying = false;
11658 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
11659 LoopDisposition D = getLoopDisposition(Op, L);
11660 if (D == LoopVariant)
11661 return LoopVariant;
11662 if (D == LoopComputable)
11663 HasVarying = true;
11665 return HasVarying ? LoopComputable : LoopInvariant;
11667 case scUDivExpr: {
11668 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11669 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
11670 if (LD == LoopVariant)
11671 return LoopVariant;
11672 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
11673 if (RD == LoopVariant)
11674 return LoopVariant;
11675 return (LD == LoopInvariant && RD == LoopInvariant) ?
11676 LoopInvariant : LoopComputable;
11678 case scUnknown:
11679 // All non-instruction values are loop invariant. All instructions are loop
11680 // invariant if they are not contained in the specified loop.
11681 // Instructions are never considered invariant in the function body
11682 // (null loop) because they are defined within the "loop".
11683 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
11684 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
11685 return LoopInvariant;
11686 case scCouldNotCompute:
11687 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11689 llvm_unreachable("Unknown SCEV kind!");
11692 bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
11693 return getLoopDisposition(S, L) == LoopInvariant;
11696 bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
11697 return getLoopDisposition(S, L) == LoopComputable;
11700 ScalarEvolution::BlockDisposition
11701 ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11702 auto &Values = BlockDispositions[S];
11703 for (auto &V : Values) {
11704 if (V.getPointer() == BB)
11705 return V.getInt();
11707 Values.emplace_back(BB, DoesNotDominateBlock);
11708 BlockDisposition D = computeBlockDisposition(S, BB);
11709 auto &Values2 = BlockDispositions[S];
11710 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
11711 if (V.getPointer() == BB) {
11712 V.setInt(D);
11713 break;
11716 return D;
11719 ScalarEvolution::BlockDisposition
11720 ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
11721 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
11722 case scConstant:
11723 return ProperlyDominatesBlock;
11724 case scTruncate:
11725 case scZeroExtend:
11726 case scSignExtend:
11727 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
11728 case scAddRecExpr: {
11729 // This uses a "dominates" query instead of "properly dominates" query
11730 // to test for proper dominance too, because the instruction which
11731 // produces the addrec's value is a PHI, and a PHI effectively properly
11732 // dominates its entire containing block.
11733 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
11734 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
11735 return DoesNotDominateBlock;
11737 // Fall through into SCEVNAryExpr handling.
11738 LLVM_FALLTHROUGH;
11740 case scAddExpr:
11741 case scMulExpr:
11742 case scUMaxExpr:
11743 case scSMaxExpr:
11744 case scUMinExpr:
11745 case scSMinExpr: {
11746 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
11747 bool Proper = true;
11748 for (const SCEV *NAryOp : NAry->operands()) {
11749 BlockDisposition D = getBlockDisposition(NAryOp, BB);
11750 if (D == DoesNotDominateBlock)
11751 return DoesNotDominateBlock;
11752 if (D == DominatesBlock)
11753 Proper = false;
11755 return Proper ? ProperlyDominatesBlock : DominatesBlock;
11757 case scUDivExpr: {
11758 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
11759 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
11760 BlockDisposition LD = getBlockDisposition(LHS, BB);
11761 if (LD == DoesNotDominateBlock)
11762 return DoesNotDominateBlock;
11763 BlockDisposition RD = getBlockDisposition(RHS, BB);
11764 if (RD == DoesNotDominateBlock)
11765 return DoesNotDominateBlock;
11766 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
11767 ProperlyDominatesBlock : DominatesBlock;
11769 case scUnknown:
11770 if (Instruction *I =
11771 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
11772 if (I->getParent() == BB)
11773 return DominatesBlock;
11774 if (DT.properlyDominates(I->getParent(), BB))
11775 return ProperlyDominatesBlock;
11776 return DoesNotDominateBlock;
11778 return ProperlyDominatesBlock;
11779 case scCouldNotCompute:
11780 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
11782 llvm_unreachable("Unknown SCEV kind!");
11785 bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
11786 return getBlockDisposition(S, BB) >= DominatesBlock;
11789 bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
11790 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
11793 bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
11794 return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
11797 bool ScalarEvolution::ExitLimit::hasOperand(const SCEV *S) const {
11798 auto IsS = [&](const SCEV *X) { return S == X; };
11799 auto ContainsS = [&](const SCEV *X) {
11800 return !isa<SCEVCouldNotCompute>(X) && SCEVExprContains(X, IsS);
11802 return ContainsS(ExactNotTaken) || ContainsS(MaxNotTaken);
11805 void
11806 ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
11807 ValuesAtScopes.erase(S);
11808 LoopDispositions.erase(S);
11809 BlockDispositions.erase(S);
11810 UnsignedRanges.erase(S);
11811 SignedRanges.erase(S);
11812 ExprValueMap.erase(S);
11813 HasRecMap.erase(S);
11814 MinTrailingZerosCache.erase(S);
11816 for (auto I = PredicatedSCEVRewrites.begin();
11817 I != PredicatedSCEVRewrites.end();) {
11818 std::pair<const SCEV *, const Loop *> Entry = I->first;
11819 if (Entry.first == S)
11820 PredicatedSCEVRewrites.erase(I++);
11821 else
11822 ++I;
11825 auto RemoveSCEVFromBackedgeMap =
11826 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
11827 for (auto I = Map.begin(), E = Map.end(); I != E;) {
11828 BackedgeTakenInfo &BEInfo = I->second;
11829 if (BEInfo.hasOperand(S, this)) {
11830 BEInfo.clear();
11831 Map.erase(I++);
11832 } else
11833 ++I;
11837 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
11838 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
11841 void
11842 ScalarEvolution::getUsedLoops(const SCEV *S,
11843 SmallPtrSetImpl<const Loop *> &LoopsUsed) {
11844 struct FindUsedLoops {
11845 FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
11846 : LoopsUsed(LoopsUsed) {}
11847 SmallPtrSetImpl<const Loop *> &LoopsUsed;
11848 bool follow(const SCEV *S) {
11849 if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
11850 LoopsUsed.insert(AR->getLoop());
11851 return true;
11854 bool isDone() const { return false; }
11857 FindUsedLoops F(LoopsUsed);
11858 SCEVTraversal<FindUsedLoops>(F).visitAll(S);
11861 void ScalarEvolution::addToLoopUseLists(const SCEV *S) {
11862 SmallPtrSet<const Loop *, 8> LoopsUsed;
11863 getUsedLoops(S, LoopsUsed);
11864 for (auto *L : LoopsUsed)
11865 LoopUsers[L].push_back(S);
11868 void ScalarEvolution::verify() const {
11869 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
11870 ScalarEvolution SE2(F, TLI, AC, DT, LI);
11872 SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
11874 // Map's SCEV expressions from one ScalarEvolution "universe" to another.
11875 struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
11876 SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
11878 const SCEV *visitConstant(const SCEVConstant *Constant) {
11879 return SE.getConstant(Constant->getAPInt());
11882 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
11883 return SE.getUnknown(Expr->getValue());
11886 const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
11887 return SE.getCouldNotCompute();
11891 SCEVMapper SCM(SE2);
11893 while (!LoopStack.empty()) {
11894 auto *L = LoopStack.pop_back_val();
11895 LoopStack.insert(LoopStack.end(), L->begin(), L->end());
11897 auto *CurBECount = SCM.visit(
11898 const_cast<ScalarEvolution *>(this)->getBackedgeTakenCount(L));
11899 auto *NewBECount = SE2.getBackedgeTakenCount(L);
11901 if (CurBECount == SE2.getCouldNotCompute() ||
11902 NewBECount == SE2.getCouldNotCompute()) {
11903 // NB! This situation is legal, but is very suspicious -- whatever pass
11904 // change the loop to make a trip count go from could not compute to
11905 // computable or vice-versa *should have* invalidated SCEV. However, we
11906 // choose not to assert here (for now) since we don't want false
11907 // positives.
11908 continue;
11911 if (containsUndefs(CurBECount) || containsUndefs(NewBECount)) {
11912 // SCEV treats "undef" as an unknown but consistent value (i.e. it does
11913 // not propagate undef aggressively). This means we can (and do) fail
11914 // verification in cases where a transform makes the trip count of a loop
11915 // go from "undef" to "undef+1" (say). The transform is fine, since in
11916 // both cases the loop iterates "undef" times, but SCEV thinks we
11917 // increased the trip count of the loop by 1 incorrectly.
11918 continue;
11921 if (SE.getTypeSizeInBits(CurBECount->getType()) >
11922 SE.getTypeSizeInBits(NewBECount->getType()))
11923 NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
11924 else if (SE.getTypeSizeInBits(CurBECount->getType()) <
11925 SE.getTypeSizeInBits(NewBECount->getType()))
11926 CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
11928 const SCEV *Delta = SE2.getMinusSCEV(CurBECount, NewBECount);
11930 // Unless VerifySCEVStrict is set, we only compare constant deltas.
11931 if ((VerifySCEVStrict || isa<SCEVConstant>(Delta)) && !Delta->isZero()) {
11932 dbgs() << "Trip Count for " << *L << " Changed!\n";
11933 dbgs() << "Old: " << *CurBECount << "\n";
11934 dbgs() << "New: " << *NewBECount << "\n";
11935 dbgs() << "Delta: " << *Delta << "\n";
11936 std::abort();
11941 bool ScalarEvolution::invalidate(
11942 Function &F, const PreservedAnalyses &PA,
11943 FunctionAnalysisManager::Invalidator &Inv) {
11944 // Invalidate the ScalarEvolution object whenever it isn't preserved or one
11945 // of its dependencies is invalidated.
11946 auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
11947 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
11948 Inv.invalidate<AssumptionAnalysis>(F, PA) ||
11949 Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
11950 Inv.invalidate<LoopAnalysis>(F, PA);
11953 AnalysisKey ScalarEvolutionAnalysis::Key;
11955 ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
11956 FunctionAnalysisManager &AM) {
11957 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
11958 AM.getResult<AssumptionAnalysis>(F),
11959 AM.getResult<DominatorTreeAnalysis>(F),
11960 AM.getResult<LoopAnalysis>(F));
11963 PreservedAnalyses
11964 ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
11965 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
11966 return PreservedAnalyses::all();
11969 INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
11970 "Scalar Evolution Analysis", false, true)
11971 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11972 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
11973 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
11974 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
11975 INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
11976 "Scalar Evolution Analysis", false, true)
11978 char ScalarEvolutionWrapperPass::ID = 0;
11980 ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
11981 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
11984 bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
11985 SE.reset(new ScalarEvolution(
11986 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
11987 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
11988 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
11989 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
11990 return false;
11993 void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
11995 void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
11996 SE->print(OS);
11999 void ScalarEvolutionWrapperPass::verifyAnalysis() const {
12000 if (!VerifySCEV)
12001 return;
12003 SE->verify();
12006 void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
12007 AU.setPreservesAll();
12008 AU.addRequiredTransitive<AssumptionCacheTracker>();
12009 AU.addRequiredTransitive<LoopInfoWrapperPass>();
12010 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
12011 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
12014 const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
12015 const SCEV *RHS) {
12016 FoldingSetNodeID ID;
12017 assert(LHS->getType() == RHS->getType() &&
12018 "Type mismatch between LHS and RHS");
12019 // Unique this node based on the arguments
12020 ID.AddInteger(SCEVPredicate::P_Equal);
12021 ID.AddPointer(LHS);
12022 ID.AddPointer(RHS);
12023 void *IP = nullptr;
12024 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12025 return S;
12026 SCEVEqualPredicate *Eq = new (SCEVAllocator)
12027 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
12028 UniquePreds.InsertNode(Eq, IP);
12029 return Eq;
12032 const SCEVPredicate *ScalarEvolution::getWrapPredicate(
12033 const SCEVAddRecExpr *AR,
12034 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12035 FoldingSetNodeID ID;
12036 // Unique this node based on the arguments
12037 ID.AddInteger(SCEVPredicate::P_Wrap);
12038 ID.AddPointer(AR);
12039 ID.AddInteger(AddedFlags);
12040 void *IP = nullptr;
12041 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
12042 return S;
12043 auto *OF = new (SCEVAllocator)
12044 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
12045 UniquePreds.InsertNode(OF, IP);
12046 return OF;
12049 namespace {
12051 class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
12052 public:
12054 /// Rewrites \p S in the context of a loop L and the SCEV predication
12055 /// infrastructure.
12057 /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
12058 /// equivalences present in \p Pred.
12060 /// If \p NewPreds is non-null, rewrite is free to add further predicates to
12061 /// \p NewPreds such that the result will be an AddRecExpr.
12062 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
12063 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12064 SCEVUnionPredicate *Pred) {
12065 SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
12066 return Rewriter.visit(S);
12069 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
12070 if (Pred) {
12071 auto ExprPreds = Pred->getPredicatesForExpr(Expr);
12072 for (auto *Pred : ExprPreds)
12073 if (const auto *IPred = dyn_cast<SCEVEqualPredicate>(Pred))
12074 if (IPred->getLHS() == Expr)
12075 return IPred->getRHS();
12077 return convertToAddRecWithPreds(Expr);
12080 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
12081 const SCEV *Operand = visit(Expr->getOperand());
12082 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12083 if (AR && AR->getLoop() == L && AR->isAffine()) {
12084 // This couldn't be folded because the operand didn't have the nuw
12085 // flag. Add the nusw flag as an assumption that we could make.
12086 const SCEV *Step = AR->getStepRecurrence(SE);
12087 Type *Ty = Expr->getType();
12088 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
12089 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
12090 SE.getSignExtendExpr(Step, Ty), L,
12091 AR->getNoWrapFlags());
12093 return SE.getZeroExtendExpr(Operand, Expr->getType());
12096 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
12097 const SCEV *Operand = visit(Expr->getOperand());
12098 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
12099 if (AR && AR->getLoop() == L && AR->isAffine()) {
12100 // This couldn't be folded because the operand didn't have the nsw
12101 // flag. Add the nssw flag as an assumption that we could make.
12102 const SCEV *Step = AR->getStepRecurrence(SE);
12103 Type *Ty = Expr->getType();
12104 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
12105 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
12106 SE.getSignExtendExpr(Step, Ty), L,
12107 AR->getNoWrapFlags());
12109 return SE.getSignExtendExpr(Operand, Expr->getType());
12112 private:
12113 explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
12114 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
12115 SCEVUnionPredicate *Pred)
12116 : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
12118 bool addOverflowAssumption(const SCEVPredicate *P) {
12119 if (!NewPreds) {
12120 // Check if we've already made this assumption.
12121 return Pred && Pred->implies(P);
12123 NewPreds->insert(P);
12124 return true;
12127 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
12128 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
12129 auto *A = SE.getWrapPredicate(AR, AddedFlags);
12130 return addOverflowAssumption(A);
12133 // If \p Expr represents a PHINode, we try to see if it can be represented
12134 // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
12135 // to add this predicate as a runtime overflow check, we return the AddRec.
12136 // If \p Expr does not meet these conditions (is not a PHI node, or we
12137 // couldn't create an AddRec for it, or couldn't add the predicate), we just
12138 // return \p Expr.
12139 const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
12140 if (!isa<PHINode>(Expr->getValue()))
12141 return Expr;
12142 Optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
12143 PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
12144 if (!PredicatedRewrite)
12145 return Expr;
12146 for (auto *P : PredicatedRewrite->second){
12147 // Wrap predicates from outer loops are not supported.
12148 if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
12149 auto *AR = cast<const SCEVAddRecExpr>(WP->getExpr());
12150 if (L != AR->getLoop())
12151 return Expr;
12153 if (!addOverflowAssumption(P))
12154 return Expr;
12156 return PredicatedRewrite->first;
12159 SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
12160 SCEVUnionPredicate *Pred;
12161 const Loop *L;
12164 } // end anonymous namespace
12166 const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
12167 SCEVUnionPredicate &Preds) {
12168 return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
12171 const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
12172 const SCEV *S, const Loop *L,
12173 SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
12174 SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
12175 S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
12176 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
12178 if (!AddRec)
12179 return nullptr;
12181 // Since the transformation was successful, we can now transfer the SCEV
12182 // predicates.
12183 for (auto *P : TransformPreds)
12184 Preds.insert(P);
12186 return AddRec;
12189 /// SCEV predicates
12190 SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
12191 SCEVPredicateKind Kind)
12192 : FastID(ID), Kind(Kind) {}
12194 SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
12195 const SCEV *LHS, const SCEV *RHS)
12196 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {
12197 assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
12198 assert(LHS != RHS && "LHS and RHS are the same SCEV");
12201 bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
12202 const auto *Op = dyn_cast<SCEVEqualPredicate>(N);
12204 if (!Op)
12205 return false;
12207 return Op->LHS == LHS && Op->RHS == RHS;
12210 bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
12212 const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
12214 void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
12215 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
12218 SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
12219 const SCEVAddRecExpr *AR,
12220 IncrementWrapFlags Flags)
12221 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
12223 const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
12225 bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
12226 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
12228 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
12231 bool SCEVWrapPredicate::isAlwaysTrue() const {
12232 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
12233 IncrementWrapFlags IFlags = Flags;
12235 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
12236 IFlags = clearFlags(IFlags, IncrementNSSW);
12238 return IFlags == IncrementAnyWrap;
12241 void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
12242 OS.indent(Depth) << *getExpr() << " Added Flags: ";
12243 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
12244 OS << "<nusw>";
12245 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
12246 OS << "<nssw>";
12247 OS << "\n";
12250 SCEVWrapPredicate::IncrementWrapFlags
12251 SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
12252 ScalarEvolution &SE) {
12253 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
12254 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
12256 // We can safely transfer the NSW flag as NSSW.
12257 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
12258 ImpliedFlags = IncrementNSSW;
12260 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
12261 // If the increment is positive, the SCEV NUW flag will also imply the
12262 // WrapPredicate NUSW flag.
12263 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
12264 if (Step->getValue()->getValue().isNonNegative())
12265 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
12268 return ImpliedFlags;
12271 /// Union predicates don't get cached so create a dummy set ID for it.
12272 SCEVUnionPredicate::SCEVUnionPredicate()
12273 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
12275 bool SCEVUnionPredicate::isAlwaysTrue() const {
12276 return all_of(Preds,
12277 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
12280 ArrayRef<const SCEVPredicate *>
12281 SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
12282 auto I = SCEVToPreds.find(Expr);
12283 if (I == SCEVToPreds.end())
12284 return ArrayRef<const SCEVPredicate *>();
12285 return I->second;
12288 bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
12289 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
12290 return all_of(Set->Preds,
12291 [this](const SCEVPredicate *I) { return this->implies(I); });
12293 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
12294 if (ScevPredsIt == SCEVToPreds.end())
12295 return false;
12296 auto &SCEVPreds = ScevPredsIt->second;
12298 return any_of(SCEVPreds,
12299 [N](const SCEVPredicate *I) { return I->implies(N); });
12302 const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
12304 void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
12305 for (auto Pred : Preds)
12306 Pred->print(OS, Depth);
12309 void SCEVUnionPredicate::add(const SCEVPredicate *N) {
12310 if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
12311 for (auto Pred : Set->Preds)
12312 add(Pred);
12313 return;
12316 if (implies(N))
12317 return;
12319 const SCEV *Key = N->getExpr();
12320 assert(Key && "Only SCEVUnionPredicate doesn't have an "
12321 " associated expression!");
12323 SCEVToPreds[Key].push_back(N);
12324 Preds.push_back(N);
12327 PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
12328 Loop &L)
12329 : SE(SE), L(L) {}
12331 const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
12332 const SCEV *Expr = SE.getSCEV(V);
12333 RewriteEntry &Entry = RewriteMap[Expr];
12335 // If we already have an entry and the version matches, return it.
12336 if (Entry.second && Generation == Entry.first)
12337 return Entry.second;
12339 // We found an entry but it's stale. Rewrite the stale entry
12340 // according to the current predicate.
12341 if (Entry.second)
12342 Expr = Entry.second;
12344 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
12345 Entry = {Generation, NewSCEV};
12347 return NewSCEV;
12350 const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
12351 if (!BackedgeCount) {
12352 SCEVUnionPredicate BackedgePred;
12353 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
12354 addPredicate(BackedgePred);
12356 return BackedgeCount;
12359 void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
12360 if (Preds.implies(&Pred))
12361 return;
12362 Preds.add(&Pred);
12363 updateGeneration();
12366 const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
12367 return Preds;
12370 void PredicatedScalarEvolution::updateGeneration() {
12371 // If the generation number wrapped recompute everything.
12372 if (++Generation == 0) {
12373 for (auto &II : RewriteMap) {
12374 const SCEV *Rewritten = II.second.second;
12375 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
12380 void PredicatedScalarEvolution::setNoOverflow(
12381 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12382 const SCEV *Expr = getSCEV(V);
12383 const auto *AR = cast<SCEVAddRecExpr>(Expr);
12385 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
12387 // Clear the statically implied flags.
12388 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
12389 addPredicate(*SE.getWrapPredicate(AR, Flags));
12391 auto II = FlagsMap.insert({V, Flags});
12392 if (!II.second)
12393 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
12396 bool PredicatedScalarEvolution::hasNoOverflow(
12397 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
12398 const SCEV *Expr = getSCEV(V);
12399 const auto *AR = cast<SCEVAddRecExpr>(Expr);
12401 Flags = SCEVWrapPredicate::clearFlags(
12402 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
12404 auto II = FlagsMap.find(V);
12406 if (II != FlagsMap.end())
12407 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
12409 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
12412 const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
12413 const SCEV *Expr = this->getSCEV(V);
12414 SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
12415 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
12417 if (!New)
12418 return nullptr;
12420 for (auto *P : NewPreds)
12421 Preds.add(P);
12423 updateGeneration();
12424 RewriteMap[SE.getSCEV(V)] = {Generation, New};
12425 return New;
12428 PredicatedScalarEvolution::PredicatedScalarEvolution(
12429 const PredicatedScalarEvolution &Init)
12430 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
12431 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
12432 for (const auto &I : Init.FlagsMap)
12433 FlagsMap.insert(I);
12436 void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
12437 // For each block.
12438 for (auto *BB : L.getBlocks())
12439 for (auto &I : *BB) {
12440 if (!SE.isSCEVable(I.getType()))
12441 continue;
12443 auto *Expr = SE.getSCEV(&I);
12444 auto II = RewriteMap.find(Expr);
12446 if (II == RewriteMap.end())
12447 continue;
12449 // Don't print things that are not interesting.
12450 if (II->second.second == Expr)
12451 continue;
12453 OS.indent(Depth) << "[PSE]" << I << ":\n";
12454 OS.indent(Depth + 2) << *Expr << "\n";
12455 OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
12459 // Match the mathematical pattern A - (A / B) * B, where A and B can be
12460 // arbitrary expressions.
12461 // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
12462 // 4, A / B becomes X / 8).
12463 bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
12464 const SCEV *&RHS) {
12465 const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
12466 if (Add == nullptr || Add->getNumOperands() != 2)
12467 return false;
12469 const SCEV *A = Add->getOperand(1);
12470 const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
12472 if (Mul == nullptr)
12473 return false;
12475 const auto MatchURemWithDivisor = [&](const SCEV *B) {
12476 // (SomeExpr + (-(SomeExpr / B) * B)).
12477 if (Expr == getURemExpr(A, B)) {
12478 LHS = A;
12479 RHS = B;
12480 return true;
12482 return false;
12485 // (SomeExpr + (-1 * (SomeExpr / B) * B)).
12486 if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
12487 return MatchURemWithDivisor(Mul->getOperand(1)) ||
12488 MatchURemWithDivisor(Mul->getOperand(2));
12490 // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
12491 if (Mul->getNumOperands() == 2)
12492 return MatchURemWithDivisor(Mul->getOperand(1)) ||
12493 MatchURemWithDivisor(Mul->getOperand(0)) ||
12494 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
12495 MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
12496 return false;