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