LLVM 23.0.0git
ScalarEvolution.h
Go to the documentation of this file.
1//===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
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// The ScalarEvolution class is an LLVM pass which can be used to analyze and
10// categorize scalar expressions in loops. It specializes in recognizing
11// general induction variables, representing them with the abstract and opaque
12// SCEV class. Given this analysis, trip counts of loops and other important
13// properties can be obtained.
14//
15// This analysis is primarily useful for induction variable substitution and
16// strength reduction.
17//
18//===----------------------------------------------------------------------===//
19
20#ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
21#define LLVM_ANALYSIS_SCALAREVOLUTION_H
22
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/SetVector.h"
35#include "llvm/IR/PassManager.h"
36#include "llvm/IR/ValueHandle.h"
37#include "llvm/IR/ValueMap.h"
38#include "llvm/Pass.h"
40#include <cassert>
41#include <cstdint>
42#include <memory>
43#include <optional>
44#include <utility>
45
46namespace llvm {
47
49class AssumptionCache;
50class BasicBlock;
51class Constant;
52class ConstantInt;
53class DataLayout;
54class DominatorTree;
55class GEPOperator;
56class LLVMContext;
57class Loop;
58class LoopInfo;
59class raw_ostream;
60class ScalarEvolution;
61class SCEVAddRecExpr;
62class SCEVUnknown;
63class StructType;
65class Type;
66enum SCEVTypes : unsigned short;
67
68LLVM_ABI extern bool VerifySCEV;
69
70/// NoWrapFlags are bitfield indices into SCEV's SubclassData.
71///
72/// Add and Mul expressions may have no-unsigned-wrap <NUW> or
73/// no-signed-wrap <NSW> properties, which are derived from the IR
74/// operator. NSW is a misnomer that we use to mean no signed overflow or
75/// underflow.
76///
77/// AddRec expressions may have a no-self-wraparound <NW> property if, in
78/// the integer domain, abs(step) * max-iteration(loop) <=
79/// unsigned-max(bitwidth). This means that the recurrence will never reach
80/// its start value if the step is non-zero. Computing the same value on
81/// each iteration is not considered wrapping, and recurrences with step = 0
82/// are trivially <NW>. <NW> is independent of the sign of step and the
83/// value the add recurrence starts with.
84///
85/// Note that NUW and NSW are also valid properties of a recurrence, and
86/// either implies NW. For convenience, NW will be set for a recurrence
87/// whenever either NUW or NSW are set.
88///
89/// We require that the flag on a SCEV apply to the entire scope in which
90/// that SCEV is defined. A SCEV's scope is set of locations dominated by
91/// a defining location, which is in turn described by the following rules:
92/// * A SCEVUnknown is at the point of definition of the Value.
93/// * A SCEVConstant is defined at all points.
94/// * A SCEVAddRec is defined starting with the header of the associated
95/// loop.
96/// * All other SCEVs are defined at the earlest point all operands are
97/// defined.
98///
99/// The above rules describe a maximally hoisted form (without regards to
100/// potential control dependence). A SCEV is defined anywhere a
101/// corresponding instruction could be defined in said maximally hoisted
102/// form. Note that SCEVUDivExpr (currently the only expression type which
103/// can trap) can be defined per these rules in regions where it would trap
104/// at runtime. A SCEV being defined does not require the existence of any
105/// instruction within the defined scope.
106enum class SCEVNoWrapFlags {
107 FlagAnyWrap = 0, // No guarantee.
108 FlagNW = (1 << 0), // No self-wrap.
109 FlagNUW = (1 << 1), // No unsigned wrap.
110 FlagNSW = (1 << 2), // No signed wrap.
111 NoWrapMask = (1 << 3) - 1,
112 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/NoWrapMask)
113};
114
115class SCEV;
116
117template <typename SCEVPtrT = const SCEV *>
118struct SCEVUseT : private PointerIntPair<SCEVPtrT, 2> {
121 using Base::getPointer;
122
123 SCEVUseT() : Base(nullptr, 0) {}
124 SCEVUseT(SCEVPtrT S) : Base(S, 0) {}
125 /// Construct with NoWrapFlags; only NUW/NSW are encoded, NW is dropped.
126 SCEVUseT(SCEVPtrT S, SCEVNoWrapFlags Flags)
127 : Base(S, static_cast<unsigned>(Flags) >> 1) {}
128 template <typename OtherPtrT, typename = std::enable_if_t<
129 std::is_convertible_v<OtherPtrT, SCEVPtrT>>>
132
133 operator SCEVPtrT() const { return getPointer(); }
134 SCEVPtrT operator->() const { return getPointer(); }
135
136 /// Returns true if the SCEVUse is canonical, i.e. no SCEVUse flags set in any
137 /// operands.
138 bool isCanonical() const { return getCanonical() == getOpaqueValue(); }
139
140 /// Return the canonical SCEV for this SCEVUse.
141 const SCEV *getCanonical() const;
142
143 /// Return the no-wrap flags for this SCEVUse, which is the union of the
144 /// use-specific flags and the underlying SCEV's flags, masked by \p Mask.
147
148 /// Return only the use-specific no-wrap flags (NUW/NSW) without the
149 /// underlying SCEV's flags.
151 SCEVNoWrapFlags UseFlags =
152 static_cast<SCEVNoWrapFlags>(Base::getInt() << 1);
154 UseFlags |= SCEVNoWrapFlags::FlagNW;
155 return UseFlags;
156 }
157
158 bool operator==(const SCEVUseT &RHS) const {
159 return getOpaqueValue() == RHS.getOpaqueValue();
160 }
161
162 bool operator!=(const SCEVUseT &RHS) const { return !(*this == RHS); }
163
164 bool operator>(const SCEVUseT &RHS) const { return Base::operator>(RHS); }
165
166 bool operator==(const SCEV *RHS) const { return getOpaqueValue() == RHS; }
167 bool operator!=(const SCEV *RHS) const { return getOpaqueValue() != RHS; }
168
169 /// Print out the internal representation of this scalar to the specified
170 /// stream. This should really only be used for debugging purposes.
171 void print(raw_ostream &OS) const;
172
173 /// This method is used for debugging.
174 void dump() const;
175
176private:
178 friend struct PointerLikeTypeTraits<SCEVUseT>;
179};
180
181/// Deduction guide for various SCEV subclass pointers.
182template <typename SCEVPtrT> SCEVUseT(SCEVPtrT) -> SCEVUseT<SCEVPtrT>;
183
185
186/// Provide PointerLikeTypeTraits for SCEVUse, so it can be used with
187/// SmallPtrSet, among others.
188template <> struct PointerLikeTypeTraits<SCEVUse> {
189 static inline void *getAsVoidPointer(SCEVUse U) { return U.getOpaqueValue(); }
190 static inline SCEVUse getFromVoidPointer(void *P) {
191 SCEVUse U;
192 U.setFromOpaqueValue(P);
193 return U;
194 }
195
196 /// The Low bits are used by the PointerIntPair.
197 static constexpr int NumLowBitsAvailable = 0;
198};
199
200template <> struct DenseMapInfo<SCEVUse> {
201 static inline SCEVUse getEmptyKey() {
202 uintptr_t Val = static_cast<uintptr_t>(-1);
204 }
205
206 static inline SCEVUse getTombstoneKey() {
207 uintptr_t Val = static_cast<uintptr_t>(-2);
209 }
210
211 static unsigned getHashValue(SCEVUse U) {
212 return hash_value(U.getOpaqueValue());
213 }
214
215 static bool isEqual(const SCEVUse LHS, const SCEVUse RHS) {
216 return LHS.getOpaqueValue() == RHS.getOpaqueValue();
217 }
218};
219
220template <> struct simplify_type<SCEVUse> {
221 using SimpleType = const SCEV *;
222
224 return Val.getPointer();
225 }
226};
227
228/// Provide CastInfo for SCEVUseT so that cast<SCEVUseT<const To *>>(use)
229/// returns SCEVUseT<const To *> with flags preserved.
230template <typename ToSCEVPtrT>
231struct CastInfo<SCEVUseT<ToSCEVPtrT>, SCEVUse,
232 std::enable_if_t<!is_simple_type<SCEVUse>::value>> {
233 using To = std::remove_cv_t<std::remove_pointer_t<ToSCEVPtrT>>;
235
236 static bool isPossible(const SCEVUse &U) { return isa<To>(U.getPointer()); }
237 static CastReturnType doCast(const SCEVUse &U) {
238 return CastReturnType(cast<To>(U.getPointer()), U.getUseNoWrapFlags());
239 }
240 static CastReturnType castFailed() { return CastReturnType(nullptr); }
242 if (!isPossible(U))
243 return castFailed();
244 return doCast(U);
245 }
246};
247
248template <typename ToSCEVPtrT>
249struct CastInfo<SCEVUseT<ToSCEVPtrT>, const SCEVUse,
250 std::enable_if_t<!is_simple_type<const SCEVUse>::value>>
251 : CastInfo<SCEVUseT<ToSCEVPtrT>, SCEVUse> {};
252
253/// This class represents an analyzed expression in the program. These are
254/// opaque objects that the client is not allowed to do much with directly.
255///
256class SCEV : public FoldingSetNode {
257 friend struct FoldingSetTrait<SCEV>;
258
259 /// A reference to an Interned FoldingSetNodeID for this node. The
260 /// ScalarEvolution's BumpPtrAllocator holds the data.
261 FoldingSetNodeIDRef FastID;
262
263 // The SCEV baseclass this node corresponds to
264 const SCEVTypes SCEVType;
265
266protected:
267 // Estimated complexity of this node's expression tree size.
268 const unsigned short ExpressionSize;
269
270 /// This field is initialized to zero and may be used in subclasses to store
271 /// miscellaneous information.
272 unsigned short SubclassData = 0;
273
274 /// Pointer to the canonical version of the SCEV, i.e. one where all operands
275 /// have no SCEVUse flags.
276 const SCEV *CanonicalSCEV = nullptr;
277
278public:
281 static constexpr auto FlagNW = SCEVNoWrapFlags::FlagNW;
282 static constexpr auto FlagNUW = SCEVNoWrapFlags::FlagNUW;
283 static constexpr auto FlagNSW = SCEVNoWrapFlags::FlagNSW;
285
286 explicit SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
287 unsigned short ExpressionSize)
288 : FastID(ID), SCEVType(SCEVTy), ExpressionSize(ExpressionSize) {}
289 SCEV(const SCEV &) = delete;
290 SCEV &operator=(const SCEV &) = delete;
291
292 SCEVTypes getSCEVType() const { return SCEVType; }
293
294 /// Return the LLVM type of this SCEV expression.
295 LLVM_ABI Type *getType() const;
296
297 /// Return operands of this SCEV expression.
299
300 /// Return true if the expression is a constant zero.
301 LLVM_ABI bool isZero() const;
302
303 /// Return true if the expression is a constant one.
304 LLVM_ABI bool isOne() const;
305
306 /// Return true if the expression is a constant all-ones value.
307 LLVM_ABI bool isAllOnesValue() const;
308
309 /// Return true if the specified scev is negated, but not a constant.
310 LLVM_ABI bool isNonConstantNegative() const;
311
312 // Returns estimated size of the mathematical expression represented by this
313 // SCEV. The rules of its calculation are following:
314 // 1) Size of a SCEV without operands (like constants and SCEVUnknown) is 1;
315 // 2) Size SCEV with operands Op1, Op2, ..., OpN is calculated by formula:
316 // (1 + Size(Op1) + ... + Size(OpN)).
317 // This value gives us an estimation of time we need to traverse through this
318 // SCEV and all its operands recursively. We may use it to avoid performing
319 // heavy transformations on SCEVs of excessive size for sake of saving the
320 // compilation time.
321 unsigned short getExpressionSize() const {
322 return ExpressionSize;
323 }
324
325 /// Print out the internal representation of this scalar to the specified
326 /// stream. This should really only be used for debugging purposes.
327 LLVM_ABI void print(raw_ostream &OS) const;
328
329 /// This method is used for debugging.
330 LLVM_ABI void dump() const;
331
332 /// Compute and set the canonical SCEV, by constructing a SCEV with the same
333 /// operands, but all SCEVUse flags dropped.
335
336 /// Return the canonical SCEV.
337 LLVM_ABI const SCEV *getCanonical() const {
338 assert(CanonicalSCEV && "canonical SCEV not yet computed");
339 return CanonicalSCEV;
340 }
341};
342
343// Specialize FoldingSetTrait for SCEV to avoid needing to compute
344// temporary FoldingSetNodeID values.
345template <> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
346 static void Profile(const SCEV &X, FoldingSetNodeID &ID) { ID = X.FastID; }
347
348 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, unsigned IDHash,
349 FoldingSetNodeID &TempID) {
350 return ID == X.FastID;
351 }
352
353 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
354 return X.FastID.ComputeHash();
355 }
356};
357
358inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
359 S.print(OS);
360 return OS;
361}
362
364 U.print(OS);
365 return OS;
366}
367
368/// An object of this class is returned by queries that could not be answered.
369/// For example, if you ask for the number of iterations of a linked-list
370/// traversal loop, you will get one of these. None of the standard SCEV
371/// operations are valid on this class, it is just a marker.
372struct SCEVCouldNotCompute : public SCEV {
374
375 /// Methods for support type inquiry through isa, cast, and dyn_cast:
376 LLVM_ABI static bool classof(const SCEV *S);
377};
378
379/// This class represents an assumption made using SCEV expressions which can
380/// be checked at run-time.
382 friend struct FoldingSetTrait<SCEVPredicate>;
383
384 /// A reference to an Interned FoldingSetNodeID for this node. The
385 /// ScalarEvolution's BumpPtrAllocator holds the data.
386 FoldingSetNodeIDRef FastID;
387
388public:
390
391protected:
393 ~SCEVPredicate() = default;
394 SCEVPredicate(const SCEVPredicate &) = default;
396
397public:
399
400 SCEVPredicateKind getKind() const { return Kind; }
401
402 /// Returns the estimated complexity of this predicate. This is roughly
403 /// measured in the number of run-time checks required.
404 virtual unsigned getComplexity() const { return 1; }
405
406 /// Returns true if the predicate is always true. This means that no
407 /// assumptions were made and nothing needs to be checked at run-time.
408 virtual bool isAlwaysTrue() const = 0;
409
410 /// Returns true if this predicate implies \p N.
411 virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const = 0;
412
413 /// Prints a textual representation of this predicate with an indentation of
414 /// \p Depth.
415 virtual void print(raw_ostream &OS, unsigned Depth = 0) const = 0;
416};
417
419 P.print(OS);
420 return OS;
421}
422
423// Specialize FoldingSetTrait for SCEVPredicate to avoid needing to compute
424// temporary FoldingSetNodeID values.
425template <>
427 static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID) {
428 ID = X.FastID;
429 }
430
431 static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID,
432 unsigned IDHash, FoldingSetNodeID &TempID) {
433 return ID == X.FastID;
434 }
435
436 static unsigned ComputeHash(const SCEVPredicate &X,
437 FoldingSetNodeID &TempID) {
438 return X.FastID.ComputeHash();
439 }
440};
441
442/// This class represents an assumption that the expression LHS Pred RHS
443/// evaluates to true, and this can be checked at run-time.
445 /// We assume that LHS Pred RHS is true.
446 const ICmpInst::Predicate Pred;
447 const SCEV *LHS;
448 const SCEV *RHS;
449
450public:
452 const ICmpInst::Predicate Pred,
453 const SCEV *LHS, const SCEV *RHS);
454
455 /// Implementation of the SCEVPredicate interface
456 bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override;
457 void print(raw_ostream &OS, unsigned Depth = 0) const override;
458 bool isAlwaysTrue() const override;
459
460 ICmpInst::Predicate getPredicate() const { return Pred; }
461
462 /// Returns the left hand side of the predicate.
463 const SCEV *getLHS() const { return LHS; }
464
465 /// Returns the right hand side of the predicate.
466 const SCEV *getRHS() const { return RHS; }
467
468 /// Methods for support type inquiry through isa, cast, and dyn_cast:
469 static bool classof(const SCEVPredicate *P) {
470 return P->getKind() == P_Compare;
471 }
472};
473
474/// This class represents an assumption made on an AddRec expression. Given an
475/// affine AddRec expression {a,+,b}, we assume that it has the nssw or nusw
476/// flags (defined below) in the first X iterations of the loop, where X is a
477/// SCEV expression returned by getPredicatedBackedgeTakenCount).
478///
479/// Note that this does not imply that X is equal to the backedge taken
480/// count. This means that if we have a nusw predicate for i32 {0,+,1} with a
481/// predicated backedge taken count of X, we only guarantee that {0,+,1} has
482/// nusw in the first X iterations. {0,+,1} may still wrap in the loop if we
483/// have more than X iterations.
485public:
486 /// Similar to SCEV::NoWrapFlags, but with slightly different semantics
487 /// for FlagNUSW. The increment is considered to be signed, and a + b
488 /// (where b is the increment) is considered to wrap if:
489 /// zext(a + b) != zext(a) + sext(b)
490 ///
491 /// If Signed is a function that takes an n-bit tuple and maps to the
492 /// integer domain as the tuples value interpreted as twos complement,
493 /// and Unsigned a function that takes an n-bit tuple and maps to the
494 /// integer domain as the base two value of input tuple, then a + b
495 /// has IncrementNUSW iff:
496 ///
497 /// 0 <= Unsigned(a) + Signed(b) < 2^n
498 ///
499 /// The IncrementNSSW flag has identical semantics with SCEV::FlagNSW.
500 ///
501 /// Note that the IncrementNUSW flag is not commutative: if base + inc
502 /// has IncrementNUSW, then inc + base doesn't neccessarily have this
503 /// property. The reason for this is that this is used for sign/zero
504 /// extending affine AddRec SCEV expressions when a SCEVWrapPredicate is
505 /// assumed. A {base,+,inc} expression is already non-commutative with
506 /// regards to base and inc, since it is interpreted as:
507 /// (((base + inc) + inc) + inc) ...
509 IncrementAnyWrap = 0, // No guarantee.
510 IncrementNUSW = (1 << 0), // No unsigned with signed increment wrap.
511 IncrementNSSW = (1 << 1), // No signed with signed increment wrap
512 // (equivalent with SCEV::NSW)
513 IncrementNoWrapMask = (1 << 2) - 1
514 };
515
516 /// Convenient IncrementWrapFlags manipulation methods.
517 [[nodiscard]] static SCEVWrapPredicate::IncrementWrapFlags
520 assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
521 assert((OffFlags & IncrementNoWrapMask) == OffFlags &&
522 "Invalid flags value!");
523 return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & ~OffFlags);
524 }
525
526 [[nodiscard]] static SCEVWrapPredicate::IncrementWrapFlags
528 assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
529 assert((Mask & IncrementNoWrapMask) == Mask && "Invalid mask value!");
530
531 return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & Mask);
532 }
533
534 [[nodiscard]] static SCEVWrapPredicate::IncrementWrapFlags
537 assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
538 assert((OnFlags & IncrementNoWrapMask) == OnFlags &&
539 "Invalid flags value!");
540
541 return (SCEVWrapPredicate::IncrementWrapFlags)(Flags | OnFlags);
542 }
543
544 /// Returns the set of SCEVWrapPredicate no wrap flags implied by a
545 /// SCEVAddRecExpr.
546 [[nodiscard]] static SCEVWrapPredicate::IncrementWrapFlags
547 getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE);
548
549private:
550 const SCEVAddRecExpr *AR;
551 IncrementWrapFlags Flags;
552
553public:
555 const SCEVAddRecExpr *AR,
556 IncrementWrapFlags Flags);
557
558 /// Returns the set assumed no overflow flags.
559 IncrementWrapFlags getFlags() const { return Flags; }
560
561 /// Implementation of the SCEVPredicate interface
562 const SCEVAddRecExpr *getExpr() const;
563 bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override;
564 void print(raw_ostream &OS, unsigned Depth = 0) const override;
565 bool isAlwaysTrue() const override;
566
567 /// Methods for support type inquiry through isa, cast, and dyn_cast:
568 static bool classof(const SCEVPredicate *P) {
569 return P->getKind() == P_Wrap;
570 }
571};
572
573/// This class represents a composition of other SCEV predicates, and is the
574/// class that most clients will interact with. This is equivalent to a
575/// logical "AND" of all the predicates in the union.
576///
577/// NB! Unlike other SCEVPredicate sub-classes this class does not live in the
578/// ScalarEvolution::Preds folding set. This is why the \c add function is sound.
580private:
581 using PredicateMap =
583
584 /// Vector with references to all predicates in this union.
586
587 /// Adds a predicate to this union.
588 void add(const SCEVPredicate *N, ScalarEvolution &SE);
589
590public:
592 ScalarEvolution &SE);
593
595
596 /// Returns a new SCEVUnionPredicate that is the union of this predicate
597 /// and the given predicate \p N.
599 ScalarEvolution &SE) const {
600 SCEVUnionPredicate Result(Preds, SE);
601 Result.add(N, SE);
602 return Result;
603 }
604
605 /// Implementation of the SCEVPredicate interface
606 bool isAlwaysTrue() const override;
607 bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override;
608 void print(raw_ostream &OS, unsigned Depth) const override;
609
610 /// We estimate the complexity of a union predicate as the size number of
611 /// predicates in the union.
612 unsigned getComplexity() const override { return Preds.size(); }
613
614 /// Methods for support type inquiry through isa, cast, and dyn_cast:
615 static bool classof(const SCEVPredicate *P) {
616 return P->getKind() == P_Union;
617 }
618};
619
620/// The main scalar evolution driver. Because client code (intentionally)
621/// can't do much with the SCEV objects directly, they must ask this class
622/// for services.
625
626public:
627 /// An enum describing the relationship between a SCEV and a loop.
629 LoopVariant, ///< The SCEV is loop-variant (unknown).
630 LoopInvariant, ///< The SCEV is loop-invariant.
631 LoopComputable ///< The SCEV varies predictably with the loop.
632 };
633
634 /// An enum describing the relationship between a SCEV and a basic block.
636 DoesNotDominateBlock, ///< The SCEV does not dominate the block.
637 DominatesBlock, ///< The SCEV dominates the block.
638 ProperlyDominatesBlock ///< The SCEV properly dominates the block.
639 };
640
641 /// Convenient NoWrapFlags manipulation. TODO: Replace with & operator of
642 /// enum class.
644 SCEV::NoWrapFlags Mask) {
645 return Flags & Mask;
646 }
647 [[nodiscard]] static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
648 SCEV::NoWrapFlags OnFlags) {
649 return Flags | OnFlags;
650 }
651 [[nodiscard]] static SCEV::NoWrapFlags
653 return Flags & ~OffFlags;
654 }
655 [[nodiscard]] static bool hasFlags(SCEV::NoWrapFlags Flags,
656 SCEV::NoWrapFlags TestFlags) {
657 return TestFlags == maskFlags(Flags, TestFlags);
658 };
659
662 LoopInfo &LI);
665
666 LLVMContext &getContext() const { return F.getContext(); }
667
668 /// Test if values of the given type are analyzable within the SCEV
669 /// framework. This primarily includes integer types, and it can optionally
670 /// include pointer types if the ScalarEvolution class has access to
671 /// target-specific information.
672 LLVM_ABI bool isSCEVable(Type *Ty) const;
673
674 /// Return the size in bits of the specified type, for which isSCEVable must
675 /// return true.
677
678 /// Return a type with the same bitwidth as the given type and which
679 /// represents how SCEV will treat the given type, for which isSCEVable must
680 /// return true. For pointer types, this is the pointer-sized integer type.
682
683 // Returns a wider type among {Ty1, Ty2}.
684 LLVM_ABI Type *getWiderType(Type *Ty1, Type *Ty2) const;
685
686 /// Return true if there exists a point in the program at which both
687 /// A and B could be operands to the same instruction.
688 /// SCEV expressions are generally assumed to correspond to instructions
689 /// which could exists in IR. In general, this requires that there exists
690 /// a use point in the program where all operands dominate the use.
691 ///
692 /// Example:
693 /// loop {
694 /// if
695 /// loop { v1 = load @global1; }
696 /// else
697 /// loop { v2 = load @global2; }
698 /// }
699 /// No SCEV with operand V1, and v2 can exist in this program.
701
702 /// Return true if the SCEV is a scAddRecExpr or it contains
703 /// scAddRecExpr. The result will be cached in HasRecMap.
704 LLVM_ABI bool containsAddRecurrence(const SCEV *S);
705
706 /// Is operation \p BinOp between \p LHS and \p RHS provably does not have
707 /// a signed/unsigned overflow (\p Signed)? If \p CtxI is specified, the
708 /// no-overflow fact should be true in the context of this instruction.
710 const SCEV *LHS, const SCEV *RHS,
711 const Instruction *CtxI = nullptr);
712
713 /// Parse NSW/NUW flags from add/sub/mul IR binary operation \p Op into
714 /// SCEV no-wrap flags, and deduce flag[s] that aren't known yet.
715 /// Does not mutate the original instruction. Returns std::nullopt if it could
716 /// not deduce more precise flags than the instruction already has, otherwise
717 /// returns proven flags.
718 LLVM_ABI std::optional<SCEV::NoWrapFlags>
720
721 /// Notify this ScalarEvolution that \p User directly uses SCEVs in \p Ops.
724
725 /// Return true if the SCEV expression contains an undef value.
726 LLVM_ABI bool containsUndefs(const SCEV *S) const;
727
728 /// Return true if the SCEV expression contains a Value that has been
729 /// optimised out and is now a nullptr.
730 LLVM_ABI bool containsErasedValue(const SCEV *S) const;
731
732 /// Return a SCEV expression for the full generality of the specified
733 /// expression.
734 LLVM_ABI const SCEV *getSCEV(Value *V);
735
736 /// Return an existing SCEV for V if there is one, otherwise return nullptr.
738
740 LLVM_ABI const SCEV *getConstant(const APInt &Val);
741 LLVM_ABI const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
743
744 LLVM_ABI const SCEV *getPtrToAddrExpr(const SCEV *Op);
745 LLVM_ABI const SCEV *getPtrToIntExpr(const SCEV *Op, Type *Ty);
746 LLVM_ABI const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty,
747 unsigned Depth = 0);
748 LLVM_ABI const SCEV *getVScale(Type *Ty);
749 LLVM_ABI const SCEV *
752 LLVM_ABI const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty,
753 unsigned Depth = 0);
754 LLVM_ABI const SCEV *getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
755 unsigned Depth = 0);
756 LLVM_ABI const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty,
757 unsigned Depth = 0);
758 LLVM_ABI const SCEV *getSignExtendExprImpl(const SCEV *Op, Type *Ty,
759 unsigned Depth = 0);
760 LLVM_ABI const SCEV *getCastExpr(SCEVTypes Kind, const SCEV *Op, Type *Ty);
761 LLVM_ABI const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
762
765 unsigned Depth = 0);
768 unsigned Depth = 0) {
770 return getAddExpr(Ops, Flags, Depth);
771 }
772 const SCEV *getAddExpr(SCEVUse Op0, SCEVUse Op1, SCEVUse Op2,
774 unsigned Depth = 0) {
775 SmallVector<SCEVUse, 3> Ops = {Op0, Op1, Op2};
776 return getAddExpr(Ops, Flags, Depth);
777 }
780 unsigned Depth = 0);
783 unsigned Depth = 0) {
785 return getMulExpr(Ops, Flags, Depth);
786 }
787 const SCEV *getMulExpr(SCEVUse Op0, SCEVUse Op1, SCEVUse Op2,
789 unsigned Depth = 0) {
790 SmallVector<SCEVUse, 3> Ops = {Op0, Op1, Op2};
791 return getMulExpr(Ops, Flags, Depth);
792 }
796 LLVM_ABI const SCEV *getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L,
797 SCEV::NoWrapFlags Flags);
799 const Loop *L, SCEV::NoWrapFlags Flags);
801 const Loop *L, SCEV::NoWrapFlags Flags) {
802 SmallVector<SCEVUse, 4> NewOp(Operands.begin(), Operands.end());
803 return getAddRecExpr(NewOp, L, Flags);
804 }
805
806 /// Checks if \p SymbolicPHI can be rewritten as an AddRecExpr under some
807 /// Predicates. If successful return these <AddRecExpr, Predicates>;
808 /// The function is intended to be called from PSCEV (the caller will decide
809 /// whether to actually add the predicates and carry out the rewrites).
810 LLVM_ABI std::optional<
811 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
812 createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI);
813
814 /// Returns an expression for a GEP
815 ///
816 /// \p GEP The GEP. The indices contained in the GEP itself are ignored,
817 /// instead we use IndexExprs.
818 /// \p IndexExprs The expressions for the indices.
820 ArrayRef<SCEVUse> IndexExprs);
821 LLVM_ABI const SCEV *getGEPExpr(SCEVUse BaseExpr,
822 ArrayRef<SCEVUse> IndexExprs,
823 Type *SrcElementTy,
825 LLVM_ABI const SCEV *getAbsExpr(const SCEV *Op, bool IsNSW);
827 SmallVectorImpl<SCEVUse> &Operands);
828 LLVM_ABI const SCEV *
837 bool Sequential = false);
839 bool Sequential = false);
840 LLVM_ABI const SCEV *getUnknown(Value *V);
842
843 /// Return a SCEV for the constant 0 of a specific type.
844 const SCEV *getZero(Type *Ty) { return getConstant(Ty, 0); }
845
846 /// Return a SCEV for the constant 1 of a specific type.
847 const SCEV *getOne(Type *Ty) { return getConstant(Ty, 1); }
848
849 /// Return a SCEV for the constant \p Power of two.
850 const SCEV *getPowerOfTwo(Type *Ty, unsigned Power) {
851 assert(Power < getTypeSizeInBits(Ty) && "Power out of range");
853 }
854
855 /// Return a SCEV for the constant -1 of a specific type.
856 const SCEV *getMinusOne(Type *Ty) {
857 return getConstant(Ty, -1, /*isSigned=*/true);
858 }
859
860 /// Return an expression for a TypeSize.
862
863 /// Return an expression for the alloc size of AllocTy that is type IntTy
864 LLVM_ABI const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
865
866 /// Return an expression for the store size of StoreTy that is type IntTy
867 LLVM_ABI const SCEV *getStoreSizeOfExpr(Type *IntTy, Type *StoreTy);
868
869 /// Return an expression for offsetof on the given field with type IntTy
870 LLVM_ABI const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy,
871 unsigned FieldNo);
872
873 /// Return the SCEV object corresponding to -V.
874 LLVM_ABI const SCEV *
876
877 /// Return the SCEV object corresponding to ~V.
878 LLVM_ABI const SCEV *getNotSCEV(const SCEV *V);
879
880 /// Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
881 ///
882 /// If the LHS and RHS are pointers which don't share a common base
883 /// (according to getPointerBase()), this returns a SCEVCouldNotCompute.
884 /// To compute the difference between two unrelated pointers, you can
885 /// explicitly convert the arguments using getPtrToIntExpr(), for pointer
886 /// types that support it.
889 unsigned Depth = 0);
890
891 /// Compute ceil(N / D). N and D are treated as unsigned values.
892 ///
893 /// Since SCEV doesn't have native ceiling division, this generates a
894 /// SCEV expression of the following form:
895 ///
896 /// umin(N, 1) + floor((N - umin(N, 1)) / D)
897 ///
898 /// A denominator of zero or poison is handled the same way as getUDivExpr().
899 LLVM_ABI const SCEV *getUDivCeilSCEV(const SCEV *N, const SCEV *D);
900
901 /// Return a SCEV corresponding to a conversion of the input value to the
902 /// specified type. If the type must be extended, it is zero extended.
903 LLVM_ABI const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
904 unsigned Depth = 0);
905
906 /// Return a SCEV corresponding to a conversion of the input value to the
907 /// specified type. If the type must be extended, it is sign extended.
908 LLVM_ABI const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty,
909 unsigned Depth = 0);
910
911 /// Return a SCEV corresponding to a conversion of the input value to the
912 /// specified type. If the type must be extended, it is zero extended. The
913 /// conversion must not be narrowing.
914 LLVM_ABI const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
915
916 /// Return a SCEV corresponding to a conversion of the input value to the
917 /// specified type. If the type must be extended, it is sign extended. The
918 /// conversion must not be narrowing.
919 LLVM_ABI const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
920
921 /// Return a SCEV corresponding to a conversion of the input value to the
922 /// specified type. If the type must be extended, it is extended with
923 /// unspecified bits. The conversion must not be narrowing.
924 LLVM_ABI const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
925
926 /// Return a SCEV corresponding to a conversion of the input value to the
927 /// specified type. The conversion must not be widening.
928 LLVM_ABI const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
929
930 /// Promote the operands to the wider of the types using zero-extension, and
931 /// then perform a umax operation with them.
933 const SCEV *RHS);
934
935 /// Promote the operands to the wider of the types using zero-extension, and
936 /// then perform a umin operation with them.
938 const SCEV *RHS,
939 bool Sequential = false);
940
941 /// Promote the operands to the wider of the types using zero-extension, and
942 /// then perform a umin operation with them. N-ary function.
944 bool Sequential = false);
945
946 /// Transitively follow the chain of pointer-type operands until reaching a
947 /// SCEV that does not have a single pointer operand. This returns a
948 /// SCEVUnknown pointer for well-formed pointer-type expressions, but corner
949 /// cases do exist.
950 LLVM_ABI const SCEV *getPointerBase(const SCEV *V);
951
952 /// Compute an expression equivalent to S - getPointerBase(S).
953 LLVM_ABI const SCEV *removePointerBase(const SCEV *S);
954
955 /// Return a SCEV expression for the specified value at the specified scope
956 /// in the program. The L value specifies a loop nest to evaluate the
957 /// expression at, where null is the top-level or a specified loop is
958 /// immediately inside of the loop.
959 ///
960 /// This method can be used to compute the exit value for a variable defined
961 /// in a loop by querying what the value will hold in the parent loop.
962 ///
963 /// In the case that a relevant loop exit value cannot be computed, the
964 /// original value V is returned.
965 LLVM_ABI const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
966
967 /// This is a convenience function which does getSCEVAtScope(getSCEV(V), L).
968 LLVM_ABI const SCEV *getSCEVAtScope(Value *V, const Loop *L);
969
970 /// Test whether entry to the loop is protected by a conditional between LHS
971 /// and RHS. This is used to help avoid max expressions in loop trip
972 /// counts, and to eliminate casts.
974 const SCEV *LHS, const SCEV *RHS);
975
976 /// Test whether entry to the basic block is protected by a conditional
977 /// between LHS and RHS.
979 CmpPredicate Pred,
980 const SCEV *LHS,
981 const SCEV *RHS);
982
983 /// Test whether the backedge of the loop is protected by a conditional
984 /// between LHS and RHS. This is used to eliminate casts.
986 const SCEV *LHS, const SCEV *RHS);
987
988 /// A version of getTripCountFromExitCount below which always picks an
989 /// evaluation type which can not result in overflow.
990 LLVM_ABI const SCEV *getTripCountFromExitCount(const SCEV *ExitCount);
991
992 /// Convert from an "exit count" (i.e. "backedge taken count") to a "trip
993 /// count". A "trip count" is the number of times the header of the loop
994 /// will execute if an exit is taken after the specified number of backedges
995 /// have been taken. (e.g. TripCount = ExitCount + 1). Note that the
996 /// expression can overflow if ExitCount = UINT_MAX. If EvalTy is not wide
997 /// enough to hold the result without overflow, result unsigned wraps with
998 /// 2s-complement semantics. ex: EC = 255 (i8), TC = 0 (i8)
999 LLVM_ABI const SCEV *getTripCountFromExitCount(const SCEV *ExitCount,
1000 Type *EvalTy, const Loop *L);
1001
1002 /// Returns the exact trip count of the loop if we can compute it, and
1003 /// the result is a small constant. '0' is used to represent an unknown
1004 /// or non-constant trip count. Note that a trip count is simply one more
1005 /// than the backedge taken count for the loop.
1006 LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L);
1007
1008 /// Return the exact trip count for this loop if we exit through ExitingBlock.
1009 /// '0' is used to represent an unknown or non-constant trip count. Note
1010 /// that a trip count is simply one more than the backedge taken count for
1011 /// the same exit.
1012 /// This "trip count" assumes that control exits via ExitingBlock. More
1013 /// precisely, it is the number of times that control will reach ExitingBlock
1014 /// before taking the branch. For loops with multiple exits, it may not be
1015 /// the number times that the loop header executes if the loop exits
1016 /// prematurely via another branch.
1017 LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L,
1018 const BasicBlock *ExitingBlock);
1019
1020 /// Returns the upper bound of the loop trip count as a normal unsigned
1021 /// value.
1022 /// Returns 0 if the trip count is unknown, not constant or requires
1023 /// SCEV predicates and \p Predicates is nullptr.
1025 const Loop *L,
1026 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr);
1027
1028 /// Returns the largest constant divisor of the trip count as a normal
1029 /// unsigned value, if possible. This means that the actual trip count is
1030 /// always a multiple of the returned value. Returns 1 if the trip count is
1031 /// unknown or not guaranteed to be the multiple of a constant., Will also
1032 /// return 1 if the trip count is very large (>= 2^32).
1033 /// Note that the argument is an exit count for loop L, NOT a trip count.
1034 LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L,
1035 const SCEV *ExitCount);
1036
1037 /// Returns the largest constant divisor of the trip count of the
1038 /// loop. Will return 1 if no trip count could be computed, or if a
1039 /// divisor could not be found.
1040 LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L);
1041
1042 /// Returns the largest constant divisor of the trip count of this loop as a
1043 /// normal unsigned value, if possible. This means that the actual trip
1044 /// count is always a multiple of the returned value (don't forget the trip
1045 /// count could very well be zero as well!). As explained in the comments
1046 /// for getSmallConstantTripCount, this assumes that control exits the loop
1047 /// via ExitingBlock.
1048 LLVM_ABI unsigned
1049 getSmallConstantTripMultiple(const Loop *L, const BasicBlock *ExitingBlock);
1050
1051 /// The terms "backedge taken count" and "exit count" are used
1052 /// interchangeably to refer to the number of times the backedge of a loop
1053 /// has executed before the loop is exited.
1055 /// An expression exactly describing the number of times the backedge has
1056 /// executed when a loop is exited.
1058 /// A constant which provides an upper bound on the exact trip count.
1060 /// An expression which provides an upper bound on the exact trip count.
1062 };
1063
1064 /// Return the number of times the backedge executes before the given exit
1065 /// would be taken; if not exactly computable, return SCEVCouldNotCompute.
1066 /// For a single exit loop, this value is equivelent to the result of
1067 /// getBackedgeTakenCount. The loop is guaranteed to exit (via *some* exit)
1068 /// before the backedge is executed (ExitCount + 1) times. Note that there
1069 /// is no guarantee about *which* exit is taken on the exiting iteration.
1070 LLVM_ABI const SCEV *getExitCount(const Loop *L,
1071 const BasicBlock *ExitingBlock,
1072 ExitCountKind Kind = Exact);
1073
1074 /// Same as above except this uses the predicated backedge taken info and
1075 /// may require predicates.
1076 LLVM_ABI const SCEV *
1077 getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock,
1079 ExitCountKind Kind = Exact);
1080
1081 /// If the specified loop has a predictable backedge-taken count, return it,
1082 /// otherwise return a SCEVCouldNotCompute object. The backedge-taken count is
1083 /// the number of times the loop header will be branched to from within the
1084 /// loop, assuming there are no abnormal exists like exception throws. This is
1085 /// one less than the trip count of the loop, since it doesn't count the first
1086 /// iteration, when the header is branched to from outside the loop.
1087 ///
1088 /// Note that it is not valid to call this method on a loop without a
1089 /// loop-invariant backedge-taken count (see
1090 /// hasLoopInvariantBackedgeTakenCount).
1091 LLVM_ABI const SCEV *getBackedgeTakenCount(const Loop *L,
1092 ExitCountKind Kind = Exact);
1093
1094 /// Similar to getBackedgeTakenCount, except it will add a set of
1095 /// SCEV predicates to Predicates that are required to be true in order for
1096 /// the answer to be correct. Predicates can be checked with run-time
1097 /// checks and can be used to perform loop versioning.
1099 const Loop *L, SmallVectorImpl<const SCEVPredicate *> &Predicates);
1100
1101 /// When successful, this returns a SCEVConstant that is greater than or equal
1102 /// to (i.e. a "conservative over-approximation") of the value returend by
1103 /// getBackedgeTakenCount. If such a value cannot be computed, it returns the
1104 /// SCEVCouldNotCompute object.
1108
1109 /// Similar to getConstantMaxBackedgeTakenCount, except it will add a set of
1110 /// SCEV predicates to Predicates that are required to be true in order for
1111 /// the answer to be correct. Predicates can be checked with run-time
1112 /// checks and can be used to perform loop versioning.
1114 const Loop *L, SmallVectorImpl<const SCEVPredicate *> &Predicates);
1115
1116 /// When successful, this returns a SCEV that is greater than or equal
1117 /// to (i.e. a "conservative over-approximation") of the value returend by
1118 /// getBackedgeTakenCount. If such a value cannot be computed, it returns the
1119 /// SCEVCouldNotCompute object.
1123
1124 /// Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of
1125 /// SCEV predicates to Predicates that are required to be true in order for
1126 /// the answer to be correct. Predicates can be checked with run-time
1127 /// checks and can be used to perform loop versioning.
1129 const Loop *L, SmallVectorImpl<const SCEVPredicate *> &Predicates);
1130
1131 /// Return true if the backedge taken count is either the value returned by
1132 /// getConstantMaxBackedgeTakenCount or zero.
1134
1135 /// Return true if the specified loop has an analyzable loop-invariant
1136 /// backedge-taken count.
1138
1139 // This method should be called by the client when it made any change that
1140 // would invalidate SCEV's answers, and the client wants to remove all loop
1141 // information held internally by ScalarEvolution. This is intended to be used
1142 // when the alternative to forget a loop is too expensive (i.e. large loop
1143 // bodies).
1144 LLVM_ABI void forgetAllLoops();
1145
1146 /// This method should be called by the client when it has changed a loop in
1147 /// a way that may effect ScalarEvolution's ability to compute a trip count,
1148 /// or if the loop is deleted. This call is potentially expensive for large
1149 /// loop bodies.
1150 LLVM_ABI void forgetLoop(const Loop *L);
1151
1152 // This method invokes forgetLoop for the outermost loop of the given loop
1153 // \p L, making ScalarEvolution forget about all this subtree. This needs to
1154 // be done whenever we make a transform that may affect the parameters of the
1155 // outer loop, such as exit counts for branches.
1156 LLVM_ABI void forgetTopmostLoop(const Loop *L);
1157
1158 /// This method should be called by the client when it has changed a value
1159 /// in a way that may effect its value, or which may disconnect it from a
1160 /// def-use chain linking it to a loop.
1161 LLVM_ABI void forgetValue(Value *V);
1162
1163 /// Forget LCSSA phi node V of loop L to which a new predecessor was added,
1164 /// such that it may no longer be trivial.
1166
1167 /// Called when the client has changed the disposition of values in
1168 /// this loop.
1169 ///
1170 /// We don't have a way to invalidate per-loop dispositions. Clear and
1171 /// recompute is simpler.
1173
1174 /// Called when the client has changed the disposition of values in
1175 /// a loop or block.
1176 ///
1177 /// We don't have a way to invalidate per-loop/per-block dispositions. Clear
1178 /// and recompute is simpler.
1180
1181 /// Determine the minimum number of zero bits that S is guaranteed to end in
1182 /// (at every loop iteration). It is, at the same time, the minimum number
1183 /// of times S is divisible by 2. For example, given {4,+,8} it returns 2.
1184 /// If S is guaranteed to be 0, it returns the bitwidth of S.
1185 /// If \p CtxI is not nullptr, return a constant multiple valid at \p CtxI.
1187 const Instruction *CtxI = nullptr);
1188
1189 /// Returns the max constant multiple of S. If \p CtxI is not nullptr, return
1190 /// a constant multiple valid at \p CtxI.
1192 const Instruction *CtxI = nullptr);
1193
1194 // Returns the max constant multiple of S. If S is exactly 0, return 1.
1196
1197 /// Determine the unsigned range for a particular SCEV.
1198 /// NOTE: This returns a copy of the reference returned by getRangeRef.
1200 return getRangeRef(S, HINT_RANGE_UNSIGNED);
1201 }
1202
1203 /// Determine the min of the unsigned range for a particular SCEV.
1205 return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMin();
1206 }
1207
1208 /// Determine the max of the unsigned range for a particular SCEV.
1210 return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMax();
1211 }
1212
1213 /// Determine the signed range for a particular SCEV.
1214 /// NOTE: This returns a copy of the reference returned by getRangeRef.
1216 return getRangeRef(S, HINT_RANGE_SIGNED);
1217 }
1218
1219 /// Determine the min of the signed range for a particular SCEV.
1221 return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMin();
1222 }
1223
1224 /// Determine the max of the signed range for a particular SCEV.
1226 return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMax();
1227 }
1228
1229 /// Test if the given expression is known to be negative.
1230 LLVM_ABI bool isKnownNegative(const SCEV *S);
1231
1232 /// Test if the given expression is known to be positive.
1233 LLVM_ABI bool isKnownPositive(const SCEV *S);
1234
1235 /// Test if the given expression is known to be non-negative.
1236 LLVM_ABI bool isKnownNonNegative(const SCEV *S);
1237
1238 /// Test if the given expression is known to be non-positive.
1239 LLVM_ABI bool isKnownNonPositive(const SCEV *S);
1240
1241 /// Test if the given expression is known to be non-zero.
1242 LLVM_ABI bool isKnownNonZero(const SCEV *S);
1243
1244 /// Test if the given expression is known to be a power of 2. OrNegative
1245 /// allows matching negative power of 2s, and OrZero allows matching 0.
1246 LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero = false,
1247 bool OrNegative = false);
1248
1249 /// Check that \p S is a multiple of \p M. When \p S is an AddRecExpr, \p S is
1250 /// a multiple of \p M if \p S starts with a multiple of \p M and at every
1251 /// iteration step \p S only adds multiples of \p M. \p Assumptions records
1252 /// the runtime predicates under which \p S is a multiple of \p M.
1253 LLVM_ABI bool
1254 isKnownMultipleOf(const SCEV *S, uint64_t M,
1256
1257 /// Return true if we know that S1 and S2 must have the same sign.
1258 LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2);
1259
1260 /// Splits SCEV expression \p S into two SCEVs. One of them is obtained from
1261 /// \p S by substitution of all AddRec sub-expression related to loop \p L
1262 /// with initial value of that SCEV. The second is obtained from \p S by
1263 /// substitution of all AddRec sub-expressions related to loop \p L with post
1264 /// increment of this AddRec in the loop \p L. In both cases all other AddRec
1265 /// sub-expressions (not related to \p L) remain the same.
1266 /// If the \p S contains non-invariant unknown SCEV the function returns
1267 /// CouldNotCompute SCEV in both values of std::pair.
1268 /// For example, for SCEV S={0, +, 1}<L1> + {0, +, 1}<L2> and loop L=L1
1269 /// the function returns pair:
1270 /// first = {0, +, 1}<L2>
1271 /// second = {1, +, 1}<L1> + {0, +, 1}<L2>
1272 /// We can see that for the first AddRec sub-expression it was replaced with
1273 /// 0 (initial value) for the first element and to {1, +, 1}<L1> (post
1274 /// increment value) for the second one. In both cases AddRec expression
1275 /// related to L2 remains the same.
1276 LLVM_ABI std::pair<const SCEV *, const SCEV *>
1277 SplitIntoInitAndPostInc(const Loop *L, const SCEV *S);
1278
1279 /// We'd like to check the predicate on every iteration of the most dominated
1280 /// loop between loops used in LHS and RHS.
1281 /// To do this we use the following list of steps:
1282 /// 1. Collect set S all loops on which either LHS or RHS depend.
1283 /// 2. If S is non-empty
1284 /// a. Let PD be the element of S which is dominated by all other elements.
1285 /// b. Let E(LHS) be value of LHS on entry of PD.
1286 /// To get E(LHS), we should just take LHS and replace all AddRecs that are
1287 /// attached to PD on with their entry values.
1288 /// Define E(RHS) in the same way.
1289 /// c. Let B(LHS) be value of L on backedge of PD.
1290 /// To get B(LHS), we should just take LHS and replace all AddRecs that are
1291 /// attached to PD on with their backedge values.
1292 /// Define B(RHS) in the same way.
1293 /// d. Note that E(LHS) and E(RHS) are automatically available on entry of PD,
1294 /// so we can assert on that.
1295 /// e. Return true if isLoopEntryGuardedByCond(Pred, E(LHS), E(RHS)) &&
1296 /// isLoopBackedgeGuardedByCond(Pred, B(LHS), B(RHS))
1298 SCEVUse RHS);
1299
1300 /// Test if the given expression is known to satisfy the condition described
1301 /// by Pred, LHS, and RHS.
1303
1304 /// Check whether the condition described by Pred, LHS, and RHS is true or
1305 /// false. If we know it, return the evaluation of this condition. If neither
1306 /// is proved, return std::nullopt.
1307 LLVM_ABI std::optional<bool>
1308 evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS);
1309
1310 /// Test if the given expression is known to satisfy the condition described
1311 /// by Pred, LHS, and RHS in the given Context.
1313 const SCEV *RHS, const Instruction *CtxI);
1314
1315 /// Check whether the condition described by Pred, LHS, and RHS is true or
1316 /// false in the given \p Context. If we know it, return the evaluation of
1317 /// this condition. If neither is proved, return std::nullopt.
1318 LLVM_ABI std::optional<bool> evaluatePredicateAt(CmpPredicate Pred,
1319 const SCEV *LHS,
1320 const SCEV *RHS,
1321 const Instruction *CtxI);
1322
1323 /// Test if the condition described by Pred, LHS, RHS is known to be true on
1324 /// every iteration of the loop of the recurrency LHS.
1326 const SCEVAddRecExpr *LHS,
1327 const SCEV *RHS);
1328
1329 /// Information about the number of loop iterations for which a loop exit's
1330 /// branch condition evaluates to the not-taken path. This is a temporary
1331 /// pair of exact and max expressions that are eventually summarized in
1332 /// ExitNotTakenInfo and BackedgeTakenInfo.
1333 struct ExitLimit {
1334 const SCEV *ExactNotTaken; // The exit is not taken exactly this many times
1335 const SCEV *ConstantMaxNotTaken; // The exit is not taken at most this many
1336 // times
1338
1339 // Not taken either exactly ConstantMaxNotTaken or zero times
1340 bool MaxOrZero = false;
1341
1342 /// A vector of predicate guards for this ExitLimit. The result is only
1343 /// valid if all of the predicates in \c Predicates evaluate to 'true' at
1344 /// run-time.
1346
1347 /// Construct either an exact exit limit from a constant, or an unknown
1348 /// one from a SCEVCouldNotCompute. No other types of SCEVs are allowed
1349 /// as arguments and asserts enforce that internally.
1350 /*implicit*/ LLVM_ABI ExitLimit(const SCEV *E);
1351 /*implicit*/ ExitLimit(SCEVUse E) : ExitLimit((const SCEV *)E) {}
1352
1353 LLVM_ABI
1354 ExitLimit(const SCEV *E, const SCEV *ConstantMaxNotTaken,
1355 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
1357
1359 const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
1361
1362 /// Test whether this ExitLimit contains any computed information, or
1363 /// whether it's all SCEVCouldNotCompute values.
1368
1369 /// Test whether this ExitLimit contains all information.
1370 bool hasFullInfo() const {
1372 }
1373 };
1374
1375 /// Compute the number of times the backedge of the specified loop will
1376 /// execute if its exit condition were a conditional branch of ExitCond.
1377 ///
1378 /// \p ControlsOnlyExit is true if ExitCond directly controls the only exit
1379 /// branch. In this case, we can assume that the loop exits only if the
1380 /// condition is true and can infer that failing to meet the condition prior
1381 /// to integer wraparound results in undefined behavior.
1382 ///
1383 /// If \p AllowPredicates is set, this call will try to use a minimal set of
1384 /// SCEV predicates in order to return an exact answer.
1385 LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond,
1386 bool ExitIfTrue,
1387 bool ControlsOnlyExit,
1388 bool AllowPredicates = false);
1389
1390 /// A predicate is said to be monotonically increasing if may go from being
1391 /// false to being true as the loop iterates, but never the other way
1392 /// around. A predicate is said to be monotonically decreasing if may go
1393 /// from being true to being false as the loop iterates, but never the other
1394 /// way around.
1399
1400 /// If, for all loop invariant X, the predicate "LHS `Pred` X" is
1401 /// monotonically increasing or decreasing, returns
1402 /// Some(MonotonicallyIncreasing) and Some(MonotonicallyDecreasing)
1403 /// respectively. If we could not prove either of these facts, returns
1404 /// std::nullopt.
1405 LLVM_ABI std::optional<MonotonicPredicateType>
1407 ICmpInst::Predicate Pred);
1408
1417 /// If the result of the predicate LHS `Pred` RHS is loop invariant with
1418 /// respect to L, return a LoopInvariantPredicate with LHS and RHS being
1419 /// invariants, available at L's entry. Otherwise, return std::nullopt.
1420 LLVM_ABI std::optional<LoopInvariantPredicate>
1422 const Loop *L, const Instruction *CtxI = nullptr);
1423
1424 /// If the result of the predicate LHS `Pred` RHS is loop invariant with
1425 /// respect to L at given Context during at least first MaxIter iterations,
1426 /// return a LoopInvariantPredicate with LHS and RHS being invariants,
1427 /// available at L's entry. Otherwise, return std::nullopt. The predicate
1428 /// should be the loop's exit condition.
1429 LLVM_ABI std::optional<LoopInvariantPredicate>
1431 const SCEV *LHS,
1432 const SCEV *RHS, const Loop *L,
1433 const Instruction *CtxI,
1434 const SCEV *MaxIter);
1435
1436 LLVM_ABI std::optional<LoopInvariantPredicate>
1438 CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
1439 const Instruction *CtxI, const SCEV *MaxIter);
1440
1441 /// Simplify LHS and RHS in a comparison with predicate Pred. Return true
1442 /// iff any changes were made. If the operands are provably equal or
1443 /// unequal, LHS and RHS are set to the same value and Pred is set to either
1444 /// ICMP_EQ or ICMP_NE.
1446 SCEVUse &RHS, unsigned Depth = 0);
1447
1448 /// Return the "disposition" of the given SCEV with respect to the given
1449 /// loop.
1451
1452 /// Return true if the value of the given SCEV is unchanging in the
1453 /// specified loop.
1454 LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L);
1455
1456 /// Determine if the SCEV can be evaluated at loop's entry. It is true if it
1457 /// doesn't depend on a SCEVUnknown of an instruction which is dominated by
1458 /// the header of loop L.
1459 LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L);
1460
1461 /// Return true if the given SCEV changes value in a known way in the
1462 /// specified loop. This property being true implies that the value is
1463 /// variant in the loop AND that we can emit an expression to compute the
1464 /// value of the expression at any particular loop iteration.
1465 LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
1466
1467 /// Return the "disposition" of the given SCEV with respect to the given
1468 /// block.
1470 const BasicBlock *BB);
1471
1472 /// Return true if elements that makes up the given SCEV dominate the
1473 /// specified basic block.
1474 LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB);
1475
1476 /// Return true if elements that makes up the given SCEV properly dominate
1477 /// the specified basic block.
1478 LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB);
1479
1480 /// Test whether the given SCEV has Op as a direct or indirect operand.
1481 LLVM_ABI bool hasOperand(const SCEV *S, const SCEV *Op) const;
1482
1483 /// Return the size of an element read or written by Inst.
1485
1486 LLVM_ABI void print(raw_ostream &OS) const;
1487 LLVM_ABI void verify() const;
1489 FunctionAnalysisManager::Invalidator &Inv);
1490
1491 /// Return the DataLayout associated with the module this SCEV instance is
1492 /// operating on.
1493 const DataLayout &getDataLayout() const { return DL; }
1494
1496 const SCEV *RHS);
1498 const SCEV *LHS,
1499 const SCEV *RHS);
1500
1501 LLVM_ABI const SCEVPredicate *
1504
1505 /// Re-writes the SCEV according to the Predicates in \p A.
1506 LLVM_ABI const SCEV *rewriteUsingPredicate(const SCEV *S, const Loop *L,
1507 const SCEVPredicate &A);
1508 /// Tries to convert the \p S expression to an AddRec expression,
1509 /// adding additional predicates to \p Preds as required.
1511 const SCEV *S, const Loop *L,
1513
1514 /// Compute \p LHS - \p RHS and returns the result as an APInt if it is a
1515 /// constant, and std::nullopt if it isn't.
1516 ///
1517 /// This is intended to be a cheaper version of getMinusSCEV. We can be
1518 /// frugal here since we just bail out of actually constructing and
1519 /// canonicalizing an expression in the cases where the result isn't going
1520 /// to be a constant.
1521 LLVM_ABI std::optional<APInt> computeConstantDifference(const SCEV *LHS,
1522 const SCEV *RHS);
1523
1524 /// Update no-wrap flags of an AddRec. This may drop the cached info about
1525 /// this AddRec (such as range info) in case if new flags may potentially
1526 /// sharpen it.
1528
1529 class LoopGuards {
1532 bool PreserveNUW = false;
1533 bool PreserveNSW = false;
1534 ScalarEvolution &SE;
1535
1536 LoopGuards(ScalarEvolution &SE) : SE(SE) {}
1537
1538 /// Recursively collect loop guards in \p Guards, starting from
1539 /// block \p Block with predecessor \p Pred. The intended starting point
1540 /// is to collect from a loop header and its predecessor.
1541 static void
1542 collectFromBlock(ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards,
1543 const BasicBlock *Block, const BasicBlock *Pred,
1545 unsigned Depth = 0);
1546
1547 /// Collect loop guards in \p Guards, starting from PHINode \p
1548 /// Phi, by calling \p collectFromBlock on the incoming blocks of
1549 /// \Phi and trying to merge the found constraints into a single
1550 /// combined one for \p Phi.
1551 static void collectFromPHI(
1555 unsigned Depth);
1556
1557 public:
1558 /// Collect rewrite map for loop guards for loop \p L, together with flags
1559 /// indicating if NUW and NSW can be preserved during rewriting.
1560 LLVM_ABI static LoopGuards collect(const Loop *L, ScalarEvolution &SE);
1561
1562 /// Try to apply the collected loop guards to \p Expr.
1563 LLVM_ABI const SCEV *rewrite(const SCEV *Expr) const;
1564 };
1565
1566 /// Try to apply information from loop guards for \p L to \p Expr.
1567 LLVM_ABI const SCEV *applyLoopGuards(const SCEV *Expr, const Loop *L);
1568 LLVM_ABI const SCEV *applyLoopGuards(const SCEV *Expr,
1569 const LoopGuards &Guards);
1570
1571 /// Return true if the loop has no abnormal exits. That is, if the loop
1572 /// is not infinite, it must exit through an explicit edge in the CFG.
1573 /// (As opposed to either a) throwing out of the function or b) entering a
1574 /// well defined infinite loop in some callee.)
1576 return getLoopProperties(L).HasNoAbnormalExits;
1577 }
1578
1579 /// Return true if this loop is finite by assumption. That is,
1580 /// to be infinite, it must also be undefined.
1581 LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L);
1582
1583 /// Return the set of Values that, if poison, will definitively result in S
1584 /// being poison as well. The returned set may be incomplete, i.e. there can
1585 /// be additional Values that also result in S being poison.
1586 LLVM_ABI void
1588 const SCEV *S);
1589
1590 /// Check whether it is poison-safe to represent the expression S using the
1591 /// instruction I. If such a replacement is performed, the poison flags of
1592 /// instructions in DropPoisonGeneratingInsts must be dropped.
1594 const SCEV *S, Instruction *I,
1595 SmallVectorImpl<Instruction *> &DropPoisonGeneratingInsts);
1596
1597 class FoldID {
1598 const SCEV *Op = nullptr;
1599 const Type *Ty = nullptr;
1600 unsigned short C;
1601
1602 public:
1603 FoldID(SCEVTypes C, const SCEV *Op, const Type *Ty) : Op(Op), Ty(Ty), C(C) {
1604 assert(Op);
1605 assert(Ty);
1606 }
1607
1608 FoldID(unsigned short C) : C(C) {}
1609
1610 unsigned computeHash() const {
1612 C, detail::combineHashValue(reinterpret_cast<uintptr_t>(Op),
1613 reinterpret_cast<uintptr_t>(Ty)));
1614 }
1615
1616 bool operator==(const FoldID &RHS) const {
1617 return std::tie(Op, Ty, C) == std::tie(RHS.Op, RHS.Ty, RHS.C);
1618 }
1619 };
1620
1621private:
1622 /// A CallbackVH to arrange for ScalarEvolution to be notified whenever a
1623 /// Value is deleted.
1624 class LLVM_ABI SCEVCallbackVH final : public CallbackVH {
1625 ScalarEvolution *SE;
1626
1627 void deleted() override;
1628 void allUsesReplacedWith(Value *New) override;
1629
1630 public:
1631 SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
1632 };
1633
1634 friend class SCEVCallbackVH;
1635 friend class SCEVExpander;
1636 friend class SCEVUnknown;
1637
1638 /// The function we are analyzing.
1639 Function &F;
1640
1641 /// Data layout of the module.
1642 const DataLayout &DL;
1643
1644 /// Does the module have any calls to the llvm.experimental.guard intrinsic
1645 /// at all? If this is false, we avoid doing work that will only help if
1646 /// thare are guards present in the IR.
1647 bool HasGuards;
1648
1649 /// The target library information for the target we are targeting.
1650 TargetLibraryInfo &TLI;
1651
1652 /// The tracker for \@llvm.assume intrinsics in this function.
1653 AssumptionCache &AC;
1654
1655 /// The dominator tree.
1656 DominatorTree &DT;
1657
1658 /// The loop information for the function we are currently analyzing.
1659 LoopInfo &LI;
1660
1661 /// This SCEV is used to represent unknown trip counts and things.
1662 std::unique_ptr<SCEVCouldNotCompute> CouldNotCompute;
1663
1664 /// The type for HasRecMap.
1665 using HasRecMapType = DenseMap<const SCEV *, bool>;
1666
1667 /// This is a cache to record whether a SCEV contains any scAddRecExpr.
1668 HasRecMapType HasRecMap;
1669
1670 /// The type for ExprValueMap.
1671 using ValueSetVector = SmallSetVector<Value *, 4>;
1672 using ExprValueMapType = DenseMap<const SCEV *, ValueSetVector>;
1673
1674 /// ExprValueMap -- This map records the original values from which
1675 /// the SCEV expr is generated from.
1676 ExprValueMapType ExprValueMap;
1677
1678 /// The type for ValueExprMap.
1679 using ValueExprMapType =
1681
1682 /// This is a cache of the values we have analyzed so far.
1683 ValueExprMapType ValueExprMap;
1684
1685 /// This is a cache for expressions that got folded to a different existing
1686 /// SCEV.
1689
1690 /// Mark predicate values currently being processed by isImpliedCond.
1691 SmallPtrSet<const Value *, 6> PendingLoopPredicates;
1692
1693 // Mark SCEVUnknown Phis currently being processed by isImpliedViaMerge.
1694 SmallPtrSet<const PHINode *, 6> PendingMerges;
1695
1696 /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of
1697 /// conditions dominating the backedge of a loop.
1698 bool WalkingBEDominatingConds = false;
1699
1700 /// Set to true by isKnownPredicateViaSplitting when we're trying to prove a
1701 /// predicate by splitting it into a set of independent predicates.
1702 bool ProvingSplitPredicate = false;
1703
1704 /// Memoized values for the getConstantMultiple
1705 DenseMap<const SCEV *, APInt> ConstantMultipleCache;
1706
1707 /// Return the Value set from which the SCEV expr is generated.
1708 ArrayRef<Value *> getSCEVValues(const SCEV *S);
1709
1710 /// Private helper method for the getConstantMultiple method. If \p CtxI is
1711 /// not nullptr, return a constant multiple valid at \p CtxI.
1712 APInt getConstantMultipleImpl(const SCEV *S,
1713 const Instruction *Ctx = nullptr);
1714
1715 /// Information about the number of times a particular loop exit may be
1716 /// reached before exiting the loop.
1717 struct ExitNotTakenInfo {
1718 PoisoningVH<BasicBlock> ExitingBlock;
1719 const SCEV *ExactNotTaken;
1720 const SCEV *ConstantMaxNotTaken;
1721 const SCEV *SymbolicMaxNotTaken;
1723
1724 explicit ExitNotTakenInfo(PoisoningVH<BasicBlock> ExitingBlock,
1725 const SCEV *ExactNotTaken,
1726 const SCEV *ConstantMaxNotTaken,
1727 const SCEV *SymbolicMaxNotTaken,
1729 : ExitingBlock(ExitingBlock), ExactNotTaken(ExactNotTaken),
1730 ConstantMaxNotTaken(ConstantMaxNotTaken),
1731 SymbolicMaxNotTaken(SymbolicMaxNotTaken), Predicates(Predicates) {}
1732
1733 bool hasAlwaysTruePredicate() const {
1734 return Predicates.empty();
1735 }
1736 };
1737
1738 /// Information about the backedge-taken count of a loop. This currently
1739 /// includes an exact count and a maximum count.
1740 ///
1741 class BackedgeTakenInfo {
1742 friend class ScalarEvolution;
1743
1744 /// A list of computable exits and their not-taken counts. Loops almost
1745 /// never have more than one computable exit.
1746 SmallVector<ExitNotTakenInfo, 1> ExitNotTaken;
1747
1748 /// Expression indicating the least constant maximum backedge-taken count of
1749 /// the loop that is known, or a SCEVCouldNotCompute. This expression is
1750 /// only valid if the predicates associated with all loop exits are true.
1751 const SCEV *ConstantMax = nullptr;
1752
1753 /// Indicating if \c ExitNotTaken has an element for every exiting block in
1754 /// the loop.
1755 bool IsComplete = false;
1756
1757 /// Expression indicating the least maximum backedge-taken count of the loop
1758 /// that is known, or a SCEVCouldNotCompute. Lazily computed on first query.
1759 const SCEV *SymbolicMax = nullptr;
1760
1761 /// True iff the backedge is taken either exactly Max or zero times.
1762 bool MaxOrZero = false;
1763
1764 bool isComplete() const { return IsComplete; }
1765 const SCEV *getConstantMax() const { return ConstantMax; }
1766
1767 LLVM_ABI const ExitNotTakenInfo *getExitNotTaken(
1768 const BasicBlock *ExitingBlock,
1769 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const;
1770
1771 public:
1772 BackedgeTakenInfo() = default;
1773 BackedgeTakenInfo(BackedgeTakenInfo &&) = default;
1774 BackedgeTakenInfo &operator=(BackedgeTakenInfo &&) = default;
1775
1776 using EdgeExitInfo = std::pair<BasicBlock *, ExitLimit>;
1777
1778 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
1779 LLVM_ABI BackedgeTakenInfo(ArrayRef<EdgeExitInfo> ExitCounts,
1780 bool IsComplete, const SCEV *ConstantMax,
1781 bool MaxOrZero);
1782
1783 /// Test whether this BackedgeTakenInfo contains any computed information,
1784 /// or whether it's all SCEVCouldNotCompute values.
1785 bool hasAnyInfo() const {
1786 return !ExitNotTaken.empty() ||
1787 !isa<SCEVCouldNotCompute>(getConstantMax());
1788 }
1789
1790 /// Test whether this BackedgeTakenInfo contains complete information.
1791 bool hasFullInfo() const { return isComplete(); }
1792
1793 /// Return an expression indicating the exact *backedge-taken*
1794 /// count of the loop if it is known or SCEVCouldNotCompute
1795 /// otherwise. If execution makes it to the backedge on every
1796 /// iteration (i.e. there are no abnormal exists like exception
1797 /// throws and thread exits) then this is the number of times the
1798 /// loop header will execute minus one.
1799 ///
1800 /// If the SCEV predicate associated with the answer can be different
1801 /// from AlwaysTrue, we must add a (non null) Predicates argument.
1802 /// The SCEV predicate associated with the answer will be added to
1803 /// Predicates. A run-time check needs to be emitted for the SCEV
1804 /// predicate in order for the answer to be valid.
1805 ///
1806 /// Note that we should always know if we need to pass a predicate
1807 /// argument or not from the way the ExitCounts vector was computed.
1808 /// If we allowed SCEV predicates to be generated when populating this
1809 /// vector, this information can contain them and therefore a
1810 /// SCEVPredicate argument should be added to getExact.
1811 LLVM_ABI const SCEV *getExact(
1812 const Loop *L, ScalarEvolution *SE,
1813 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const;
1814
1815 /// Return the number of times this loop exit may fall through to the back
1816 /// edge, or SCEVCouldNotCompute. The loop is guaranteed not to exit via
1817 /// this block before this number of iterations, but may exit via another
1818 /// block. If \p Predicates is null the function returns CouldNotCompute if
1819 /// predicates are required, otherwise it fills in the required predicates.
1820 const SCEV *getExact(
1821 const BasicBlock *ExitingBlock, ScalarEvolution *SE,
1822 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const {
1823 if (auto *ENT = getExitNotTaken(ExitingBlock, Predicates))
1824 return ENT->ExactNotTaken;
1825 else
1826 return SE->getCouldNotCompute();
1827 }
1828
1829 /// Get the constant max backedge taken count for the loop.
1830 LLVM_ABI const SCEV *getConstantMax(
1831 ScalarEvolution *SE,
1832 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const;
1833
1834 /// Get the constant max backedge taken count for the particular loop exit.
1835 const SCEV *getConstantMax(
1836 const BasicBlock *ExitingBlock, ScalarEvolution *SE,
1837 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const {
1838 if (auto *ENT = getExitNotTaken(ExitingBlock, Predicates))
1839 return ENT->ConstantMaxNotTaken;
1840 else
1841 return SE->getCouldNotCompute();
1842 }
1843
1844 /// Get the symbolic max backedge taken count for the loop.
1845 LLVM_ABI const SCEV *getSymbolicMax(
1846 const Loop *L, ScalarEvolution *SE,
1847 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr);
1848
1849 /// Get the symbolic max backedge taken count for the particular loop exit.
1850 const SCEV *getSymbolicMax(
1851 const BasicBlock *ExitingBlock, ScalarEvolution *SE,
1852 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr) const {
1853 if (auto *ENT = getExitNotTaken(ExitingBlock, Predicates))
1854 return ENT->SymbolicMaxNotTaken;
1855 else
1856 return SE->getCouldNotCompute();
1857 }
1858
1859 /// Return true if the number of times this backedge is taken is either the
1860 /// value returned by getConstantMax or zero.
1861 LLVM_ABI bool isConstantMaxOrZero(ScalarEvolution *SE) const;
1862 };
1863
1864 /// Cache the backedge-taken count of the loops for this function as they
1865 /// are computed.
1866 DenseMap<const Loop *, BackedgeTakenInfo> BackedgeTakenCounts;
1867
1868 /// Cache the predicated backedge-taken count of the loops for this
1869 /// function as they are computed.
1870 DenseMap<const Loop *, BackedgeTakenInfo> PredicatedBackedgeTakenCounts;
1871
1872 /// Loops whose backedge taken counts directly use this non-constant SCEV.
1873 DenseMap<const SCEV *, SmallPtrSet<PointerIntPair<const Loop *, 1, bool>, 4>>
1874 BECountUsers;
1875
1876 /// This map contains entries for all of the PHI instructions that we
1877 /// attempt to compute constant evolutions for. This allows us to avoid
1878 /// potentially expensive recomputation of these properties. An instruction
1879 /// maps to null if we are unable to compute its exit value.
1880 DenseMap<PHINode *, Constant *> ConstantEvolutionLoopExitValue;
1881
1882 /// This map contains entries for all the expressions that we attempt to
1883 /// compute getSCEVAtScope information for, which can be expensive in
1884 /// extreme cases.
1885 DenseMap<const SCEV *, SmallVector<std::pair<const Loop *, const SCEV *>, 2>>
1886 ValuesAtScopes;
1887
1888 /// Reverse map for invalidation purposes: Stores of which SCEV and which
1889 /// loop this is the value-at-scope of.
1890 DenseMap<const SCEV *, SmallVector<std::pair<const Loop *, const SCEV *>, 2>>
1891 ValuesAtScopesUsers;
1892
1893 /// Memoized computeLoopDisposition results.
1894 DenseMap<const SCEV *,
1896 LoopDispositions;
1897
1898 struct LoopProperties {
1899 /// Set to true if the loop contains no instruction that can abnormally exit
1900 /// the loop (i.e. via throwing an exception, by terminating the thread
1901 /// cleanly or by infinite looping in a called function). Strictly
1902 /// speaking, the last one is not leaving the loop, but is identical to
1903 /// leaving the loop for reasoning about undefined behavior.
1904 bool HasNoAbnormalExits;
1905
1906 /// Set to true if the loop contains no instruction that can have side
1907 /// effects (i.e. via throwing an exception, volatile or atomic access).
1908 bool HasNoSideEffects;
1909 };
1910
1911 /// Cache for \c getLoopProperties.
1912 DenseMap<const Loop *, LoopProperties> LoopPropertiesCache;
1913
1914 /// Return a \c LoopProperties instance for \p L, creating one if necessary.
1915 LLVM_ABI LoopProperties getLoopProperties(const Loop *L);
1916
1917 bool loopHasNoSideEffects(const Loop *L) {
1918 return getLoopProperties(L).HasNoSideEffects;
1919 }
1920
1921 /// Compute a LoopDisposition value.
1922 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
1923
1924 /// Memoized computeBlockDisposition results.
1925 DenseMap<
1926 const SCEV *,
1928 BlockDispositions;
1929
1930 /// Compute a BlockDisposition value.
1931 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
1932
1933 /// Stores all SCEV that use a given SCEV as its direct operand.
1934 DenseMap<const SCEV *, SmallPtrSet<const SCEV *, 8> > SCEVUsers;
1935
1936 /// Memoized results from getRange
1937 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
1938
1939 /// Memoized results from getRange
1940 DenseMap<const SCEV *, ConstantRange> SignedRanges;
1941
1942 /// Used to parameterize getRange
1943 enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED };
1944
1945 /// Set the memoized range for the given SCEV.
1946 const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint,
1947 ConstantRange CR) {
1948 DenseMap<const SCEV *, ConstantRange> &Cache =
1949 Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges;
1950
1951 auto Pair = Cache.insert_or_assign(S, std::move(CR));
1952 return Pair.first->second;
1953 }
1954
1955 /// Determine the range for a particular SCEV.
1956 /// NOTE: This returns a reference to an entry in a cache. It must be
1957 /// copied if its needed for longer.
1958 LLVM_ABI const ConstantRange &getRangeRef(const SCEV *S, RangeSignHint Hint,
1959 unsigned Depth = 0);
1960
1961 /// Determine the range for a particular SCEV, but evaluates ranges for
1962 /// operands iteratively first.
1963 const ConstantRange &getRangeRefIter(const SCEV *S, RangeSignHint Hint);
1964
1965 /// Determines the range for the affine SCEVAddRecExpr {\p Start,+,\p Step}.
1966 /// Helper for \c getRange.
1967 ConstantRange getRangeForAffineAR(const SCEV *Start, const SCEV *Step,
1968 const APInt &MaxBECount);
1969
1970 /// Determines the range for the affine non-self-wrapping SCEVAddRecExpr {\p
1971 /// Start,+,\p Step}<nw>.
1972 ConstantRange getRangeForAffineNoSelfWrappingAR(const SCEVAddRecExpr *AddRec,
1973 const SCEV *MaxBECount,
1974 unsigned BitWidth,
1975 RangeSignHint SignHint);
1976
1977 /// Try to compute a range for the affine SCEVAddRecExpr {\p Start,+,\p
1978 /// Step} by "factoring out" a ternary expression from the add recurrence.
1979 /// Helper called by \c getRange.
1980 ConstantRange getRangeViaFactoring(const SCEV *Start, const SCEV *Step,
1981 const APInt &MaxBECount);
1982
1983 /// If the unknown expression U corresponds to a simple recurrence, return
1984 /// a constant range which represents the entire recurrence. Note that
1985 /// *add* recurrences with loop invariant steps aren't represented by
1986 /// SCEVUnknowns and thus don't use this mechanism.
1987 ConstantRange getRangeForUnknownRecurrence(const SCEVUnknown *U);
1988
1989 /// We know that there is no SCEV for the specified value. Analyze the
1990 /// expression recursively.
1991 const SCEV *createSCEV(Value *V);
1992
1993 /// We know that there is no SCEV for the specified value. Create a new SCEV
1994 /// for \p V iteratively.
1995 const SCEV *createSCEVIter(Value *V);
1996 /// Collect operands of \p V for which SCEV expressions should be constructed
1997 /// first. Returns a SCEV directly if it can be constructed trivially for \p
1998 /// V.
1999 const SCEV *getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops);
2000
2001 /// Returns SCEV for the first operand of a phi if all phi operands have
2002 /// identical opcodes and operands.
2003 const SCEV *createNodeForPHIWithIdenticalOperands(PHINode *PN);
2004
2005 /// Provide the special handling we need to analyze PHI SCEVs.
2006 const SCEV *createNodeForPHI(PHINode *PN);
2007
2008 /// Helper function called from createNodeForPHI.
2009 const SCEV *createAddRecFromPHI(PHINode *PN);
2010
2011 /// A helper function for createAddRecFromPHI to handle simple cases.
2012 const SCEV *createSimpleAffineAddRec(PHINode *PN, Value *BEValueV,
2013 Value *StartValueV);
2014
2015 /// Helper function called from createNodeForPHI.
2016 const SCEV *createNodeFromSelectLikePHI(PHINode *PN);
2017
2018 /// Provide special handling for a select-like instruction (currently this
2019 /// is either a select instruction or a phi node). \p Ty is the type of the
2020 /// instruction being processed, that is assumed equivalent to
2021 /// "Cond ? TrueVal : FalseVal".
2022 std::optional<const SCEV *>
2023 createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty, ICmpInst *Cond,
2024 Value *TrueVal, Value *FalseVal);
2025
2026 /// See if we can model this select-like instruction via umin_seq expression.
2027 const SCEV *createNodeForSelectOrPHIViaUMinSeq(Value *I, Value *Cond,
2028 Value *TrueVal,
2029 Value *FalseVal);
2030
2031 /// Given a value \p V, which is a select-like instruction (currently this is
2032 /// either a select instruction or a phi node), which is assumed equivalent to
2033 /// Cond ? TrueVal : FalseVal
2034 /// see if we can model it as a SCEV expression.
2035 const SCEV *createNodeForSelectOrPHI(Value *V, Value *Cond, Value *TrueVal,
2036 Value *FalseVal);
2037
2038 /// Provide the special handling we need to analyze GEP SCEVs.
2039 const SCEV *createNodeForGEP(GEPOperator *GEP);
2040
2041 /// Implementation code for getSCEVAtScope; called at most once for each
2042 /// SCEV+Loop pair.
2043 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
2044
2045 /// Return the BackedgeTakenInfo for the given loop, lazily computing new
2046 /// values if the loop hasn't been analyzed yet. The returned result is
2047 /// guaranteed not to be predicated.
2048 BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
2049
2050 /// Similar to getBackedgeTakenInfo, but will add predicates as required
2051 /// with the purpose of returning complete information.
2052 BackedgeTakenInfo &getPredicatedBackedgeTakenInfo(const Loop *L);
2053
2054 /// Compute the number of times the specified loop will iterate.
2055 /// If AllowPredicates is set, we will create new SCEV predicates as
2056 /// necessary in order to return an exact answer.
2057 BackedgeTakenInfo computeBackedgeTakenCount(const Loop *L,
2058 bool AllowPredicates = false);
2059
2060 /// Compute the number of times the backedge of the specified loop will
2061 /// execute if it exits via the specified block. If AllowPredicates is set,
2062 /// this call will try to use a minimal set of SCEV predicates in order to
2063 /// return an exact answer.
2064 ExitLimit computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
2065 bool IsOnlyExit, bool AllowPredicates = false);
2066
2067 // Helper functions for computeExitLimitFromCond to avoid exponential time
2068 // complexity.
2069
2070 class ExitLimitCache {
2071 // It may look like we need key on the whole (L, ExitIfTrue,
2072 // ControlsOnlyExit, AllowPredicates) tuple, but recursive calls to
2073 // computeExitLimitFromCondCached from computeExitLimitFromCondImpl only
2074 // vary the in \c ExitCond and \c ControlsOnlyExit parameters. We remember
2075 // the initial values of the other values to assert our assumption.
2076 SmallDenseMap<PointerIntPair<Value *, 1>, ExitLimit> TripCountMap;
2077
2078 const Loop *L;
2079 bool ExitIfTrue;
2080 bool AllowPredicates;
2081
2082 public:
2083 ExitLimitCache(const Loop *L, bool ExitIfTrue, bool AllowPredicates)
2084 : L(L), ExitIfTrue(ExitIfTrue), AllowPredicates(AllowPredicates) {}
2085
2086 LLVM_ABI std::optional<ExitLimit> find(const Loop *L, Value *ExitCond,
2087 bool ExitIfTrue,
2088 bool ControlsOnlyExit,
2089 bool AllowPredicates);
2090
2091 LLVM_ABI void insert(const Loop *L, Value *ExitCond, bool ExitIfTrue,
2092 bool ControlsOnlyExit, bool AllowPredicates,
2093 const ExitLimit &EL);
2094 };
2095
2096 using ExitLimitCacheTy = ExitLimitCache;
2097
2098 ExitLimit computeExitLimitFromCondCached(ExitLimitCacheTy &Cache,
2099 const Loop *L, Value *ExitCond,
2100 bool ExitIfTrue,
2101 bool ControlsOnlyExit,
2102 bool AllowPredicates);
2103 ExitLimit computeExitLimitFromCondImpl(ExitLimitCacheTy &Cache, const Loop *L,
2104 Value *ExitCond, bool ExitIfTrue,
2105 bool ControlsOnlyExit,
2106 bool AllowPredicates);
2107 std::optional<ScalarEvolution::ExitLimit> computeExitLimitFromCondFromBinOp(
2108 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
2109 bool ControlsOnlyExit, bool AllowPredicates);
2110
2111 /// Compute the number of times the backedge of the specified loop will
2112 /// execute if its exit condition were a conditional branch of the ICmpInst
2113 /// ExitCond and ExitIfTrue. If AllowPredicates is set, this call will try
2114 /// to use a minimal set of SCEV predicates in order to return an exact
2115 /// answer.
2116 ExitLimit computeExitLimitFromICmp(const Loop *L, ICmpInst *ExitCond,
2117 bool ExitIfTrue,
2118 bool IsSubExpr,
2119 bool AllowPredicates = false);
2120
2121 /// Variant of previous which takes the components representing an ICmp
2122 /// as opposed to the ICmpInst itself. Note that the prior version can
2123 /// return more precise results in some cases and is preferred when caller
2124 /// has a materialized ICmp.
2125 ExitLimit computeExitLimitFromICmp(const Loop *L, CmpPredicate Pred,
2126 SCEVUse LHS, SCEVUse RHS, bool IsSubExpr,
2127 bool AllowPredicates = false);
2128
2129 /// Compute the number of times the backedge of the specified loop will
2130 /// execute if its exit condition were a switch with a single exiting case
2131 /// to ExitingBB.
2132 ExitLimit computeExitLimitFromSingleExitSwitch(const Loop *L,
2133 SwitchInst *Switch,
2134 BasicBlock *ExitingBB,
2135 bool IsSubExpr);
2136
2137 /// Compute the exit limit of a loop that is controlled by a
2138 /// "(IV >> 1) != 0" type comparison. We cannot compute the exact trip
2139 /// count in these cases (since SCEV has no way of expressing them), but we
2140 /// can still sometimes compute an upper bound.
2141 ///
2142 /// Return an ExitLimit for a loop whose backedge is guarded by `LHS Pred
2143 /// RHS`.
2144 ExitLimit computeShiftCompareExitLimit(Value *LHS, Value *RHS, const Loop *L,
2145 ICmpInst::Predicate Pred);
2146
2147 /// If the loop is known to execute a constant number of times (the
2148 /// condition evolves only from constants), try to evaluate a few iterations
2149 /// of the loop until we get the exit condition gets a value of ExitWhen
2150 /// (true or false). If we cannot evaluate the exit count of the loop,
2151 /// return CouldNotCompute.
2152 const SCEV *computeExitCountExhaustively(const Loop *L, Value *Cond,
2153 bool ExitWhen);
2154
2155 /// Return the number of times an exit condition comparing the specified
2156 /// value to zero will execute. If not computable, return CouldNotCompute.
2157 /// If AllowPredicates is set, this call will try to use a minimal set of
2158 /// SCEV predicates in order to return an exact answer.
2159 ExitLimit howFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr,
2160 bool AllowPredicates = false);
2161
2162 /// Return the number of times an exit condition checking the specified
2163 /// value for nonzero will execute. If not computable, return
2164 /// CouldNotCompute.
2165 ExitLimit howFarToNonZero(const SCEV *V, const Loop *L);
2166
2167 /// Return the number of times an exit condition containing the specified
2168 /// less-than comparison will execute. If not computable, return
2169 /// CouldNotCompute.
2170 ///
2171 /// \p isSigned specifies whether the less-than is signed.
2172 ///
2173 /// \p ControlsOnlyExit is true when the LHS < RHS condition directly controls
2174 /// the branch (loops exits only if condition is true). In this case, we can
2175 /// use NoWrapFlags to skip overflow checks.
2176 ///
2177 /// If \p AllowPredicates is set, this call will try to use a minimal set of
2178 /// SCEV predicates in order to return an exact answer.
2179 ExitLimit howManyLessThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
2180 bool isSigned, bool ControlsOnlyExit,
2181 bool AllowPredicates = false);
2182
2183 ExitLimit howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
2184 bool isSigned, bool IsSubExpr,
2185 bool AllowPredicates = false);
2186
2187 /// Return a predecessor of BB (which may not be an immediate predecessor)
2188 /// which has exactly one successor from which BB is reachable, or null if
2189 /// no such block is found.
2190 std::pair<const BasicBlock *, const BasicBlock *>
2191 getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB) const;
2192
2193 /// Test whether the condition described by Pred, LHS, and RHS is true
2194 /// whenever the given FoundCondValue value evaluates to true in given
2195 /// Context. If Context is nullptr, then the found predicate is true
2196 /// everywhere. LHS and FoundLHS may have different type width.
2197 LLVM_ABI bool isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
2198 const SCEV *RHS, const Value *FoundCondValue,
2199 bool Inverse,
2200 const Instruction *Context = nullptr);
2201
2202 /// Test whether the condition described by Pred, LHS, and RHS is true
2203 /// whenever the given FoundCondValue value evaluates to true in given
2204 /// Context. If Context is nullptr, then the found predicate is true
2205 /// everywhere. LHS and FoundLHS must have same type width.
2206 LLVM_ABI bool isImpliedCondBalancedTypes(CmpPredicate Pred, SCEVUse LHS,
2207 SCEVUse RHS, CmpPredicate FoundPred,
2208 SCEVUse FoundLHS, SCEVUse FoundRHS,
2209 const Instruction *CtxI);
2210
2211 /// Test whether the condition described by Pred, LHS, and RHS is true
2212 /// whenever the condition described by FoundPred, FoundLHS, FoundRHS is
2213 /// true in given Context. If Context is nullptr, then the found predicate is
2214 /// true everywhere.
2215 LLVM_ABI bool isImpliedCond(CmpPredicate Pred, const SCEV *LHS,
2216 const SCEV *RHS, CmpPredicate FoundPred,
2217 const SCEV *FoundLHS, const SCEV *FoundRHS,
2218 const Instruction *Context = nullptr);
2219
2220 /// Test whether the condition described by Pred, LHS, and RHS is true
2221 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2222 /// true in given Context. If Context is nullptr, then the found predicate is
2223 /// true everywhere.
2224 bool isImpliedCondOperands(CmpPredicate Pred, const SCEV *LHS,
2225 const SCEV *RHS, const SCEV *FoundLHS,
2226 const SCEV *FoundRHS,
2227 const Instruction *Context = nullptr);
2228
2229 /// Test whether the condition described by Pred, LHS, and RHS is true
2230 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2231 /// true. Here LHS is an operation that includes FoundLHS as one of its
2232 /// arguments.
2233 bool isImpliedViaOperations(CmpPredicate Pred, const SCEV *LHS,
2234 const SCEV *RHS, const SCEV *FoundLHS,
2235 const SCEV *FoundRHS, unsigned Depth = 0);
2236
2237 /// Test whether the condition described by Pred, LHS, and RHS is true.
2238 /// Use only simple non-recursive types of checks, such as range analysis etc.
2239 bool isKnownViaNonRecursiveReasoning(CmpPredicate Pred, SCEVUse LHS,
2240 SCEVUse RHS);
2241
2242 /// Test whether the condition described by Pred, LHS, and RHS is true
2243 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2244 /// true.
2245 bool isImpliedCondOperandsHelper(CmpPredicate Pred, const SCEV *LHS,
2246 const SCEV *RHS, const SCEV *FoundLHS,
2247 const SCEV *FoundRHS);
2248
2249 /// Test whether the condition described by Pred, LHS, and RHS is true
2250 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2251 /// true. Utility function used by isImpliedCondOperands. Tries to get
2252 /// cases like "X `sgt` 0 => X - 1 `sgt` -1".
2253 bool isImpliedCondOperandsViaRanges(CmpPredicate Pred, const SCEV *LHS,
2254 const SCEV *RHS, CmpPredicate FoundPred,
2255 const SCEV *FoundLHS,
2256 const SCEV *FoundRHS);
2257
2258 /// Return true if the condition denoted by \p LHS \p Pred \p RHS is implied
2259 /// by a call to @llvm.experimental.guard in \p BB.
2260 bool isImpliedViaGuard(const BasicBlock *BB, CmpPredicate Pred,
2261 const SCEV *LHS, const SCEV *RHS);
2262
2263 /// Test whether the condition described by Pred, LHS, and RHS is true
2264 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2265 /// true.
2266 ///
2267 /// This routine tries to rule out certain kinds of integer overflow, and
2268 /// then tries to reason about arithmetic properties of the predicates.
2269 bool isImpliedCondOperandsViaNoOverflow(CmpPredicate Pred, const SCEV *LHS,
2270 const SCEV *RHS, const SCEV *FoundLHS,
2271 const SCEV *FoundRHS);
2272
2273 /// Test whether the condition described by Pred, LHS, and RHS is true
2274 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2275 /// true.
2276 ///
2277 /// This routine tries to weaken the known condition basing on fact that
2278 /// FoundLHS is an AddRec.
2279 bool isImpliedCondOperandsViaAddRecStart(CmpPredicate Pred, const SCEV *LHS,
2280 const SCEV *RHS,
2281 const SCEV *FoundLHS,
2282 const SCEV *FoundRHS,
2283 const Instruction *CtxI);
2284
2285 /// Test whether the condition described by Pred, LHS, and RHS is true
2286 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2287 /// true.
2288 ///
2289 /// This routine tries to figure out predicate for Phis which are SCEVUnknown
2290 /// if it is true for every possible incoming value from their respective
2291 /// basic blocks.
2292 bool isImpliedViaMerge(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS,
2293 const SCEV *FoundLHS, const SCEV *FoundRHS,
2294 unsigned Depth);
2295
2296 /// Test whether the condition described by Pred, LHS, and RHS is true
2297 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
2298 /// true.
2299 ///
2300 /// This routine tries to reason about shifts.
2301 bool isImpliedCondOperandsViaShift(CmpPredicate Pred, const SCEV *LHS,
2302 const SCEV *RHS, const SCEV *FoundLHS,
2303 const SCEV *FoundRHS);
2304
2305 /// If we know that the specified Phi is in the header of its containing
2306 /// loop, we know the loop executes a constant number of times, and the PHI
2307 /// node is just a recurrence involving constants, fold it.
2308 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt &BEs,
2309 const Loop *L);
2310
2311 /// Test if the given expression is known to satisfy the condition described
2312 /// by Pred and the known constant ranges of LHS and RHS.
2313 bool isKnownPredicateViaConstantRanges(CmpPredicate Pred, SCEVUse LHS,
2314 SCEVUse RHS);
2315
2316 /// Try to prove the condition described by "LHS Pred RHS" by ruling out
2317 /// integer overflow.
2318 ///
2319 /// For instance, this will return true for "A s< (A + C)<nsw>" if C is
2320 /// positive.
2321 bool isKnownPredicateViaNoOverflow(CmpPredicate Pred, SCEVUse LHS,
2322 SCEVUse RHS);
2323
2324 /// Try to split Pred LHS RHS into logical conjunctions (and's) and try to
2325 /// prove them individually.
2326 bool isKnownPredicateViaSplitting(CmpPredicate Pred, SCEVUse LHS,
2327 SCEVUse RHS);
2328
2329 /// Try to match the Expr as "(L + R)<Flags>".
2330 bool splitBinaryAdd(SCEVUse Expr, SCEVUse &L, SCEVUse &R,
2331 SCEV::NoWrapFlags &Flags);
2332
2333 /// Forget predicated/non-predicated backedge taken counts for the given loop.
2334 void forgetBackedgeTakenCounts(const Loop *L, bool Predicated);
2335
2336 /// Drop memoized information for all \p SCEVs.
2337 void forgetMemoizedResults(ArrayRef<SCEVUse> SCEVs);
2338
2339 /// Helper for forgetMemoizedResults.
2340 void forgetMemoizedResultsImpl(const SCEV *S);
2341
2342 /// Iterate over instructions in \p Worklist and their users. Erase entries
2343 /// from ValueExprMap and collect SCEV expressions in \p ToForget
2344 void visitAndClearUsers(SmallVectorImpl<Instruction *> &Worklist,
2345 SmallPtrSetImpl<Instruction *> &Visited,
2346 SmallVectorImpl<SCEVUse> &ToForget);
2347
2348 /// Erase Value from ValueExprMap and ExprValueMap.
2349 void eraseValueFromMap(Value *V);
2350
2351 /// Insert V to S mapping into ValueExprMap and ExprValueMap.
2352 void insertValueToMap(Value *V, const SCEV *S);
2353
2354 /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
2355 /// pointer.
2356 bool checkValidity(const SCEV *S) const;
2357
2358 /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
2359 /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}. This is
2360 /// equivalent to proving no signed (resp. unsigned) wrap in
2361 /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
2362 /// (resp. `SCEVZeroExtendExpr`).
2363 template <typename ExtendOpTy>
2364 bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
2365 const Loop *L);
2366
2367 /// Try to prove NSW or NUW on \p AR relying on ConstantRange manipulation.
2368 SCEV::NoWrapFlags proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR);
2369
2370 /// Try to prove NSW on \p AR by proving facts about conditions known on
2371 /// entry and backedge.
2372 SCEV::NoWrapFlags proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR);
2373
2374 /// Try to prove NUW on \p AR by proving facts about conditions known on
2375 /// entry and backedge.
2376 SCEV::NoWrapFlags proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR);
2377
2378 std::optional<MonotonicPredicateType>
2379 getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
2380 ICmpInst::Predicate Pred);
2381
2382 /// Return SCEV no-wrap flags that can be proven based on reasoning about
2383 /// how poison produced from no-wrap flags on this value (e.g. a nuw add)
2384 /// would trigger undefined behavior on overflow.
2385 SCEV::NoWrapFlags getNoWrapFlagsFromUB(const Value *V);
2386
2387 /// Return a scope which provides an upper bound on the defining scope of
2388 /// 'S'. Specifically, return the first instruction in said bounding scope.
2389 /// Return nullptr if the scope is trivial (function entry).
2390 /// (See scope definition rules associated with flag discussion above)
2391 const Instruction *getNonTrivialDefiningScopeBound(const SCEV *S);
2392
2393 /// Return a scope which provides an upper bound on the defining scope for
2394 /// a SCEV with the operands in Ops. The outparam Precise is set if the
2395 /// bound found is a precise bound (i.e. must be the defining scope.)
2396 const Instruction *getDefiningScopeBound(ArrayRef<SCEVUse> Ops,
2397 bool &Precise);
2398
2399 /// Wrapper around the above for cases which don't care if the bound
2400 /// is precise.
2401 const Instruction *getDefiningScopeBound(ArrayRef<SCEVUse> Ops);
2402
2403 /// Given two instructions in the same function, return true if we can
2404 /// prove B must execute given A executes.
2405 bool isGuaranteedToTransferExecutionTo(const Instruction *A,
2406 const Instruction *B);
2407
2408 /// Returns true if \p Op is guaranteed not to cause immediate UB.
2409 bool isGuaranteedNotToCauseUB(const SCEV *Op);
2410
2411 /// Returns true if \p Op is guaranteed to not be poison.
2412 static bool isGuaranteedNotToBePoison(const SCEV *Op);
2413
2414 /// Return true if the SCEV corresponding to \p I is never poison. Proving
2415 /// this is more complex than proving that just \p I is never poison, since
2416 /// SCEV commons expressions across control flow, and you can have cases
2417 /// like:
2418 ///
2419 /// idx0 = a + b;
2420 /// ptr[idx0] = 100;
2421 /// if (<condition>) {
2422 /// idx1 = a +nsw b;
2423 /// ptr[idx1] = 200;
2424 /// }
2425 ///
2426 /// where the SCEV expression (+ a b) is guaranteed to not be poison (and
2427 /// hence not sign-overflow) only if "<condition>" is true. Since both
2428 /// `idx0` and `idx1` will be mapped to the same SCEV expression, (+ a b),
2429 /// it is not okay to annotate (+ a b) with <nsw> in the above example.
2430 bool isSCEVExprNeverPoison(const Instruction *I);
2431
2432 /// This is like \c isSCEVExprNeverPoison but it specifically works for
2433 /// instructions that will get mapped to SCEV add recurrences. Return true
2434 /// if \p I will never generate poison under the assumption that \p I is an
2435 /// add recurrence on the loop \p L.
2436 bool isAddRecNeverPoison(const Instruction *I, const Loop *L);
2437
2438 /// Similar to createAddRecFromPHI, but with the additional flexibility of
2439 /// suggesting runtime overflow checks in case casts are encountered.
2440 /// If successful, the analysis records that for this loop, \p SymbolicPHI,
2441 /// which is the UnknownSCEV currently representing the PHI, can be rewritten
2442 /// into an AddRec, assuming some predicates; The function then returns the
2443 /// AddRec and the predicates as a pair, and caches this pair in
2444 /// PredicatedSCEVRewrites.
2445 /// If the analysis is not successful, a mapping from the \p SymbolicPHI to
2446 /// itself (with no predicates) is recorded, and a nullptr with an empty
2447 /// predicates vector is returned as a pair.
2448 std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
2449 createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI);
2450
2451 /// Compute the maximum backedge count based on the range of values
2452 /// permitted by Start, End, and Stride. This is for loops of the form
2453 /// {Start, +, Stride} LT End.
2454 ///
2455 /// Preconditions:
2456 /// * the induction variable is known to be positive.
2457 /// * the induction variable is assumed not to overflow (i.e. either it
2458 /// actually doesn't, or we'd have to immediately execute UB)
2459 /// We *don't* assert these preconditions so please be careful.
2460 const SCEV *computeMaxBECountForLT(const SCEV *Start, const SCEV *Stride,
2461 const SCEV *End, unsigned BitWidth,
2462 bool IsSigned);
2463
2464 /// Verify if an linear IV with positive stride can overflow when in a
2465 /// less-than comparison, knowing the invariant term of the comparison,
2466 /// the stride.
2467 bool canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, bool IsSigned);
2468
2469 /// Verify if an linear IV with negative stride can overflow when in a
2470 /// greater-than comparison, knowing the invariant term of the comparison,
2471 /// the stride.
2472 bool canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, bool IsSigned);
2473
2474 /// Get add expr already created or create a new one.
2475 const SCEV *getOrCreateAddExpr(ArrayRef<SCEVUse> Ops,
2476 SCEV::NoWrapFlags Flags);
2477
2478 /// Get mul expr already created or create a new one.
2479 const SCEV *getOrCreateMulExpr(ArrayRef<SCEVUse> Ops,
2480 SCEV::NoWrapFlags Flags);
2481
2482 // Get addrec expr already created or create a new one.
2483 const SCEV *getOrCreateAddRecExpr(ArrayRef<SCEVUse> Ops, const Loop *L,
2484 SCEV::NoWrapFlags Flags);
2485
2486 /// Return x if \p Val is f(x) where f is a 1-1 function.
2487 const SCEV *stripInjectiveFunctions(const SCEV *Val) const;
2488
2489 /// Find all of the loops transitively used in \p S, and fill \p LoopsUsed.
2490 /// A loop is considered "used" by an expression if it contains
2491 /// an add rec on said loop.
2492 void getUsedLoops(const SCEV *S, SmallPtrSetImpl<const Loop *> &LoopsUsed);
2493
2494 /// Look for a SCEV expression with type `SCEVType` and operands `Ops` in
2495 /// `UniqueSCEVs`. Return if found, else nullptr.
2496 SCEV *findExistingSCEVInCache(SCEVTypes SCEVType, ArrayRef<const SCEV *> Ops);
2497 SCEV *findExistingSCEVInCache(SCEVTypes SCEVType, ArrayRef<SCEVUse> Ops);
2498
2499 /// Get reachable blocks in this function, making limited use of SCEV
2500 /// reasoning about conditions.
2501 void getReachableBlocks(SmallPtrSetImpl<BasicBlock *> &Reachable,
2502 Function &F);
2503
2504 /// Return the given SCEV expression with a new set of operands.
2505 /// This preserves the origial nowrap flags.
2506 const SCEV *getWithOperands(const SCEV *S, SmallVectorImpl<SCEVUse> &NewOps);
2507
2508 FoldingSet<SCEV> UniqueSCEVs;
2509 FoldingSet<SCEVPredicate> UniquePreds;
2510 BumpPtrAllocator SCEVAllocator;
2511
2512 /// This maps loops to a list of addrecs that directly use said loop.
2513 DenseMap<const Loop *, SmallVector<const SCEVAddRecExpr *, 4>> LoopUsers;
2514
2515 /// Cache tentative mappings from UnknownSCEVs in a Loop, to a SCEV expression
2516 /// they can be rewritten into under certain predicates.
2517 DenseMap<std::pair<const SCEVUnknown *, const Loop *>,
2518 std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
2519 PredicatedSCEVRewrites;
2520
2521 /// Set of AddRecs for which proving NUW via an induction has already been
2522 /// tried.
2523 SmallPtrSet<const SCEVAddRecExpr *, 16> UnsignedWrapViaInductionTried;
2524
2525 /// Set of AddRecs for which proving NSW via an induction has already been
2526 /// tried.
2527 SmallPtrSet<const SCEVAddRecExpr *, 16> SignedWrapViaInductionTried;
2528
2529 /// The head of a linked list of all SCEVUnknown values that have been
2530 /// allocated. This is used by releaseMemory to locate them all and call
2531 /// their destructors.
2532 SCEVUnknown *FirstUnknown = nullptr;
2533};
2534
2535/// Analysis pass that exposes the \c ScalarEvolution for a function.
2537 : public AnalysisInfoMixin<ScalarEvolutionAnalysis> {
2539
2540 LLVM_ABI static AnalysisKey Key;
2541
2542public:
2544
2546};
2547
2548/// Verifier pass for the \c ScalarEvolutionAnalysis results.
2550 : public PassInfoMixin<ScalarEvolutionVerifierPass> {
2551public:
2553 static bool isRequired() { return true; }
2554};
2555
2556/// Printer pass for the \c ScalarEvolutionAnalysis results.
2558 : public PassInfoMixin<ScalarEvolutionPrinterPass> {
2559 raw_ostream &OS;
2560
2561public:
2562 explicit ScalarEvolutionPrinterPass(raw_ostream &OS) : OS(OS) {}
2563
2565
2566 static bool isRequired() { return true; }
2567};
2568
2570 std::unique_ptr<ScalarEvolution> SE;
2571
2572public:
2573 static char ID;
2574
2576
2577 ScalarEvolution &getSE() { return *SE; }
2578 const ScalarEvolution &getSE() const { return *SE; }
2579
2580 bool runOnFunction(Function &F) override;
2581 void releaseMemory() override;
2582 void getAnalysisUsage(AnalysisUsage &AU) const override;
2583 void print(raw_ostream &OS, const Module * = nullptr) const override;
2584 void verifyAnalysis() const override;
2585};
2586
2587/// An interface layer with SCEV used to manage how we see SCEV expressions
2588/// for values in the context of existing predicates. We can add new
2589/// predicates, but we cannot remove them.
2590///
2591/// This layer has multiple purposes:
2592/// - provides a simple interface for SCEV versioning.
2593/// - guarantees that the order of transformations applied on a SCEV
2594/// expression for a single Value is consistent across two different
2595/// getSCEV calls. This means that, for example, once we've obtained
2596/// an AddRec expression for a certain value through expression
2597/// rewriting, we will continue to get an AddRec expression for that
2598/// Value.
2599/// - lowers the number of expression rewrites.
2601public:
2603
2604 LLVM_ABI const SCEVPredicate &getPredicate() const;
2605
2606 /// Returns the SCEV expression of V, in the context of the current SCEV
2607 /// predicate. The order of transformations applied on the expression of V
2608 /// returned by ScalarEvolution is guaranteed to be preserved, even when
2609 /// adding new predicates.
2610 LLVM_ABI const SCEV *getSCEV(Value *V);
2611
2612 /// Returns the rewritten SCEV for \p Expr in the context of the current SCEV
2613 /// predicate. The order of transformations applied on the expression of \p
2614 /// Expr returned by ScalarEvolution is guaranteed to be preserved, even when
2615 /// adding new predicates.
2616 LLVM_ABI const SCEV *getPredicatedSCEV(const SCEV *Expr);
2617
2618 /// Get the (predicated) backedge count for the analyzed loop.
2620
2621 /// Get the (predicated) symbolic max backedge count for the analyzed loop.
2623
2624 /// Returns the upper bound of the loop trip count as a normal unsigned
2625 /// value, or 0 if the trip count is unknown.
2627
2628 /// Adds a new predicate.
2629 LLVM_ABI void addPredicate(const SCEVPredicate &Pred);
2630
2631 /// Attempts to produce an AddRecExpr for V by adding additional SCEV
2632 /// predicates. If we can't transform the expression into an AddRecExpr we
2633 /// return nullptr and not add additional SCEV predicates to the current
2634 /// context.
2636
2637 /// Proves that V doesn't overflow by adding SCEV predicate.
2640
2641 /// Returns true if we've proved that V doesn't wrap by means of a SCEV
2642 /// predicate.
2645
2646 /// Returns the ScalarEvolution analysis used.
2647 ScalarEvolution *getSE() const { return &SE; }
2648
2649 /// We need to explicitly define the copy constructor because of FlagsMap.
2651
2652 /// Print the SCEV mappings done by the Predicated Scalar Evolution.
2653 /// The printed text is indented by \p Depth.
2654 LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const;
2655
2656 /// Check if \p AR1 and \p AR2 are equal, while taking into account
2657 /// Equal predicates in Preds.
2659 const SCEVAddRecExpr *AR2) const;
2660
2661private:
2662 /// Increments the version number of the predicate. This needs to be called
2663 /// every time the SCEV predicate changes.
2664 void updateGeneration();
2665
2666 /// Holds a SCEV and the version number of the SCEV predicate used to
2667 /// perform the rewrite of the expression.
2668 using RewriteEntry = std::pair<unsigned, const SCEV *>;
2669
2670 /// Maps a SCEV to the rewrite result of that SCEV at a certain version
2671 /// number. If this number doesn't match the current Generation, we will
2672 /// need to do a rewrite. To preserve the transformation order of previous
2673 /// rewrites, we will rewrite the previous result instead of the original
2674 /// SCEV.
2676
2677 /// Records what NoWrap flags we've added to a Value *.
2679
2680 /// The ScalarEvolution analysis.
2681 ScalarEvolution &SE;
2682
2683 /// The analyzed Loop.
2684 const Loop &L;
2685
2686 /// The SCEVPredicate that forms our context. We will rewrite all
2687 /// expressions assuming that this predicate true.
2688 std::unique_ptr<SCEVUnionPredicate> Preds;
2689
2690 /// Marks the version of the SCEV predicate used. When rewriting a SCEV
2691 /// expression we mark it with the version of the predicate. We use this to
2692 /// figure out if the predicate has changed from the last rewrite of the
2693 /// SCEV. If so, we need to perform a new rewrite.
2694 unsigned Generation = 0;
2695
2696 /// The backedge taken count.
2697 const SCEV *BackedgeCount = nullptr;
2698
2699 /// The symbolic backedge taken count.
2700 const SCEV *SymbolicMaxBackedgeCount = nullptr;
2701
2702 /// The constant max trip count for the loop.
2703 std::optional<unsigned> SmallConstantMaxTripCount;
2704};
2705
2706template <> struct DenseMapInfo<ScalarEvolution::FoldID> {
2709 return ID;
2710 }
2713 return ID;
2714 }
2715
2716 static unsigned getHashValue(const ScalarEvolution::FoldID &Val) {
2717 return Val.computeHash();
2718 }
2719
2722 return LHS == RHS;
2723 }
2724};
2725
2726template <> inline const SCEV *SCEVUseT<const SCEV *>::getCanonical() const {
2727 return getPointer()->getCanonical();
2728}
2729
2730template <typename SCEVPtrT>
2732 getPointer()->print(OS);
2734 if (any(Flags & SCEV::FlagNUW))
2735 OS << "(u nuw)";
2736 if (any(Flags & SCEV::FlagNSW))
2737 OS << "(u nsw)";
2738}
2739
2740#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2741template <typename SCEVPtrT>
2743 print(dbgs());
2744 dbgs() << '\n';
2745}
2746#endif
2747
2748} // end namespace llvm
2749
2750#endif // LLVM_ANALYSIS_SCALAREVOLUTION_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
constexpr LLT S1
This file implements a class to represent arbitrary precision integral constant values and operations...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
This file defines a hash set that can be used to remove duplication of nodes in a graph.
Hexagon Common GEP
Value * getPointer(Value *Ptr)
This header defines various interfaces for pass management in LLVM.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define P(N)
This file defines the PointerIntPair class.
const SmallVectorImpl< MachineOperand > & Cond
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Value handle with callbacks on RAUW and destruction.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This class represents a range of values.
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
FoldingSetNodeIDRef - This class describes a reference to an interned FoldingSetNodeID,...
Definition FoldingSet.h:172
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:209
FunctionPass(char &pid)
Definition Pass.h:316
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags none()
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
bool operator>(const PointerIntPair &RHS) const
Value handle that poisons itself if the Value is deleted.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
LLVM_ABI void addPredicate(const SCEVPredicate &Pred)
Adds a new predicate.
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
LLVM_ABI const SCEVPredicate & getPredicate() const
LLVM_ABI const SCEV * getPredicatedSCEV(const SCEV *Expr)
Returns the rewritten SCEV for Expr in the context of the current SCEV predicate.
LLVM_ABI bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Returns true if we've proved that V doesn't wrap by means of a SCEV predicate.
LLVM_ABI void setNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags)
Proves that V doesn't overflow by adding SCEV predicate.
LLVM_ABI void print(raw_ostream &OS, unsigned Depth) const
Print the SCEV mappings done by the Predicated Scalar Evolution.
LLVM_ABI bool areAddRecsEqualWithPreds(const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const
Check if AR1 and AR2 are equal, while taking into account Equal predicates in Preds.
LLVM_ABI PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L)
LLVM_ABI const SCEVAddRecExpr * getAsAddRec(Value *V)
Attempts to produce an AddRecExpr for V by adding additional SCEV predicates.
LLVM_ABI unsigned getSmallConstantMaxTripCount()
Returns the upper bound of the loop trip count as a normal unsigned value, or 0 if the trip count is ...
LLVM_ABI const SCEV * getBackedgeTakenCount()
Get the (predicated) backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max backedge count for the analyzed loop.
LLVM_ABI const SCEV * getSCEV(Value *V)
Returns the SCEV expression of V, in the context of the current SCEV predicate.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
This node represents a polynomial recurrence on the trip count of the specified loop.
SCEVComparePredicate(const FoldingSetNodeIDRef ID, const ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
const SCEV * getRHS() const
Returns the right hand side of the predicate.
ICmpInst::Predicate getPredicate() const
bool isAlwaysTrue() const override
Returns true if the predicate is always true.
const SCEV * getLHS() const
Returns the left hand side of the predicate.
static bool classof(const SCEVPredicate *P)
Methods for support type inquiry through isa, cast, and dyn_cast:
bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const override
Implementation of the SCEVPredicate interface.
This class represents an assumption made using SCEV expressions which can be checked at run-time.
SCEVPredicateKind getKind() const
virtual unsigned getComplexity() const
Returns the estimated complexity of this predicate.
SCEVPredicate & operator=(const SCEVPredicate &)=default
SCEVPredicate(const SCEVPredicate &)=default
virtual bool implies(const SCEVPredicate *N, ScalarEvolution &SE) const =0
Returns true if this predicate implies N.
virtual void print(raw_ostream &OS, unsigned Depth=0) const =0
Prints a textual representation of this predicate with an indentation of Depth.
~SCEVPredicate()=default
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
SCEVPredicateKind Kind
unsigned getComplexity() const override
We estimate the complexity of a union predicate as the size number of predicates in the union.
SCEVUnionPredicate(ArrayRef< const SCEVPredicate * > Preds, ScalarEvolution &SE)
Union predicates don't get cached so create a dummy set ID for it.
SCEVUnionPredicate getUnionWith(const SCEVPredicate *N, ScalarEvolution &SE) const
Returns a new SCEVUnionPredicate that is the union of this predicate and the given predicate N.
ArrayRef< const SCEVPredicate * > getPredicates() const
static bool classof(const SCEVPredicate *P)
Methods for support type inquiry through isa, cast, and dyn_cast:
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an assumption made on an AddRec expression.
IncrementWrapFlags
Similar to SCEV::NoWrapFlags, but with slightly different semantics for FlagNUSW.
SCEVWrapPredicate(const FoldingSetNodeIDRef ID, const SCEVAddRecExpr *AR, IncrementWrapFlags Flags)
static SCEVWrapPredicate::IncrementWrapFlags setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OnFlags)
static SCEVWrapPredicate::IncrementWrapFlags clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, SCEVWrapPredicate::IncrementWrapFlags OffFlags)
Convenient IncrementWrapFlags manipulation methods.
static bool classof(const SCEVPredicate *P)
Methods for support type inquiry through isa, cast, and dyn_cast:
IncrementWrapFlags getFlags() const
Returns the set assumed no overflow flags.
static SCEVWrapPredicate::IncrementWrapFlags maskFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, int Mask)
This class represents an analyzed expression in the program.
LLVM_ABI const SCEV * getCanonical() const
Return the canonical SCEV.
static constexpr auto NoWrapMask
unsigned short getExpressionSize() const
SCEV & operator=(const SCEV &)=delete
SCEVNoWrapFlags NoWrapFlags
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
static constexpr auto FlagNUW
LLVM_ABI void computeAndSetCanonical(ScalarEvolution &SE)
Compute and set the canonical SCEV, by constructing a SCEV with the same operands,...
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
SCEV(const SCEV &)=delete
const SCEV * CanonicalSCEV
Pointer to the canonical version of the SCEV, i.e.
static constexpr auto FlagAnyWrap
LLVM_ABI void dump() const
This method is used for debugging.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
LLVM_ABI bool isNonConstantNegative() const
Return true if the specified scev is negated, but not a constant.
static constexpr auto FlagNSW
LLVM_ABI ArrayRef< SCEVUse > operands() const
Return operands of this SCEV expression.
const unsigned short ExpressionSize
LLVM_ABI void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEV(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy, unsigned short ExpressionSize)
SCEVTypes getSCEVType() const
unsigned short SubclassData
This field is initialized to zero and may be used in subclasses to store miscellaneous information.
static constexpr auto FlagNW
LLVM_ABI Type * getType() const
Return the LLVM type of this SCEV expression.
Analysis pass that exposes the ScalarEvolution for a function.
LLVM_ABI ScalarEvolution run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Verifier pass for the ScalarEvolutionAnalysis results.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
const ScalarEvolution & getSE() const
bool operator==(const FoldID &RHS) const
FoldID(SCEVTypes C, const SCEV *Op, const Type *Ty)
static LLVM_ABI LoopGuards collect(const Loop *L, ScalarEvolution &SE)
Collect rewrite map for loop guards for loop L, together with flags indicating if NUW and NSW can be ...
LLVM_ABI const SCEV * rewrite(const SCEV *Expr) const
Try to apply the collected loop guards to Expr.
The main scalar evolution driver.
LLVM_ABI const SCEV * getUDivExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
const SCEV * getConstantMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEVConstant that is greater than or equal to (i.e.
static bool hasFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags TestFlags)
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
LLVM_ABI bool isKnownNonNegative(const SCEV *S)
Test if the given expression is known to be non-negative.
LLVM_ABI bool isKnownOnEveryIteration(CmpPredicate Pred, const SCEVAddRecExpr *LHS, const SCEV *RHS)
Test if the condition described by Pred, LHS, RHS is known to be true on every iteration of the loop ...
LLVM_ABI const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterationsImpl(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
LLVM_ABI const SCEV * getUDivCeilSCEV(const SCEV *N, const SCEV *D)
Compute ceil(N / D).
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantExitCondDuringFirstIterations(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI, const SCEV *MaxIter)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L at given Context duri...
LLVM_ABI Type * getWiderType(Type *Ty1, Type *Ty2) const
LLVM_ABI const SCEV * getAbsExpr(const SCEV *Op, bool IsNSW)
LLVM_ABI bool isKnownNonPositive(const SCEV *S)
Test if the given expression is known to be non-positive.
LLVM_ABI bool isKnownNegative(const SCEV *S)
Test if the given expression is known to be negative.
LLVM_ABI const SCEV * getPredicatedConstantMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getConstantMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * removePointerBase(const SCEV *S)
Compute an expression equivalent to S - getPointerBase(S).
LLVM_ABI bool isLoopEntryGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS.
LLVM_ABI bool isKnownNonZero(const SCEV *S)
Test if the given expression is known to be non-zero.
LLVM_ABI const SCEV * getURemExpr(SCEVUse LHS, SCEVUse RHS)
Represents an unsigned remainder expression based on unsigned division.
LLVM_ABI const SCEV * getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSMinExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI void setNoWrapFlags(SCEVAddRecExpr *AddRec, SCEV::NoWrapFlags Flags)
Update no-wrap flags of an AddRec.
LLVM_ABI const SCEV * getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umax operatio...
const SCEV * getZero(Type *Ty)
Return a SCEV for the constant 0 of a specific type.
LLVM_ABI bool willNotOverflow(Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI=nullptr)
Is operation BinOp between LHS and RHS provably does not have a signed/unsigned overflow (Signed)?
LLVM_ABI ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsOnlyExit, bool AllowPredicates=false)
Compute the number of times the backedge of the specified loop will execute if its exit condition wer...
LLVM_ABI const SCEV * getZeroExtendExprImpl(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI const SCEVPredicate * getEqualPredicate(const SCEV *LHS, const SCEV *RHS)
LLVM_ABI unsigned getSmallConstantTripMultiple(const Loop *L, const SCEV *ExitCount)
Returns the largest constant divisor of the trip count as a normal unsigned value,...
LLVM_ABI uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
LLVM_ABI const SCEV * getConstant(ConstantInt *V)
LLVM_ABI const SCEV * getPredicatedBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getBackedgeTakenCount, except it will add a set of SCEV predicates to Predicates that are ...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI const SCEV * getMinusSCEV(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS.
ConstantRange getSignedRange(const SCEV *S)
Determine the signed range for a particular SCEV.
LLVM_ABI const SCEV * getAddRecExpr(SCEVUse Start, SCEVUse Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
LLVM_ABI const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
bool loopHasNoAbnormalExits(const Loop *L)
Return true if the loop has no abnormal exits.
LLVM_ABI const SCEV * getTripCountFromExitCount(const SCEV *ExitCount)
A version of getTripCountFromExitCount below which always picks an evaluation type which can not resu...
LLVM_ABI ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC, DominatorTree &DT, LoopInfo &LI)
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI const SCEV * getTruncateOrNoop(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI const SCEV * getLosslessPtrToIntExpr(const SCEV *Op)
const SCEV * getMulExpr(SCEVUse Op0, SCEVUse Op1, SCEVUse Op2, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
LLVM_ABI const SCEV * getCastExpr(SCEVTypes Kind, const SCEV *Op, Type *Ty)
LLVM_ABI const SCEV * getSequentialMinMaxExpr(SCEVTypes Kind, SmallVectorImpl< SCEVUse > &Operands)
LLVM_ABI std::optional< bool > evaluatePredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Check whether the condition described by Pred, LHS, and RHS is true or false in the given Context.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
LLVM_ABI const SCEV * getPtrToIntExpr(const SCEV *Op, Type *Ty)
LLVM_ABI bool isBackedgeTakenCountMaxOrZero(const Loop *L)
Return true if the backedge taken count is either the value returned by getConstantMaxBackedgeTakenCo...
LLVM_ABI void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI bool isKnownPositive(const SCEV *S)
Test if the given expression is known to be positive.
LLVM_ABI bool SimplifyICmpOperands(CmpPredicate &Pred, SCEVUse &LHS, SCEVUse &RHS, unsigned Depth=0)
Simplify LHS and RHS in a comparison with predicate Pred.
APInt getUnsignedRangeMin(const SCEV *S)
Determine the min of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo)
Return an expression for offsetof on the given field with type IntTy.
LLVM_ABI LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L)
Return the "disposition" of the given SCEV with respect to the given loop.
LLVM_ABI bool containsAddRecurrence(const SCEV *S)
Return true if the SCEV is a scAddRecExpr or it contains scAddRecExpr.
LLVM_ABI const SCEV * getSignExtendExprImpl(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool hasOperand(const SCEV *S, const SCEV *Op) const
Test whether the given SCEV has Op as a direct or indirect operand.
LLVM_ABI const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
LLVM_ABI Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
LLVM_ABI const SCEVPredicate * getComparePredicate(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
LLVM_ABI bool haveSameSign(const SCEV *S1, const SCEV *S2)
Return true if we know that S1 and S2 must have the same sign.
LLVM_ABI const SCEV * getNotSCEV(const SCEV *V)
Return the SCEV object corresponding to ~V.
LLVM_ABI const SCEV * getElementCount(Type *Ty, ElementCount EC, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
LLVM_ABI bool instructionCouldExistWithOperands(const SCEV *A, const SCEV *B)
Return true if there exists a point in the program at which both A and B could be operands to the sam...
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
LLVM_ABI void print(raw_ostream &OS) const
LLVM_ABI const SCEV * getPredicatedExitCount(const Loop *L, const BasicBlock *ExitingBlock, SmallVectorImpl< const SCEVPredicate * > *Predicates, ExitCountKind Kind=Exact)
Same as above except this uses the predicated backedge taken info and may require predicates.
static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags)
LLVM_ABI void forgetTopmostLoop(const Loop *L)
friend class ScalarEvolutionsTest
LLVM_ABI void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
APInt getSignedRangeMin(const SCEV *S)
Determine the min of the signed range for a particular SCEV.
LLVM_ABI const SCEV * getNoopOrAnyExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
LLVM_ABI const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMaxExpr(SCEVUse LHS, SCEVUse RHS)
static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags Mask)
Convenient NoWrapFlags manipulation.
MonotonicPredicateType
A predicate is said to be monotonically increasing if may go from being false to being true as the lo...
LLVM_ABI std::optional< LoopInvariantPredicate > getLoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L, const Instruction *CtxI=nullptr)
If the result of the predicate LHS Pred RHS is loop invariant with respect to L, return a LoopInvaria...
LLVM_ABI const SCEV * getStoreSizeOfExpr(Type *IntTy, Type *StoreTy)
Return an expression for the store size of StoreTy that is type IntTy.
LLVM_ABI const SCEVPredicate * getWrapPredicate(const SCEVAddRecExpr *AR, SCEVWrapPredicate::IncrementWrapFlags AddedFlags)
LLVM_ABI bool isLoopBackedgeGuardedByCond(const Loop *L, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether the backedge of the loop is protected by a conditional between LHS and RHS.
LLVM_ABI APInt getNonZeroConstantMultiple(const SCEV *S)
const SCEV * getMinusOne(Type *Ty)
Return a SCEV for the constant -1 of a specific type.
static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags)
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
LLVM_ABI BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB)
Return the "disposition" of the given SCEV with respect to the given block.
LLVM_ABI const SCEV * getNoopOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI bool loopIsFiniteByAssumption(const Loop *L)
Return true if this loop is finite by assumption.
LLVM_ABI const SCEV * getExistingSCEV(Value *V)
Return an existing SCEV for V if there is one, otherwise return nullptr.
LLVM_ABI APInt getConstantMultiple(const SCEV *S, const Instruction *CtxI=nullptr)
Returns the max constant multiple of S.
LoopDisposition
An enum describing the relationship between a SCEV and a loop.
@ LoopComputable
The SCEV varies predictably with the loop.
@ LoopVariant
The SCEV is loop-variant (unknown).
@ LoopInvariant
The SCEV is loop-invariant.
LLVM_ABI bool isKnownMultipleOf(const SCEV *S, uint64_t M, SmallVectorImpl< const SCEVPredicate * > &Assumptions)
Check that S is a multiple of M.
LLVM_ABI const SCEV * getAnyExtendExpr(const SCEV *Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
const SCEV * getAddRecExpr(const SmallVectorImpl< SCEVUse > &Operands, const Loop *L, SCEV::NoWrapFlags Flags)
LLVM_ABI bool isKnownToBeAPowerOfTwo(const SCEV *S, bool OrZero=false, bool OrNegative=false)
Test if the given expression is known to be a power of 2.
LLVM_ABI std::optional< SCEV::NoWrapFlags > getStrengthenedNoWrapFlagsFromBinOp(const OverflowingBinaryOperator *OBO)
Parse NSW/NUW flags from add/sub/mul IR binary operation Op into SCEV no-wrap flags,...
LLVM_ABI void forgetLcssaPhiWithNewPredecessor(Loop *L, PHINode *V)
Forget LCSSA phi node V of loop L to which a new predecessor was added, such that it may no longer be...
LLVM_ABI bool containsUndefs(const SCEV *S) const
Return true if the SCEV expression contains an undef value.
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI const SCEV * getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
LLVM_ABI bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L)
Determine if the SCEV can be evaluated at loop's entry.
LLVM_ABI uint32_t getMinTrailingZeros(const SCEV *S, const Instruction *CtxI=nullptr)
Determine the minimum number of zero bits that S is guaranteed to end in (at every loop iteration).
BlockDisposition
An enum describing the relationship between a SCEV and a basic block.
@ DominatesBlock
The SCEV dominates the block.
@ ProperlyDominatesBlock
The SCEV properly dominates the block.
@ DoesNotDominateBlock
The SCEV does not dominate the block.
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
LLVM_ABI void getPoisonGeneratingValues(SmallPtrSetImpl< const Value * > &Result, const SCEV *S)
Return the set of Values that, if poison, will definitively result in S being poison as well.
LLVM_ABI void forgetLoopDispositions()
Called when the client has changed the disposition of values in this loop.
LLVM_ABI const SCEV * getVScale(Type *Ty)
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
LLVM_ABI bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop.
LLVM_ABI const SCEV * getPointerBase(const SCEV *V)
Transitively follow the chain of pointer-type operands until reaching a SCEV that does not have a sin...
const SCEV * getPowerOfTwo(Type *Ty, unsigned Power)
Return a SCEV for the constant Power of two.
LLVM_ABI void forgetAllLoops()
LLVM_ABI bool dominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV dominate the specified basic block.
const SCEV * getAddExpr(SCEVUse Op0, SCEVUse Op1, SCEVUse Op2, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
LLVM_ABI const SCEV * getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
ExitCountKind
The terms "backedge taken count" and "exit count" are used interchangeably to refer to the number of ...
@ SymbolicMaximum
An expression which provides an upper bound on the exact trip count.
@ ConstantMaximum
A constant which provides an upper bound on the exact trip count.
@ Exact
An expression exactly describing the number of times the backedge has executed when a loop is exited.
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * applyLoopGuards(const SCEV *Expr, const Loop *L)
Try to apply information from loop guards for L to Expr.
LLVM_ABI const SCEV * getPtrToAddrExpr(const SCEV *Op)
LLVM_ABI const SCEVAddRecExpr * convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Preds)
Tries to convert the S expression to an AddRec expression, adding additional predicates to Preds as r...
LLVM_ABI const SCEV * getSMaxExpr(SCEVUse LHS, SCEVUse RHS)
LLVM_ABI const SCEV * getElementSize(Instruction *Inst)
Return the size of an element read or written by Inst.
LLVM_ABI const SCEV * getSizeOfExpr(Type *IntTy, TypeSize Size)
Return an expression for a TypeSize.
LLVM_ABI std::optional< bool > evaluatePredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Check whether the condition described by Pred, LHS, and RHS is true or false.
LLVM_ABI const SCEV * getUnknown(Value *V)
const SCEV * getAddExpr(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
LLVM_ABI std::optional< std::pair< const SCEV *, SmallVector< const SCEVPredicate *, 3 > > > createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI)
Checks if SymbolicPHI can be rewritten as an AddRecExpr under some Predicates.
LLVM_ABI const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool isKnownViaInduction(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS)
We'd like to check the predicate on every iteration of the most dominated loop between loops used in ...
LLVM_ABI std::optional< APInt > computeConstantDifference(const SCEV *LHS, const SCEV *RHS)
Compute LHS - RHS and returns the result as an APInt if it is a constant, and std::nullopt if it isn'...
LLVM_ABI bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block.
LLVM_ABI const SCEV * getUDivExactExpr(SCEVUse LHS, SCEVUse RHS)
Get a canonical unsigned division expression, or something simpler if possible.
LLVM_ABI const SCEV * rewriteUsingPredicate(const SCEV *S, const Loop *L, const SCEVPredicate &A)
Re-writes the SCEV according to the Predicates in A.
LLVM_ABI std::pair< const SCEV *, const SCEV * > SplitIntoInitAndPostInc(const Loop *L, const SCEV *S)
Splits SCEV expression S into two SCEVs.
LLVM_ABI bool canReuseInstruction(const SCEV *S, Instruction *I, SmallVectorImpl< Instruction * > &DropPoisonGeneratingInsts)
Check whether it is poison-safe to represent the expression S using the instruction I.
LLVM_ABI bool isKnownPredicateAt(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS, const Instruction *CtxI)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
LLVM_ABI const SCEV * getPredicatedSymbolicMaxBackedgeTakenCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > &Predicates)
Similar to getSymbolicMaxBackedgeTakenCount, except it will add a set of SCEV predicates to Predicate...
LLVM_ABI const SCEV * getGEPExpr(GEPOperator *GEP, ArrayRef< SCEVUse > IndexExprs)
Returns an expression for a GEP.
LLVM_ABI const SCEV * getUMinExpr(SCEVUse LHS, SCEVUse RHS, bool Sequential=false)
LLVM_ABI void registerUser(const SCEV *User, ArrayRef< const SCEV * > Ops)
Notify this ScalarEvolution that User directly uses SCEVs in Ops.
LLVM_ABI bool isBasicBlockEntryGuardedByCond(const BasicBlock *BB, CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the basic block is protected by a conditional between LHS and RHS.
LLVM_ABI const SCEV * getTruncateOrSignExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_ABI bool containsErasedValue(const SCEV *S) const
Return true if the SCEV expression contains a Value that has been optimised out and is now a nullptr.
const SCEV * getSymbolicMaxBackedgeTakenCount(const Loop *L)
When successful, this returns a SCEV that is greater than or equal to (i.e.
const SCEV * getMulExpr(SCEVUse LHS, SCEVUse RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
APInt getSignedRangeMax(const SCEV *S)
Determine the max of the signed range for a particular SCEV.
LLVM_ABI void verify() const
LLVMContext & getContext() const
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:291
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Class to represent struct types.
Provides information about what library functions are available for the current target.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
See the file comment.
Definition ValueMap.h:84
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
unsigned combineHashValue(unsigned a, unsigned b)
Simplistic combination of 32-bit hash values into 32-bit hash values.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
hash_code hash_value(const FixedPointSemantics &Val)
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
FoldingSetBase::Node FoldingSetNode
Definition FoldingSet.h:408
LLVM_ABI bool VerifySCEV
SCEVUseT(SCEVPtrT) -> SCEVUseT< SCEVPtrT >
Deduction guide for various SCEV subclass pointers.
SCEVNoWrapFlags
NoWrapFlags are bitfield indices into SCEV's SubclassData.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
SCEVUseT< const SCEV * > SCEVUse
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
#define N
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition PassManager.h:93
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
This struct provides a method for customizing the way a cast is performed.
Definition Casting.h:476
static CastReturnType castFailed()
Definition Casting.h:490
static CastReturnType doCast(const From &f)
Definition Casting.h:481
typename cast_retty< To, From >::ret_type CastReturnType
Definition Casting.h:479
static bool isPossible(const From &f)
Definition Casting.h:254
DefaultFoldingSetTrait - This class provides default implementations for FoldingSetTrait implementati...
Definition FoldingSet.h:115
static bool isEqual(const SCEVUse LHS, const SCEVUse RHS)
static unsigned getHashValue(SCEVUse U)
static unsigned getHashValue(const ScalarEvolution::FoldID &Val)
static ScalarEvolution::FoldID getTombstoneKey()
static ScalarEvolution::FoldID getEmptyKey()
static bool isEqual(const ScalarEvolution::FoldID &LHS, const ScalarEvolution::FoldID &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID)
static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID, unsigned IDHash, FoldingSetNodeID &TempID)
static unsigned ComputeHash(const SCEVPredicate &X, FoldingSetNodeID &TempID)
static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, unsigned IDHash, FoldingSetNodeID &TempID)
static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID)
static void Profile(const SCEV &X, FoldingSetNodeID &ID)
FoldingSetTrait - This trait class is used to define behavior of how to "profile" (in the FoldingSet ...
Definition FoldingSet.h:145
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:70
static constexpr int NumLowBitsAvailable
The Low bits are used by the PointerIntPair.
static void * getAsVoidPointer(SCEVUse U)
static SCEVUse getFromVoidPointer(void *P)
A traits type that is used to handle pointer types and things that are just wrappers for pointers as ...
static LLVM_ABI bool classof(const SCEV *S)
Methods for support type inquiry through isa, cast, and dyn_cast:
bool operator==(const SCEVUseT &RHS) const
const SCEV * getCanonical() const
Return the canonical SCEV for this SCEVUse.
bool operator!=(const SCEVUseT &RHS) const
SCEVPtrT operator->() const
SCEVUseT(const SCEVUseT< OtherPtrT > &Other)
void * getOpaqueValue() const
bool isCanonical() const
Returns true if the SCEVUse is canonical, i.e.
SCEVNoWrapFlags getUseNoWrapFlags() const
const SCEV * getPointer() const
bool operator==(const SCEV *RHS) const
void dump() const
This method is used for debugging.
SCEVUseT(SCEVPtrT S, SCEVNoWrapFlags Flags)
Construct with NoWrapFlags; only NUW/NSW are encoded, NW is dropped.
SCEVNoWrapFlags getNoWrapFlags(SCEVNoWrapFlags Mask=SCEVNoWrapFlags::NoWrapMask) const
Return the no-wrap flags for this SCEVUse, which is the union of the use-specific flags and the under...
bool operator>(const SCEVUseT &RHS) const
PointerIntPair< SCEVPtrT, 2 > Base
bool operator!=(const SCEV *RHS) const
void print(raw_ostream &OS) const
Print out the internal representation of this scalar to the specified stream.
SCEVUseT(SCEVPtrT S)
Information about the number of loop iterations for which a loop exit's branch condition evaluates to...
LLVM_ABI ExitLimit(const SCEV *E)
Construct either an exact exit limit from a constant, or an unknown one from a SCEVCouldNotCompute.
bool hasAnyInfo() const
Test whether this ExitLimit contains any computed information, or whether it's all SCEVCouldNotComput...
SmallVector< const SCEVPredicate *, 4 > Predicates
A vector of predicate guards for this ExitLimit.
bool hasFullInfo() const
Test whether this ExitLimit contains all information.
LoopInvariantPredicate(CmpPredicate Pred, const SCEV *LHS, const SCEV *RHS)
static SimpleType getSimplifiedValue(SCEVUse &Val)
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition Casting.h:34