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