1 //===- ConstantRange.cpp - ConstantRange implementation -------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // Represent a range of possible values that may occur when the program is run
10 // for an integral value. This keeps track of a lower and upper bound for the
11 // constant, which MAY wrap around the end of the numeric range. To do this, it
12 // keeps track of a [lower, upper) bound, which specifies an interval just like
13 // STL iterators. When used with boolean values, the following are important
14 // ranges (other integral ranges use min/max values for special range values):
16 // [F, F) = {} = Empty set
19 // [T, T) = {F, T} = Full set
21 //===----------------------------------------------------------------------===//
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/ConstantRange.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Metadata.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/KnownBits.h"
35 #include "llvm/Support/raw_ostream.h"
42 ConstantRange::ConstantRange(uint32_t BitWidth
, bool Full
)
43 : Lower(Full
? APInt::getMaxValue(BitWidth
) : APInt::getMinValue(BitWidth
)),
46 ConstantRange::ConstantRange(APInt V
)
47 : Lower(std::move(V
)), Upper(Lower
+ 1) {}
49 ConstantRange::ConstantRange(APInt L
, APInt U
)
50 : Lower(std::move(L
)), Upper(std::move(U
)) {
51 assert(Lower
.getBitWidth() == Upper
.getBitWidth() &&
52 "ConstantRange with unequal bit widths");
53 assert((Lower
!= Upper
|| (Lower
.isMaxValue() || Lower
.isMinValue())) &&
54 "Lower == Upper, but they aren't min or max value!");
57 ConstantRange
ConstantRange::fromKnownBits(const KnownBits
&Known
,
59 assert(!Known
.hasConflict() && "Expected valid KnownBits");
61 if (Known
.isUnknown())
62 return getFull(Known
.getBitWidth());
64 // For unsigned ranges, or signed ranges with known sign bit, create a simple
65 // range between the smallest and largest possible value.
66 if (!IsSigned
|| Known
.isNegative() || Known
.isNonNegative())
67 return ConstantRange(Known
.One
, ~Known
.Zero
+ 1);
69 // If we don't know the sign bit, pick the lower bound as a negative number
70 // and the upper bound as a non-negative one.
71 APInt Lower
= Known
.One
, Upper
= ~Known
.Zero
;
74 return ConstantRange(Lower
, Upper
+ 1);
77 ConstantRange
ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred
,
78 const ConstantRange
&CR
) {
82 uint32_t W
= CR
.getBitWidth();
85 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
86 case CmpInst::ICMP_EQ
:
88 case CmpInst::ICMP_NE
:
89 if (CR
.isSingleElement())
90 return ConstantRange(CR
.getUpper(), CR
.getLower());
92 case CmpInst::ICMP_ULT
: {
93 APInt
UMax(CR
.getUnsignedMax());
94 if (UMax
.isMinValue())
96 return ConstantRange(APInt::getMinValue(W
), std::move(UMax
));
98 case CmpInst::ICMP_SLT
: {
99 APInt
SMax(CR
.getSignedMax());
100 if (SMax
.isMinSignedValue())
102 return ConstantRange(APInt::getSignedMinValue(W
), std::move(SMax
));
104 case CmpInst::ICMP_ULE
:
105 return getNonEmpty(APInt::getMinValue(W
), CR
.getUnsignedMax() + 1);
106 case CmpInst::ICMP_SLE
:
107 return getNonEmpty(APInt::getSignedMinValue(W
), CR
.getSignedMax() + 1);
108 case CmpInst::ICMP_UGT
: {
109 APInt
UMin(CR
.getUnsignedMin());
110 if (UMin
.isMaxValue())
112 return ConstantRange(std::move(UMin
) + 1, APInt::getNullValue(W
));
114 case CmpInst::ICMP_SGT
: {
115 APInt
SMin(CR
.getSignedMin());
116 if (SMin
.isMaxSignedValue())
118 return ConstantRange(std::move(SMin
) + 1, APInt::getSignedMinValue(W
));
120 case CmpInst::ICMP_UGE
:
121 return getNonEmpty(CR
.getUnsignedMin(), APInt::getNullValue(W
));
122 case CmpInst::ICMP_SGE
:
123 return getNonEmpty(CR
.getSignedMin(), APInt::getSignedMinValue(W
));
127 ConstantRange
ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred
,
128 const ConstantRange
&CR
) {
129 // Follows from De-Morgan's laws:
131 // ~(~A union ~B) == A intersect B.
133 return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred
), CR
)
137 ConstantRange
ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred
,
139 // Computes the exact range that is equal to both the constant ranges returned
140 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
141 // when RHS is a singleton such as an APInt and so the assert is valid.
142 // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
143 // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
145 assert(makeAllowedICmpRegion(Pred
, C
) == makeSatisfyingICmpRegion(Pred
, C
));
146 return makeAllowedICmpRegion(Pred
, C
);
149 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate
&Pred
,
151 bool Success
= false;
153 if (isFullSet() || isEmptySet()) {
154 Pred
= isEmptySet() ? CmpInst::ICMP_ULT
: CmpInst::ICMP_UGE
;
155 RHS
= APInt(getBitWidth(), 0);
157 } else if (auto *OnlyElt
= getSingleElement()) {
158 Pred
= CmpInst::ICMP_EQ
;
161 } else if (auto *OnlyMissingElt
= getSingleMissingElement()) {
162 Pred
= CmpInst::ICMP_NE
;
163 RHS
= *OnlyMissingElt
;
165 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
167 getLower().isMinSignedValue() ? CmpInst::ICMP_SLT
: CmpInst::ICMP_ULT
;
170 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
172 getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE
: CmpInst::ICMP_UGE
;
177 assert((!Success
|| ConstantRange::makeExactICmpRegion(Pred
, RHS
) == *this) &&
183 /// Exact mul nuw region for single element RHS.
184 static ConstantRange
makeExactMulNUWRegion(const APInt
&V
) {
185 unsigned BitWidth
= V
.getBitWidth();
187 return ConstantRange::getFull(V
.getBitWidth());
189 return ConstantRange::getNonEmpty(
190 APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth
), V
,
191 APInt::Rounding::UP
),
192 APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth
), V
,
193 APInt::Rounding::DOWN
) + 1);
196 /// Exact mul nsw region for single element RHS.
197 static ConstantRange
makeExactMulNSWRegion(const APInt
&V
) {
198 // Handle special case for 0, -1 and 1. See the last for reason why we
199 // specialize -1 and 1.
200 unsigned BitWidth
= V
.getBitWidth();
201 if (V
== 0 || V
.isOneValue())
202 return ConstantRange::getFull(BitWidth
);
204 APInt MinValue
= APInt::getSignedMinValue(BitWidth
);
205 APInt MaxValue
= APInt::getSignedMaxValue(BitWidth
);
206 // e.g. Returning [-127, 127], represented as [-127, -128).
207 if (V
.isAllOnesValue())
208 return ConstantRange(-MaxValue
, MinValue
);
211 if (V
.isNegative()) {
212 Lower
= APIntOps::RoundingSDiv(MaxValue
, V
, APInt::Rounding::UP
);
213 Upper
= APIntOps::RoundingSDiv(MinValue
, V
, APInt::Rounding::DOWN
);
215 Lower
= APIntOps::RoundingSDiv(MinValue
, V
, APInt::Rounding::UP
);
216 Upper
= APIntOps::RoundingSDiv(MaxValue
, V
, APInt::Rounding::DOWN
);
218 // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1).
219 // Upper + 1 is guaranteed not to overflow, because |divisor| > 1. 0, -1,
220 // and 1 are already handled as special cases.
221 return ConstantRange(Lower
, Upper
+ 1);
225 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp
,
226 const ConstantRange
&Other
,
227 unsigned NoWrapKind
) {
228 using OBO
= OverflowingBinaryOperator
;
230 assert(Instruction::isBinaryOp(BinOp
) && "Binary operators only!");
232 assert((NoWrapKind
== OBO::NoSignedWrap
||
233 NoWrapKind
== OBO::NoUnsignedWrap
) &&
234 "NoWrapKind invalid!");
236 bool Unsigned
= NoWrapKind
== OBO::NoUnsignedWrap
;
237 unsigned BitWidth
= Other
.getBitWidth();
241 llvm_unreachable("Unsupported binary op");
243 case Instruction::Add
: {
245 return getNonEmpty(APInt::getNullValue(BitWidth
),
246 -Other
.getUnsignedMax());
248 APInt SignedMinVal
= APInt::getSignedMinValue(BitWidth
);
249 APInt SMin
= Other
.getSignedMin(), SMax
= Other
.getSignedMax();
251 SMin
.isNegative() ? SignedMinVal
- SMin
: SignedMinVal
,
252 SMax
.isStrictlyPositive() ? SignedMinVal
- SMax
: SignedMinVal
);
255 case Instruction::Sub
: {
257 return getNonEmpty(Other
.getUnsignedMax(), APInt::getMinValue(BitWidth
));
259 APInt SignedMinVal
= APInt::getSignedMinValue(BitWidth
);
260 APInt SMin
= Other
.getSignedMin(), SMax
= Other
.getSignedMax();
262 SMax
.isStrictlyPositive() ? SignedMinVal
+ SMax
: SignedMinVal
,
263 SMin
.isNegative() ? SignedMinVal
+ SMin
: SignedMinVal
);
266 case Instruction::Mul
:
268 return makeExactMulNUWRegion(Other
.getUnsignedMax());
270 return makeExactMulNSWRegion(Other
.getSignedMin())
271 .intersectWith(makeExactMulNSWRegion(Other
.getSignedMax()));
275 ConstantRange
ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp
,
277 unsigned NoWrapKind
) {
278 // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
279 // "for all" and "for any" coincide in this case.
280 return makeGuaranteedNoWrapRegion(BinOp
, ConstantRange(Other
), NoWrapKind
);
283 bool ConstantRange::isFullSet() const {
284 return Lower
== Upper
&& Lower
.isMaxValue();
287 bool ConstantRange::isEmptySet() const {
288 return Lower
== Upper
&& Lower
.isMinValue();
291 bool ConstantRange::isWrappedSet() const {
292 return Lower
.ugt(Upper
) && !Upper
.isNullValue();
295 bool ConstantRange::isUpperWrapped() const {
296 return Lower
.ugt(Upper
);
299 bool ConstantRange::isSignWrappedSet() const {
300 return Lower
.sgt(Upper
) && !Upper
.isMinSignedValue();
303 bool ConstantRange::isUpperSignWrapped() const {
304 return Lower
.sgt(Upper
);
308 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange
&Other
) const {
309 assert(getBitWidth() == Other
.getBitWidth());
312 if (Other
.isFullSet())
314 return (Upper
- Lower
).ult(Other
.Upper
- Other
.Lower
);
318 ConstantRange::isSizeLargerThan(uint64_t MaxSize
) const {
319 assert(MaxSize
&& "MaxSize can't be 0.");
320 // If this a full set, we need special handling to avoid needing an extra bit
321 // to represent the size.
323 return APInt::getMaxValue(getBitWidth()).ugt(MaxSize
- 1);
325 return (Upper
- Lower
).ugt(MaxSize
);
328 bool ConstantRange::isAllNegative() const {
329 // Empty set is all negative, full set is not.
335 return !isUpperSignWrapped() && !Upper
.isStrictlyPositive();
338 bool ConstantRange::isAllNonNegative() const {
339 // Empty and full set are automatically treated correctly.
340 return !isSignWrappedSet() && Lower
.isNonNegative();
343 APInt
ConstantRange::getUnsignedMax() const {
344 if (isFullSet() || isUpperWrapped())
345 return APInt::getMaxValue(getBitWidth());
346 return getUpper() - 1;
349 APInt
ConstantRange::getUnsignedMin() const {
350 if (isFullSet() || isWrappedSet())
351 return APInt::getMinValue(getBitWidth());
355 APInt
ConstantRange::getSignedMax() const {
356 if (isFullSet() || isUpperSignWrapped())
357 return APInt::getSignedMaxValue(getBitWidth());
358 return getUpper() - 1;
361 APInt
ConstantRange::getSignedMin() const {
362 if (isFullSet() || isSignWrappedSet())
363 return APInt::getSignedMinValue(getBitWidth());
367 bool ConstantRange::contains(const APInt
&V
) const {
371 if (!isUpperWrapped())
372 return Lower
.ule(V
) && V
.ult(Upper
);
373 return Lower
.ule(V
) || V
.ult(Upper
);
376 bool ConstantRange::contains(const ConstantRange
&Other
) const {
377 if (isFullSet() || Other
.isEmptySet()) return true;
378 if (isEmptySet() || Other
.isFullSet()) return false;
380 if (!isUpperWrapped()) {
381 if (Other
.isUpperWrapped())
384 return Lower
.ule(Other
.getLower()) && Other
.getUpper().ule(Upper
);
387 if (!Other
.isUpperWrapped())
388 return Other
.getUpper().ule(Upper
) ||
389 Lower
.ule(Other
.getLower());
391 return Other
.getUpper().ule(Upper
) && Lower
.ule(Other
.getLower());
394 ConstantRange
ConstantRange::subtract(const APInt
&Val
) const {
395 assert(Val
.getBitWidth() == getBitWidth() && "Wrong bit width");
396 // If the set is empty or full, don't modify the endpoints.
399 return ConstantRange(Lower
- Val
, Upper
- Val
);
402 ConstantRange
ConstantRange::difference(const ConstantRange
&CR
) const {
403 return intersectWith(CR
.inverse());
406 static ConstantRange
getPreferredRange(
407 const ConstantRange
&CR1
, const ConstantRange
&CR2
,
408 ConstantRange::PreferredRangeType Type
) {
409 if (Type
== ConstantRange::Unsigned
) {
410 if (!CR1
.isWrappedSet() && CR2
.isWrappedSet())
412 if (CR1
.isWrappedSet() && !CR2
.isWrappedSet())
414 } else if (Type
== ConstantRange::Signed
) {
415 if (!CR1
.isSignWrappedSet() && CR2
.isSignWrappedSet())
417 if (CR1
.isSignWrappedSet() && !CR2
.isSignWrappedSet())
421 if (CR1
.isSizeStrictlySmallerThan(CR2
))
426 ConstantRange
ConstantRange::intersectWith(const ConstantRange
&CR
,
427 PreferredRangeType Type
) const {
428 assert(getBitWidth() == CR
.getBitWidth() &&
429 "ConstantRange types don't agree!");
431 // Handle common cases.
432 if ( isEmptySet() || CR
.isFullSet()) return *this;
433 if (CR
.isEmptySet() || isFullSet()) return CR
;
435 if (!isUpperWrapped() && CR
.isUpperWrapped())
436 return CR
.intersectWith(*this, Type
);
438 if (!isUpperWrapped() && !CR
.isUpperWrapped()) {
439 if (Lower
.ult(CR
.Lower
)) {
442 if (Upper
.ule(CR
.Lower
))
447 if (Upper
.ult(CR
.Upper
))
448 return ConstantRange(CR
.Lower
, Upper
);
456 if (Upper
.ult(CR
.Upper
))
461 if (Lower
.ult(CR
.Upper
))
462 return ConstantRange(Lower
, CR
.Upper
);
469 if (isUpperWrapped() && !CR
.isUpperWrapped()) {
470 if (CR
.Lower
.ult(Upper
)) {
471 // ------U L--- : this
473 if (CR
.Upper
.ult(Upper
))
476 // ------U L--- : this
478 if (CR
.Upper
.ule(Lower
))
479 return ConstantRange(CR
.Lower
, Upper
);
481 // ------U L--- : this
483 return getPreferredRange(*this, CR
, Type
);
485 if (CR
.Lower
.ult(Lower
)) {
488 if (CR
.Upper
.ule(Lower
))
493 return ConstantRange(Lower
, CR
.Upper
);
496 // --U L------ : this
501 if (CR
.Upper
.ult(Upper
)) {
502 // ------U L-- : this
504 if (CR
.Lower
.ult(Upper
))
505 return getPreferredRange(*this, CR
, Type
);
509 if (CR
.Lower
.ult(Lower
))
510 return ConstantRange(Lower
, CR
.Upper
);
512 // ----U L---- : this
516 if (CR
.Upper
.ule(Lower
)) {
519 if (CR
.Lower
.ult(Lower
))
524 return ConstantRange(CR
.Lower
, Upper
);
527 // --U L------ : this
529 return getPreferredRange(*this, CR
, Type
);
532 ConstantRange
ConstantRange::unionWith(const ConstantRange
&CR
,
533 PreferredRangeType Type
) const {
534 assert(getBitWidth() == CR
.getBitWidth() &&
535 "ConstantRange types don't agree!");
537 if ( isFullSet() || CR
.isEmptySet()) return *this;
538 if (CR
.isFullSet() || isEmptySet()) return CR
;
540 if (!isUpperWrapped() && CR
.isUpperWrapped())
541 return CR
.unionWith(*this, Type
);
543 if (!isUpperWrapped() && !CR
.isUpperWrapped()) {
544 // L---U and L---U : this
549 if (CR
.Upper
.ult(Lower
) || Upper
.ult(CR
.Lower
))
550 return getPreferredRange(
551 ConstantRange(Lower
, CR
.Upper
), ConstantRange(CR
.Lower
, Upper
), Type
);
553 APInt L
= CR
.Lower
.ult(Lower
) ? CR
.Lower
: Lower
;
554 APInt U
= (CR
.Upper
- 1).ugt(Upper
- 1) ? CR
.Upper
: Upper
;
556 if (L
.isNullValue() && U
.isNullValue())
559 return ConstantRange(std::move(L
), std::move(U
));
562 if (!CR
.isUpperWrapped()) {
563 // ------U L----- and ------U L----- : this
565 if (CR
.Upper
.ule(Upper
) || CR
.Lower
.uge(Lower
))
568 // ------U L----- : this
570 if (CR
.Lower
.ule(Upper
) && Lower
.ule(CR
.Upper
))
573 // ----U L---- : this
578 if (Upper
.ult(CR
.Lower
) && CR
.Upper
.ult(Lower
))
579 return getPreferredRange(
580 ConstantRange(Lower
, CR
.Upper
), ConstantRange(CR
.Lower
, Upper
), Type
);
582 // ----U L----- : this
584 if (Upper
.ult(CR
.Lower
) && Lower
.ule(CR
.Upper
))
585 return ConstantRange(CR
.Lower
, Upper
);
587 // ------U L---- : this
589 assert(CR
.Lower
.ule(Upper
) && CR
.Upper
.ult(Lower
) &&
590 "ConstantRange::unionWith missed a case with one range wrapped");
591 return ConstantRange(Lower
, CR
.Upper
);
594 // ------U L---- and ------U L---- : this
595 // -U L----------- and ------------U L : CR
596 if (CR
.Lower
.ule(Upper
) || Lower
.ule(CR
.Upper
))
599 APInt L
= CR
.Lower
.ult(Lower
) ? CR
.Lower
: Lower
;
600 APInt U
= CR
.Upper
.ugt(Upper
) ? CR
.Upper
: Upper
;
602 return ConstantRange(std::move(L
), std::move(U
));
605 ConstantRange
ConstantRange::castOp(Instruction::CastOps CastOp
,
606 uint32_t ResultBitWidth
) const {
609 llvm_unreachable("unsupported cast type");
610 case Instruction::Trunc
:
611 return truncate(ResultBitWidth
);
612 case Instruction::SExt
:
613 return signExtend(ResultBitWidth
);
614 case Instruction::ZExt
:
615 return zeroExtend(ResultBitWidth
);
616 case Instruction::BitCast
:
618 case Instruction::FPToUI
:
619 case Instruction::FPToSI
:
620 if (getBitWidth() == ResultBitWidth
)
624 case Instruction::UIToFP
: {
625 // TODO: use input range if available
626 auto BW
= getBitWidth();
627 APInt Min
= APInt::getMinValue(BW
).zextOrSelf(ResultBitWidth
);
628 APInt Max
= APInt::getMaxValue(BW
).zextOrSelf(ResultBitWidth
);
629 return ConstantRange(std::move(Min
), std::move(Max
));
631 case Instruction::SIToFP
: {
632 // TODO: use input range if available
633 auto BW
= getBitWidth();
634 APInt SMin
= APInt::getSignedMinValue(BW
).sextOrSelf(ResultBitWidth
);
635 APInt SMax
= APInt::getSignedMaxValue(BW
).sextOrSelf(ResultBitWidth
);
636 return ConstantRange(std::move(SMin
), std::move(SMax
));
638 case Instruction::FPTrunc
:
639 case Instruction::FPExt
:
640 case Instruction::IntToPtr
:
641 case Instruction::PtrToInt
:
642 case Instruction::AddrSpaceCast
:
643 // Conservatively return getFull set.
648 ConstantRange
ConstantRange::zeroExtend(uint32_t DstTySize
) const {
649 if (isEmptySet()) return getEmpty(DstTySize
);
651 unsigned SrcTySize
= getBitWidth();
652 assert(SrcTySize
< DstTySize
&& "Not a value extension");
653 if (isFullSet() || isUpperWrapped()) {
654 // Change into [0, 1 << src bit width)
655 APInt
LowerExt(DstTySize
, 0);
656 if (!Upper
) // special case: [X, 0) -- not really wrapping around
657 LowerExt
= Lower
.zext(DstTySize
);
658 return ConstantRange(std::move(LowerExt
),
659 APInt::getOneBitSet(DstTySize
, SrcTySize
));
662 return ConstantRange(Lower
.zext(DstTySize
), Upper
.zext(DstTySize
));
665 ConstantRange
ConstantRange::signExtend(uint32_t DstTySize
) const {
666 if (isEmptySet()) return getEmpty(DstTySize
);
668 unsigned SrcTySize
= getBitWidth();
669 assert(SrcTySize
< DstTySize
&& "Not a value extension");
671 // special case: [X, INT_MIN) -- not really wrapping around
672 if (Upper
.isMinSignedValue())
673 return ConstantRange(Lower
.sext(DstTySize
), Upper
.zext(DstTySize
));
675 if (isFullSet() || isSignWrappedSet()) {
676 return ConstantRange(APInt::getHighBitsSet(DstTySize
,DstTySize
-SrcTySize
+1),
677 APInt::getLowBitsSet(DstTySize
, SrcTySize
-1) + 1);
680 return ConstantRange(Lower
.sext(DstTySize
), Upper
.sext(DstTySize
));
683 ConstantRange
ConstantRange::truncate(uint32_t DstTySize
) const {
684 assert(getBitWidth() > DstTySize
&& "Not a value truncation");
686 return getEmpty(DstTySize
);
688 return getFull(DstTySize
);
690 APInt
LowerDiv(Lower
), UpperDiv(Upper
);
691 ConstantRange
Union(DstTySize
, /*isFullSet=*/false);
693 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
694 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
695 // then we do the union with [MaxValue, Upper)
696 if (isUpperWrapped()) {
697 // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
699 if (Upper
.getActiveBits() > DstTySize
||
700 Upper
.countTrailingOnes() == DstTySize
)
701 return getFull(DstTySize
);
703 Union
= ConstantRange(APInt::getMaxValue(DstTySize
),Upper
.trunc(DstTySize
));
704 UpperDiv
.setAllBits();
706 // Union covers the MaxValue case, so return if the remaining range is just
708 if (LowerDiv
== UpperDiv
)
712 // Chop off the most significant bits that are past the destination bitwidth.
713 if (LowerDiv
.getActiveBits() > DstTySize
) {
714 // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
715 APInt Adjust
= LowerDiv
& APInt::getBitsSetFrom(getBitWidth(), DstTySize
);
720 unsigned UpperDivWidth
= UpperDiv
.getActiveBits();
721 if (UpperDivWidth
<= DstTySize
)
722 return ConstantRange(LowerDiv
.trunc(DstTySize
),
723 UpperDiv
.trunc(DstTySize
)).unionWith(Union
);
725 // The truncated value wraps around. Check if we can do better than fullset.
726 if (UpperDivWidth
== DstTySize
+ 1) {
727 // Clear the MSB so that UpperDiv wraps around.
728 UpperDiv
.clearBit(DstTySize
);
729 if (UpperDiv
.ult(LowerDiv
))
730 return ConstantRange(LowerDiv
.trunc(DstTySize
),
731 UpperDiv
.trunc(DstTySize
)).unionWith(Union
);
734 return getFull(DstTySize
);
737 ConstantRange
ConstantRange::zextOrTrunc(uint32_t DstTySize
) const {
738 unsigned SrcTySize
= getBitWidth();
739 if (SrcTySize
> DstTySize
)
740 return truncate(DstTySize
);
741 if (SrcTySize
< DstTySize
)
742 return zeroExtend(DstTySize
);
746 ConstantRange
ConstantRange::sextOrTrunc(uint32_t DstTySize
) const {
747 unsigned SrcTySize
= getBitWidth();
748 if (SrcTySize
> DstTySize
)
749 return truncate(DstTySize
);
750 if (SrcTySize
< DstTySize
)
751 return signExtend(DstTySize
);
755 ConstantRange
ConstantRange::binaryOp(Instruction::BinaryOps BinOp
,
756 const ConstantRange
&Other
) const {
757 assert(Instruction::isBinaryOp(BinOp
) && "Binary operators only!");
760 case Instruction::Add
:
762 case Instruction::Sub
:
764 case Instruction::Mul
:
765 return multiply(Other
);
766 case Instruction::UDiv
:
768 case Instruction::SDiv
:
770 case Instruction::URem
:
772 case Instruction::SRem
:
774 case Instruction::Shl
:
776 case Instruction::LShr
:
778 case Instruction::AShr
:
780 case Instruction::And
:
781 return binaryAnd(Other
);
782 case Instruction::Or
:
783 return binaryOr(Other
);
784 // Note: floating point operations applied to abstract ranges are just
785 // ideal integer operations with a lossy representation
786 case Instruction::FAdd
:
788 case Instruction::FSub
:
790 case Instruction::FMul
:
791 return multiply(Other
);
793 // Conservatively return getFull set.
799 ConstantRange::add(const ConstantRange
&Other
) const {
800 if (isEmptySet() || Other
.isEmptySet())
802 if (isFullSet() || Other
.isFullSet())
805 APInt NewLower
= getLower() + Other
.getLower();
806 APInt NewUpper
= getUpper() + Other
.getUpper() - 1;
807 if (NewLower
== NewUpper
)
810 ConstantRange X
= ConstantRange(std::move(NewLower
), std::move(NewUpper
));
811 if (X
.isSizeStrictlySmallerThan(*this) ||
812 X
.isSizeStrictlySmallerThan(Other
))
813 // We've wrapped, therefore, full set.
818 ConstantRange
ConstantRange::addWithNoSignedWrap(const APInt
&Other
) const {
819 // Calculate the subset of this range such that "X + Other" is
820 // guaranteed not to wrap (overflow) for all X in this subset.
821 auto NSWRange
= ConstantRange::makeExactNoWrapRegion(
822 BinaryOperator::Add
, Other
, OverflowingBinaryOperator::NoSignedWrap
);
823 auto NSWConstrainedRange
= intersectWith(NSWRange
);
825 return NSWConstrainedRange
.add(ConstantRange(Other
));
829 ConstantRange::sub(const ConstantRange
&Other
) const {
830 if (isEmptySet() || Other
.isEmptySet())
832 if (isFullSet() || Other
.isFullSet())
835 APInt NewLower
= getLower() - Other
.getUpper() + 1;
836 APInt NewUpper
= getUpper() - Other
.getLower();
837 if (NewLower
== NewUpper
)
840 ConstantRange X
= ConstantRange(std::move(NewLower
), std::move(NewUpper
));
841 if (X
.isSizeStrictlySmallerThan(*this) ||
842 X
.isSizeStrictlySmallerThan(Other
))
843 // We've wrapped, therefore, full set.
849 ConstantRange::multiply(const ConstantRange
&Other
) const {
850 // TODO: If either operand is a single element and the multiply is known to
851 // be non-wrapping, round the result min and max value to the appropriate
852 // multiple of that element. If wrapping is possible, at least adjust the
853 // range according to the greatest power-of-two factor of the single element.
855 if (isEmptySet() || Other
.isEmptySet())
858 // Multiplication is signedness-independent. However different ranges can be
859 // obtained depending on how the input ranges are treated. These different
860 // ranges are all conservatively correct, but one might be better than the
861 // other. We calculate two ranges; one treating the inputs as unsigned
862 // and the other signed, then return the smallest of these ranges.
864 // Unsigned range first.
865 APInt this_min
= getUnsignedMin().zext(getBitWidth() * 2);
866 APInt this_max
= getUnsignedMax().zext(getBitWidth() * 2);
867 APInt Other_min
= Other
.getUnsignedMin().zext(getBitWidth() * 2);
868 APInt Other_max
= Other
.getUnsignedMax().zext(getBitWidth() * 2);
870 ConstantRange Result_zext
= ConstantRange(this_min
* Other_min
,
871 this_max
* Other_max
+ 1);
872 ConstantRange UR
= Result_zext
.truncate(getBitWidth());
874 // If the unsigned range doesn't wrap, and isn't negative then it's a range
875 // from one positive number to another which is as good as we can generate.
876 // In this case, skip the extra work of generating signed ranges which aren't
877 // going to be better than this range.
878 if (!UR
.isUpperWrapped() &&
879 (UR
.getUpper().isNonNegative() || UR
.getUpper().isMinSignedValue()))
882 // Now the signed range. Because we could be dealing with negative numbers
883 // here, the lower bound is the smallest of the cartesian product of the
884 // lower and upper ranges; for example:
885 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
886 // Similarly for the upper bound, swapping min for max.
888 this_min
= getSignedMin().sext(getBitWidth() * 2);
889 this_max
= getSignedMax().sext(getBitWidth() * 2);
890 Other_min
= Other
.getSignedMin().sext(getBitWidth() * 2);
891 Other_max
= Other
.getSignedMax().sext(getBitWidth() * 2);
893 auto L
= {this_min
* Other_min
, this_min
* Other_max
,
894 this_max
* Other_min
, this_max
* Other_max
};
895 auto Compare
= [](const APInt
&A
, const APInt
&B
) { return A
.slt(B
); };
896 ConstantRange
Result_sext(std::min(L
, Compare
), std::max(L
, Compare
) + 1);
897 ConstantRange SR
= Result_sext
.truncate(getBitWidth());
899 return UR
.isSizeStrictlySmallerThan(SR
) ? UR
: SR
;
903 ConstantRange::smax(const ConstantRange
&Other
) const {
904 // X smax Y is: range(smax(X_smin, Y_smin),
905 // smax(X_smax, Y_smax))
906 if (isEmptySet() || Other
.isEmptySet())
908 APInt NewL
= APIntOps::smax(getSignedMin(), Other
.getSignedMin());
909 APInt NewU
= APIntOps::smax(getSignedMax(), Other
.getSignedMax()) + 1;
910 return getNonEmpty(std::move(NewL
), std::move(NewU
));
914 ConstantRange::umax(const ConstantRange
&Other
) const {
915 // X umax Y is: range(umax(X_umin, Y_umin),
916 // umax(X_umax, Y_umax))
917 if (isEmptySet() || Other
.isEmptySet())
919 APInt NewL
= APIntOps::umax(getUnsignedMin(), Other
.getUnsignedMin());
920 APInt NewU
= APIntOps::umax(getUnsignedMax(), Other
.getUnsignedMax()) + 1;
921 return getNonEmpty(std::move(NewL
), std::move(NewU
));
925 ConstantRange::smin(const ConstantRange
&Other
) const {
926 // X smin Y is: range(smin(X_smin, Y_smin),
927 // smin(X_smax, Y_smax))
928 if (isEmptySet() || Other
.isEmptySet())
930 APInt NewL
= APIntOps::smin(getSignedMin(), Other
.getSignedMin());
931 APInt NewU
= APIntOps::smin(getSignedMax(), Other
.getSignedMax()) + 1;
932 return getNonEmpty(std::move(NewL
), std::move(NewU
));
936 ConstantRange::umin(const ConstantRange
&Other
) const {
937 // X umin Y is: range(umin(X_umin, Y_umin),
938 // umin(X_umax, Y_umax))
939 if (isEmptySet() || Other
.isEmptySet())
941 APInt NewL
= APIntOps::umin(getUnsignedMin(), Other
.getUnsignedMin());
942 APInt NewU
= APIntOps::umin(getUnsignedMax(), Other
.getUnsignedMax()) + 1;
943 return getNonEmpty(std::move(NewL
), std::move(NewU
));
947 ConstantRange::udiv(const ConstantRange
&RHS
) const {
948 if (isEmptySet() || RHS
.isEmptySet() || RHS
.getUnsignedMax().isNullValue())
951 APInt Lower
= getUnsignedMin().udiv(RHS
.getUnsignedMax());
953 APInt RHS_umin
= RHS
.getUnsignedMin();
954 if (RHS_umin
.isNullValue()) {
955 // We want the lowest value in RHS excluding zero. Usually that would be 1
956 // except for a range in the form of [X, 1) in which case it would be X.
957 if (RHS
.getUpper() == 1)
958 RHS_umin
= RHS
.getLower();
963 APInt Upper
= getUnsignedMax().udiv(RHS_umin
) + 1;
964 return getNonEmpty(std::move(Lower
), std::move(Upper
));
967 ConstantRange
ConstantRange::sdiv(const ConstantRange
&RHS
) const {
968 // We split up the LHS and RHS into positive and negative components
969 // and then also compute the positive and negative components of the result
970 // separately by combining division results with the appropriate signs.
971 APInt Zero
= APInt::getNullValue(getBitWidth());
972 APInt SignedMin
= APInt::getSignedMinValue(getBitWidth());
973 ConstantRange
PosFilter(APInt(getBitWidth(), 1), SignedMin
);
974 ConstantRange
NegFilter(SignedMin
, Zero
);
975 ConstantRange PosL
= intersectWith(PosFilter
);
976 ConstantRange NegL
= intersectWith(NegFilter
);
977 ConstantRange PosR
= RHS
.intersectWith(PosFilter
);
978 ConstantRange NegR
= RHS
.intersectWith(NegFilter
);
980 ConstantRange PosRes
= getEmpty();
981 if (!PosL
.isEmptySet() && !PosR
.isEmptySet())
983 PosRes
= ConstantRange(PosL
.Lower
.sdiv(PosR
.Upper
- 1),
984 (PosL
.Upper
- 1).sdiv(PosR
.Lower
) + 1);
986 if (!NegL
.isEmptySet() && !NegR
.isEmptySet()) {
989 // We need to deal with one tricky case here: SignedMin / -1 is UB on the
990 // IR level, so we'll want to exclude this case when calculating bounds.
991 // (For APInts the operation is well-defined and yields SignedMin.) We
992 // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
993 APInt Lo
= (NegL
.Upper
- 1).sdiv(NegR
.Lower
);
994 if (NegL
.Lower
.isMinSignedValue() && NegR
.Upper
.isNullValue()) {
995 // Remove -1 from the LHS. Skip if it's the only element, as this would
996 // leave us with an empty set.
997 if (!NegR
.Lower
.isAllOnesValue()) {
999 if (RHS
.Lower
.isAllOnesValue())
1000 // Negative part of [-1, X] without -1 is [SignedMin, X].
1001 AdjNegRUpper
= RHS
.Upper
;
1003 // [X, -1] without -1 is [X, -2].
1004 AdjNegRUpper
= NegR
.Upper
- 1;
1006 PosRes
= PosRes
.unionWith(
1007 ConstantRange(Lo
, NegL
.Lower
.sdiv(AdjNegRUpper
- 1) + 1));
1010 // Remove SignedMin from the RHS. Skip if it's the only element, as this
1011 // would leave us with an empty set.
1012 if (NegL
.Upper
!= SignedMin
+ 1) {
1014 if (Upper
== SignedMin
+ 1)
1015 // Negative part of [X, SignedMin] without SignedMin is [X, -1].
1016 AdjNegLLower
= Lower
;
1018 // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
1019 AdjNegLLower
= NegL
.Lower
+ 1;
1021 PosRes
= PosRes
.unionWith(
1022 ConstantRange(std::move(Lo
),
1023 AdjNegLLower
.sdiv(NegR
.Upper
- 1) + 1));
1026 PosRes
= PosRes
.unionWith(
1027 ConstantRange(std::move(Lo
), NegL
.Lower
.sdiv(NegR
.Upper
- 1) + 1));
1031 ConstantRange NegRes
= getEmpty();
1032 if (!PosL
.isEmptySet() && !NegR
.isEmptySet())
1034 NegRes
= ConstantRange((PosL
.Upper
- 1).sdiv(NegR
.Upper
- 1),
1035 PosL
.Lower
.sdiv(NegR
.Lower
) + 1);
1037 if (!NegL
.isEmptySet() && !PosR
.isEmptySet())
1039 NegRes
= NegRes
.unionWith(
1040 ConstantRange(NegL
.Lower
.sdiv(PosR
.Lower
),
1041 (NegL
.Upper
- 1).sdiv(PosR
.Upper
- 1) + 1));
1043 // Prefer a non-wrapping signed range here.
1044 ConstantRange Res
= NegRes
.unionWith(PosRes
, PreferredRangeType::Signed
);
1046 // Preserve the zero that we dropped when splitting the LHS by sign.
1047 if (contains(Zero
) && (!PosR
.isEmptySet() || !NegR
.isEmptySet()))
1048 Res
= Res
.unionWith(ConstantRange(Zero
));
1052 ConstantRange
ConstantRange::urem(const ConstantRange
&RHS
) const {
1053 if (isEmptySet() || RHS
.isEmptySet() || RHS
.getUnsignedMax().isNullValue())
1056 // L % R for L < R is L.
1057 if (getUnsignedMax().ult(RHS
.getUnsignedMin()))
1060 // L % R is <= L and < R.
1061 APInt Upper
= APIntOps::umin(getUnsignedMax(), RHS
.getUnsignedMax() - 1) + 1;
1062 return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(Upper
));
1065 ConstantRange
ConstantRange::srem(const ConstantRange
&RHS
) const {
1066 if (isEmptySet() || RHS
.isEmptySet())
1069 ConstantRange AbsRHS
= RHS
.abs();
1070 APInt MinAbsRHS
= AbsRHS
.getUnsignedMin();
1071 APInt MaxAbsRHS
= AbsRHS
.getUnsignedMax();
1073 // Modulus by zero is UB.
1074 if (MaxAbsRHS
.isNullValue())
1077 if (MinAbsRHS
.isNullValue())
1080 APInt MinLHS
= getSignedMin(), MaxLHS
= getSignedMax();
1082 if (MinLHS
.isNonNegative()) {
1083 // L % R for L < R is L.
1084 if (MaxLHS
.ult(MinAbsRHS
))
1087 // L % R is <= L and < R.
1088 APInt Upper
= APIntOps::umin(MaxLHS
, MaxAbsRHS
- 1) + 1;
1089 return ConstantRange(APInt::getNullValue(getBitWidth()), std::move(Upper
));
1092 // Same basic logic as above, but the result is negative.
1093 if (MaxLHS
.isNegative()) {
1094 if (MinLHS
.ugt(-MinAbsRHS
))
1097 APInt Lower
= APIntOps::umax(MinLHS
, -MaxAbsRHS
+ 1);
1098 return ConstantRange(std::move(Lower
), APInt(getBitWidth(), 1));
1101 // LHS range crosses zero.
1102 APInt Lower
= APIntOps::umax(MinLHS
, -MaxAbsRHS
+ 1);
1103 APInt Upper
= APIntOps::umin(MaxLHS
, MaxAbsRHS
- 1) + 1;
1104 return ConstantRange(std::move(Lower
), std::move(Upper
));
1108 ConstantRange::binaryAnd(const ConstantRange
&Other
) const {
1109 if (isEmptySet() || Other
.isEmptySet())
1112 // TODO: replace this with something less conservative
1114 APInt umin
= APIntOps::umin(Other
.getUnsignedMax(), getUnsignedMax());
1115 return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(umin
) + 1);
1119 ConstantRange::binaryOr(const ConstantRange
&Other
) const {
1120 if (isEmptySet() || Other
.isEmptySet())
1123 // TODO: replace this with something less conservative
1125 APInt umax
= APIntOps::umax(getUnsignedMin(), Other
.getUnsignedMin());
1126 return getNonEmpty(std::move(umax
), APInt::getNullValue(getBitWidth()));
1130 ConstantRange::shl(const ConstantRange
&Other
) const {
1131 if (isEmptySet() || Other
.isEmptySet())
1134 APInt max
= getUnsignedMax();
1135 APInt Other_umax
= Other
.getUnsignedMax();
1137 // If we are shifting by maximum amount of
1138 // zero return return the original range.
1139 if (Other_umax
.isNullValue())
1141 // there's overflow!
1142 if (Other_umax
.ugt(max
.countLeadingZeros()))
1145 // FIXME: implement the other tricky cases
1147 APInt min
= getUnsignedMin();
1148 min
<<= Other
.getUnsignedMin();
1151 return ConstantRange(std::move(min
), std::move(max
) + 1);
1155 ConstantRange::lshr(const ConstantRange
&Other
) const {
1156 if (isEmptySet() || Other
.isEmptySet())
1159 APInt max
= getUnsignedMax().lshr(Other
.getUnsignedMin()) + 1;
1160 APInt min
= getUnsignedMin().lshr(Other
.getUnsignedMax());
1161 return getNonEmpty(std::move(min
), std::move(max
));
1165 ConstantRange::ashr(const ConstantRange
&Other
) const {
1166 if (isEmptySet() || Other
.isEmptySet())
1169 // May straddle zero, so handle both positive and negative cases.
1170 // 'PosMax' is the upper bound of the result of the ashr
1171 // operation, when Upper of the LHS of ashr is a non-negative.
1172 // number. Since ashr of a non-negative number will result in a
1173 // smaller number, the Upper value of LHS is shifted right with
1174 // the minimum value of 'Other' instead of the maximum value.
1175 APInt PosMax
= getSignedMax().ashr(Other
.getUnsignedMin()) + 1;
1177 // 'PosMin' is the lower bound of the result of the ashr
1178 // operation, when Lower of the LHS is a non-negative number.
1179 // Since ashr of a non-negative number will result in a smaller
1180 // number, the Lower value of LHS is shifted right with the
1181 // maximum value of 'Other'.
1182 APInt PosMin
= getSignedMin().ashr(Other
.getUnsignedMax());
1184 // 'NegMax' is the upper bound of the result of the ashr
1185 // operation, when Upper of the LHS of ashr is a negative number.
1186 // Since 'ashr' of a negative number will result in a bigger
1187 // number, the Upper value of LHS is shifted right with the
1188 // maximum value of 'Other'.
1189 APInt NegMax
= getSignedMax().ashr(Other
.getUnsignedMax()) + 1;
1191 // 'NegMin' is the lower bound of the result of the ashr
1192 // operation, when Lower of the LHS of ashr is a negative number.
1193 // Since 'ashr' of a negative number will result in a bigger
1194 // number, the Lower value of LHS is shifted right with the
1195 // minimum value of 'Other'.
1196 APInt NegMin
= getSignedMin().ashr(Other
.getUnsignedMin());
1199 if (getSignedMin().isNonNegative()) {
1200 // Upper and Lower of LHS are non-negative.
1203 } else if (getSignedMax().isNegative()) {
1204 // Upper and Lower of LHS are negative.
1208 // Upper is non-negative and Lower is negative.
1212 return getNonEmpty(std::move(min
), std::move(max
));
1215 ConstantRange
ConstantRange::uadd_sat(const ConstantRange
&Other
) const {
1216 if (isEmptySet() || Other
.isEmptySet())
1219 APInt NewL
= getUnsignedMin().uadd_sat(Other
.getUnsignedMin());
1220 APInt NewU
= getUnsignedMax().uadd_sat(Other
.getUnsignedMax()) + 1;
1221 return getNonEmpty(std::move(NewL
), std::move(NewU
));
1224 ConstantRange
ConstantRange::sadd_sat(const ConstantRange
&Other
) const {
1225 if (isEmptySet() || Other
.isEmptySet())
1228 APInt NewL
= getSignedMin().sadd_sat(Other
.getSignedMin());
1229 APInt NewU
= getSignedMax().sadd_sat(Other
.getSignedMax()) + 1;
1230 return getNonEmpty(std::move(NewL
), std::move(NewU
));
1233 ConstantRange
ConstantRange::usub_sat(const ConstantRange
&Other
) const {
1234 if (isEmptySet() || Other
.isEmptySet())
1237 APInt NewL
= getUnsignedMin().usub_sat(Other
.getUnsignedMax());
1238 APInt NewU
= getUnsignedMax().usub_sat(Other
.getUnsignedMin()) + 1;
1239 return getNonEmpty(std::move(NewL
), std::move(NewU
));
1242 ConstantRange
ConstantRange::ssub_sat(const ConstantRange
&Other
) const {
1243 if (isEmptySet() || Other
.isEmptySet())
1246 APInt NewL
= getSignedMin().ssub_sat(Other
.getSignedMax());
1247 APInt NewU
= getSignedMax().ssub_sat(Other
.getSignedMin()) + 1;
1248 return getNonEmpty(std::move(NewL
), std::move(NewU
));
1251 ConstantRange
ConstantRange::inverse() const {
1256 return ConstantRange(Upper
, Lower
);
1259 ConstantRange
ConstantRange::abs() const {
1263 if (isSignWrappedSet()) {
1265 // Check whether the range crosses zero.
1266 if (Upper
.isStrictlyPositive() || !Lower
.isStrictlyPositive())
1267 Lo
= APInt::getNullValue(getBitWidth());
1269 Lo
= APIntOps::umin(Lower
, -Upper
+ 1);
1271 // SignedMin is included in the result range.
1272 return ConstantRange(Lo
, APInt::getSignedMinValue(getBitWidth()) + 1);
1275 APInt SMin
= getSignedMin(), SMax
= getSignedMax();
1277 // All non-negative.
1278 if (SMin
.isNonNegative())
1282 if (SMax
.isNegative())
1283 return ConstantRange(-SMax
, -SMin
+ 1);
1285 // Range crosses zero.
1286 return ConstantRange(APInt::getNullValue(getBitWidth()),
1287 APIntOps::umax(-SMin
, SMax
) + 1);
1290 ConstantRange::OverflowResult
ConstantRange::unsignedAddMayOverflow(
1291 const ConstantRange
&Other
) const {
1292 if (isEmptySet() || Other
.isEmptySet())
1293 return OverflowResult::MayOverflow
;
1295 APInt Min
= getUnsignedMin(), Max
= getUnsignedMax();
1296 APInt OtherMin
= Other
.getUnsignedMin(), OtherMax
= Other
.getUnsignedMax();
1298 // a u+ b overflows high iff a u> ~b.
1299 if (Min
.ugt(~OtherMin
))
1300 return OverflowResult::AlwaysOverflowsHigh
;
1301 if (Max
.ugt(~OtherMax
))
1302 return OverflowResult::MayOverflow
;
1303 return OverflowResult::NeverOverflows
;
1306 ConstantRange::OverflowResult
ConstantRange::signedAddMayOverflow(
1307 const ConstantRange
&Other
) const {
1308 if (isEmptySet() || Other
.isEmptySet())
1309 return OverflowResult::MayOverflow
;
1311 APInt Min
= getSignedMin(), Max
= getSignedMax();
1312 APInt OtherMin
= Other
.getSignedMin(), OtherMax
= Other
.getSignedMax();
1314 APInt SignedMin
= APInt::getSignedMinValue(getBitWidth());
1315 APInt SignedMax
= APInt::getSignedMaxValue(getBitWidth());
1317 // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
1318 // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
1319 if (Min
.isNonNegative() && OtherMin
.isNonNegative() &&
1320 Min
.sgt(SignedMax
- OtherMin
))
1321 return OverflowResult::AlwaysOverflowsHigh
;
1322 if (Max
.isNegative() && OtherMax
.isNegative() &&
1323 Max
.slt(SignedMin
- OtherMax
))
1324 return OverflowResult::AlwaysOverflowsLow
;
1326 if (Max
.isNonNegative() && OtherMax
.isNonNegative() &&
1327 Max
.sgt(SignedMax
- OtherMax
))
1328 return OverflowResult::MayOverflow
;
1329 if (Min
.isNegative() && OtherMin
.isNegative() &&
1330 Min
.slt(SignedMin
- OtherMin
))
1331 return OverflowResult::MayOverflow
;
1333 return OverflowResult::NeverOverflows
;
1336 ConstantRange::OverflowResult
ConstantRange::unsignedSubMayOverflow(
1337 const ConstantRange
&Other
) const {
1338 if (isEmptySet() || Other
.isEmptySet())
1339 return OverflowResult::MayOverflow
;
1341 APInt Min
= getUnsignedMin(), Max
= getUnsignedMax();
1342 APInt OtherMin
= Other
.getUnsignedMin(), OtherMax
= Other
.getUnsignedMax();
1344 // a u- b overflows low iff a u< b.
1345 if (Max
.ult(OtherMin
))
1346 return OverflowResult::AlwaysOverflowsLow
;
1347 if (Min
.ult(OtherMax
))
1348 return OverflowResult::MayOverflow
;
1349 return OverflowResult::NeverOverflows
;
1352 ConstantRange::OverflowResult
ConstantRange::signedSubMayOverflow(
1353 const ConstantRange
&Other
) const {
1354 if (isEmptySet() || Other
.isEmptySet())
1355 return OverflowResult::MayOverflow
;
1357 APInt Min
= getSignedMin(), Max
= getSignedMax();
1358 APInt OtherMin
= Other
.getSignedMin(), OtherMax
= Other
.getSignedMax();
1360 APInt SignedMin
= APInt::getSignedMinValue(getBitWidth());
1361 APInt SignedMax
= APInt::getSignedMaxValue(getBitWidth());
1363 // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
1364 // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
1365 if (Min
.isNonNegative() && OtherMax
.isNegative() &&
1366 Min
.sgt(SignedMax
+ OtherMax
))
1367 return OverflowResult::AlwaysOverflowsHigh
;
1368 if (Max
.isNegative() && OtherMin
.isNonNegative() &&
1369 Max
.slt(SignedMin
+ OtherMin
))
1370 return OverflowResult::AlwaysOverflowsLow
;
1372 if (Max
.isNonNegative() && OtherMin
.isNegative() &&
1373 Max
.sgt(SignedMax
+ OtherMin
))
1374 return OverflowResult::MayOverflow
;
1375 if (Min
.isNegative() && OtherMax
.isNonNegative() &&
1376 Min
.slt(SignedMin
+ OtherMax
))
1377 return OverflowResult::MayOverflow
;
1379 return OverflowResult::NeverOverflows
;
1382 ConstantRange::OverflowResult
ConstantRange::unsignedMulMayOverflow(
1383 const ConstantRange
&Other
) const {
1384 if (isEmptySet() || Other
.isEmptySet())
1385 return OverflowResult::MayOverflow
;
1387 APInt Min
= getUnsignedMin(), Max
= getUnsignedMax();
1388 APInt OtherMin
= Other
.getUnsignedMin(), OtherMax
= Other
.getUnsignedMax();
1391 (void) Min
.umul_ov(OtherMin
, Overflow
);
1393 return OverflowResult::AlwaysOverflowsHigh
;
1395 (void) Max
.umul_ov(OtherMax
, Overflow
);
1397 return OverflowResult::MayOverflow
;
1399 return OverflowResult::NeverOverflows
;
1402 void ConstantRange::print(raw_ostream
&OS
) const {
1405 else if (isEmptySet())
1408 OS
<< "[" << Lower
<< "," << Upper
<< ")";
1411 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1412 LLVM_DUMP_METHOD
void ConstantRange::dump() const {
1417 ConstantRange
llvm::getConstantRangeFromMetadata(const MDNode
&Ranges
) {
1418 const unsigned NumRanges
= Ranges
.getNumOperands() / 2;
1419 assert(NumRanges
>= 1 && "Must have at least one range!");
1420 assert(Ranges
.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
1422 auto *FirstLow
= mdconst::extract
<ConstantInt
>(Ranges
.getOperand(0));
1423 auto *FirstHigh
= mdconst::extract
<ConstantInt
>(Ranges
.getOperand(1));
1425 ConstantRange
CR(FirstLow
->getValue(), FirstHigh
->getValue());
1427 for (unsigned i
= 1; i
< NumRanges
; ++i
) {
1428 auto *Low
= mdconst::extract
<ConstantInt
>(Ranges
.getOperand(2 * i
+ 0));
1429 auto *High
= mdconst::extract
<ConstantInt
>(Ranges
.getOperand(2 * i
+ 1));
1431 // Note: unionWith will potentially create a range that contains values not
1432 // contained in any of the original N ranges.
1433 CR
= CR
.unionWith(ConstantRange(Low
->getValue(), High
->getValue()));