LLVM 20.0.0git
ConstantRange.cpp
Go to the documentation of this file.
1//===- ConstantRange.cpp - ConstantRange implementation -------------------===//
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// 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):
15//
16// [F, F) = {} = Empty set
17// [T, F) = {T}
18// [F, T) = {F}
19// [T, T) = {F, T} = Full set
20//
21//===----------------------------------------------------------------------===//
22
24#include "llvm/ADT/APInt.h"
25#include "llvm/Config/llvm-config.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/IR/Operator.h"
34#include "llvm/Support/Debug.h"
38#include <algorithm>
39#include <cassert>
40#include <cstdint>
41#include <optional>
42
43using namespace llvm;
44
46 : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
47 Upper(Lower) {}
48
50 : Lower(std::move(V)), Upper(Lower + 1) {}
51
53 : Lower(std::move(L)), Upper(std::move(U)) {
54 assert(Lower.getBitWidth() == Upper.getBitWidth() &&
55 "ConstantRange with unequal bit widths");
56 assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
57 "Lower == Upper, but they aren't min or max value!");
58}
59
61 bool IsSigned) {
62 if (Known.hasConflict())
63 return getEmpty(Known.getBitWidth());
64 if (Known.isUnknown())
65 return getFull(Known.getBitWidth());
66
67 // For unsigned ranges, or signed ranges with known sign bit, create a simple
68 // range between the smallest and largest possible value.
69 if (!IsSigned || Known.isNegative() || Known.isNonNegative())
70 return ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1);
71
72 // If we don't know the sign bit, pick the lower bound as a negative number
73 // and the upper bound as a non-negative one.
74 APInt Lower = Known.getMinValue(), Upper = Known.getMaxValue();
75 Lower.setSignBit();
76 Upper.clearSignBit();
77 return ConstantRange(Lower, Upper + 1);
78}
79
81 // TODO: We could return conflicting known bits here, but consumers are
82 // likely not prepared for that.
83 if (isEmptySet())
84 return KnownBits(getBitWidth());
85
86 // We can only retain the top bits that are the same between min and max.
87 APInt Min = getUnsignedMin();
88 APInt Max = getUnsignedMax();
90 if (std::optional<unsigned> DifferentBit =
92 Known.Zero.clearLowBits(*DifferentBit + 1);
93 Known.One.clearLowBits(*DifferentBit + 1);
94 }
95 return Known;
96}
97
99 const ConstantRange &CR) {
100 if (CR.isEmptySet())
101 return CR;
102
103 uint32_t W = CR.getBitWidth();
104 switch (Pred) {
105 default:
106 llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
107 case CmpInst::ICMP_EQ:
108 return CR;
109 case CmpInst::ICMP_NE:
110 if (CR.isSingleElement())
111 return ConstantRange(CR.getUpper(), CR.getLower());
112 return getFull(W);
113 case CmpInst::ICMP_ULT: {
115 if (UMax.isMinValue())
116 return getEmpty(W);
117 return ConstantRange(APInt::getMinValue(W), std::move(UMax));
118 }
119 case CmpInst::ICMP_SLT: {
120 APInt SMax(CR.getSignedMax());
121 if (SMax.isMinSignedValue())
122 return getEmpty(W);
123 return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
124 }
126 return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
129 case CmpInst::ICMP_UGT: {
131 if (UMin.isMaxValue())
132 return getEmpty(W);
133 return ConstantRange(std::move(UMin) + 1, APInt::getZero(W));
134 }
135 case CmpInst::ICMP_SGT: {
136 APInt SMin(CR.getSignedMin());
137 if (SMin.isMaxSignedValue())
138 return getEmpty(W);
139 return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
140 }
145 }
146}
147
149 const ConstantRange &CR) {
150 // Follows from De-Morgan's laws:
151 //
152 // ~(~A union ~B) == A intersect B.
153 //
155 .inverse();
156}
157
159 const APInt &C) {
160 // Computes the exact range that is equal to both the constant ranges returned
161 // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
162 // when RHS is a singleton such as an APInt and so the assert is valid.
163 // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
164 // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
165 //
167 return makeAllowedICmpRegion(Pred, C);
168}
169
171 const ConstantRange &CR1, const ConstantRange &CR2) {
172 if (CR1.isEmptySet() || CR2.isEmptySet())
173 return true;
174
175 return (CR1.isAllNonNegative() && CR2.isAllNonNegative()) ||
176 (CR1.isAllNegative() && CR2.isAllNegative());
177}
178
180 const ConstantRange &CR1, const ConstantRange &CR2) {
181 if (CR1.isEmptySet() || CR2.isEmptySet())
182 return true;
183
184 return (CR1.isAllNonNegative() && CR2.isAllNegative()) ||
185 (CR1.isAllNegative() && CR2.isAllNonNegative());
186}
187
189 CmpInst::Predicate Pred, const ConstantRange &CR1,
190 const ConstantRange &CR2) {
192 "Only for relational integer predicates!");
193
194 CmpInst::Predicate FlippedSignednessPred =
196
198 return FlippedSignednessPred;
199
201 return CmpInst::getInversePredicate(FlippedSignednessPred);
202
204}
205
207 APInt &RHS, APInt &Offset) const {
208 Offset = APInt(getBitWidth(), 0);
209 if (isFullSet() || isEmptySet()) {
211 RHS = APInt(getBitWidth(), 0);
212 } else if (auto *OnlyElt = getSingleElement()) {
213 Pred = CmpInst::ICMP_EQ;
214 RHS = *OnlyElt;
215 } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
216 Pred = CmpInst::ICMP_NE;
217 RHS = *OnlyMissingElt;
218 } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
219 Pred =
221 RHS = getUpper();
222 } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
223 Pred =
225 RHS = getLower();
226 } else {
227 Pred = CmpInst::ICMP_ULT;
228 RHS = getUpper() - getLower();
229 Offset = -getLower();
230 }
231
233 "Bad result!");
234}
235
237 APInt &RHS) const {
240 return Offset.isZero();
241}
242
244 const ConstantRange &Other) const {
245 if (isEmptySet() || Other.isEmptySet())
246 return true;
247
248 switch (Pred) {
249 case CmpInst::ICMP_EQ:
250 if (const APInt *L = getSingleElement())
251 if (const APInt *R = Other.getSingleElement())
252 return *L == *R;
253 return false;
254 case CmpInst::ICMP_NE:
255 return inverse().contains(Other);
257 return getUnsignedMax().ult(Other.getUnsignedMin());
259 return getUnsignedMax().ule(Other.getUnsignedMin());
261 return getUnsignedMin().ugt(Other.getUnsignedMax());
263 return getUnsignedMin().uge(Other.getUnsignedMax());
265 return getSignedMax().slt(Other.getSignedMin());
267 return getSignedMax().sle(Other.getSignedMin());
269 return getSignedMin().sgt(Other.getSignedMax());
271 return getSignedMin().sge(Other.getSignedMax());
272 default:
273 llvm_unreachable("Invalid ICmp predicate");
274 }
275}
276
277/// Exact mul nuw region for single element RHS.
279 unsigned BitWidth = V.getBitWidth();
280 if (V == 0)
281 return ConstantRange::getFull(V.getBitWidth());
282
288}
289
290/// Exact mul nsw region for single element RHS.
292 // Handle 0 and -1 separately to avoid division by zero or overflow.
293 unsigned BitWidth = V.getBitWidth();
294 if (V == 0)
295 return ConstantRange::getFull(BitWidth);
296
299 // e.g. Returning [-127, 127], represented as [-127, -128).
300 if (V.isAllOnes())
301 return ConstantRange(-MaxValue, MinValue);
302
304 if (V.isNegative()) {
307 } else {
310 }
312}
313
316 const ConstantRange &Other,
317 unsigned NoWrapKind) {
318 using OBO = OverflowingBinaryOperator;
319
320 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
321
322 assert((NoWrapKind == OBO::NoSignedWrap ||
323 NoWrapKind == OBO::NoUnsignedWrap) &&
324 "NoWrapKind invalid!");
325
326 bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
327 unsigned BitWidth = Other.getBitWidth();
328
329 switch (BinOp) {
330 default:
331 llvm_unreachable("Unsupported binary op");
332
333 case Instruction::Add: {
334 if (Unsigned)
335 return getNonEmpty(APInt::getZero(BitWidth), -Other.getUnsignedMax());
336
338 APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
339 return getNonEmpty(
340 SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,
341 SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);
342 }
343
344 case Instruction::Sub: {
345 if (Unsigned)
346 return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth));
347
349 APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
350 return getNonEmpty(
351 SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,
352 SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);
353 }
354
355 case Instruction::Mul:
356 if (Unsigned)
357 return makeExactMulNUWRegion(Other.getUnsignedMax());
358
359 // Avoid one makeExactMulNSWRegion() call for the common case of constants.
360 if (const APInt *C = Other.getSingleElement())
361 return makeExactMulNSWRegion(*C);
362
363 return makeExactMulNSWRegion(Other.getSignedMin())
364 .intersectWith(makeExactMulNSWRegion(Other.getSignedMax()));
365
366 case Instruction::Shl: {
367 // For given range of shift amounts, if we ignore all illegal shift amounts
368 // (that always produce poison), what shift amount range is left?
369 ConstantRange ShAmt = Other.intersectWith(
371 if (ShAmt.isEmptySet()) {
372 // If the entire range of shift amounts is already poison-producing,
373 // then we can freely add more poison-producing flags ontop of that.
374 return getFull(BitWidth);
375 }
376 // There are some legal shift amounts, we can compute conservatively-correct
377 // range of no-wrap inputs. Note that by now we have clamped the ShAmtUMax
378 // to be at most bitwidth-1, which results in most conservative range.
379 APInt ShAmtUMax = ShAmt.getUnsignedMax();
380 if (Unsigned)
382 APInt::getMaxValue(BitWidth).lshr(ShAmtUMax) + 1);
384 APInt::getSignedMaxValue(BitWidth).ashr(ShAmtUMax) + 1);
385 }
386 }
387}
388
390 const APInt &Other,
391 unsigned NoWrapKind) {
392 // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
393 // "for all" and "for any" coincide in this case.
394 return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);
395}
396
398 const APInt &C) {
399 unsigned BitWidth = Mask.getBitWidth();
400
401 if ((Mask & C) != C)
402 return getFull(BitWidth);
403
404 if (Mask.isZero())
405 return getEmpty(BitWidth);
406
407 // If (Val & Mask) != C, constrained to the non-equality being
408 // satisfiable, then the value must be larger than the lowest set bit of
409 // Mask, offset by constant C.
411 APInt::getOneBitSet(BitWidth, Mask.countr_zero()) + C, C);
412}
413
415 return Lower == Upper && Lower.isMaxValue();
416}
417
419 return Lower == Upper && Lower.isMinValue();
420}
421
423 return Lower.ugt(Upper) && !Upper.isZero();
424}
425
427 return Lower.ugt(Upper);
428}
429
431 return Lower.sgt(Upper) && !Upper.isMinSignedValue();
432}
433
435 return Lower.sgt(Upper);
436}
437
438bool
440 assert(getBitWidth() == Other.getBitWidth());
441 if (isFullSet())
442 return false;
443 if (Other.isFullSet())
444 return true;
445 return (Upper - Lower).ult(Other.Upper - Other.Lower);
446}
447
448bool
450 // If this a full set, we need special handling to avoid needing an extra bit
451 // to represent the size.
452 if (isFullSet())
453 return MaxSize == 0 || APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
454
455 return (Upper - Lower).ugt(MaxSize);
456}
457
459 // Empty set is all negative, full set is not.
460 if (isEmptySet())
461 return true;
462 if (isFullSet())
463 return false;
464
465 return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
466}
467
469 // Empty and full set are automatically treated correctly.
470 return !isSignWrappedSet() && Lower.isNonNegative();
471}
472
474 // Empty set is all positive, full set is not.
475 if (isEmptySet())
476 return true;
477 if (isFullSet())
478 return false;
479
480 return !isSignWrappedSet() && Lower.isStrictlyPositive();
481}
482
484 if (isFullSet() || isUpperWrapped())
486 return getUpper() - 1;
487}
488
490 if (isFullSet() || isWrappedSet())
492 return getLower();
493}
494
496 if (isFullSet() || isUpperSignWrapped())
498 return getUpper() - 1;
499}
500
502 if (isFullSet() || isSignWrappedSet())
504 return getLower();
505}
506
507bool ConstantRange::contains(const APInt &V) const {
508 if (Lower == Upper)
509 return isFullSet();
510
511 if (!isUpperWrapped())
512 return Lower.ule(V) && V.ult(Upper);
513 return Lower.ule(V) || V.ult(Upper);
514}
515
517 if (isFullSet() || Other.isEmptySet()) return true;
518 if (isEmptySet() || Other.isFullSet()) return false;
519
520 if (!isUpperWrapped()) {
521 if (Other.isUpperWrapped())
522 return false;
523
524 return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
525 }
526
527 if (!Other.isUpperWrapped())
528 return Other.getUpper().ule(Upper) ||
529 Lower.ule(Other.getLower());
530
531 return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
532}
533
535 if (isEmptySet())
536 return 0;
537
538 return getUnsignedMax().getActiveBits();
539}
540
542 if (isEmptySet())
543 return 0;
544
545 return std::max(getSignedMin().getSignificantBits(),
546 getSignedMax().getSignificantBits());
547}
548
550 assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
551 // If the set is empty or full, don't modify the endpoints.
552 if (Lower == Upper)
553 return *this;
554 return ConstantRange(Lower - Val, Upper - Val);
555}
556
558 return intersectWith(CR.inverse());
559}
560
562 const ConstantRange &CR1, const ConstantRange &CR2,
565 if (!CR1.isWrappedSet() && CR2.isWrappedSet())
566 return CR1;
567 if (CR1.isWrappedSet() && !CR2.isWrappedSet())
568 return CR2;
569 } else if (Type == ConstantRange::Signed) {
570 if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
571 return CR1;
572 if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
573 return CR2;
574 }
575
576 if (CR1.isSizeStrictlySmallerThan(CR2))
577 return CR1;
578 return CR2;
579}
580
582 PreferredRangeType Type) const {
583 assert(getBitWidth() == CR.getBitWidth() &&
584 "ConstantRange types don't agree!");
585
586 // Handle common cases.
587 if ( isEmptySet() || CR.isFullSet()) return *this;
588 if (CR.isEmptySet() || isFullSet()) return CR;
589
590 if (!isUpperWrapped() && CR.isUpperWrapped())
591 return CR.intersectWith(*this, Type);
592
593 if (!isUpperWrapped() && !CR.isUpperWrapped()) {
594 if (Lower.ult(CR.Lower)) {
595 // L---U : this
596 // L---U : CR
597 if (Upper.ule(CR.Lower))
598 return getEmpty();
599
600 // L---U : this
601 // L---U : CR
602 if (Upper.ult(CR.Upper))
603 return ConstantRange(CR.Lower, Upper);
604
605 // L-------U : this
606 // L---U : CR
607 return CR;
608 }
609 // L---U : this
610 // L-------U : CR
611 if (Upper.ult(CR.Upper))
612 return *this;
613
614 // L-----U : this
615 // L-----U : CR
616 if (Lower.ult(CR.Upper))
617 return ConstantRange(Lower, CR.Upper);
618
619 // L---U : this
620 // L---U : CR
621 return getEmpty();
622 }
623
624 if (isUpperWrapped() && !CR.isUpperWrapped()) {
625 if (CR.Lower.ult(Upper)) {
626 // ------U L--- : this
627 // L--U : CR
628 if (CR.Upper.ult(Upper))
629 return CR;
630
631 // ------U L--- : this
632 // L------U : CR
633 if (CR.Upper.ule(Lower))
634 return ConstantRange(CR.Lower, Upper);
635
636 // ------U L--- : this
637 // L----------U : CR
638 return getPreferredRange(*this, CR, Type);
639 }
640 if (CR.Lower.ult(Lower)) {
641 // --U L---- : this
642 // L--U : CR
643 if (CR.Upper.ule(Lower))
644 return getEmpty();
645
646 // --U L---- : this
647 // L------U : CR
648 return ConstantRange(Lower, CR.Upper);
649 }
650
651 // --U L------ : this
652 // L--U : CR
653 return CR;
654 }
655
656 if (CR.Upper.ult(Upper)) {
657 // ------U L-- : this
658 // --U L------ : CR
659 if (CR.Lower.ult(Upper))
660 return getPreferredRange(*this, CR, Type);
661
662 // ----U L-- : this
663 // --U L---- : CR
664 if (CR.Lower.ult(Lower))
665 return ConstantRange(Lower, CR.Upper);
666
667 // ----U L---- : this
668 // --U L-- : CR
669 return CR;
670 }
671 if (CR.Upper.ule(Lower)) {
672 // --U L-- : this
673 // ----U L---- : CR
674 if (CR.Lower.ult(Lower))
675 return *this;
676
677 // --U L---- : this
678 // ----U L-- : CR
679 return ConstantRange(CR.Lower, Upper);
680 }
681
682 // --U L------ : this
683 // ------U L-- : CR
684 return getPreferredRange(*this, CR, Type);
685}
686
688 PreferredRangeType Type) const {
689 assert(getBitWidth() == CR.getBitWidth() &&
690 "ConstantRange types don't agree!");
691
692 if ( isFullSet() || CR.isEmptySet()) return *this;
693 if (CR.isFullSet() || isEmptySet()) return CR;
694
695 if (!isUpperWrapped() && CR.isUpperWrapped())
696 return CR.unionWith(*this, Type);
697
698 if (!isUpperWrapped() && !CR.isUpperWrapped()) {
699 // L---U and L---U : this
700 // L---U L---U : CR
701 // result in one of
702 // L---------U
703 // -----U L-----
704 if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
705 return getPreferredRange(
706 ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
707
708 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
709 APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
710
711 if (L.isZero() && U.isZero())
712 return getFull();
713
714 return ConstantRange(std::move(L), std::move(U));
715 }
716
717 if (!CR.isUpperWrapped()) {
718 // ------U L----- and ------U L----- : this
719 // L--U L--U : CR
720 if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
721 return *this;
722
723 // ------U L----- : this
724 // L---------U : CR
725 if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
726 return getFull();
727
728 // ----U L---- : this
729 // L---U : CR
730 // results in one of
731 // ----------U L----
732 // ----U L----------
733 if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
734 return getPreferredRange(
735 ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
736
737 // ----U L----- : this
738 // L----U : CR
739 if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
740 return ConstantRange(CR.Lower, Upper);
741
742 // ------U L---- : this
743 // L-----U : CR
744 assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
745 "ConstantRange::unionWith missed a case with one range wrapped");
746 return ConstantRange(Lower, CR.Upper);
747 }
748
749 // ------U L---- and ------U L---- : this
750 // -U L----------- and ------------U L : CR
751 if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
752 return getFull();
753
754 APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
755 APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
756
757 return ConstantRange(std::move(L), std::move(U));
758}
759
760std::optional<ConstantRange>
762 // TODO: This can be implemented more efficiently.
763 ConstantRange Result = intersectWith(CR);
764 if (Result == inverse().unionWith(CR.inverse()).inverse())
765 return Result;
766 return std::nullopt;
767}
768
769std::optional<ConstantRange>
771 // TODO: This can be implemented more efficiently.
772 ConstantRange Result = unionWith(CR);
773 if (Result == inverse().intersectWith(CR.inverse()).inverse())
774 return Result;
775 return std::nullopt;
776}
777
779 uint32_t ResultBitWidth) const {
780 switch (CastOp) {
781 default:
782 llvm_unreachable("unsupported cast type");
783 case Instruction::Trunc:
784 return truncate(ResultBitWidth);
785 case Instruction::SExt:
786 return signExtend(ResultBitWidth);
787 case Instruction::ZExt:
788 return zeroExtend(ResultBitWidth);
789 case Instruction::BitCast:
790 return *this;
791 case Instruction::FPToUI:
792 case Instruction::FPToSI:
793 if (getBitWidth() == ResultBitWidth)
794 return *this;
795 else
796 return getFull(ResultBitWidth);
797 case Instruction::UIToFP: {
798 // TODO: use input range if available
799 auto BW = getBitWidth();
800 APInt Min = APInt::getMinValue(BW);
801 APInt Max = APInt::getMaxValue(BW);
802 if (ResultBitWidth > BW) {
803 Min = Min.zext(ResultBitWidth);
804 Max = Max.zext(ResultBitWidth);
805 }
806 return getNonEmpty(std::move(Min), std::move(Max) + 1);
807 }
808 case Instruction::SIToFP: {
809 // TODO: use input range if available
810 auto BW = getBitWidth();
813 if (ResultBitWidth > BW) {
814 SMin = SMin.sext(ResultBitWidth);
815 SMax = SMax.sext(ResultBitWidth);
816 }
817 return getNonEmpty(std::move(SMin), std::move(SMax) + 1);
818 }
819 case Instruction::FPTrunc:
820 case Instruction::FPExt:
821 case Instruction::IntToPtr:
822 case Instruction::PtrToInt:
823 case Instruction::AddrSpaceCast:
824 // Conservatively return getFull set.
825 return getFull(ResultBitWidth);
826 };
827}
828
830 if (isEmptySet()) return getEmpty(DstTySize);
831
832 unsigned SrcTySize = getBitWidth();
833 assert(SrcTySize < DstTySize && "Not a value extension");
834 if (isFullSet() || isUpperWrapped()) {
835 // Change into [0, 1 << src bit width)
836 APInt LowerExt(DstTySize, 0);
837 if (!Upper) // special case: [X, 0) -- not really wrapping around
838 LowerExt = Lower.zext(DstTySize);
839 return ConstantRange(std::move(LowerExt),
840 APInt::getOneBitSet(DstTySize, SrcTySize));
841 }
842
843 return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
844}
845
847 if (isEmptySet()) return getEmpty(DstTySize);
848
849 unsigned SrcTySize = getBitWidth();
850 assert(SrcTySize < DstTySize && "Not a value extension");
851
852 // special case: [X, INT_MIN) -- not really wrapping around
853 if (Upper.isMinSignedValue())
854 return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
855
856 if (isFullSet() || isSignWrappedSet()) {
857 return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
858 APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
859 }
860
861 return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
862}
863
865 assert(getBitWidth() > DstTySize && "Not a value truncation");
866 if (isEmptySet())
867 return getEmpty(DstTySize);
868 if (isFullSet())
869 return getFull(DstTySize);
870
871 APInt LowerDiv(Lower), UpperDiv(Upper);
872 ConstantRange Union(DstTySize, /*isFullSet=*/false);
873
874 // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
875 // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
876 // then we do the union with [MaxValue, Upper)
877 if (isUpperWrapped()) {
878 // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
879 // truncated range.
880 if (Upper.getActiveBits() > DstTySize || Upper.countr_one() == DstTySize)
881 return getFull(DstTySize);
882
883 Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
884 UpperDiv.setAllBits();
885
886 // Union covers the MaxValue case, so return if the remaining range is just
887 // MaxValue(DstTy).
888 if (LowerDiv == UpperDiv)
889 return Union;
890 }
891
892 // Chop off the most significant bits that are past the destination bitwidth.
893 if (LowerDiv.getActiveBits() > DstTySize) {
894 // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
895 APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
896 LowerDiv -= Adjust;
897 UpperDiv -= Adjust;
898 }
899
900 unsigned UpperDivWidth = UpperDiv.getActiveBits();
901 if (UpperDivWidth <= DstTySize)
902 return ConstantRange(LowerDiv.trunc(DstTySize),
903 UpperDiv.trunc(DstTySize)).unionWith(Union);
904
905 // The truncated value wraps around. Check if we can do better than fullset.
906 if (UpperDivWidth == DstTySize + 1) {
907 // Clear the MSB so that UpperDiv wraps around.
908 UpperDiv.clearBit(DstTySize);
909 if (UpperDiv.ult(LowerDiv))
910 return ConstantRange(LowerDiv.trunc(DstTySize),
911 UpperDiv.trunc(DstTySize)).unionWith(Union);
912 }
913
914 return getFull(DstTySize);
915}
916
918 unsigned SrcTySize = getBitWidth();
919 if (SrcTySize > DstTySize)
920 return truncate(DstTySize);
921 if (SrcTySize < DstTySize)
922 return zeroExtend(DstTySize);
923 return *this;
924}
925
927 unsigned SrcTySize = getBitWidth();
928 if (SrcTySize > DstTySize)
929 return truncate(DstTySize);
930 if (SrcTySize < DstTySize)
931 return signExtend(DstTySize);
932 return *this;
933}
934
936 const ConstantRange &Other) const {
937 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
938
939 switch (BinOp) {
940 case Instruction::Add:
941 return add(Other);
942 case Instruction::Sub:
943 return sub(Other);
944 case Instruction::Mul:
945 return multiply(Other);
946 case Instruction::UDiv:
947 return udiv(Other);
948 case Instruction::SDiv:
949 return sdiv(Other);
950 case Instruction::URem:
951 return urem(Other);
952 case Instruction::SRem:
953 return srem(Other);
954 case Instruction::Shl:
955 return shl(Other);
956 case Instruction::LShr:
957 return lshr(Other);
958 case Instruction::AShr:
959 return ashr(Other);
960 case Instruction::And:
961 return binaryAnd(Other);
962 case Instruction::Or:
963 return binaryOr(Other);
964 case Instruction::Xor:
965 return binaryXor(Other);
966 // Note: floating point operations applied to abstract ranges are just
967 // ideal integer operations with a lossy representation
968 case Instruction::FAdd:
969 return add(Other);
970 case Instruction::FSub:
971 return sub(Other);
972 case Instruction::FMul:
973 return multiply(Other);
974 default:
975 // Conservatively return getFull set.
976 return getFull();
977 }
978}
979
981 const ConstantRange &Other,
982 unsigned NoWrapKind) const {
983 assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
984
985 switch (BinOp) {
986 case Instruction::Add:
987 return addWithNoWrap(Other, NoWrapKind);
988 case Instruction::Sub:
989 return subWithNoWrap(Other, NoWrapKind);
990 case Instruction::Mul:
991 return multiplyWithNoWrap(Other, NoWrapKind);
992 case Instruction::Shl:
993 return shlWithNoWrap(Other, NoWrapKind);
994 default:
995 // Don't know about this Overflowing Binary Operation.
996 // Conservatively fallback to plain binop handling.
997 return binaryOp(BinOp, Other);
998 }
999}
1000
1002 switch (IntrinsicID) {
1003 case Intrinsic::uadd_sat:
1004 case Intrinsic::usub_sat:
1005 case Intrinsic::sadd_sat:
1006 case Intrinsic::ssub_sat:
1007 case Intrinsic::umin:
1008 case Intrinsic::umax:
1009 case Intrinsic::smin:
1010 case Intrinsic::smax:
1011 case Intrinsic::abs:
1012 case Intrinsic::ctlz:
1013 case Intrinsic::cttz:
1014 case Intrinsic::ctpop:
1015 return true;
1016 default:
1017 return false;
1018 }
1019}
1020
1023 switch (IntrinsicID) {
1024 case Intrinsic::uadd_sat:
1025 return Ops[0].uadd_sat(Ops[1]);
1026 case Intrinsic::usub_sat:
1027 return Ops[0].usub_sat(Ops[1]);
1028 case Intrinsic::sadd_sat:
1029 return Ops[0].sadd_sat(Ops[1]);
1030 case Intrinsic::ssub_sat:
1031 return Ops[0].ssub_sat(Ops[1]);
1032 case Intrinsic::umin:
1033 return Ops[0].umin(Ops[1]);
1034 case Intrinsic::umax:
1035 return Ops[0].umax(Ops[1]);
1036 case Intrinsic::smin:
1037 return Ops[0].smin(Ops[1]);
1038 case Intrinsic::smax:
1039 return Ops[0].smax(Ops[1]);
1040 case Intrinsic::abs: {
1041 const APInt *IntMinIsPoison = Ops[1].getSingleElement();
1042 assert(IntMinIsPoison && "Must be known (immarg)");
1043 assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean");
1044 return Ops[0].abs(IntMinIsPoison->getBoolValue());
1045 }
1046 case Intrinsic::ctlz: {
1047 const APInt *ZeroIsPoison = Ops[1].getSingleElement();
1048 assert(ZeroIsPoison && "Must be known (immarg)");
1049 assert(ZeroIsPoison->getBitWidth() == 1 && "Must be boolean");
1050 return Ops[0].ctlz(ZeroIsPoison->getBoolValue());
1051 }
1052 case Intrinsic::cttz: {
1053 const APInt *ZeroIsPoison = Ops[1].getSingleElement();
1054 assert(ZeroIsPoison && "Must be known (immarg)");
1055 assert(ZeroIsPoison->getBitWidth() == 1 && "Must be boolean");
1056 return Ops[0].cttz(ZeroIsPoison->getBoolValue());
1057 }
1058 case Intrinsic::ctpop:
1059 return Ops[0].ctpop();
1060 default:
1061 assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported");
1062 llvm_unreachable("Unsupported intrinsic");
1063 }
1064}
1065
1068 if (isEmptySet() || Other.isEmptySet())
1069 return getEmpty();
1070 if (isFullSet() || Other.isFullSet())
1071 return getFull();
1072
1073 APInt NewLower = getLower() + Other.getLower();
1074 APInt NewUpper = getUpper() + Other.getUpper() - 1;
1075 if (NewLower == NewUpper)
1076 return getFull();
1077
1078 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
1079 if (X.isSizeStrictlySmallerThan(*this) ||
1080 X.isSizeStrictlySmallerThan(Other))
1081 // We've wrapped, therefore, full set.
1082 return getFull();
1083 return X;
1084}
1085
1087 unsigned NoWrapKind,
1088 PreferredRangeType RangeType) const {
1089 // Calculate the range for "X + Y" which is guaranteed not to wrap(overflow).
1090 // (X is from this, and Y is from Other)
1091 if (isEmptySet() || Other.isEmptySet())
1092 return getEmpty();
1093 if (isFullSet() && Other.isFullSet())
1094 return getFull();
1095
1096 using OBO = OverflowingBinaryOperator;
1097 ConstantRange Result = add(Other);
1098
1099 // If an overflow happens for every value pair in these two constant ranges,
1100 // we must return Empty set. In this case, we get that for free, because we
1101 // get lucky that intersection of add() with uadd_sat()/sadd_sat() results
1102 // in an empty set.
1103
1104 if (NoWrapKind & OBO::NoSignedWrap)
1105 Result = Result.intersectWith(sadd_sat(Other), RangeType);
1106
1107 if (NoWrapKind & OBO::NoUnsignedWrap)
1108 Result = Result.intersectWith(uadd_sat(Other), RangeType);
1109
1110 return Result;
1111}
1112
1115 if (isEmptySet() || Other.isEmptySet())
1116 return getEmpty();
1117 if (isFullSet() || Other.isFullSet())
1118 return getFull();
1119
1120 APInt NewLower = getLower() - Other.getUpper() + 1;
1121 APInt NewUpper = getUpper() - Other.getLower();
1122 if (NewLower == NewUpper)
1123 return getFull();
1124
1125 ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
1126 if (X.isSizeStrictlySmallerThan(*this) ||
1127 X.isSizeStrictlySmallerThan(Other))
1128 // We've wrapped, therefore, full set.
1129 return getFull();
1130 return X;
1131}
1132
1134 unsigned NoWrapKind,
1135 PreferredRangeType RangeType) const {
1136 // Calculate the range for "X - Y" which is guaranteed not to wrap(overflow).
1137 // (X is from this, and Y is from Other)
1138 if (isEmptySet() || Other.isEmptySet())
1139 return getEmpty();
1140 if (isFullSet() && Other.isFullSet())
1141 return getFull();
1142
1143 using OBO = OverflowingBinaryOperator;
1144 ConstantRange Result = sub(Other);
1145
1146 // If an overflow happens for every value pair in these two constant ranges,
1147 // we must return Empty set. In signed case, we get that for free, because we
1148 // get lucky that intersection of sub() with ssub_sat() results in an
1149 // empty set. But for unsigned we must perform the overflow check manually.
1150
1151 if (NoWrapKind & OBO::NoSignedWrap)
1152 Result = Result.intersectWith(ssub_sat(Other), RangeType);
1153
1154 if (NoWrapKind & OBO::NoUnsignedWrap) {
1155 if (getUnsignedMax().ult(Other.getUnsignedMin()))
1156 return getEmpty(); // Always overflows.
1157 Result = Result.intersectWith(usub_sat(Other), RangeType);
1158 }
1159
1160 return Result;
1161}
1162
1165 // TODO: If either operand is a single element and the multiply is known to
1166 // be non-wrapping, round the result min and max value to the appropriate
1167 // multiple of that element. If wrapping is possible, at least adjust the
1168 // range according to the greatest power-of-two factor of the single element.
1169
1170 if (isEmptySet() || Other.isEmptySet())
1171 return getEmpty();
1172
1173 if (const APInt *C = getSingleElement()) {
1174 if (C->isOne())
1175 return Other;
1176 if (C->isAllOnes())
1178 }
1179
1180 if (const APInt *C = Other.getSingleElement()) {
1181 if (C->isOne())
1182 return *this;
1183 if (C->isAllOnes())
1184 return ConstantRange(APInt::getZero(getBitWidth())).sub(*this);
1185 }
1186
1187 // Multiplication is signedness-independent. However different ranges can be
1188 // obtained depending on how the input ranges are treated. These different
1189 // ranges are all conservatively correct, but one might be better than the
1190 // other. We calculate two ranges; one treating the inputs as unsigned
1191 // and the other signed, then return the smallest of these ranges.
1192
1193 // Unsigned range first.
1194 APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
1195 APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
1196 APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
1197 APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
1198
1199 ConstantRange Result_zext = ConstantRange(this_min * Other_min,
1200 this_max * Other_max + 1);
1201 ConstantRange UR = Result_zext.truncate(getBitWidth());
1202
1203 // If the unsigned range doesn't wrap, and isn't negative then it's a range
1204 // from one positive number to another which is as good as we can generate.
1205 // In this case, skip the extra work of generating signed ranges which aren't
1206 // going to be better than this range.
1207 if (!UR.isUpperWrapped() &&
1209 return UR;
1210
1211 // Now the signed range. Because we could be dealing with negative numbers
1212 // here, the lower bound is the smallest of the cartesian product of the
1213 // lower and upper ranges; for example:
1214 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1215 // Similarly for the upper bound, swapping min for max.
1216
1217 this_min = getSignedMin().sext(getBitWidth() * 2);
1218 this_max = getSignedMax().sext(getBitWidth() * 2);
1219 Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
1220 Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
1221
1222 auto L = {this_min * Other_min, this_min * Other_max,
1223 this_max * Other_min, this_max * Other_max};
1224 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1225 ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
1226 ConstantRange SR = Result_sext.truncate(getBitWidth());
1227
1228 return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
1229}
1230
1233 unsigned NoWrapKind,
1234 PreferredRangeType RangeType) const {
1235 if (isEmptySet() || Other.isEmptySet())
1236 return getEmpty();
1237 if (isFullSet() && Other.isFullSet())
1238 return getFull();
1239
1240 ConstantRange Result = multiply(Other);
1241
1243 Result = Result.intersectWith(smul_sat(Other), RangeType);
1244
1246 Result = Result.intersectWith(umul_sat(Other), RangeType);
1247
1248 // mul nsw nuw X, Y s>= 0 if X s> 1 or Y s> 1
1249 if ((NoWrapKind == (OverflowingBinaryOperator::NoSignedWrap |
1251 !Result.isAllNonNegative()) {
1252 if (getSignedMin().sgt(1) || Other.getSignedMin().sgt(1))
1253 Result = Result.intersectWith(
1256 RangeType);
1257 }
1258
1259 return Result;
1260}
1261
1263 if (isEmptySet() || Other.isEmptySet())
1264 return getEmpty();
1265
1266 APInt Min = getSignedMin();
1267 APInt Max = getSignedMax();
1268 APInt OtherMin = Other.getSignedMin();
1269 APInt OtherMax = Other.getSignedMax();
1270
1271 bool O1, O2, O3, O4;
1272 auto Muls = {Min.smul_ov(OtherMin, O1), Min.smul_ov(OtherMax, O2),
1273 Max.smul_ov(OtherMin, O3), Max.smul_ov(OtherMax, O4)};
1274 if (O1 || O2 || O3 || O4)
1275 return getFull();
1276
1277 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1278 return getNonEmpty(std::min(Muls, Compare), std::max(Muls, Compare) + 1);
1279}
1280
1283 // X smax Y is: range(smax(X_smin, Y_smin),
1284 // smax(X_smax, Y_smax))
1285 if (isEmptySet() || Other.isEmptySet())
1286 return getEmpty();
1287 APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
1288 APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
1289 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1290 if (isSignWrappedSet() || Other.isSignWrappedSet())
1291 return Res.intersectWith(unionWith(Other, Signed), Signed);
1292 return Res;
1293}
1294
1297 // X umax Y is: range(umax(X_umin, Y_umin),
1298 // umax(X_umax, Y_umax))
1299 if (isEmptySet() || Other.isEmptySet())
1300 return getEmpty();
1301 APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1302 APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1303 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1304 if (isWrappedSet() || Other.isWrappedSet())
1306 return Res;
1307}
1308
1311 // X smin Y is: range(smin(X_smin, Y_smin),
1312 // smin(X_smax, Y_smax))
1313 if (isEmptySet() || Other.isEmptySet())
1314 return getEmpty();
1315 APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
1316 APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
1317 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1318 if (isSignWrappedSet() || Other.isSignWrappedSet())
1319 return Res.intersectWith(unionWith(Other, Signed), Signed);
1320 return Res;
1321}
1322
1325 // X umin Y is: range(umin(X_umin, Y_umin),
1326 // umin(X_umax, Y_umax))
1327 if (isEmptySet() || Other.isEmptySet())
1328 return getEmpty();
1329 APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
1330 APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1331 ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1332 if (isWrappedSet() || Other.isWrappedSet())
1334 return Res;
1335}
1336
1339 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1340 return getEmpty();
1341
1342 APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
1343
1344 APInt RHS_umin = RHS.getUnsignedMin();
1345 if (RHS_umin.isZero()) {
1346 // We want the lowest value in RHS excluding zero. Usually that would be 1
1347 // except for a range in the form of [X, 1) in which case it would be X.
1348 if (RHS.getUpper() == 1)
1349 RHS_umin = RHS.getLower();
1350 else
1351 RHS_umin = 1;
1352 }
1353
1354 APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
1355 return getNonEmpty(std::move(Lower), std::move(Upper));
1356}
1357
1359 // We split up the LHS and RHS into positive and negative components
1360 // and then also compute the positive and negative components of the result
1361 // separately by combining division results with the appropriate signs.
1364 // There are no positive 1-bit values. The 1 would get interpreted as -1.
1365 ConstantRange PosFilter =
1366 getBitWidth() == 1 ? getEmpty()
1367 : ConstantRange(APInt(getBitWidth(), 1), SignedMin);
1368 ConstantRange NegFilter(SignedMin, Zero);
1369 ConstantRange PosL = intersectWith(PosFilter);
1370 ConstantRange NegL = intersectWith(NegFilter);
1371 ConstantRange PosR = RHS.intersectWith(PosFilter);
1372 ConstantRange NegR = RHS.intersectWith(NegFilter);
1373
1374 ConstantRange PosRes = getEmpty();
1375 if (!PosL.isEmptySet() && !PosR.isEmptySet())
1376 // pos / pos = pos.
1377 PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1),
1378 (PosL.Upper - 1).sdiv(PosR.Lower) + 1);
1379
1380 if (!NegL.isEmptySet() && !NegR.isEmptySet()) {
1381 // neg / neg = pos.
1382 //
1383 // We need to deal with one tricky case here: SignedMin / -1 is UB on the
1384 // IR level, so we'll want to exclude this case when calculating bounds.
1385 // (For APInts the operation is well-defined and yields SignedMin.) We
1386 // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
1387 APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower);
1388 if (NegL.Lower.isMinSignedValue() && NegR.Upper.isZero()) {
1389 // Remove -1 from the LHS. Skip if it's the only element, as this would
1390 // leave us with an empty set.
1391 if (!NegR.Lower.isAllOnes()) {
1392 APInt AdjNegRUpper;
1393 if (RHS.Lower.isAllOnes())
1394 // Negative part of [-1, X] without -1 is [SignedMin, X].
1395 AdjNegRUpper = RHS.Upper;
1396 else
1397 // [X, -1] without -1 is [X, -2].
1398 AdjNegRUpper = NegR.Upper - 1;
1399
1400 PosRes = PosRes.unionWith(
1401 ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1));
1402 }
1403
1404 // Remove SignedMin from the RHS. Skip if it's the only element, as this
1405 // would leave us with an empty set.
1406 if (NegL.Upper != SignedMin + 1) {
1407 APInt AdjNegLLower;
1408 if (Upper == SignedMin + 1)
1409 // Negative part of [X, SignedMin] without SignedMin is [X, -1].
1410 AdjNegLLower = Lower;
1411 else
1412 // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
1413 AdjNegLLower = NegL.Lower + 1;
1414
1415 PosRes = PosRes.unionWith(
1416 ConstantRange(std::move(Lo),
1417 AdjNegLLower.sdiv(NegR.Upper - 1) + 1));
1418 }
1419 } else {
1420 PosRes = PosRes.unionWith(
1421 ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1));
1422 }
1423 }
1424
1425 ConstantRange NegRes = getEmpty();
1426 if (!PosL.isEmptySet() && !NegR.isEmptySet())
1427 // pos / neg = neg.
1428 NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1),
1429 PosL.Lower.sdiv(NegR.Lower) + 1);
1430
1431 if (!NegL.isEmptySet() && !PosR.isEmptySet())
1432 // neg / pos = neg.
1433 NegRes = NegRes.unionWith(
1434 ConstantRange(NegL.Lower.sdiv(PosR.Lower),
1435 (NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1));
1436
1437 // Prefer a non-wrapping signed range here.
1439
1440 // Preserve the zero that we dropped when splitting the LHS by sign.
1441 if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))
1442 Res = Res.unionWith(ConstantRange(Zero));
1443 return Res;
1444}
1445
1447 if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1448 return getEmpty();
1449
1450 if (const APInt *RHSInt = RHS.getSingleElement()) {
1451 // UREM by null is UB.
1452 if (RHSInt->isZero())
1453 return getEmpty();
1454 // Use APInt's implementation of UREM for single element ranges.
1455 if (const APInt *LHSInt = getSingleElement())
1456 return {LHSInt->urem(*RHSInt)};
1457 }
1458
1459 // L % R for L < R is L.
1460 if (getUnsignedMax().ult(RHS.getUnsignedMin()))
1461 return *this;
1462
1463 // L % R is <= L and < R.
1464 APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
1465 return getNonEmpty(APInt::getZero(getBitWidth()), std::move(Upper));
1466}
1467
1469 if (isEmptySet() || RHS.isEmptySet())
1470 return getEmpty();
1471
1472 if (const APInt *RHSInt = RHS.getSingleElement()) {
1473 // SREM by null is UB.
1474 if (RHSInt->isZero())
1475 return getEmpty();
1476 // Use APInt's implementation of SREM for single element ranges.
1477 if (const APInt *LHSInt = getSingleElement())
1478 return {LHSInt->srem(*RHSInt)};
1479 }
1480
1481 ConstantRange AbsRHS = RHS.abs();
1482 APInt MinAbsRHS = AbsRHS.getUnsignedMin();
1483 APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
1484
1485 // Modulus by zero is UB.
1486 if (MaxAbsRHS.isZero())
1487 return getEmpty();
1488
1489 if (MinAbsRHS.isZero())
1490 ++MinAbsRHS;
1491
1492 APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
1493
1494 if (MinLHS.isNonNegative()) {
1495 // L % R for L < R is L.
1496 if (MaxLHS.ult(MinAbsRHS))
1497 return *this;
1498
1499 // L % R is <= L and < R.
1500 APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1501 return ConstantRange(APInt::getZero(getBitWidth()), std::move(Upper));
1502 }
1503
1504 // Same basic logic as above, but the result is negative.
1505 if (MaxLHS.isNegative()) {
1506 if (MinLHS.ugt(-MinAbsRHS))
1507 return *this;
1508
1509 APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1510 return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
1511 }
1512
1513 // LHS range crosses zero.
1514 APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1515 APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1516 return ConstantRange(std::move(Lower), std::move(Upper));
1517}
1518
1521}
1522
1523/// Estimate the 'bit-masked AND' operation's lower bound.
1524///
1525/// E.g., given two ranges as follows (single quotes are separators and
1526/// have no meaning here),
1527///
1528/// LHS = [10'00101'1, ; LLo
1529/// 10'10000'0] ; LHi
1530/// RHS = [10'11111'0, ; RLo
1531/// 10'11111'1] ; RHi
1532///
1533/// we know that the higher 2 bits of the result is always 10; and we also
1534/// notice that RHS[1:6] are always 1, so the result[1:6] cannot be less than
1535/// LHS[1:6] (i.e., 00101). Thus, the lower bound is 10'00101'0.
1536///
1537/// The algorithm is as follows,
1538/// 1. we first calculate a mask to find the higher common bits by
1539/// Mask = ~((LLo ^ LHi) | (RLo ^ RHi) | (LLo ^ RLo));
1540/// Mask = clear all non-leading-ones bits in Mask;
1541/// in the example, the Mask is set to 11'00000'0;
1542/// 2. calculate a new mask by setting all common leading bits to 1 in RHS, and
1543/// keeping the longest leading ones (i.e., 11'11111'0 in the example);
1544/// 3. return (LLo & new mask) as the lower bound;
1545/// 4. repeat the step 2 and 3 with LHS and RHS swapped, and update the lower
1546/// bound with the larger one.
1548 const ConstantRange &RHS) {
1549 auto BitWidth = LHS.getBitWidth();
1550 // If either is full set or unsigned wrapped, then the range must contain '0'
1551 // which leads the lower bound to 0.
1552 if ((LHS.isFullSet() || RHS.isFullSet()) ||
1553 (LHS.isWrappedSet() || RHS.isWrappedSet()))
1554 return APInt::getZero(BitWidth);
1555
1556 auto LLo = LHS.getLower();
1557 auto LHi = LHS.getUpper() - 1;
1558 auto RLo = RHS.getLower();
1559 auto RHi = RHS.getUpper() - 1;
1560
1561 // Calculate the mask for the higher common bits.
1562 auto Mask = ~((LLo ^ LHi) | (RLo ^ RHi) | (LLo ^ RLo));
1563 unsigned LeadingOnes = Mask.countLeadingOnes();
1564 Mask.clearLowBits(BitWidth - LeadingOnes);
1565
1566 auto estimateBound = [BitWidth, &Mask](APInt ALo, const APInt &BLo,
1567 const APInt &BHi) {
1568 unsigned LeadingOnes = ((BLo & BHi) | Mask).countLeadingOnes();
1569 unsigned StartBit = BitWidth - LeadingOnes;
1570 ALo.clearLowBits(StartBit);
1571 return ALo;
1572 };
1573
1574 auto LowerBoundByLHS = estimateBound(LLo, RLo, RHi);
1575 auto LowerBoundByRHS = estimateBound(RLo, LLo, LHi);
1576
1577 return APIntOps::umax(LowerBoundByLHS, LowerBoundByRHS);
1578}
1579
1581 if (isEmptySet() || Other.isEmptySet())
1582 return getEmpty();
1583
1584 ConstantRange KnownBitsRange =
1585 fromKnownBits(toKnownBits() & Other.toKnownBits(), false);
1586 auto LowerBound = estimateBitMaskedAndLowerBound(*this, Other);
1587 ConstantRange UMinUMaxRange = getNonEmpty(
1588 LowerBound, APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax()) + 1);
1589 return KnownBitsRange.intersectWith(UMinUMaxRange);
1590}
1591
1593 if (isEmptySet() || Other.isEmptySet())
1594 return getEmpty();
1595
1596 ConstantRange KnownBitsRange =
1597 fromKnownBits(toKnownBits() | Other.toKnownBits(), false);
1598
1599 // ~a & ~b >= x
1600 // <=> ~(~a & ~b) <= ~x
1601 // <=> a | b <= ~x
1602 // <=> a | b < ~x + 1 = -x
1603 // thus, UpperBound(a | b) == -LowerBound(~a & ~b)
1604 auto UpperBound =
1606 // Upper wrapped range.
1607 ConstantRange UMaxUMinRange = getNonEmpty(
1608 APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin()), UpperBound);
1609 return KnownBitsRange.intersectWith(UMaxUMinRange);
1610}
1611
1613 if (isEmptySet() || Other.isEmptySet())
1614 return getEmpty();
1615
1616 // Use APInt's implementation of XOR for single element ranges.
1617 if (isSingleElement() && Other.isSingleElement())
1618 return {*getSingleElement() ^ *Other.getSingleElement()};
1619
1620 // Special-case binary complement, since we can give a precise answer.
1621 if (Other.isSingleElement() && Other.getSingleElement()->isAllOnes())
1622 return binaryNot();
1623 if (isSingleElement() && getSingleElement()->isAllOnes())
1624 return Other.binaryNot();
1625
1626 KnownBits LHSKnown = toKnownBits();
1627 KnownBits RHSKnown = Other.toKnownBits();
1628 KnownBits Known = LHSKnown ^ RHSKnown;
1629 ConstantRange CR = fromKnownBits(Known, /*IsSigned*/ false);
1630 // Typically the following code doesn't improve the result if BW = 1.
1631 if (getBitWidth() == 1)
1632 return CR;
1633
1634 // If LHS is known to be the subset of RHS, treat LHS ^ RHS as RHS -nuw/nsw
1635 // LHS. If RHS is known to be the subset of LHS, treat LHS ^ RHS as LHS
1636 // -nuw/nsw RHS.
1637 if ((~LHSKnown.Zero).isSubsetOf(RHSKnown.One))
1639 else if ((~RHSKnown.Zero).isSubsetOf(LHSKnown.One))
1640 CR = CR.intersectWith(this->sub(Other), PreferredRangeType::Unsigned);
1641 return CR;
1642}
1643
1646 if (isEmptySet() || Other.isEmptySet())
1647 return getEmpty();
1648
1649 APInt Min = getUnsignedMin();
1650 APInt Max = getUnsignedMax();
1651 if (const APInt *RHS = Other.getSingleElement()) {
1652 unsigned BW = getBitWidth();
1653 if (RHS->uge(BW))
1654 return getEmpty();
1655
1656 unsigned EqualLeadingBits = (Min ^ Max).countl_zero();
1657 if (RHS->ule(EqualLeadingBits))
1658 return getNonEmpty(Min << *RHS, (Max << *RHS) + 1);
1659
1660 return getNonEmpty(APInt::getZero(BW),
1661 APInt::getBitsSetFrom(BW, RHS->getZExtValue()) + 1);
1662 }
1663
1664 APInt OtherMax = Other.getUnsignedMax();
1665 if (isAllNegative() && OtherMax.ule(Min.countl_one())) {
1666 // For negative numbers, if the shift does not overflow in a signed sense,
1667 // a larger shift will make the number smaller.
1668 Max <<= Other.getUnsignedMin();
1669 Min <<= OtherMax;
1670 return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);
1671 }
1672
1673 // There's overflow!
1674 if (OtherMax.ugt(Max.countl_zero()))
1675 return getFull();
1676
1677 // FIXME: implement the other tricky cases
1678
1679 Min <<= Other.getUnsignedMin();
1680 Max <<= OtherMax;
1681
1682 return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);
1683}
1684
1686 const ConstantRange &RHS) {
1687 unsigned BitWidth = LHS.getBitWidth();
1688 bool Overflow;
1689 APInt LHSMin = LHS.getUnsignedMin();
1690 unsigned RHSMin = RHS.getUnsignedMin().getLimitedValue(BitWidth);
1691 APInt MinShl = LHSMin.ushl_ov(RHSMin, Overflow);
1692 if (Overflow)
1693 return ConstantRange::getEmpty(BitWidth);
1694 APInt LHSMax = LHS.getUnsignedMax();
1695 unsigned RHSMax = RHS.getUnsignedMax().getLimitedValue(BitWidth);
1696 APInt MaxShl = MinShl;
1697 unsigned MaxShAmt = LHSMax.countLeadingZeros();
1698 if (RHSMin <= MaxShAmt)
1699 MaxShl = LHSMax << std::min(RHSMax, MaxShAmt);
1700 RHSMin = std::max(RHSMin, MaxShAmt + 1);
1701 RHSMax = std::min(RHSMax, LHSMin.countLeadingZeros());
1702 if (RHSMin <= RHSMax)
1703 MaxShl = APIntOps::umax(MaxShl,
1705 return ConstantRange::getNonEmpty(MinShl, MaxShl + 1);
1706}
1707
1709 const APInt &LHSMax,
1710 unsigned RHSMin,
1711 unsigned RHSMax) {
1712 unsigned BitWidth = LHSMin.getBitWidth();
1713 bool Overflow;
1714 APInt MinShl = LHSMin.sshl_ov(RHSMin, Overflow);
1715 if (Overflow)
1716 return ConstantRange::getEmpty(BitWidth);
1717 APInt MaxShl = MinShl;
1718 unsigned MaxShAmt = LHSMax.countLeadingZeros() - 1;
1719 if (RHSMin <= MaxShAmt)
1720 MaxShl = LHSMax << std::min(RHSMax, MaxShAmt);
1721 RHSMin = std::max(RHSMin, MaxShAmt + 1);
1722 RHSMax = std::min(RHSMax, LHSMin.countLeadingZeros() - 1);
1723 if (RHSMin <= RHSMax)
1724 MaxShl = APIntOps::umax(MaxShl,
1725 APInt::getBitsSet(BitWidth, RHSMin, BitWidth - 1));
1726 return ConstantRange::getNonEmpty(MinShl, MaxShl + 1);
1727}
1728
1730 const APInt &LHSMax,
1731 unsigned RHSMin, unsigned RHSMax) {
1732 unsigned BitWidth = LHSMin.getBitWidth();
1733 bool Overflow;
1734 APInt MaxShl = LHSMax.sshl_ov(RHSMin, Overflow);
1735 if (Overflow)
1736 return ConstantRange::getEmpty(BitWidth);
1737 APInt MinShl = MaxShl;
1738 unsigned MaxShAmt = LHSMin.countLeadingOnes() - 1;
1739 if (RHSMin <= MaxShAmt)
1740 MinShl = LHSMin.shl(std::min(RHSMax, MaxShAmt));
1741 RHSMin = std::max(RHSMin, MaxShAmt + 1);
1742 RHSMax = std::min(RHSMax, LHSMax.countLeadingOnes() - 1);
1743 if (RHSMin <= RHSMax)
1744 MinShl = APInt::getSignMask(BitWidth);
1745 return ConstantRange::getNonEmpty(MinShl, MaxShl + 1);
1746}
1747
1749 const ConstantRange &RHS) {
1750 unsigned BitWidth = LHS.getBitWidth();
1751 unsigned RHSMin = RHS.getUnsignedMin().getLimitedValue(BitWidth);
1752 unsigned RHSMax = RHS.getUnsignedMax().getLimitedValue(BitWidth);
1753 APInt LHSMin = LHS.getSignedMin();
1754 APInt LHSMax = LHS.getSignedMax();
1755 if (LHSMin.isNonNegative())
1756 return computeShlNSWWithNNegLHS(LHSMin, LHSMax, RHSMin, RHSMax);
1757 else if (LHSMax.isNegative())
1758 return computeShlNSWWithNegLHS(LHSMin, LHSMax, RHSMin, RHSMax);
1759 return computeShlNSWWithNNegLHS(APInt::getZero(BitWidth), LHSMax, RHSMin,
1760 RHSMax)
1762 RHSMin, RHSMax),
1764}
1765
1767 unsigned NoWrapKind,
1768 PreferredRangeType RangeType) const {
1769 if (isEmptySet() || Other.isEmptySet())
1770 return getEmpty();
1771
1772 switch (NoWrapKind) {
1773 case 0:
1774 return shl(Other);
1776 return computeShlNSW(*this, Other);
1778 return computeShlNUW(*this, Other);
1781 return computeShlNSW(*this, Other)
1782 .intersectWith(computeShlNUW(*this, Other), RangeType);
1783 default:
1784 llvm_unreachable("Invalid NoWrapKind");
1785 }
1786}
1787
1790 if (isEmptySet() || Other.isEmptySet())
1791 return getEmpty();
1792
1793 APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
1794 APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
1795 return getNonEmpty(std::move(min), std::move(max));
1796}
1797
1800 if (isEmptySet() || Other.isEmptySet())
1801 return getEmpty();
1802
1803 // May straddle zero, so handle both positive and negative cases.
1804 // 'PosMax' is the upper bound of the result of the ashr
1805 // operation, when Upper of the LHS of ashr is a non-negative.
1806 // number. Since ashr of a non-negative number will result in a
1807 // smaller number, the Upper value of LHS is shifted right with
1808 // the minimum value of 'Other' instead of the maximum value.
1809 APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
1810
1811 // 'PosMin' is the lower bound of the result of the ashr
1812 // operation, when Lower of the LHS is a non-negative number.
1813 // Since ashr of a non-negative number will result in a smaller
1814 // number, the Lower value of LHS is shifted right with the
1815 // maximum value of 'Other'.
1816 APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
1817
1818 // 'NegMax' is the upper bound of the result of the ashr
1819 // operation, when Upper of the LHS of ashr is a negative number.
1820 // Since 'ashr' of a negative number will result in a bigger
1821 // number, the Upper value of LHS is shifted right with the
1822 // maximum value of 'Other'.
1823 APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
1824
1825 // 'NegMin' is the lower bound of the result of the ashr
1826 // operation, when Lower of the LHS of ashr is a negative number.
1827 // Since 'ashr' of a negative number will result in a bigger
1828 // number, the Lower value of LHS is shifted right with the
1829 // minimum value of 'Other'.
1830 APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
1831
1832 APInt max, min;
1833 if (getSignedMin().isNonNegative()) {
1834 // Upper and Lower of LHS are non-negative.
1835 min = PosMin;
1836 max = PosMax;
1837 } else if (getSignedMax().isNegative()) {
1838 // Upper and Lower of LHS are negative.
1839 min = NegMin;
1840 max = NegMax;
1841 } else {
1842 // Upper is non-negative and Lower is negative.
1843 min = NegMin;
1844 max = PosMax;
1845 }
1846 return getNonEmpty(std::move(min), std::move(max));
1847}
1848
1850 if (isEmptySet() || Other.isEmptySet())
1851 return getEmpty();
1852
1853 APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
1854 APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
1855 return getNonEmpty(std::move(NewL), std::move(NewU));
1856}
1857
1859 if (isEmptySet() || Other.isEmptySet())
1860 return getEmpty();
1861
1862 APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
1863 APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
1864 return getNonEmpty(std::move(NewL), std::move(NewU));
1865}
1866
1868 if (isEmptySet() || Other.isEmptySet())
1869 return getEmpty();
1870
1871 APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
1872 APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
1873 return getNonEmpty(std::move(NewL), std::move(NewU));
1874}
1875
1877 if (isEmptySet() || Other.isEmptySet())
1878 return getEmpty();
1879
1880 APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
1881 APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
1882 return getNonEmpty(std::move(NewL), std::move(NewU));
1883}
1884
1886 if (isEmptySet() || Other.isEmptySet())
1887 return getEmpty();
1888
1889 APInt NewL = getUnsignedMin().umul_sat(Other.getUnsignedMin());
1890 APInt NewU = getUnsignedMax().umul_sat(Other.getUnsignedMax()) + 1;
1891 return getNonEmpty(std::move(NewL), std::move(NewU));
1892}
1893
1895 if (isEmptySet() || Other.isEmptySet())
1896 return getEmpty();
1897
1898 // Because we could be dealing with negative numbers here, the lower bound is
1899 // the smallest of the cartesian product of the lower and upper ranges;
1900 // for example:
1901 // [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1902 // Similarly for the upper bound, swapping min for max.
1903
1904 APInt Min = getSignedMin();
1905 APInt Max = getSignedMax();
1906 APInt OtherMin = Other.getSignedMin();
1907 APInt OtherMax = Other.getSignedMax();
1908
1909 auto L = {Min.smul_sat(OtherMin), Min.smul_sat(OtherMax),
1910 Max.smul_sat(OtherMin), Max.smul_sat(OtherMax)};
1911 auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1912 return getNonEmpty(std::min(L, Compare), std::max(L, Compare) + 1);
1913}
1914
1916 if (isEmptySet() || Other.isEmptySet())
1917 return getEmpty();
1918
1919 APInt NewL = getUnsignedMin().ushl_sat(Other.getUnsignedMin());
1920 APInt NewU = getUnsignedMax().ushl_sat(Other.getUnsignedMax()) + 1;
1921 return getNonEmpty(std::move(NewL), std::move(NewU));
1922}
1923
1925 if (isEmptySet() || Other.isEmptySet())
1926 return getEmpty();
1927
1928 APInt Min = getSignedMin(), Max = getSignedMax();
1929 APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax();
1930 APInt NewL = Min.sshl_sat(Min.isNonNegative() ? ShAmtMin : ShAmtMax);
1931 APInt NewU = Max.sshl_sat(Max.isNegative() ? ShAmtMin : ShAmtMax) + 1;
1932 return getNonEmpty(std::move(NewL), std::move(NewU));
1933}
1934
1936 if (isFullSet())
1937 return getEmpty();
1938 if (isEmptySet())
1939 return getFull();
1940 return ConstantRange(Upper, Lower);
1941}
1942
1943ConstantRange ConstantRange::abs(bool IntMinIsPoison) const {
1944 if (isEmptySet())
1945 return getEmpty();
1946
1947 if (isSignWrappedSet()) {
1948 APInt Lo;
1949 // Check whether the range crosses zero.
1950 if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
1952 else
1953 Lo = APIntOps::umin(Lower, -Upper + 1);
1954
1955 // If SignedMin is not poison, then it is included in the result range.
1956 if (IntMinIsPoison)
1958 else
1960 }
1961
1963
1964 // Skip SignedMin if it is poison.
1965 if (IntMinIsPoison && SMin.isMinSignedValue()) {
1966 // The range may become empty if it *only* contains SignedMin.
1967 if (SMax.isMinSignedValue())
1968 return getEmpty();
1969 ++SMin;
1970 }
1971
1972 // All non-negative.
1973 if (SMin.isNonNegative())
1974 return ConstantRange(SMin, SMax + 1);
1975
1976 // All negative.
1977 if (SMax.isNegative())
1978 return ConstantRange(-SMax, -SMin + 1);
1979
1980 // Range crosses zero.
1982 APIntOps::umax(-SMin, SMax) + 1);
1983}
1984
1985ConstantRange ConstantRange::ctlz(bool ZeroIsPoison) const {
1986 if (isEmptySet())
1987 return getEmpty();
1988
1990 if (ZeroIsPoison && contains(Zero)) {
1991 // ZeroIsPoison is set, and zero is contained. We discern three cases, in
1992 // which a zero can appear:
1993 // 1) Lower is zero, handling cases of kind [0, 1), [0, 2), etc.
1994 // 2) Upper is zero, wrapped set, handling cases of kind [3, 0], etc.
1995 // 3) Zero contained in a wrapped set, e.g., [3, 2), [3, 1), etc.
1996
1997 if (getLower().isZero()) {
1998 if ((getUpper() - 1).isZero()) {
1999 // We have in input interval of kind [0, 1). In this case we cannot
2000 // really help but return empty-set.
2001 return getEmpty();
2002 }
2003
2004 // Compute the resulting range by excluding zero from Lower.
2005 return ConstantRange(
2006 APInt(getBitWidth(), (getUpper() - 1).countl_zero()),
2007 APInt(getBitWidth(), (getLower() + 1).countl_zero() + 1));
2008 } else if ((getUpper() - 1).isZero()) {
2009 // Compute the resulting range by excluding zero from Upper.
2010 return ConstantRange(Zero,
2012 } else {
2013 return ConstantRange(Zero, APInt(getBitWidth(), getBitWidth()));
2014 }
2015 }
2016
2017 // Zero is either safe or not in the range. The output range is composed by
2018 // the result of countLeadingZero of the two extremes.
2021}
2022
2024 const APInt &Upper) {
2025 assert(!ConstantRange(Lower, Upper).isWrappedSet() &&
2026 "Unexpected wrapped set.");
2027 assert(Lower != Upper && "Unexpected empty set.");
2028 unsigned BitWidth = Lower.getBitWidth();
2029 if (Lower + 1 == Upper)
2030 return ConstantRange(APInt(BitWidth, Lower.countr_zero()));
2031 if (Lower.isZero())
2033 APInt(BitWidth, BitWidth + 1));
2034
2035 // Calculate longest common prefix.
2036 unsigned LCPLength = (Lower ^ (Upper - 1)).countl_zero();
2037 // If Lower is {LCP, 000...}, the maximum is Lower.countr_zero().
2038 // Otherwise, the maximum is BitWidth - LCPLength - 1 ({LCP, 100...}).
2039 return ConstantRange(
2042 std::max(BitWidth - LCPLength - 1, Lower.countr_zero()) + 1));
2043}
2044
2045ConstantRange ConstantRange::cttz(bool ZeroIsPoison) const {
2046 if (isEmptySet())
2047 return getEmpty();
2048
2049 unsigned BitWidth = getBitWidth();
2051 if (ZeroIsPoison && contains(Zero)) {
2052 // ZeroIsPoison is set, and zero is contained. We discern three cases, in
2053 // which a zero can appear:
2054 // 1) Lower is zero, handling cases of kind [0, 1), [0, 2), etc.
2055 // 2) Upper is zero, wrapped set, handling cases of kind [3, 0], etc.
2056 // 3) Zero contained in a wrapped set, e.g., [3, 2), [3, 1), etc.
2057
2058 if (Lower.isZero()) {
2059 if (Upper == 1) {
2060 // We have in input interval of kind [0, 1). In this case we cannot
2061 // really help but return empty-set.
2062 return getEmpty();
2063 }
2064
2065 // Compute the resulting range by excluding zero from Lower.
2067 } else if (Upper == 1) {
2068 // Compute the resulting range by excluding zero from Upper.
2069 return getUnsignedCountTrailingZerosRange(Lower, Zero);
2070 } else {
2072 ConstantRange CR2 =
2074 return CR1.unionWith(CR2);
2075 }
2076 }
2077
2078 if (isFullSet())
2079 return getNonEmpty(Zero, APInt(BitWidth, BitWidth) + 1);
2080 if (!isWrappedSet())
2081 return getUnsignedCountTrailingZerosRange(Lower, Upper);
2082 // The range is wrapped. We decompose it into two ranges, [0, Upper) and
2083 // [Lower, 0).
2084 // Handle [Lower, 0)
2086 // Handle [0, Upper)
2088 return CR1.unionWith(CR2);
2089}
2090
2092 const APInt &Upper) {
2093 assert(!ConstantRange(Lower, Upper).isWrappedSet() &&
2094 "Unexpected wrapped set.");
2095 assert(Lower != Upper && "Unexpected empty set.");
2096 unsigned BitWidth = Lower.getBitWidth();
2097 if (Lower + 1 == Upper)
2098 return ConstantRange(APInt(BitWidth, Lower.popcount()));
2099
2100 APInt Max = Upper - 1;
2101 // Calculate longest common prefix.
2102 unsigned LCPLength = (Lower ^ Max).countl_zero();
2103 unsigned LCPPopCount = Lower.getHiBits(LCPLength).popcount();
2104 // If Lower is {LCP, 000...}, the minimum is the popcount of LCP.
2105 // Otherwise, the minimum is the popcount of LCP + 1.
2106 unsigned MinBits =
2107 LCPPopCount + (Lower.countr_zero() < BitWidth - LCPLength ? 1 : 0);
2108 // If Max is {LCP, 111...}, the maximum is the popcount of LCP + (BitWidth -
2109 // length of LCP).
2110 // Otherwise, the minimum is the popcount of LCP + (BitWidth -
2111 // length of LCP - 1).
2112 unsigned MaxBits = LCPPopCount + (BitWidth - LCPLength) -
2113 (Max.countr_one() < BitWidth - LCPLength ? 1 : 0);
2114 return ConstantRange(APInt(BitWidth, MinBits), APInt(BitWidth, MaxBits + 1));
2115}
2116
2118 if (isEmptySet())
2119 return getEmpty();
2120
2121 unsigned BitWidth = getBitWidth();
2123 if (isFullSet())
2124 return getNonEmpty(Zero, APInt(BitWidth, BitWidth) + 1);
2125 if (!isWrappedSet())
2126 return getUnsignedPopCountRange(Lower, Upper);
2127 // The range is wrapped. We decompose it into two ranges, [0, Upper) and
2128 // [Lower, 0).
2129 // Handle [Lower, 0) == [Lower, Max]
2131 APInt(BitWidth, BitWidth + 1));
2132 // Handle [0, Upper)
2133 ConstantRange CR2 = getUnsignedPopCountRange(Zero, Upper);
2134 return CR1.unionWith(CR2);
2135}
2136
2138 const ConstantRange &Other) const {
2139 if (isEmptySet() || Other.isEmptySet())
2141
2142 APInt Min = getUnsignedMin(), Max = getUnsignedMax();
2143 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
2144
2145 // a u+ b overflows high iff a u> ~b.
2146 if (Min.ugt(~OtherMin))
2148 if (Max.ugt(~OtherMax))
2151}
2152
2154 const ConstantRange &Other) const {
2155 if (isEmptySet() || Other.isEmptySet())
2157
2158 APInt Min = getSignedMin(), Max = getSignedMax();
2159 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
2160
2163
2164 // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
2165 // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
2166 if (Min.isNonNegative() && OtherMin.isNonNegative() &&
2167 Min.sgt(SignedMax - OtherMin))
2169 if (Max.isNegative() && OtherMax.isNegative() &&
2170 Max.slt(SignedMin - OtherMax))
2172
2173 if (Max.isNonNegative() && OtherMax.isNonNegative() &&
2174 Max.sgt(SignedMax - OtherMax))
2176 if (Min.isNegative() && OtherMin.isNegative() &&
2177 Min.slt(SignedMin - OtherMin))
2179
2181}
2182
2184 const ConstantRange &Other) const {
2185 if (isEmptySet() || Other.isEmptySet())
2187
2188 APInt Min = getUnsignedMin(), Max = getUnsignedMax();
2189 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
2190
2191 // a u- b overflows low iff a u< b.
2192 if (Max.ult(OtherMin))
2194 if (Min.ult(OtherMax))
2197}
2198
2200 const ConstantRange &Other) const {
2201 if (isEmptySet() || Other.isEmptySet())
2203
2204 APInt Min = getSignedMin(), Max = getSignedMax();
2205 APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
2206
2209
2210 // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
2211 // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
2212 if (Min.isNonNegative() && OtherMax.isNegative() &&
2213 Min.sgt(SignedMax + OtherMax))
2215 if (Max.isNegative() && OtherMin.isNonNegative() &&
2216 Max.slt(SignedMin + OtherMin))
2218
2219 if (Max.isNonNegative() && OtherMin.isNegative() &&
2220 Max.sgt(SignedMax + OtherMin))
2222 if (Min.isNegative() && OtherMax.isNonNegative() &&
2223 Min.slt(SignedMin + OtherMax))
2225
2227}
2228
2230 const ConstantRange &Other) const {
2231 if (isEmptySet() || Other.isEmptySet())
2233
2234 APInt Min = getUnsignedMin(), Max = getUnsignedMax();
2235 APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
2236 bool Overflow;
2237
2238 (void) Min.umul_ov(OtherMin, Overflow);
2239 if (Overflow)
2241
2242 (void) Max.umul_ov(OtherMax, Overflow);
2243 if (Overflow)
2245
2247}
2248
2250 if (isFullSet())
2251 OS << "full-set";
2252 else if (isEmptySet())
2253 OS << "empty-set";
2254 else
2255 OS << "[" << Lower << "," << Upper << ")";
2256}
2257
2258#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2260 print(dbgs());
2261}
2262#endif
2263
2265 const unsigned NumRanges = Ranges.getNumOperands() / 2;
2266 assert(NumRanges >= 1 && "Must have at least one range!");
2267 assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
2268
2269 auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
2270 auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
2271
2272 ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
2273
2274 for (unsigned i = 1; i < NumRanges; ++i) {
2275 auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
2276 auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
2277
2278 // Note: unionWith will potentially create a range that contains values not
2279 // contained in any of the original N ranges.
2280 CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
2281 }
2282
2283 return CR;
2284}
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:622
static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS, const ConstantRange &RHS)
Estimate the 'bit-masked AND' operation's lower bound.
static ConstantRange computeShlNUW(const ConstantRange &LHS, const ConstantRange &RHS)
static ConstantRange getUnsignedPopCountRange(const APInt &Lower, const APInt &Upper)
static ConstantRange computeShlNSW(const ConstantRange &LHS, const ConstantRange &RHS)
static ConstantRange makeExactMulNUWRegion(const APInt &V)
Exact mul nuw region for single element RHS.
static ConstantRange computeShlNSWWithNNegLHS(const APInt &LHSMin, const APInt &LHSMax, unsigned RHSMin, unsigned RHSMax)
static ConstantRange makeExactMulNSWRegion(const APInt &V)
Exact mul nsw region for single element RHS.
static ConstantRange getPreferredRange(const ConstantRange &CR1, const ConstantRange &CR2, ConstantRange::PreferredRangeType Type)
static ConstantRange getUnsignedCountTrailingZerosRange(const APInt &Lower, const APInt &Upper)
static ConstantRange computeShlNSWWithNegLHS(const APInt &LHSMin, const APInt &LHSMax, unsigned RHSMin, unsigned RHSMax)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:533
This file contains the declarations for metadata subclasses.
uint64_t High
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1945
APInt usub_sat(const APInt &RHS) const
Definition: APInt.cpp:2029
APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition: APInt.cpp:1547
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition: APInt.h:234
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition: APInt.h:1407
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:986
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition: APInt.h:229
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition: APInt.h:423
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1492
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:910
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition: APInt.h:206
APInt sshl_ov(const APInt &Amt, bool &Overflow) const
Definition: APInt.cpp:1962
APInt smul_sat(const APInt &RHS) const
Definition: APInt.cpp:2038
unsigned countLeadingOnes() const
Definition: APInt.h:1603
APInt sadd_sat(const APInt &RHS) const
Definition: APInt.cpp:2000
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition: APInt.h:1201
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition: APInt.h:371
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition: APInt.h:1182
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition: APInt.h:258
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition: APInt.h:380
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1468
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1111
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition: APInt.h:209
bool isMinValue() const
Determine if this is the smallest unsigned value.
Definition: APInt.h:417
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition: APInt.h:216
bool isNegative() const
Determine sign of this APInt.
Definition: APInt.h:329
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition: APInt.cpp:1618
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition: APInt.h:1166
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:219
APInt sshl_sat(const APInt &RHS) const
Definition: APInt.cpp:2060
APInt ushl_sat(const APInt &RHS) const
Definition: APInt.cpp:2074
APInt ushl_ov(const APInt &Amt, bool &Overflow) const
Definition: APInt.cpp:1979
unsigned countLeadingZeros() const
Definition: APInt.h:1585
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition: APInt.h:356
unsigned countl_one() const
Count the number of leading one bits.
Definition: APInt.h:1594
void clearLowBits(unsigned loBits)
Set bottom loBits bits to 0.
Definition: APInt.h:1417
APInt uadd_sat(const APInt &RHS) const
Definition: APInt.cpp:2010
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition: APInt.h:827
void setAllBits()
Set every bit to 1.
Definition: APInt.h:1319
bool getBoolValue() const
Convert APInt to a boolean value.
Definition: APInt.h:471
APInt smul_ov(const APInt &RHS, bool &Overflow) const
Definition: APInt.cpp:1934
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition: APInt.h:334
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1150
APInt sext(unsigned width) const
Sign extend to a new width.
Definition: APInt.cpp:959
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition: APInt.h:873
APInt umul_sat(const APInt &RHS) const
Definition: APInt.cpp:2051
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition: APInt.h:306
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1130
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition: APInt.h:296
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:200
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1237
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition: APInt.h:286
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:239
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition: APInt.h:851
unsigned countr_one() const
Count the number of trailing one bits.
Definition: APInt.h:1635
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1221
void clearSignBit()
Set the sign bit to 0.
Definition: APInt.h:1431
APInt ssub_sat(const APInt &RHS) const
Definition: APInt.cpp:2019
bool isMaxValue() const
Determine if this is the largest unsigned value.
Definition: APInt.h:399
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:673
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:702
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:703
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:697
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:696
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:700
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:698
@ ICMP_EQ
equal
Definition: InstrTypes.h:694
@ ICMP_NE
not equal
Definition: InstrTypes.h:695
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:701
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:699
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:787
bool isIntPredicate() const
Definition: InstrTypes.h:781
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Definition: InstrTypes.h:924
This class represents a range of values.
Definition: ConstantRange.h:47
ConstantRange multiply(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
unsigned getActiveBits() const
Compute the maximal number of active bits needed to represent every value in this range.
ConstantRange zextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
std::optional< ConstantRange > exactUnionWith(const ConstantRange &CR) const
Union the two ranges and return the result if it can be represented exactly, otherwise return std::nu...
bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const
Set up Pred and RHS such that ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.
ConstantRange umul_sat(const ConstantRange &Other) const
Perform an unsigned saturating multiplication of two constant ranges.
static CmpInst::Predicate getEquivalentPredWithFlippedSignedness(CmpInst::Predicate Pred, const ConstantRange &CR1, const ConstantRange &CR2)
If the comparison between constant ranges this and Other is insensitive to the signedness of the comp...
ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
ConstantRange binaryXor(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-xor of a value in this ra...
const APInt * getSingleMissingElement() const
If this set contains all but a single element, return it, otherwise return null.
static ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
const APInt & getLower() const
Return the lower value for this range.
OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
bool isAllNegative() const
Return true if all values in this range are negative.
ConstantRange truncate(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
ConstantRange sshl_sat(const ConstantRange &Other) const
Perform a signed saturating left shift of this constant range by a value in Other.
ConstantRange smul_fast(const ConstantRange &Other) const
Return range of possible values for a signed multiplication of this and Other.
ConstantRange lshr(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a logical right shift of a value i...
KnownBits toKnownBits() const
Return known bits for values in this range.
ConstantRange castOp(Instruction::CastOps CastOp, uint32_t BitWidth) const
Return a new range representing the possible values resulting from an application of the specified ca...
ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
ConstantRange srem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed remainder operation of a ...
bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other? NOTE: false does not mean that inverse pr...
ConstantRange sadd_sat(const ConstantRange &Other) const
Perform a signed saturating addition of two constant ranges.
ConstantRange ushl_sat(const ConstantRange &Other) const
Perform an unsigned saturating left shift of this constant range by a value in Other.
static ConstantRange intrinsic(Intrinsic::ID IntrinsicID, ArrayRef< ConstantRange > Ops)
Compute range of intrinsic result for the given operand ranges.
void dump() const
Allow printing from a debugger easily.
bool isEmptySet() const
Return true if this set contains no members.
ConstantRange smul_sat(const ConstantRange &Other) const
Perform a signed saturating multiplication of two constant ranges.
bool isAllPositive() const
Return true if all values in this range are positive.
ConstantRange shl(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a left shift of a value in this ra...
ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
bool isSignWrappedSet() const
Return true if this set wraps around the signed domain.
bool isSizeLargerThan(uint64_t MaxSize) const
Compare set size of this range with Value.
APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
ConstantRange abs(bool IntMinIsPoison=false) const
Calculate absolute value range.
static bool isIntrinsicSupported(Intrinsic::ID IntrinsicID)
Returns true if ConstantRange calculations are supported for intrinsic with IntrinsicID.
static ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the largest range such that all values in the returned range satisfy the given predicate with...
bool isWrappedSet() const
Return true if this set wraps around the unsigned domain.
ConstantRange usub_sat(const ConstantRange &Other) const
Perform an unsigned saturating subtraction of two constant ranges.
ConstantRange uadd_sat(const ConstantRange &Other) const
Perform an unsigned saturating addition of two constant ranges.
ConstantRange overflowingBinaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind) const
Return a new range representing the possible values resulting from an application of the specified ov...
void print(raw_ostream &OS) const
Print out the bounds to a stream.
ConstantRange(uint32_t BitWidth, bool isFullSet)
Initialize a full or empty set for the specified bit width.
OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
ConstantRange subWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind, PreferredRangeType RangeType=Smallest) const
Return a new range representing the possible values resulting from an subtraction with wrap type NoWr...
bool isSingleElement() const
Return true if this set contains exactly one member.
ConstantRange ssub_sat(const ConstantRange &Other) const
Perform a signed saturating subtraction of two constant ranges.
bool isAllNonNegative() const
Return true if all values in this range are non-negative.
ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
ConstantRange sdiv(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed division of a value in th...
const APInt & getUpper() const
Return the upper value for this range.
bool isUpperWrapped() const
Return true if the exclusive upper bound wraps around the unsigned domain.
ConstantRange shlWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind, PreferredRangeType RangeType=Smallest) const
Return a new range representing the possible values resulting from a left shift with wrap type NoWrap...
ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
std::optional< ConstantRange > exactIntersectWith(const ConstantRange &CR) const
Intersect the two ranges and return the result if it can be represented exactly, otherwise return std...
ConstantRange ashr(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a arithmetic right shift of a valu...
ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static bool areInsensitiveToSignednessOfInvertedICmpPredicate(const ConstantRange &CR1, const ConstantRange &CR2)
Return true iff CR1 ult CR2 is equivalent to CR1 sge CR2.
OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
ConstantRange addWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind, PreferredRangeType RangeType=Smallest) const
Return a new range representing the possible values resulting from an addition with wrap type NoWrapK...
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange makeMaskNotEqualRange(const APInt &Mask, const APInt &C)
Initialize a range containing all values X that satisfy (X & Mask) != C.
static bool areInsensitiveToSignednessOfICmpPredicate(const ConstantRange &CR1, const ConstantRange &CR2)
Return true iff CR1 ult CR2 is equivalent to CR1 slt CR2.
ConstantRange cttz(bool ZeroIsPoison=false) const
Calculate cttz range.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
Definition: ConstantRange.h:84
ConstantRange ctpop() const
Calculate ctpop range.
static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind)
Produce the largest range containing all X such that "X BinOp Y" is guaranteed not to wrap (overflow)...
ConstantRange smin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed minimum of a value in thi...
ConstantRange udiv(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned division of a value in...
unsigned getMinSignedBits() const
Compute the maximal number of bits needed to represent every value in this signed range.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
ConstantRange binaryNot() const
Return a new range representing the possible values resulting from a binary-xor of a value in this ra...
ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
ConstantRange binaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other) const
Return a new range representing the possible values resulting from an application of the specified bi...
ConstantRange binaryOr(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-or of a value in this ran...
OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
ConstantRange ctlz(bool ZeroIsPoison=false) const
Calculate ctlz range.
ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
ConstantRange sextOrTrunc(uint32_t BitWidth) const
Make this range have the bit width given by BitWidth.
static ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
bool isSizeStrictlySmallerThan(const ConstantRange &CR) const
Compare set size of this range with the range CR.
ConstantRange multiplyWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind, PreferredRangeType RangeType=Smallest) const
Return a new range representing the possible values resulting from a multiplication with wrap type No...
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
bool isBinaryOp() const
Definition: Instruction.h:279
Metadata node.
Definition: Metadata.h:1069
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition: Operator.h:77
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::optional< unsigned > GetMostSignificantDifferentBit(const APInt &A, const APInt &B)
Compare two values, and if they are different, return the position of the most significant bit that i...
Definition: APInt.cpp:2975
APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A unsign-divided by B, rounded by the given rounding mode.
Definition: APInt.cpp:2736
APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM)
Return A sign-divided by B, rounded by the given rounding mode.
Definition: APInt.cpp:2754
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition: APInt.h:2217
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition: APInt.h:2222
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition: APInt.h:2227
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition: APInt.h:2232
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
@ Offset
Definition: DWP.cpp:480
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition: bit.h:281
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
@ Other
Any other memory.
@ UMin
Unsigned integer min implemented in terms of select(cmp()).
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ SMin
Signed integer min implemented in terms of select(cmp()).
@ UMax
Unsigned integer max implemented in terms of select(cmp()).
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:217
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition: KnownBits.h:293
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:100
bool isUnknown() const
Returns true if we don't know any bits.
Definition: KnownBits.h:65
bool hasConflict() const
Returns true if there is conflicting information.
Definition: KnownBits.h:50
unsigned getBitWidth() const
Get the bit width of this value.
Definition: KnownBits.h:43
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition: KnownBits.h:137
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition: KnownBits.h:121
bool isNegative() const
Returns true if this value is known to be negative.
Definition: KnownBits.h:97