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