xref: /freebsd/contrib/llvm-project/llvm/lib/IR/ConstantRange.cpp (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
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/ADT/APInt.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/ConstantRange.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstdint>
40 
41 using namespace llvm;
42 
43 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
44     : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
45       Upper(Lower) {}
46 
47 ConstantRange::ConstantRange(APInt V)
48     : Lower(std::move(V)), Upper(Lower + 1) {}
49 
50 ConstantRange::ConstantRange(APInt L, APInt U)
51     : Lower(std::move(L)), Upper(std::move(U)) {
52   assert(Lower.getBitWidth() == Upper.getBitWidth() &&
53          "ConstantRange with unequal bit widths");
54   assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
55          "Lower == Upper, but they aren't min or max value!");
56 }
57 
58 ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,
59                                            bool IsSigned) {
60   assert(!Known.hasConflict() && "Expected valid KnownBits");
61 
62   if (Known.isUnknown())
63     return getFull(Known.getBitWidth());
64 
65   // For unsigned ranges, or signed ranges with known sign bit, create a simple
66   // range between the smallest and largest possible value.
67   if (!IsSigned || Known.isNegative() || Known.isNonNegative())
68     return ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1);
69 
70   // If we don't know the sign bit, pick the lower bound as a negative number
71   // and the upper bound as a non-negative one.
72   APInt Lower = Known.getMinValue(), Upper = Known.getMaxValue();
73   Lower.setSignBit();
74   Upper.clearSignBit();
75   return ConstantRange(Lower, Upper + 1);
76 }
77 
78 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
79                                                    const ConstantRange &CR) {
80   if (CR.isEmptySet())
81     return CR;
82 
83   uint32_t W = CR.getBitWidth();
84   switch (Pred) {
85   default:
86     llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
87   case CmpInst::ICMP_EQ:
88     return CR;
89   case CmpInst::ICMP_NE:
90     if (CR.isSingleElement())
91       return ConstantRange(CR.getUpper(), CR.getLower());
92     return getFull(W);
93   case CmpInst::ICMP_ULT: {
94     APInt UMax(CR.getUnsignedMax());
95     if (UMax.isMinValue())
96       return getEmpty(W);
97     return ConstantRange(APInt::getMinValue(W), std::move(UMax));
98   }
99   case CmpInst::ICMP_SLT: {
100     APInt SMax(CR.getSignedMax());
101     if (SMax.isMinSignedValue())
102       return getEmpty(W);
103     return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
104   }
105   case CmpInst::ICMP_ULE:
106     return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
107   case CmpInst::ICMP_SLE:
108     return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1);
109   case CmpInst::ICMP_UGT: {
110     APInt UMin(CR.getUnsignedMin());
111     if (UMin.isMaxValue())
112       return getEmpty(W);
113     return ConstantRange(std::move(UMin) + 1, APInt::getZero(W));
114   }
115   case CmpInst::ICMP_SGT: {
116     APInt SMin(CR.getSignedMin());
117     if (SMin.isMaxSignedValue())
118       return getEmpty(W);
119     return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
120   }
121   case CmpInst::ICMP_UGE:
122     return getNonEmpty(CR.getUnsignedMin(), APInt::getZero(W));
123   case CmpInst::ICMP_SGE:
124     return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W));
125   }
126 }
127 
128 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
129                                                       const ConstantRange &CR) {
130   // Follows from De-Morgan's laws:
131   //
132   // ~(~A union ~B) == A intersect B.
133   //
134   return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
135       .inverse();
136 }
137 
138 ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
139                                                  const APInt &C) {
140   // Computes the exact range that is equal to both the constant ranges returned
141   // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
142   // when RHS is a singleton such as an APInt and so the assert is valid.
143   // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
144   // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
145   //
146   assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
147   return makeAllowedICmpRegion(Pred, C);
148 }
149 
150 bool ConstantRange::areInsensitiveToSignednessOfICmpPredicate(
151     const ConstantRange &CR1, const ConstantRange &CR2) {
152   if (CR1.isEmptySet() || CR2.isEmptySet())
153     return true;
154 
155   return (CR1.isAllNonNegative() && CR2.isAllNonNegative()) ||
156          (CR1.isAllNegative() && CR2.isAllNegative());
157 }
158 
159 bool ConstantRange::areInsensitiveToSignednessOfInvertedICmpPredicate(
160     const ConstantRange &CR1, const ConstantRange &CR2) {
161   if (CR1.isEmptySet() || CR2.isEmptySet())
162     return true;
163 
164   return (CR1.isAllNonNegative() && CR2.isAllNegative()) ||
165          (CR1.isAllNegative() && CR2.isAllNonNegative());
166 }
167 
168 CmpInst::Predicate ConstantRange::getEquivalentPredWithFlippedSignedness(
169     CmpInst::Predicate Pred, const ConstantRange &CR1,
170     const ConstantRange &CR2) {
171   assert(CmpInst::isIntPredicate(Pred) && CmpInst::isRelational(Pred) &&
172          "Only for relational integer predicates!");
173 
174   CmpInst::Predicate FlippedSignednessPred =
175       CmpInst::getFlippedSignednessPredicate(Pred);
176 
177   if (areInsensitiveToSignednessOfICmpPredicate(CR1, CR2))
178     return FlippedSignednessPred;
179 
180   if (areInsensitiveToSignednessOfInvertedICmpPredicate(CR1, CR2))
181     return CmpInst::getInversePredicate(FlippedSignednessPred);
182 
183   return CmpInst::Predicate::BAD_ICMP_PREDICATE;
184 }
185 
186 void ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
187                                       APInt &RHS, APInt &Offset) const {
188   Offset = APInt(getBitWidth(), 0);
189   if (isFullSet() || isEmptySet()) {
190     Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
191     RHS = APInt(getBitWidth(), 0);
192   } else if (auto *OnlyElt = getSingleElement()) {
193     Pred = CmpInst::ICMP_EQ;
194     RHS = *OnlyElt;
195   } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
196     Pred = CmpInst::ICMP_NE;
197     RHS = *OnlyMissingElt;
198   } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
199     Pred =
200         getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
201     RHS = getUpper();
202   } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
203     Pred =
204         getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
205     RHS = getLower();
206   } else {
207     Pred = CmpInst::ICMP_ULT;
208     RHS = getUpper() - getLower();
209     Offset = -getLower();
210   }
211 
212   assert(ConstantRange::makeExactICmpRegion(Pred, RHS) == add(Offset) &&
213          "Bad result!");
214 }
215 
216 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
217                                       APInt &RHS) const {
218   APInt Offset;
219   getEquivalentICmp(Pred, RHS, Offset);
220   return Offset.isZero();
221 }
222 
223 bool ConstantRange::icmp(CmpInst::Predicate Pred,
224                          const ConstantRange &Other) const {
225   return makeSatisfyingICmpRegion(Pred, Other).contains(*this);
226 }
227 
228 /// Exact mul nuw region for single element RHS.
229 static ConstantRange makeExactMulNUWRegion(const APInt &V) {
230   unsigned BitWidth = V.getBitWidth();
231   if (V == 0)
232     return ConstantRange::getFull(V.getBitWidth());
233 
234   return ConstantRange::getNonEmpty(
235       APIntOps::RoundingUDiv(APInt::getMinValue(BitWidth), V,
236                              APInt::Rounding::UP),
237       APIntOps::RoundingUDiv(APInt::getMaxValue(BitWidth), V,
238                              APInt::Rounding::DOWN) + 1);
239 }
240 
241 /// Exact mul nsw region for single element RHS.
242 static ConstantRange makeExactMulNSWRegion(const APInt &V) {
243   // Handle special case for 0, -1 and 1. See the last for reason why we
244   // specialize -1 and 1.
245   unsigned BitWidth = V.getBitWidth();
246   if (V == 0 || V.isOne())
247     return ConstantRange::getFull(BitWidth);
248 
249   APInt MinValue = APInt::getSignedMinValue(BitWidth);
250   APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
251   // e.g. Returning [-127, 127], represented as [-127, -128).
252   if (V.isAllOnes())
253     return ConstantRange(-MaxValue, MinValue);
254 
255   APInt Lower, Upper;
256   if (V.isNegative()) {
257     Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);
258     Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);
259   } else {
260     Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);
261     Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);
262   }
263   // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1).
264   // Upper + 1 is guaranteed not to overflow, because |divisor| > 1. 0, -1,
265   // and 1 are already handled as special cases.
266   return ConstantRange(Lower, Upper + 1);
267 }
268 
269 ConstantRange
270 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
271                                           const ConstantRange &Other,
272                                           unsigned NoWrapKind) {
273   using OBO = OverflowingBinaryOperator;
274 
275   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
276 
277   assert((NoWrapKind == OBO::NoSignedWrap ||
278           NoWrapKind == OBO::NoUnsignedWrap) &&
279          "NoWrapKind invalid!");
280 
281   bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
282   unsigned BitWidth = Other.getBitWidth();
283 
284   switch (BinOp) {
285   default:
286     llvm_unreachable("Unsupported binary op");
287 
288   case Instruction::Add: {
289     if (Unsigned)
290       return getNonEmpty(APInt::getZero(BitWidth), -Other.getUnsignedMax());
291 
292     APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
293     APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
294     return getNonEmpty(
295         SMin.isNegative() ? SignedMinVal - SMin : SignedMinVal,
296         SMax.isStrictlyPositive() ? SignedMinVal - SMax : SignedMinVal);
297   }
298 
299   case Instruction::Sub: {
300     if (Unsigned)
301       return getNonEmpty(Other.getUnsignedMax(), APInt::getMinValue(BitWidth));
302 
303     APInt SignedMinVal = APInt::getSignedMinValue(BitWidth);
304     APInt SMin = Other.getSignedMin(), SMax = Other.getSignedMax();
305     return getNonEmpty(
306         SMax.isStrictlyPositive() ? SignedMinVal + SMax : SignedMinVal,
307         SMin.isNegative() ? SignedMinVal + SMin : SignedMinVal);
308   }
309 
310   case Instruction::Mul:
311     if (Unsigned)
312       return makeExactMulNUWRegion(Other.getUnsignedMax());
313 
314     return makeExactMulNSWRegion(Other.getSignedMin())
315         .intersectWith(makeExactMulNSWRegion(Other.getSignedMax()));
316 
317   case Instruction::Shl: {
318     // For given range of shift amounts, if we ignore all illegal shift amounts
319     // (that always produce poison), what shift amount range is left?
320     ConstantRange ShAmt = Other.intersectWith(
321         ConstantRange(APInt(BitWidth, 0), APInt(BitWidth, (BitWidth - 1) + 1)));
322     if (ShAmt.isEmptySet()) {
323       // If the entire range of shift amounts is already poison-producing,
324       // then we can freely add more poison-producing flags ontop of that.
325       return getFull(BitWidth);
326     }
327     // There are some legal shift amounts, we can compute conservatively-correct
328     // range of no-wrap inputs. Note that by now we have clamped the ShAmtUMax
329     // to be at most bitwidth-1, which results in most conservative range.
330     APInt ShAmtUMax = ShAmt.getUnsignedMax();
331     if (Unsigned)
332       return getNonEmpty(APInt::getZero(BitWidth),
333                          APInt::getMaxValue(BitWidth).lshr(ShAmtUMax) + 1);
334     return getNonEmpty(APInt::getSignedMinValue(BitWidth).ashr(ShAmtUMax),
335                        APInt::getSignedMaxValue(BitWidth).ashr(ShAmtUMax) + 1);
336   }
337   }
338 }
339 
340 ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
341                                                    const APInt &Other,
342                                                    unsigned NoWrapKind) {
343   // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
344   // "for all" and "for any" coincide in this case.
345   return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);
346 }
347 
348 bool ConstantRange::isFullSet() const {
349   return Lower == Upper && Lower.isMaxValue();
350 }
351 
352 bool ConstantRange::isEmptySet() const {
353   return Lower == Upper && Lower.isMinValue();
354 }
355 
356 bool ConstantRange::isWrappedSet() const {
357   return Lower.ugt(Upper) && !Upper.isZero();
358 }
359 
360 bool ConstantRange::isUpperWrapped() const {
361   return Lower.ugt(Upper);
362 }
363 
364 bool ConstantRange::isSignWrappedSet() const {
365   return Lower.sgt(Upper) && !Upper.isMinSignedValue();
366 }
367 
368 bool ConstantRange::isUpperSignWrapped() const {
369   return Lower.sgt(Upper);
370 }
371 
372 bool
373 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
374   assert(getBitWidth() == Other.getBitWidth());
375   if (isFullSet())
376     return false;
377   if (Other.isFullSet())
378     return true;
379   return (Upper - Lower).ult(Other.Upper - Other.Lower);
380 }
381 
382 bool
383 ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
384   // If this a full set, we need special handling to avoid needing an extra bit
385   // to represent the size.
386   if (isFullSet())
387     return MaxSize == 0 || APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
388 
389   return (Upper - Lower).ugt(MaxSize);
390 }
391 
392 bool ConstantRange::isAllNegative() const {
393   // Empty set is all negative, full set is not.
394   if (isEmptySet())
395     return true;
396   if (isFullSet())
397     return false;
398 
399   return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
400 }
401 
402 bool ConstantRange::isAllNonNegative() const {
403   // Empty and full set are automatically treated correctly.
404   return !isSignWrappedSet() && Lower.isNonNegative();
405 }
406 
407 APInt ConstantRange::getUnsignedMax() const {
408   if (isFullSet() || isUpperWrapped())
409     return APInt::getMaxValue(getBitWidth());
410   return getUpper() - 1;
411 }
412 
413 APInt ConstantRange::getUnsignedMin() const {
414   if (isFullSet() || isWrappedSet())
415     return APInt::getMinValue(getBitWidth());
416   return getLower();
417 }
418 
419 APInt ConstantRange::getSignedMax() const {
420   if (isFullSet() || isUpperSignWrapped())
421     return APInt::getSignedMaxValue(getBitWidth());
422   return getUpper() - 1;
423 }
424 
425 APInt ConstantRange::getSignedMin() const {
426   if (isFullSet() || isSignWrappedSet())
427     return APInt::getSignedMinValue(getBitWidth());
428   return getLower();
429 }
430 
431 bool ConstantRange::contains(const APInt &V) const {
432   if (Lower == Upper)
433     return isFullSet();
434 
435   if (!isUpperWrapped())
436     return Lower.ule(V) && V.ult(Upper);
437   return Lower.ule(V) || V.ult(Upper);
438 }
439 
440 bool ConstantRange::contains(const ConstantRange &Other) const {
441   if (isFullSet() || Other.isEmptySet()) return true;
442   if (isEmptySet() || Other.isFullSet()) return false;
443 
444   if (!isUpperWrapped()) {
445     if (Other.isUpperWrapped())
446       return false;
447 
448     return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
449   }
450 
451   if (!Other.isUpperWrapped())
452     return Other.getUpper().ule(Upper) ||
453            Lower.ule(Other.getLower());
454 
455   return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
456 }
457 
458 unsigned ConstantRange::getActiveBits() const {
459   if (isEmptySet())
460     return 0;
461 
462   return getUnsignedMax().getActiveBits();
463 }
464 
465 unsigned ConstantRange::getMinSignedBits() const {
466   if (isEmptySet())
467     return 0;
468 
469   return std::max(getSignedMin().getMinSignedBits(),
470                   getSignedMax().getMinSignedBits());
471 }
472 
473 ConstantRange ConstantRange::subtract(const APInt &Val) const {
474   assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
475   // If the set is empty or full, don't modify the endpoints.
476   if (Lower == Upper)
477     return *this;
478   return ConstantRange(Lower - Val, Upper - Val);
479 }
480 
481 ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
482   return intersectWith(CR.inverse());
483 }
484 
485 static ConstantRange getPreferredRange(
486     const ConstantRange &CR1, const ConstantRange &CR2,
487     ConstantRange::PreferredRangeType Type) {
488   if (Type == ConstantRange::Unsigned) {
489     if (!CR1.isWrappedSet() && CR2.isWrappedSet())
490       return CR1;
491     if (CR1.isWrappedSet() && !CR2.isWrappedSet())
492       return CR2;
493   } else if (Type == ConstantRange::Signed) {
494     if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
495       return CR1;
496     if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
497       return CR2;
498   }
499 
500   if (CR1.isSizeStrictlySmallerThan(CR2))
501     return CR1;
502   return CR2;
503 }
504 
505 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
506                                            PreferredRangeType Type) const {
507   assert(getBitWidth() == CR.getBitWidth() &&
508          "ConstantRange types don't agree!");
509 
510   // Handle common cases.
511   if (   isEmptySet() || CR.isFullSet()) return *this;
512   if (CR.isEmptySet() ||    isFullSet()) return CR;
513 
514   if (!isUpperWrapped() && CR.isUpperWrapped())
515     return CR.intersectWith(*this, Type);
516 
517   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
518     if (Lower.ult(CR.Lower)) {
519       // L---U       : this
520       //       L---U : CR
521       if (Upper.ule(CR.Lower))
522         return getEmpty();
523 
524       // L---U       : this
525       //   L---U     : CR
526       if (Upper.ult(CR.Upper))
527         return ConstantRange(CR.Lower, Upper);
528 
529       // L-------U   : this
530       //   L---U     : CR
531       return CR;
532     }
533     //   L---U     : this
534     // L-------U   : CR
535     if (Upper.ult(CR.Upper))
536       return *this;
537 
538     //   L-----U   : this
539     // L-----U     : CR
540     if (Lower.ult(CR.Upper))
541       return ConstantRange(Lower, CR.Upper);
542 
543     //       L---U : this
544     // L---U       : CR
545     return getEmpty();
546   }
547 
548   if (isUpperWrapped() && !CR.isUpperWrapped()) {
549     if (CR.Lower.ult(Upper)) {
550       // ------U   L--- : this
551       //  L--U          : CR
552       if (CR.Upper.ult(Upper))
553         return CR;
554 
555       // ------U   L--- : this
556       //  L------U      : CR
557       if (CR.Upper.ule(Lower))
558         return ConstantRange(CR.Lower, Upper);
559 
560       // ------U   L--- : this
561       //  L----------U  : CR
562       return getPreferredRange(*this, CR, Type);
563     }
564     if (CR.Lower.ult(Lower)) {
565       // --U      L---- : this
566       //     L--U       : CR
567       if (CR.Upper.ule(Lower))
568         return getEmpty();
569 
570       // --U      L---- : this
571       //     L------U   : CR
572       return ConstantRange(Lower, CR.Upper);
573     }
574 
575     // --U  L------ : this
576     //        L--U  : CR
577     return CR;
578   }
579 
580   if (CR.Upper.ult(Upper)) {
581     // ------U L-- : this
582     // --U L------ : CR
583     if (CR.Lower.ult(Upper))
584       return getPreferredRange(*this, CR, Type);
585 
586     // ----U   L-- : this
587     // --U   L---- : CR
588     if (CR.Lower.ult(Lower))
589       return ConstantRange(Lower, CR.Upper);
590 
591     // ----U L---- : this
592     // --U     L-- : CR
593     return CR;
594   }
595   if (CR.Upper.ule(Lower)) {
596     // --U     L-- : this
597     // ----U L---- : CR
598     if (CR.Lower.ult(Lower))
599       return *this;
600 
601     // --U   L---- : this
602     // ----U   L-- : CR
603     return ConstantRange(CR.Lower, Upper);
604   }
605 
606   // --U L------ : this
607   // ------U L-- : CR
608   return getPreferredRange(*this, CR, Type);
609 }
610 
611 ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
612                                        PreferredRangeType Type) const {
613   assert(getBitWidth() == CR.getBitWidth() &&
614          "ConstantRange types don't agree!");
615 
616   if (   isFullSet() || CR.isEmptySet()) return *this;
617   if (CR.isFullSet() ||    isEmptySet()) return CR;
618 
619   if (!isUpperWrapped() && CR.isUpperWrapped())
620     return CR.unionWith(*this, Type);
621 
622   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
623     //        L---U  and  L---U        : this
624     //  L---U                   L---U  : CR
625     // result in one of
626     //  L---------U
627     // -----U L-----
628     if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
629       return getPreferredRange(
630           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
631 
632     APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
633     APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
634 
635     if (L.isZero() && U.isZero())
636       return getFull();
637 
638     return ConstantRange(std::move(L), std::move(U));
639   }
640 
641   if (!CR.isUpperWrapped()) {
642     // ------U   L-----  and  ------U   L----- : this
643     //   L--U                            L--U  : CR
644     if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
645       return *this;
646 
647     // ------U   L----- : this
648     //    L---------U   : CR
649     if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
650       return getFull();
651 
652     // ----U       L---- : this
653     //       L---U       : CR
654     // results in one of
655     // ----------U L----
656     // ----U L----------
657     if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
658       return getPreferredRange(
659           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
660 
661     // ----U     L----- : this
662     //        L----U    : CR
663     if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
664       return ConstantRange(CR.Lower, Upper);
665 
666     // ------U    L---- : this
667     //    L-----U       : CR
668     assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
669            "ConstantRange::unionWith missed a case with one range wrapped");
670     return ConstantRange(Lower, CR.Upper);
671   }
672 
673   // ------U    L----  and  ------U    L---- : this
674   // -U  L-----------  and  ------------U  L : CR
675   if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
676     return getFull();
677 
678   APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
679   APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
680 
681   return ConstantRange(std::move(L), std::move(U));
682 }
683 
684 Optional<ConstantRange>
685 ConstantRange::exactIntersectWith(const ConstantRange &CR) const {
686   // TODO: This can be implemented more efficiently.
687   ConstantRange Result = intersectWith(CR);
688   if (Result == inverse().unionWith(CR.inverse()).inverse())
689     return Result;
690   return None;
691 }
692 
693 Optional<ConstantRange>
694 ConstantRange::exactUnionWith(const ConstantRange &CR) const {
695   // TODO: This can be implemented more efficiently.
696   ConstantRange Result = unionWith(CR);
697   if (Result == inverse().intersectWith(CR.inverse()).inverse())
698     return Result;
699   return None;
700 }
701 
702 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
703                                     uint32_t ResultBitWidth) const {
704   switch (CastOp) {
705   default:
706     llvm_unreachable("unsupported cast type");
707   case Instruction::Trunc:
708     return truncate(ResultBitWidth);
709   case Instruction::SExt:
710     return signExtend(ResultBitWidth);
711   case Instruction::ZExt:
712     return zeroExtend(ResultBitWidth);
713   case Instruction::BitCast:
714     return *this;
715   case Instruction::FPToUI:
716   case Instruction::FPToSI:
717     if (getBitWidth() == ResultBitWidth)
718       return *this;
719     else
720       return getFull(ResultBitWidth);
721   case Instruction::UIToFP: {
722     // TODO: use input range if available
723     auto BW = getBitWidth();
724     APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
725     APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
726     return ConstantRange(std::move(Min), std::move(Max));
727   }
728   case Instruction::SIToFP: {
729     // TODO: use input range if available
730     auto BW = getBitWidth();
731     APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
732     APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
733     return ConstantRange(std::move(SMin), std::move(SMax));
734   }
735   case Instruction::FPTrunc:
736   case Instruction::FPExt:
737   case Instruction::IntToPtr:
738   case Instruction::PtrToInt:
739   case Instruction::AddrSpaceCast:
740     // Conservatively return getFull set.
741     return getFull(ResultBitWidth);
742   };
743 }
744 
745 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
746   if (isEmptySet()) return getEmpty(DstTySize);
747 
748   unsigned SrcTySize = getBitWidth();
749   assert(SrcTySize < DstTySize && "Not a value extension");
750   if (isFullSet() || isUpperWrapped()) {
751     // Change into [0, 1 << src bit width)
752     APInt LowerExt(DstTySize, 0);
753     if (!Upper) // special case: [X, 0) -- not really wrapping around
754       LowerExt = Lower.zext(DstTySize);
755     return ConstantRange(std::move(LowerExt),
756                          APInt::getOneBitSet(DstTySize, SrcTySize));
757   }
758 
759   return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
760 }
761 
762 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
763   if (isEmptySet()) return getEmpty(DstTySize);
764 
765   unsigned SrcTySize = getBitWidth();
766   assert(SrcTySize < DstTySize && "Not a value extension");
767 
768   // special case: [X, INT_MIN) -- not really wrapping around
769   if (Upper.isMinSignedValue())
770     return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
771 
772   if (isFullSet() || isSignWrappedSet()) {
773     return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
774                          APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
775   }
776 
777   return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
778 }
779 
780 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
781   assert(getBitWidth() > DstTySize && "Not a value truncation");
782   if (isEmptySet())
783     return getEmpty(DstTySize);
784   if (isFullSet())
785     return getFull(DstTySize);
786 
787   APInt LowerDiv(Lower), UpperDiv(Upper);
788   ConstantRange Union(DstTySize, /*isFullSet=*/false);
789 
790   // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
791   // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
792   // then we do the union with [MaxValue, Upper)
793   if (isUpperWrapped()) {
794     // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
795     // truncated range.
796     if (Upper.getActiveBits() > DstTySize ||
797         Upper.countTrailingOnes() == DstTySize)
798       return getFull(DstTySize);
799 
800     Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
801     UpperDiv.setAllBits();
802 
803     // Union covers the MaxValue case, so return if the remaining range is just
804     // MaxValue(DstTy).
805     if (LowerDiv == UpperDiv)
806       return Union;
807   }
808 
809   // Chop off the most significant bits that are past the destination bitwidth.
810   if (LowerDiv.getActiveBits() > DstTySize) {
811     // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
812     APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
813     LowerDiv -= Adjust;
814     UpperDiv -= Adjust;
815   }
816 
817   unsigned UpperDivWidth = UpperDiv.getActiveBits();
818   if (UpperDivWidth <= DstTySize)
819     return ConstantRange(LowerDiv.trunc(DstTySize),
820                          UpperDiv.trunc(DstTySize)).unionWith(Union);
821 
822   // The truncated value wraps around. Check if we can do better than fullset.
823   if (UpperDivWidth == DstTySize + 1) {
824     // Clear the MSB so that UpperDiv wraps around.
825     UpperDiv.clearBit(DstTySize);
826     if (UpperDiv.ult(LowerDiv))
827       return ConstantRange(LowerDiv.trunc(DstTySize),
828                            UpperDiv.trunc(DstTySize)).unionWith(Union);
829   }
830 
831   return getFull(DstTySize);
832 }
833 
834 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
835   unsigned SrcTySize = getBitWidth();
836   if (SrcTySize > DstTySize)
837     return truncate(DstTySize);
838   if (SrcTySize < DstTySize)
839     return zeroExtend(DstTySize);
840   return *this;
841 }
842 
843 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
844   unsigned SrcTySize = getBitWidth();
845   if (SrcTySize > DstTySize)
846     return truncate(DstTySize);
847   if (SrcTySize < DstTySize)
848     return signExtend(DstTySize);
849   return *this;
850 }
851 
852 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
853                                       const ConstantRange &Other) const {
854   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
855 
856   switch (BinOp) {
857   case Instruction::Add:
858     return add(Other);
859   case Instruction::Sub:
860     return sub(Other);
861   case Instruction::Mul:
862     return multiply(Other);
863   case Instruction::UDiv:
864     return udiv(Other);
865   case Instruction::SDiv:
866     return sdiv(Other);
867   case Instruction::URem:
868     return urem(Other);
869   case Instruction::SRem:
870     return srem(Other);
871   case Instruction::Shl:
872     return shl(Other);
873   case Instruction::LShr:
874     return lshr(Other);
875   case Instruction::AShr:
876     return ashr(Other);
877   case Instruction::And:
878     return binaryAnd(Other);
879   case Instruction::Or:
880     return binaryOr(Other);
881   case Instruction::Xor:
882     return binaryXor(Other);
883   // Note: floating point operations applied to abstract ranges are just
884   // ideal integer operations with a lossy representation
885   case Instruction::FAdd:
886     return add(Other);
887   case Instruction::FSub:
888     return sub(Other);
889   case Instruction::FMul:
890     return multiply(Other);
891   default:
892     // Conservatively return getFull set.
893     return getFull();
894   }
895 }
896 
897 ConstantRange ConstantRange::overflowingBinaryOp(Instruction::BinaryOps BinOp,
898                                                  const ConstantRange &Other,
899                                                  unsigned NoWrapKind) const {
900   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
901 
902   switch (BinOp) {
903   case Instruction::Add:
904     return addWithNoWrap(Other, NoWrapKind);
905   case Instruction::Sub:
906     return subWithNoWrap(Other, NoWrapKind);
907   default:
908     // Don't know about this Overflowing Binary Operation.
909     // Conservatively fallback to plain binop handling.
910     return binaryOp(BinOp, Other);
911   }
912 }
913 
914 bool ConstantRange::isIntrinsicSupported(Intrinsic::ID IntrinsicID) {
915   switch (IntrinsicID) {
916   case Intrinsic::uadd_sat:
917   case Intrinsic::usub_sat:
918   case Intrinsic::sadd_sat:
919   case Intrinsic::ssub_sat:
920   case Intrinsic::umin:
921   case Intrinsic::umax:
922   case Intrinsic::smin:
923   case Intrinsic::smax:
924   case Intrinsic::abs:
925     return true;
926   default:
927     return false;
928   }
929 }
930 
931 ConstantRange ConstantRange::intrinsic(Intrinsic::ID IntrinsicID,
932                                        ArrayRef<ConstantRange> Ops) {
933   switch (IntrinsicID) {
934   case Intrinsic::uadd_sat:
935     return Ops[0].uadd_sat(Ops[1]);
936   case Intrinsic::usub_sat:
937     return Ops[0].usub_sat(Ops[1]);
938   case Intrinsic::sadd_sat:
939     return Ops[0].sadd_sat(Ops[1]);
940   case Intrinsic::ssub_sat:
941     return Ops[0].ssub_sat(Ops[1]);
942   case Intrinsic::umin:
943     return Ops[0].umin(Ops[1]);
944   case Intrinsic::umax:
945     return Ops[0].umax(Ops[1]);
946   case Intrinsic::smin:
947     return Ops[0].smin(Ops[1]);
948   case Intrinsic::smax:
949     return Ops[0].smax(Ops[1]);
950   case Intrinsic::abs: {
951     const APInt *IntMinIsPoison = Ops[1].getSingleElement();
952     assert(IntMinIsPoison && "Must be known (immarg)");
953     assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean");
954     return Ops[0].abs(IntMinIsPoison->getBoolValue());
955   }
956   default:
957     assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported");
958     llvm_unreachable("Unsupported intrinsic");
959   }
960 }
961 
962 ConstantRange
963 ConstantRange::add(const ConstantRange &Other) const {
964   if (isEmptySet() || Other.isEmptySet())
965     return getEmpty();
966   if (isFullSet() || Other.isFullSet())
967     return getFull();
968 
969   APInt NewLower = getLower() + Other.getLower();
970   APInt NewUpper = getUpper() + Other.getUpper() - 1;
971   if (NewLower == NewUpper)
972     return getFull();
973 
974   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
975   if (X.isSizeStrictlySmallerThan(*this) ||
976       X.isSizeStrictlySmallerThan(Other))
977     // We've wrapped, therefore, full set.
978     return getFull();
979   return X;
980 }
981 
982 ConstantRange ConstantRange::addWithNoWrap(const ConstantRange &Other,
983                                            unsigned NoWrapKind,
984                                            PreferredRangeType RangeType) const {
985   // Calculate the range for "X + Y" which is guaranteed not to wrap(overflow).
986   // (X is from this, and Y is from Other)
987   if (isEmptySet() || Other.isEmptySet())
988     return getEmpty();
989   if (isFullSet() && Other.isFullSet())
990     return getFull();
991 
992   using OBO = OverflowingBinaryOperator;
993   ConstantRange Result = add(Other);
994 
995   // If an overflow happens for every value pair in these two constant ranges,
996   // we must return Empty set. In this case, we get that for free, because we
997   // get lucky that intersection of add() with uadd_sat()/sadd_sat() results
998   // in an empty set.
999 
1000   if (NoWrapKind & OBO::NoSignedWrap)
1001     Result = Result.intersectWith(sadd_sat(Other), RangeType);
1002 
1003   if (NoWrapKind & OBO::NoUnsignedWrap)
1004     Result = Result.intersectWith(uadd_sat(Other), RangeType);
1005 
1006   return Result;
1007 }
1008 
1009 ConstantRange
1010 ConstantRange::sub(const ConstantRange &Other) const {
1011   if (isEmptySet() || Other.isEmptySet())
1012     return getEmpty();
1013   if (isFullSet() || Other.isFullSet())
1014     return getFull();
1015 
1016   APInt NewLower = getLower() - Other.getUpper() + 1;
1017   APInt NewUpper = getUpper() - Other.getLower();
1018   if (NewLower == NewUpper)
1019     return getFull();
1020 
1021   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
1022   if (X.isSizeStrictlySmallerThan(*this) ||
1023       X.isSizeStrictlySmallerThan(Other))
1024     // We've wrapped, therefore, full set.
1025     return getFull();
1026   return X;
1027 }
1028 
1029 ConstantRange ConstantRange::subWithNoWrap(const ConstantRange &Other,
1030                                            unsigned NoWrapKind,
1031                                            PreferredRangeType RangeType) const {
1032   // Calculate the range for "X - Y" which is guaranteed not to wrap(overflow).
1033   // (X is from this, and Y is from Other)
1034   if (isEmptySet() || Other.isEmptySet())
1035     return getEmpty();
1036   if (isFullSet() && Other.isFullSet())
1037     return getFull();
1038 
1039   using OBO = OverflowingBinaryOperator;
1040   ConstantRange Result = sub(Other);
1041 
1042   // If an overflow happens for every value pair in these two constant ranges,
1043   // we must return Empty set. In signed case, we get that for free, because we
1044   // get lucky that intersection of sub() with ssub_sat() results in an
1045   // empty set. But for unsigned we must perform the overflow check manually.
1046 
1047   if (NoWrapKind & OBO::NoSignedWrap)
1048     Result = Result.intersectWith(ssub_sat(Other), RangeType);
1049 
1050   if (NoWrapKind & OBO::NoUnsignedWrap) {
1051     if (getUnsignedMax().ult(Other.getUnsignedMin()))
1052       return getEmpty(); // Always overflows.
1053     Result = Result.intersectWith(usub_sat(Other), RangeType);
1054   }
1055 
1056   return Result;
1057 }
1058 
1059 ConstantRange
1060 ConstantRange::multiply(const ConstantRange &Other) const {
1061   // TODO: If either operand is a single element and the multiply is known to
1062   // be non-wrapping, round the result min and max value to the appropriate
1063   // multiple of that element. If wrapping is possible, at least adjust the
1064   // range according to the greatest power-of-two factor of the single element.
1065 
1066   if (isEmptySet() || Other.isEmptySet())
1067     return getEmpty();
1068 
1069   // Multiplication is signedness-independent. However different ranges can be
1070   // obtained depending on how the input ranges are treated. These different
1071   // ranges are all conservatively correct, but one might be better than the
1072   // other. We calculate two ranges; one treating the inputs as unsigned
1073   // and the other signed, then return the smallest of these ranges.
1074 
1075   // Unsigned range first.
1076   APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
1077   APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
1078   APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
1079   APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
1080 
1081   ConstantRange Result_zext = ConstantRange(this_min * Other_min,
1082                                             this_max * Other_max + 1);
1083   ConstantRange UR = Result_zext.truncate(getBitWidth());
1084 
1085   // If the unsigned range doesn't wrap, and isn't negative then it's a range
1086   // from one positive number to another which is as good as we can generate.
1087   // In this case, skip the extra work of generating signed ranges which aren't
1088   // going to be better than this range.
1089   if (!UR.isUpperWrapped() &&
1090       (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
1091     return UR;
1092 
1093   // Now the signed range. Because we could be dealing with negative numbers
1094   // here, the lower bound is the smallest of the cartesian product of the
1095   // lower and upper ranges; for example:
1096   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1097   // Similarly for the upper bound, swapping min for max.
1098 
1099   this_min = getSignedMin().sext(getBitWidth() * 2);
1100   this_max = getSignedMax().sext(getBitWidth() * 2);
1101   Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
1102   Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
1103 
1104   auto L = {this_min * Other_min, this_min * Other_max,
1105             this_max * Other_min, this_max * Other_max};
1106   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1107   ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
1108   ConstantRange SR = Result_sext.truncate(getBitWidth());
1109 
1110   return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
1111 }
1112 
1113 ConstantRange ConstantRange::smul_fast(const ConstantRange &Other) const {
1114   if (isEmptySet() || Other.isEmptySet())
1115     return getEmpty();
1116 
1117   APInt Min = getSignedMin();
1118   APInt Max = getSignedMax();
1119   APInt OtherMin = Other.getSignedMin();
1120   APInt OtherMax = Other.getSignedMax();
1121 
1122   bool O1, O2, O3, O4;
1123   auto Muls = {Min.smul_ov(OtherMin, O1), Min.smul_ov(OtherMax, O2),
1124                Max.smul_ov(OtherMin, O3), Max.smul_ov(OtherMax, O4)};
1125   if (O1 || O2 || O3 || O4)
1126     return getFull();
1127 
1128   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1129   return getNonEmpty(std::min(Muls, Compare), std::max(Muls, Compare) + 1);
1130 }
1131 
1132 ConstantRange
1133 ConstantRange::smax(const ConstantRange &Other) const {
1134   // X smax Y is: range(smax(X_smin, Y_smin),
1135   //                    smax(X_smax, Y_smax))
1136   if (isEmptySet() || Other.isEmptySet())
1137     return getEmpty();
1138   APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
1139   APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
1140   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1141   if (isSignWrappedSet() || Other.isSignWrappedSet())
1142     return Res.intersectWith(unionWith(Other, Signed), Signed);
1143   return Res;
1144 }
1145 
1146 ConstantRange
1147 ConstantRange::umax(const ConstantRange &Other) const {
1148   // X umax Y is: range(umax(X_umin, Y_umin),
1149   //                    umax(X_umax, Y_umax))
1150   if (isEmptySet() || Other.isEmptySet())
1151     return getEmpty();
1152   APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1153   APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1154   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1155   if (isWrappedSet() || Other.isWrappedSet())
1156     return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
1157   return Res;
1158 }
1159 
1160 ConstantRange
1161 ConstantRange::smin(const ConstantRange &Other) const {
1162   // X smin Y is: range(smin(X_smin, Y_smin),
1163   //                    smin(X_smax, Y_smax))
1164   if (isEmptySet() || Other.isEmptySet())
1165     return getEmpty();
1166   APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
1167   APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
1168   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1169   if (isSignWrappedSet() || Other.isSignWrappedSet())
1170     return Res.intersectWith(unionWith(Other, Signed), Signed);
1171   return Res;
1172 }
1173 
1174 ConstantRange
1175 ConstantRange::umin(const ConstantRange &Other) const {
1176   // X umin Y is: range(umin(X_umin, Y_umin),
1177   //                    umin(X_umax, Y_umax))
1178   if (isEmptySet() || Other.isEmptySet())
1179     return getEmpty();
1180   APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
1181   APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1182   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1183   if (isWrappedSet() || Other.isWrappedSet())
1184     return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
1185   return Res;
1186 }
1187 
1188 ConstantRange
1189 ConstantRange::udiv(const ConstantRange &RHS) const {
1190   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1191     return getEmpty();
1192 
1193   APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
1194 
1195   APInt RHS_umin = RHS.getUnsignedMin();
1196   if (RHS_umin.isZero()) {
1197     // We want the lowest value in RHS excluding zero. Usually that would be 1
1198     // except for a range in the form of [X, 1) in which case it would be X.
1199     if (RHS.getUpper() == 1)
1200       RHS_umin = RHS.getLower();
1201     else
1202       RHS_umin = 1;
1203   }
1204 
1205   APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
1206   return getNonEmpty(std::move(Lower), std::move(Upper));
1207 }
1208 
1209 ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const {
1210   // We split up the LHS and RHS into positive and negative components
1211   // and then also compute the positive and negative components of the result
1212   // separately by combining division results with the appropriate signs.
1213   APInt Zero = APInt::getZero(getBitWidth());
1214   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1215   ConstantRange PosFilter(APInt(getBitWidth(), 1), SignedMin);
1216   ConstantRange NegFilter(SignedMin, Zero);
1217   ConstantRange PosL = intersectWith(PosFilter);
1218   ConstantRange NegL = intersectWith(NegFilter);
1219   ConstantRange PosR = RHS.intersectWith(PosFilter);
1220   ConstantRange NegR = RHS.intersectWith(NegFilter);
1221 
1222   ConstantRange PosRes = getEmpty();
1223   if (!PosL.isEmptySet() && !PosR.isEmptySet())
1224     // pos / pos = pos.
1225     PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1),
1226                            (PosL.Upper - 1).sdiv(PosR.Lower) + 1);
1227 
1228   if (!NegL.isEmptySet() && !NegR.isEmptySet()) {
1229     // neg / neg = pos.
1230     //
1231     // We need to deal with one tricky case here: SignedMin / -1 is UB on the
1232     // IR level, so we'll want to exclude this case when calculating bounds.
1233     // (For APInts the operation is well-defined and yields SignedMin.) We
1234     // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
1235     APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower);
1236     if (NegL.Lower.isMinSignedValue() && NegR.Upper.isZero()) {
1237       // Remove -1 from the LHS. Skip if it's the only element, as this would
1238       // leave us with an empty set.
1239       if (!NegR.Lower.isAllOnes()) {
1240         APInt AdjNegRUpper;
1241         if (RHS.Lower.isAllOnes())
1242           // Negative part of [-1, X] without -1 is [SignedMin, X].
1243           AdjNegRUpper = RHS.Upper;
1244         else
1245           // [X, -1] without -1 is [X, -2].
1246           AdjNegRUpper = NegR.Upper - 1;
1247 
1248         PosRes = PosRes.unionWith(
1249             ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1));
1250       }
1251 
1252       // Remove SignedMin from the RHS. Skip if it's the only element, as this
1253       // would leave us with an empty set.
1254       if (NegL.Upper != SignedMin + 1) {
1255         APInt AdjNegLLower;
1256         if (Upper == SignedMin + 1)
1257           // Negative part of [X, SignedMin] without SignedMin is [X, -1].
1258           AdjNegLLower = Lower;
1259         else
1260           // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
1261           AdjNegLLower = NegL.Lower + 1;
1262 
1263         PosRes = PosRes.unionWith(
1264             ConstantRange(std::move(Lo),
1265                           AdjNegLLower.sdiv(NegR.Upper - 1) + 1));
1266       }
1267     } else {
1268       PosRes = PosRes.unionWith(
1269           ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1));
1270     }
1271   }
1272 
1273   ConstantRange NegRes = getEmpty();
1274   if (!PosL.isEmptySet() && !NegR.isEmptySet())
1275     // pos / neg = neg.
1276     NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1),
1277                            PosL.Lower.sdiv(NegR.Lower) + 1);
1278 
1279   if (!NegL.isEmptySet() && !PosR.isEmptySet())
1280     // neg / pos = neg.
1281     NegRes = NegRes.unionWith(
1282         ConstantRange(NegL.Lower.sdiv(PosR.Lower),
1283                       (NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1));
1284 
1285   // Prefer a non-wrapping signed range here.
1286   ConstantRange Res = NegRes.unionWith(PosRes, PreferredRangeType::Signed);
1287 
1288   // Preserve the zero that we dropped when splitting the LHS by sign.
1289   if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))
1290     Res = Res.unionWith(ConstantRange(Zero));
1291   return Res;
1292 }
1293 
1294 ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
1295   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1296     return getEmpty();
1297 
1298   if (const APInt *RHSInt = RHS.getSingleElement()) {
1299     // UREM by null is UB.
1300     if (RHSInt->isZero())
1301       return getEmpty();
1302     // Use APInt's implementation of UREM for single element ranges.
1303     if (const APInt *LHSInt = getSingleElement())
1304       return {LHSInt->urem(*RHSInt)};
1305   }
1306 
1307   // L % R for L < R is L.
1308   if (getUnsignedMax().ult(RHS.getUnsignedMin()))
1309     return *this;
1310 
1311   // L % R is <= L and < R.
1312   APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
1313   return getNonEmpty(APInt::getZero(getBitWidth()), std::move(Upper));
1314 }
1315 
1316 ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {
1317   if (isEmptySet() || RHS.isEmptySet())
1318     return getEmpty();
1319 
1320   if (const APInt *RHSInt = RHS.getSingleElement()) {
1321     // SREM by null is UB.
1322     if (RHSInt->isZero())
1323       return getEmpty();
1324     // Use APInt's implementation of SREM for single element ranges.
1325     if (const APInt *LHSInt = getSingleElement())
1326       return {LHSInt->srem(*RHSInt)};
1327   }
1328 
1329   ConstantRange AbsRHS = RHS.abs();
1330   APInt MinAbsRHS = AbsRHS.getUnsignedMin();
1331   APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
1332 
1333   // Modulus by zero is UB.
1334   if (MaxAbsRHS.isZero())
1335     return getEmpty();
1336 
1337   if (MinAbsRHS.isZero())
1338     ++MinAbsRHS;
1339 
1340   APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
1341 
1342   if (MinLHS.isNonNegative()) {
1343     // L % R for L < R is L.
1344     if (MaxLHS.ult(MinAbsRHS))
1345       return *this;
1346 
1347     // L % R is <= L and < R.
1348     APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1349     return ConstantRange(APInt::getZero(getBitWidth()), std::move(Upper));
1350   }
1351 
1352   // Same basic logic as above, but the result is negative.
1353   if (MaxLHS.isNegative()) {
1354     if (MinLHS.ugt(-MinAbsRHS))
1355       return *this;
1356 
1357     APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1358     return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
1359   }
1360 
1361   // LHS range crosses zero.
1362   APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1363   APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1364   return ConstantRange(std::move(Lower), std::move(Upper));
1365 }
1366 
1367 ConstantRange ConstantRange::binaryNot() const {
1368   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
1369 }
1370 
1371 ConstantRange
1372 ConstantRange::binaryAnd(const ConstantRange &Other) const {
1373   if (isEmptySet() || Other.isEmptySet())
1374     return getEmpty();
1375 
1376   // Use APInt's implementation of AND for single element ranges.
1377   if (isSingleElement() && Other.isSingleElement())
1378     return {*getSingleElement() & *Other.getSingleElement()};
1379 
1380   // TODO: replace this with something less conservative
1381 
1382   APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
1383   return getNonEmpty(APInt::getZero(getBitWidth()), std::move(umin) + 1);
1384 }
1385 
1386 ConstantRange
1387 ConstantRange::binaryOr(const ConstantRange &Other) const {
1388   if (isEmptySet() || Other.isEmptySet())
1389     return getEmpty();
1390 
1391   // Use APInt's implementation of OR for single element ranges.
1392   if (isSingleElement() && Other.isSingleElement())
1393     return {*getSingleElement() | *Other.getSingleElement()};
1394 
1395   // TODO: replace this with something less conservative
1396 
1397   APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1398   return getNonEmpty(std::move(umax), APInt::getZero(getBitWidth()));
1399 }
1400 
1401 ConstantRange ConstantRange::binaryXor(const ConstantRange &Other) const {
1402   if (isEmptySet() || Other.isEmptySet())
1403     return getEmpty();
1404 
1405   // Use APInt's implementation of XOR for single element ranges.
1406   if (isSingleElement() && Other.isSingleElement())
1407     return {*getSingleElement() ^ *Other.getSingleElement()};
1408 
1409   // Special-case binary complement, since we can give a precise answer.
1410   if (Other.isSingleElement() && Other.getSingleElement()->isAllOnes())
1411     return binaryNot();
1412   if (isSingleElement() && getSingleElement()->isAllOnes())
1413     return Other.binaryNot();
1414 
1415   // TODO: replace this with something less conservative
1416   return getFull();
1417 }
1418 
1419 ConstantRange
1420 ConstantRange::shl(const ConstantRange &Other) const {
1421   if (isEmptySet() || Other.isEmptySet())
1422     return getEmpty();
1423 
1424   APInt Min = getUnsignedMin();
1425   APInt Max = getUnsignedMax();
1426   if (const APInt *RHS = Other.getSingleElement()) {
1427     unsigned BW = getBitWidth();
1428     if (RHS->uge(BW))
1429       return getEmpty();
1430 
1431     unsigned EqualLeadingBits = (Min ^ Max).countLeadingZeros();
1432     if (RHS->ule(EqualLeadingBits))
1433       return getNonEmpty(Min << *RHS, (Max << *RHS) + 1);
1434 
1435     return getNonEmpty(APInt::getZero(BW),
1436                        APInt::getBitsSetFrom(BW, RHS->getZExtValue()) + 1);
1437   }
1438 
1439   APInt OtherMax = Other.getUnsignedMax();
1440 
1441   // There's overflow!
1442   if (OtherMax.ugt(Max.countLeadingZeros()))
1443     return getFull();
1444 
1445   // FIXME: implement the other tricky cases
1446 
1447   Min <<= Other.getUnsignedMin();
1448   Max <<= OtherMax;
1449 
1450   return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);
1451 }
1452 
1453 ConstantRange
1454 ConstantRange::lshr(const ConstantRange &Other) const {
1455   if (isEmptySet() || Other.isEmptySet())
1456     return getEmpty();
1457 
1458   APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
1459   APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
1460   return getNonEmpty(std::move(min), std::move(max));
1461 }
1462 
1463 ConstantRange
1464 ConstantRange::ashr(const ConstantRange &Other) const {
1465   if (isEmptySet() || Other.isEmptySet())
1466     return getEmpty();
1467 
1468   // May straddle zero, so handle both positive and negative cases.
1469   // 'PosMax' is the upper bound of the result of the ashr
1470   // operation, when Upper of the LHS of ashr is a non-negative.
1471   // number. Since ashr of a non-negative number will result in a
1472   // smaller number, the Upper value of LHS is shifted right with
1473   // the minimum value of 'Other' instead of the maximum value.
1474   APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
1475 
1476   // 'PosMin' is the lower bound of the result of the ashr
1477   // operation, when Lower of the LHS is a non-negative number.
1478   // Since ashr of a non-negative number will result in a smaller
1479   // number, the Lower value of LHS is shifted right with the
1480   // maximum value of 'Other'.
1481   APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
1482 
1483   // 'NegMax' is the upper bound of the result of the ashr
1484   // operation, when Upper of the LHS of ashr is a negative number.
1485   // Since 'ashr' of a negative number will result in a bigger
1486   // number, the Upper value of LHS is shifted right with the
1487   // maximum value of 'Other'.
1488   APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
1489 
1490   // 'NegMin' is the lower bound of the result of the ashr
1491   // operation, when Lower of the LHS of ashr is a negative number.
1492   // Since 'ashr' of a negative number will result in a bigger
1493   // number, the Lower value of LHS is shifted right with the
1494   // minimum value of 'Other'.
1495   APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
1496 
1497   APInt max, min;
1498   if (getSignedMin().isNonNegative()) {
1499     // Upper and Lower of LHS are non-negative.
1500     min = PosMin;
1501     max = PosMax;
1502   } else if (getSignedMax().isNegative()) {
1503     // Upper and Lower of LHS are negative.
1504     min = NegMin;
1505     max = NegMax;
1506   } else {
1507     // Upper is non-negative and Lower is negative.
1508     min = NegMin;
1509     max = PosMax;
1510   }
1511   return getNonEmpty(std::move(min), std::move(max));
1512 }
1513 
1514 ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
1515   if (isEmptySet() || Other.isEmptySet())
1516     return getEmpty();
1517 
1518   APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
1519   APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
1520   return getNonEmpty(std::move(NewL), std::move(NewU));
1521 }
1522 
1523 ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
1524   if (isEmptySet() || Other.isEmptySet())
1525     return getEmpty();
1526 
1527   APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
1528   APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
1529   return getNonEmpty(std::move(NewL), std::move(NewU));
1530 }
1531 
1532 ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
1533   if (isEmptySet() || Other.isEmptySet())
1534     return getEmpty();
1535 
1536   APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
1537   APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
1538   return getNonEmpty(std::move(NewL), std::move(NewU));
1539 }
1540 
1541 ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
1542   if (isEmptySet() || Other.isEmptySet())
1543     return getEmpty();
1544 
1545   APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
1546   APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
1547   return getNonEmpty(std::move(NewL), std::move(NewU));
1548 }
1549 
1550 ConstantRange ConstantRange::umul_sat(const ConstantRange &Other) const {
1551   if (isEmptySet() || Other.isEmptySet())
1552     return getEmpty();
1553 
1554   APInt NewL = getUnsignedMin().umul_sat(Other.getUnsignedMin());
1555   APInt NewU = getUnsignedMax().umul_sat(Other.getUnsignedMax()) + 1;
1556   return getNonEmpty(std::move(NewL), std::move(NewU));
1557 }
1558 
1559 ConstantRange ConstantRange::smul_sat(const ConstantRange &Other) const {
1560   if (isEmptySet() || Other.isEmptySet())
1561     return getEmpty();
1562 
1563   // Because we could be dealing with negative numbers here, the lower bound is
1564   // the smallest of the cartesian product of the lower and upper ranges;
1565   // for example:
1566   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1567   // Similarly for the upper bound, swapping min for max.
1568 
1569   APInt Min = getSignedMin();
1570   APInt Max = getSignedMax();
1571   APInt OtherMin = Other.getSignedMin();
1572   APInt OtherMax = Other.getSignedMax();
1573 
1574   auto L = {Min.smul_sat(OtherMin), Min.smul_sat(OtherMax),
1575             Max.smul_sat(OtherMin), Max.smul_sat(OtherMax)};
1576   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1577   return getNonEmpty(std::min(L, Compare), std::max(L, Compare) + 1);
1578 }
1579 
1580 ConstantRange ConstantRange::ushl_sat(const ConstantRange &Other) const {
1581   if (isEmptySet() || Other.isEmptySet())
1582     return getEmpty();
1583 
1584   APInt NewL = getUnsignedMin().ushl_sat(Other.getUnsignedMin());
1585   APInt NewU = getUnsignedMax().ushl_sat(Other.getUnsignedMax()) + 1;
1586   return getNonEmpty(std::move(NewL), std::move(NewU));
1587 }
1588 
1589 ConstantRange ConstantRange::sshl_sat(const ConstantRange &Other) const {
1590   if (isEmptySet() || Other.isEmptySet())
1591     return getEmpty();
1592 
1593   APInt Min = getSignedMin(), Max = getSignedMax();
1594   APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax();
1595   APInt NewL = Min.sshl_sat(Min.isNonNegative() ? ShAmtMin : ShAmtMax);
1596   APInt NewU = Max.sshl_sat(Max.isNegative() ? ShAmtMin : ShAmtMax) + 1;
1597   return getNonEmpty(std::move(NewL), std::move(NewU));
1598 }
1599 
1600 ConstantRange ConstantRange::inverse() const {
1601   if (isFullSet())
1602     return getEmpty();
1603   if (isEmptySet())
1604     return getFull();
1605   return ConstantRange(Upper, Lower);
1606 }
1607 
1608 ConstantRange ConstantRange::abs(bool IntMinIsPoison) const {
1609   if (isEmptySet())
1610     return getEmpty();
1611 
1612   if (isSignWrappedSet()) {
1613     APInt Lo;
1614     // Check whether the range crosses zero.
1615     if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
1616       Lo = APInt::getZero(getBitWidth());
1617     else
1618       Lo = APIntOps::umin(Lower, -Upper + 1);
1619 
1620     // If SignedMin is not poison, then it is included in the result range.
1621     if (IntMinIsPoison)
1622       return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()));
1623     else
1624       return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);
1625   }
1626 
1627   APInt SMin = getSignedMin(), SMax = getSignedMax();
1628 
1629   // Skip SignedMin if it is poison.
1630   if (IntMinIsPoison && SMin.isMinSignedValue()) {
1631     // The range may become empty if it *only* contains SignedMin.
1632     if (SMax.isMinSignedValue())
1633       return getEmpty();
1634     ++SMin;
1635   }
1636 
1637   // All non-negative.
1638   if (SMin.isNonNegative())
1639     return *this;
1640 
1641   // All negative.
1642   if (SMax.isNegative())
1643     return ConstantRange(-SMax, -SMin + 1);
1644 
1645   // Range crosses zero.
1646   return ConstantRange(APInt::getZero(getBitWidth()),
1647                        APIntOps::umax(-SMin, SMax) + 1);
1648 }
1649 
1650 ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
1651     const ConstantRange &Other) const {
1652   if (isEmptySet() || Other.isEmptySet())
1653     return OverflowResult::MayOverflow;
1654 
1655   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1656   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1657 
1658   // a u+ b overflows high iff a u> ~b.
1659   if (Min.ugt(~OtherMin))
1660     return OverflowResult::AlwaysOverflowsHigh;
1661   if (Max.ugt(~OtherMax))
1662     return OverflowResult::MayOverflow;
1663   return OverflowResult::NeverOverflows;
1664 }
1665 
1666 ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
1667     const ConstantRange &Other) const {
1668   if (isEmptySet() || Other.isEmptySet())
1669     return OverflowResult::MayOverflow;
1670 
1671   APInt Min = getSignedMin(), Max = getSignedMax();
1672   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1673 
1674   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1675   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1676 
1677   // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
1678   // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
1679   if (Min.isNonNegative() && OtherMin.isNonNegative() &&
1680       Min.sgt(SignedMax - OtherMin))
1681     return OverflowResult::AlwaysOverflowsHigh;
1682   if (Max.isNegative() && OtherMax.isNegative() &&
1683       Max.slt(SignedMin - OtherMax))
1684     return OverflowResult::AlwaysOverflowsLow;
1685 
1686   if (Max.isNonNegative() && OtherMax.isNonNegative() &&
1687       Max.sgt(SignedMax - OtherMax))
1688     return OverflowResult::MayOverflow;
1689   if (Min.isNegative() && OtherMin.isNegative() &&
1690       Min.slt(SignedMin - OtherMin))
1691     return OverflowResult::MayOverflow;
1692 
1693   return OverflowResult::NeverOverflows;
1694 }
1695 
1696 ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
1697     const ConstantRange &Other) const {
1698   if (isEmptySet() || Other.isEmptySet())
1699     return OverflowResult::MayOverflow;
1700 
1701   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1702   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1703 
1704   // a u- b overflows low iff a u< b.
1705   if (Max.ult(OtherMin))
1706     return OverflowResult::AlwaysOverflowsLow;
1707   if (Min.ult(OtherMax))
1708     return OverflowResult::MayOverflow;
1709   return OverflowResult::NeverOverflows;
1710 }
1711 
1712 ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
1713     const ConstantRange &Other) const {
1714   if (isEmptySet() || Other.isEmptySet())
1715     return OverflowResult::MayOverflow;
1716 
1717   APInt Min = getSignedMin(), Max = getSignedMax();
1718   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1719 
1720   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1721   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1722 
1723   // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
1724   // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
1725   if (Min.isNonNegative() && OtherMax.isNegative() &&
1726       Min.sgt(SignedMax + OtherMax))
1727     return OverflowResult::AlwaysOverflowsHigh;
1728   if (Max.isNegative() && OtherMin.isNonNegative() &&
1729       Max.slt(SignedMin + OtherMin))
1730     return OverflowResult::AlwaysOverflowsLow;
1731 
1732   if (Max.isNonNegative() && OtherMin.isNegative() &&
1733       Max.sgt(SignedMax + OtherMin))
1734     return OverflowResult::MayOverflow;
1735   if (Min.isNegative() && OtherMax.isNonNegative() &&
1736       Min.slt(SignedMin + OtherMax))
1737     return OverflowResult::MayOverflow;
1738 
1739   return OverflowResult::NeverOverflows;
1740 }
1741 
1742 ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
1743     const ConstantRange &Other) const {
1744   if (isEmptySet() || Other.isEmptySet())
1745     return OverflowResult::MayOverflow;
1746 
1747   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1748   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1749   bool Overflow;
1750 
1751   (void) Min.umul_ov(OtherMin, Overflow);
1752   if (Overflow)
1753     return OverflowResult::AlwaysOverflowsHigh;
1754 
1755   (void) Max.umul_ov(OtherMax, Overflow);
1756   if (Overflow)
1757     return OverflowResult::MayOverflow;
1758 
1759   return OverflowResult::NeverOverflows;
1760 }
1761 
1762 void ConstantRange::print(raw_ostream &OS) const {
1763   if (isFullSet())
1764     OS << "full-set";
1765   else if (isEmptySet())
1766     OS << "empty-set";
1767   else
1768     OS << "[" << Lower << "," << Upper << ")";
1769 }
1770 
1771 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1772 LLVM_DUMP_METHOD void ConstantRange::dump() const {
1773   print(dbgs());
1774 }
1775 #endif
1776 
1777 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
1778   const unsigned NumRanges = Ranges.getNumOperands() / 2;
1779   assert(NumRanges >= 1 && "Must have at least one range!");
1780   assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
1781 
1782   auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
1783   auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
1784 
1785   ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
1786 
1787   for (unsigned i = 1; i < NumRanges; ++i) {
1788     auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
1789     auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
1790 
1791     // Note: unionWith will potentially create a range that contains values not
1792     // contained in any of the original N ranges.
1793     CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
1794   }
1795 
1796   return CR;
1797 }
1798