xref: /llvm-project/llvm/lib/IR/ConstantRange.cpp (revision 2feffecb8853b1cdd38a0653df63d70412e65c12)
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 
23 #include "llvm/IR/ConstantRange.h"
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"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/KnownBits.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <cstdint>
41 #include <optional>
42 
43 using namespace llvm;
44 
45 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
46     : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
47       Upper(Lower) {}
48 
49 ConstantRange::ConstantRange(APInt V)
50     : Lower(std::move(V)), Upper(Lower + 1) {}
51 
52 ConstantRange::ConstantRange(APInt L, APInt U)
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 
60 ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,
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 
80 KnownBits ConstantRange::toKnownBits() const {
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();
89   KnownBits Known = KnownBits::makeConstant(Min);
90   if (std::optional<unsigned> DifferentBit =
91           APIntOps::GetMostSignificantDifferentBit(Min, Max)) {
92     Known.Zero.clearLowBits(*DifferentBit + 1);
93     Known.One.clearLowBits(*DifferentBit + 1);
94   }
95   return Known;
96 }
97 
98 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
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: {
114     APInt UMax(CR.getUnsignedMax());
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   }
125   case CmpInst::ICMP_ULE:
126     return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
127   case CmpInst::ICMP_SLE:
128     return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1);
129   case CmpInst::ICMP_UGT: {
130     APInt UMin(CR.getUnsignedMin());
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   }
141   case CmpInst::ICMP_UGE:
142     return getNonEmpty(CR.getUnsignedMin(), APInt::getZero(W));
143   case CmpInst::ICMP_SGE:
144     return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W));
145   }
146 }
147 
148 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
149                                                       const ConstantRange &CR) {
150   // Follows from De-Morgan's laws:
151   //
152   // ~(~A union ~B) == A intersect B.
153   //
154   return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
155       .inverse();
156 }
157 
158 ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
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   //
166   assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
167   return makeAllowedICmpRegion(Pred, C);
168 }
169 
170 bool ConstantRange::areInsensitiveToSignednessOfICmpPredicate(
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 
179 bool ConstantRange::areInsensitiveToSignednessOfInvertedICmpPredicate(
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 
188 CmpInst::Predicate ConstantRange::getEquivalentPredWithFlippedSignedness(
189     CmpInst::Predicate Pred, const ConstantRange &CR1,
190     const ConstantRange &CR2) {
191   assert(CmpInst::isIntPredicate(Pred) && CmpInst::isRelational(Pred) &&
192          "Only for relational integer predicates!");
193 
194   CmpInst::Predicate FlippedSignednessPred =
195       ICmpInst::getFlippedSignednessPredicate(Pred);
196 
197   if (areInsensitiveToSignednessOfICmpPredicate(CR1, CR2))
198     return FlippedSignednessPred;
199 
200   if (areInsensitiveToSignednessOfInvertedICmpPredicate(CR1, CR2))
201     return CmpInst::getInversePredicate(FlippedSignednessPred);
202 
203   return CmpInst::Predicate::BAD_ICMP_PREDICATE;
204 }
205 
206 void ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
207                                       APInt &RHS, APInt &Offset) const {
208   Offset = APInt(getBitWidth(), 0);
209   if (isFullSet() || isEmptySet()) {
210     Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
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 =
220         getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
221     RHS = getUpper();
222   } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
223     Pred =
224         getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
225     RHS = getLower();
226   } else {
227     Pred = CmpInst::ICMP_ULT;
228     RHS = getUpper() - getLower();
229     Offset = -getLower();
230   }
231 
232   assert(ConstantRange::makeExactICmpRegion(Pred, RHS) == add(Offset) &&
233          "Bad result!");
234 }
235 
236 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
237                                       APInt &RHS) const {
238   APInt Offset;
239   getEquivalentICmp(Pred, RHS, Offset);
240   return Offset.isZero();
241 }
242 
243 bool ConstantRange::icmp(CmpInst::Predicate Pred,
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);
256   case CmpInst::ICMP_ULT:
257     return getUnsignedMax().ult(Other.getUnsignedMin());
258   case CmpInst::ICMP_ULE:
259     return getUnsignedMax().ule(Other.getUnsignedMin());
260   case CmpInst::ICMP_UGT:
261     return getUnsignedMin().ugt(Other.getUnsignedMax());
262   case CmpInst::ICMP_UGE:
263     return getUnsignedMin().uge(Other.getUnsignedMax());
264   case CmpInst::ICMP_SLT:
265     return getSignedMax().slt(Other.getSignedMin());
266   case CmpInst::ICMP_SLE:
267     return getSignedMax().sle(Other.getSignedMin());
268   case CmpInst::ICMP_SGT:
269     return getSignedMin().sgt(Other.getSignedMax());
270   case CmpInst::ICMP_SGE:
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.
278 static ConstantRange makeExactMulNUWRegion(const APInt &V) {
279   unsigned BitWidth = V.getBitWidth();
280   if (V == 0)
281     return ConstantRange::getFull(V.getBitWidth());
282 
283   return ConstantRange::getNonEmpty(
284       APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth), V,
285                              APInt::Rounding::UP),
286       APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth), V,
287                              APInt::Rounding::DOWN) + 1);
288 }
289 
290 /// Exact mul nsw region for single element RHS.
291 static ConstantRange makeExactMulNSWRegion(const APInt &V) {
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 
297   APInt MinValue = APInt::getSignedMinValue(BitWidth);
298   APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
299   // e.g. Returning [-127, 127], represented as [-127, -128).
300   if (V.isAllOnes())
301     return ConstantRange(-MaxValue, MinValue);
302 
303   APInt Lower, Upper;
304   if (V.isNegative()) {
305     Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);
306     Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);
307   } else {
308     Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);
309     Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);
310   }
311   return ConstantRange::getNonEmpty(Lower, Upper + 1);
312 }
313 
314 ConstantRange
315 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
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 
337     APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
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 
348     APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
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(
370         ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, (BitWidth - 1) + 1)));
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)
381       return getNonEmpty(APInt::getZero(BitWidth),
382                          APInt::getMaxValue(BitWidth).lshr(ShAmtUMax) + 1);
383     return getNonEmpty(APInt::getSignedMinValue(BitWidth).ashr(ShAmtUMax),
384                        APInt::getSignedMaxValue(BitWidth).ashr(ShAmtUMax) + 1);
385   }
386   }
387 }
388 
389 ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
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 
397 ConstantRange ConstantRange::makeMaskNotEqualRange(const APInt &Mask,
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.
410   return ConstantRange::getNonEmpty(
411       APInt::getOneBitSet(BitWidth, Mask.countr_zero()) + C, C);
412 }
413 
414 bool ConstantRange::isFullSet() const {
415   return Lower == Upper && Lower.isMaxValue();
416 }
417 
418 bool ConstantRange::isEmptySet() const {
419   return Lower == Upper && Lower.isMinValue();
420 }
421 
422 bool ConstantRange::isWrappedSet() const {
423   return Lower.ugt(Upper) && !Upper.isZero();
424 }
425 
426 bool ConstantRange::isUpperWrapped() const {
427   return Lower.ugt(Upper);
428 }
429 
430 bool ConstantRange::isSignWrappedSet() const {
431   return Lower.sgt(Upper) && !Upper.isMinSignedValue();
432 }
433 
434 bool ConstantRange::isUpperSignWrapped() const {
435   return Lower.sgt(Upper);
436 }
437 
438 bool
439 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
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 
448 bool
449 ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
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 
458 bool ConstantRange::isAllNegative() const {
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 
468 bool ConstantRange::isAllNonNegative() const {
469   // Empty and full set are automatically treated correctly.
470   return !isSignWrappedSet() && Lower.isNonNegative();
471 }
472 
473 bool ConstantRange::isAllPositive() const {
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 
483 APInt ConstantRange::getUnsignedMax() const {
484   if (isFullSet() || isUpperWrapped())
485     return APInt::getMaxValue(getBitWidth());
486   return getUpper() - 1;
487 }
488 
489 APInt ConstantRange::getUnsignedMin() const {
490   if (isFullSet() || isWrappedSet())
491     return APInt::getMinValue(getBitWidth());
492   return getLower();
493 }
494 
495 APInt ConstantRange::getSignedMax() const {
496   if (isFullSet() || isUpperSignWrapped())
497     return APInt::getSignedMaxValue(getBitWidth());
498   return getUpper() - 1;
499 }
500 
501 APInt ConstantRange::getSignedMin() const {
502   if (isFullSet() || isSignWrappedSet())
503     return APInt::getSignedMinValue(getBitWidth());
504   return getLower();
505 }
506 
507 bool 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 
516 bool ConstantRange::contains(const ConstantRange &Other) const {
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 
534 unsigned ConstantRange::getActiveBits() const {
535   if (isEmptySet())
536     return 0;
537 
538   return getUnsignedMax().getActiveBits();
539 }
540 
541 unsigned ConstantRange::getMinSignedBits() const {
542   if (isEmptySet())
543     return 0;
544 
545   return std::max(getSignedMin().getSignificantBits(),
546                   getSignedMax().getSignificantBits());
547 }
548 
549 ConstantRange ConstantRange::subtract(const APInt &Val) const {
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 
557 ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
558   return intersectWith(CR.inverse());
559 }
560 
561 static ConstantRange getPreferredRange(
562     const ConstantRange &CR1, const ConstantRange &CR2,
563     ConstantRange::PreferredRangeType Type) {
564   if (Type == ConstantRange::Unsigned) {
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 
581 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
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 
687 ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
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 
760 std::optional<ConstantRange>
761 ConstantRange::exactIntersectWith(const ConstantRange &CR) const {
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 
769 std::optional<ConstantRange>
770 ConstantRange::exactUnionWith(const ConstantRange &CR) const {
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 
778 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
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();
811     APInt SMin = APInt::getSignedMinValue(BW);
812     APInt SMax = APInt::getSignedMaxValue(BW);
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 
829 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
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 
846 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
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 
864 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
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 
917 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
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 
926 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
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 
935 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
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 
980 ConstantRange ConstantRange::overflowingBinaryOp(Instruction::BinaryOps BinOp,
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 
1001 bool ConstantRange::isIntrinsicSupported(Intrinsic::ID IntrinsicID) {
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 
1021 ConstantRange ConstantRange::intrinsic(Intrinsic::ID IntrinsicID,
1022                                        ArrayRef<ConstantRange> Ops) {
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 
1066 ConstantRange
1067 ConstantRange::add(const ConstantRange &Other) const {
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 
1086 ConstantRange ConstantRange::addWithNoWrap(const ConstantRange &Other,
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 
1113 ConstantRange
1114 ConstantRange::sub(const ConstantRange &Other) const {
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 
1133 ConstantRange ConstantRange::subWithNoWrap(const ConstantRange &Other,
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 
1163 ConstantRange
1164 ConstantRange::multiply(const ConstantRange &Other) const {
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())
1177       return ConstantRange(APInt::getZero(getBitWidth())).sub(Other);
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() &&
1208       (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
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 
1231 ConstantRange
1232 ConstantRange::multiplyWithNoWrap(const ConstantRange &Other,
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 
1242   if (NoWrapKind & OverflowingBinaryOperator::NoSignedWrap)
1243     Result = Result.intersectWith(smul_sat(Other), RangeType);
1244 
1245   if (NoWrapKind & OverflowingBinaryOperator::NoUnsignedWrap)
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 |
1250                       OverflowingBinaryOperator::NoUnsignedWrap)) &&
1251       !Result.isAllNonNegative()) {
1252     if (getSignedMin().sgt(1) || Other.getSignedMin().sgt(1))
1253       Result = Result.intersectWith(
1254           getNonEmpty(APInt::getZero(getBitWidth()),
1255                       APInt::getSignedMinValue(getBitWidth())),
1256           RangeType);
1257   }
1258 
1259   return Result;
1260 }
1261 
1262 ConstantRange ConstantRange::smul_fast(const ConstantRange &Other) const {
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 
1281 ConstantRange
1282 ConstantRange::smax(const ConstantRange &Other) const {
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 
1295 ConstantRange
1296 ConstantRange::umax(const ConstantRange &Other) const {
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())
1305     return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
1306   return Res;
1307 }
1308 
1309 ConstantRange
1310 ConstantRange::smin(const ConstantRange &Other) const {
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 
1323 ConstantRange
1324 ConstantRange::umin(const ConstantRange &Other) const {
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())
1333     return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
1334   return Res;
1335 }
1336 
1337 ConstantRange
1338 ConstantRange::udiv(const ConstantRange &RHS) const {
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 
1358 ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const {
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.
1362   APInt Zero = APInt::getZero(getBitWidth());
1363   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
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.
1438   ConstantRange Res = NegRes.unionWith(PosRes, PreferredRangeType::Signed);
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 
1446 ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
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 
1468 ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {
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 
1519 ConstantRange ConstantRange::binaryNot() const {
1520   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
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.
1547 static APInt estimateBitMaskedAndLowerBound(const ConstantRange &LHS,
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 
1580 ConstantRange ConstantRange::binaryAnd(const ConstantRange &Other) const {
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 
1592 ConstantRange ConstantRange::binaryOr(const ConstantRange &Other) const {
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 =
1605       -estimateBitMaskedAndLowerBound(binaryNot(), Other.binaryNot());
1606   // Upper wrapped range.
1607   ConstantRange UMaxUMinRange = getNonEmpty(
1608       APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin()), UpperBound);
1609   return KnownBitsRange.intersectWith(UMaxUMinRange);
1610 }
1611 
1612 ConstantRange ConstantRange::binaryXor(const ConstantRange &Other) const {
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))
1638     CR = CR.intersectWith(Other.sub(*this), PreferredRangeType::Unsigned);
1639   else if ((~RHSKnown.Zero).isSubsetOf(LHSKnown.One))
1640     CR = CR.intersectWith(this->sub(Other), PreferredRangeType::Unsigned);
1641   return CR;
1642 }
1643 
1644 ConstantRange
1645 ConstantRange::shl(const ConstantRange &Other) const {
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 
1685 static ConstantRange computeShlNUW(const ConstantRange &LHS,
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,
1704                             APInt::getHighBitsSet(BitWidth, BitWidth - RHSMin));
1705   return ConstantRange::getNonEmpty(MinShl, MaxShl + 1);
1706 }
1707 
1708 static ConstantRange computeShlNSWWithNNegLHS(const APInt &LHSMin,
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 
1729 static ConstantRange computeShlNSWWithNegLHS(const APInt &LHSMin,
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 
1748 static ConstantRange computeShlNSW(const ConstantRange &LHS,
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)
1761       .unionWith(computeShlNSWWithNegLHS(LHSMin, APInt::getAllOnes(BitWidth),
1762                                          RHSMin, RHSMax),
1763                  ConstantRange::Signed);
1764 }
1765 
1766 ConstantRange ConstantRange::shlWithNoWrap(const ConstantRange &Other,
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);
1775   case OverflowingBinaryOperator::NoSignedWrap:
1776     return computeShlNSW(*this, Other);
1777   case OverflowingBinaryOperator::NoUnsignedWrap:
1778     return computeShlNUW(*this, Other);
1779   case OverflowingBinaryOperator::NoSignedWrap |
1780       OverflowingBinaryOperator::NoUnsignedWrap:
1781     return computeShlNSW(*this, Other)
1782         .intersectWith(computeShlNUW(*this, Other), RangeType);
1783   default:
1784     llvm_unreachable("Invalid NoWrapKind");
1785   }
1786 }
1787 
1788 ConstantRange
1789 ConstantRange::lshr(const ConstantRange &Other) const {
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 
1798 ConstantRange
1799 ConstantRange::ashr(const ConstantRange &Other) const {
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 
1849 ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
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 
1858 ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
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 
1867 ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
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 
1876 ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
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 
1885 ConstantRange ConstantRange::umul_sat(const ConstantRange &Other) const {
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 
1894 ConstantRange ConstantRange::smul_sat(const ConstantRange &Other) const {
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 
1915 ConstantRange ConstantRange::ushl_sat(const ConstantRange &Other) const {
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 
1924 ConstantRange ConstantRange::sshl_sat(const ConstantRange &Other) const {
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 
1935 ConstantRange ConstantRange::inverse() const {
1936   if (isFullSet())
1937     return getEmpty();
1938   if (isEmptySet())
1939     return getFull();
1940   return ConstantRange(Upper, Lower);
1941 }
1942 
1943 ConstantRange 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())
1951       Lo = APInt::getZero(getBitWidth());
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)
1957       return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()));
1958     else
1959       return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);
1960   }
1961 
1962   APInt SMin = getSignedMin(), SMax = getSignedMax();
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.
1981   return ConstantRange::getNonEmpty(APInt::getZero(getBitWidth()),
1982                                     APIntOps::umax(-SMin, SMax) + 1);
1983 }
1984 
1985 ConstantRange ConstantRange::ctlz(bool ZeroIsPoison) const {
1986   if (isEmptySet())
1987     return getEmpty();
1988 
1989   APInt Zero = APInt::getZero(getBitWidth());
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,
2011                            APInt(getBitWidth(), getLower().countl_zero() + 1));
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.
2019   return getNonEmpty(APInt(getBitWidth(), getUnsignedMax().countl_zero()),
2020                      APInt(getBitWidth(), getUnsignedMin().countl_zero()) + 1);
2021 }
2022 
2023 static ConstantRange getUnsignedCountTrailingZerosRange(const APInt &Lower,
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())
2032     return ConstantRange(APInt::getZero(BitWidth),
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(
2040       APInt::getZero(BitWidth),
2041       APInt(BitWidth,
2042             std::max(BitWidth - LCPLength - 1, Lower.countr_zero()) + 1));
2043 }
2044 
2045 ConstantRange ConstantRange::cttz(bool ZeroIsPoison) const {
2046   if (isEmptySet())
2047     return getEmpty();
2048 
2049   unsigned BitWidth = getBitWidth();
2050   APInt Zero = APInt::getZero(BitWidth);
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.
2066       return getUnsignedCountTrailingZerosRange(APInt(BitWidth, 1), Upper);
2067     } else if (Upper == 1) {
2068       // Compute the resulting range by excluding zero from Upper.
2069       return getUnsignedCountTrailingZerosRange(Lower, Zero);
2070     } else {
2071       ConstantRange CR1 = getUnsignedCountTrailingZerosRange(Lower, Zero);
2072       ConstantRange CR2 =
2073           getUnsignedCountTrailingZerosRange(APInt(BitWidth, 1), Upper);
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)
2085   ConstantRange CR1 = getUnsignedCountTrailingZerosRange(Lower, Zero);
2086   // Handle [0, Upper)
2087   ConstantRange CR2 = getUnsignedCountTrailingZerosRange(Zero, Upper);
2088   return CR1.unionWith(CR2);
2089 }
2090 
2091 static ConstantRange getUnsignedPopCountRange(const APInt &Lower,
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 
2117 ConstantRange ConstantRange::ctpop() const {
2118   if (isEmptySet())
2119     return getEmpty();
2120 
2121   unsigned BitWidth = getBitWidth();
2122   APInt Zero = APInt::getZero(BitWidth);
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]
2130   ConstantRange CR1 = ConstantRange(APInt(BitWidth, Lower.countl_one()),
2131                                     APInt(BitWidth, BitWidth + 1));
2132   // Handle [0, Upper)
2133   ConstantRange CR2 = getUnsignedPopCountRange(Zero, Upper);
2134   return CR1.unionWith(CR2);
2135 }
2136 
2137 ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
2138     const ConstantRange &Other) const {
2139   if (isEmptySet() || Other.isEmptySet())
2140     return OverflowResult::MayOverflow;
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))
2147     return OverflowResult::AlwaysOverflowsHigh;
2148   if (Max.ugt(~OtherMax))
2149     return OverflowResult::MayOverflow;
2150   return OverflowResult::NeverOverflows;
2151 }
2152 
2153 ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
2154     const ConstantRange &Other) const {
2155   if (isEmptySet() || Other.isEmptySet())
2156     return OverflowResult::MayOverflow;
2157 
2158   APInt Min = getSignedMin(), Max = getSignedMax();
2159   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
2160 
2161   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
2162   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
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))
2168     return OverflowResult::AlwaysOverflowsHigh;
2169   if (Max.isNegative() && OtherMax.isNegative() &&
2170       Max.slt(SignedMin - OtherMax))
2171     return OverflowResult::AlwaysOverflowsLow;
2172 
2173   if (Max.isNonNegative() && OtherMax.isNonNegative() &&
2174       Max.sgt(SignedMax - OtherMax))
2175     return OverflowResult::MayOverflow;
2176   if (Min.isNegative() && OtherMin.isNegative() &&
2177       Min.slt(SignedMin - OtherMin))
2178     return OverflowResult::MayOverflow;
2179 
2180   return OverflowResult::NeverOverflows;
2181 }
2182 
2183 ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
2184     const ConstantRange &Other) const {
2185   if (isEmptySet() || Other.isEmptySet())
2186     return OverflowResult::MayOverflow;
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))
2193     return OverflowResult::AlwaysOverflowsLow;
2194   if (Min.ult(OtherMax))
2195     return OverflowResult::MayOverflow;
2196   return OverflowResult::NeverOverflows;
2197 }
2198 
2199 ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
2200     const ConstantRange &Other) const {
2201   if (isEmptySet() || Other.isEmptySet())
2202     return OverflowResult::MayOverflow;
2203 
2204   APInt Min = getSignedMin(), Max = getSignedMax();
2205   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
2206 
2207   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
2208   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
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))
2214     return OverflowResult::AlwaysOverflowsHigh;
2215   if (Max.isNegative() && OtherMin.isNonNegative() &&
2216       Max.slt(SignedMin + OtherMin))
2217     return OverflowResult::AlwaysOverflowsLow;
2218 
2219   if (Max.isNonNegative() && OtherMin.isNegative() &&
2220       Max.sgt(SignedMax + OtherMin))
2221     return OverflowResult::MayOverflow;
2222   if (Min.isNegative() && OtherMax.isNonNegative() &&
2223       Min.slt(SignedMin + OtherMax))
2224     return OverflowResult::MayOverflow;
2225 
2226   return OverflowResult::NeverOverflows;
2227 }
2228 
2229 ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
2230     const ConstantRange &Other) const {
2231   if (isEmptySet() || Other.isEmptySet())
2232     return OverflowResult::MayOverflow;
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)
2240     return OverflowResult::AlwaysOverflowsHigh;
2241 
2242   (void) Max.umul_ov(OtherMax, Overflow);
2243   if (Overflow)
2244     return OverflowResult::MayOverflow;
2245 
2246   return OverflowResult::NeverOverflows;
2247 }
2248 
2249 void ConstantRange::print(raw_ostream &OS) const {
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)
2259 LLVM_DUMP_METHOD void ConstantRange::dump() const {
2260   print(dbgs());
2261 }
2262 #endif
2263 
2264 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
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 }
2285