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 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
685                                     uint32_t ResultBitWidth) const {
686   switch (CastOp) {
687   default:
688     llvm_unreachable("unsupported cast type");
689   case Instruction::Trunc:
690     return truncate(ResultBitWidth);
691   case Instruction::SExt:
692     return signExtend(ResultBitWidth);
693   case Instruction::ZExt:
694     return zeroExtend(ResultBitWidth);
695   case Instruction::BitCast:
696     return *this;
697   case Instruction::FPToUI:
698   case Instruction::FPToSI:
699     if (getBitWidth() == ResultBitWidth)
700       return *this;
701     else
702       return getFull(ResultBitWidth);
703   case Instruction::UIToFP: {
704     // TODO: use input range if available
705     auto BW = getBitWidth();
706     APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
707     APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
708     return ConstantRange(std::move(Min), std::move(Max));
709   }
710   case Instruction::SIToFP: {
711     // TODO: use input range if available
712     auto BW = getBitWidth();
713     APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
714     APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
715     return ConstantRange(std::move(SMin), std::move(SMax));
716   }
717   case Instruction::FPTrunc:
718   case Instruction::FPExt:
719   case Instruction::IntToPtr:
720   case Instruction::PtrToInt:
721   case Instruction::AddrSpaceCast:
722     // Conservatively return getFull set.
723     return getFull(ResultBitWidth);
724   };
725 }
726 
727 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
728   if (isEmptySet()) return getEmpty(DstTySize);
729 
730   unsigned SrcTySize = getBitWidth();
731   assert(SrcTySize < DstTySize && "Not a value extension");
732   if (isFullSet() || isUpperWrapped()) {
733     // Change into [0, 1 << src bit width)
734     APInt LowerExt(DstTySize, 0);
735     if (!Upper) // special case: [X, 0) -- not really wrapping around
736       LowerExt = Lower.zext(DstTySize);
737     return ConstantRange(std::move(LowerExt),
738                          APInt::getOneBitSet(DstTySize, SrcTySize));
739   }
740 
741   return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
742 }
743 
744 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
745   if (isEmptySet()) return getEmpty(DstTySize);
746 
747   unsigned SrcTySize = getBitWidth();
748   assert(SrcTySize < DstTySize && "Not a value extension");
749 
750   // special case: [X, INT_MIN) -- not really wrapping around
751   if (Upper.isMinSignedValue())
752     return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
753 
754   if (isFullSet() || isSignWrappedSet()) {
755     return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
756                          APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
757   }
758 
759   return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
760 }
761 
762 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
763   assert(getBitWidth() > DstTySize && "Not a value truncation");
764   if (isEmptySet())
765     return getEmpty(DstTySize);
766   if (isFullSet())
767     return getFull(DstTySize);
768 
769   APInt LowerDiv(Lower), UpperDiv(Upper);
770   ConstantRange Union(DstTySize, /*isFullSet=*/false);
771 
772   // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
773   // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
774   // then we do the union with [MaxValue, Upper)
775   if (isUpperWrapped()) {
776     // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
777     // truncated range.
778     if (Upper.getActiveBits() > DstTySize ||
779         Upper.countTrailingOnes() == DstTySize)
780       return getFull(DstTySize);
781 
782     Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
783     UpperDiv.setAllBits();
784 
785     // Union covers the MaxValue case, so return if the remaining range is just
786     // MaxValue(DstTy).
787     if (LowerDiv == UpperDiv)
788       return Union;
789   }
790 
791   // Chop off the most significant bits that are past the destination bitwidth.
792   if (LowerDiv.getActiveBits() > DstTySize) {
793     // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
794     APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
795     LowerDiv -= Adjust;
796     UpperDiv -= Adjust;
797   }
798 
799   unsigned UpperDivWidth = UpperDiv.getActiveBits();
800   if (UpperDivWidth <= DstTySize)
801     return ConstantRange(LowerDiv.trunc(DstTySize),
802                          UpperDiv.trunc(DstTySize)).unionWith(Union);
803 
804   // The truncated value wraps around. Check if we can do better than fullset.
805   if (UpperDivWidth == DstTySize + 1) {
806     // Clear the MSB so that UpperDiv wraps around.
807     UpperDiv.clearBit(DstTySize);
808     if (UpperDiv.ult(LowerDiv))
809       return ConstantRange(LowerDiv.trunc(DstTySize),
810                            UpperDiv.trunc(DstTySize)).unionWith(Union);
811   }
812 
813   return getFull(DstTySize);
814 }
815 
816 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
817   unsigned SrcTySize = getBitWidth();
818   if (SrcTySize > DstTySize)
819     return truncate(DstTySize);
820   if (SrcTySize < DstTySize)
821     return zeroExtend(DstTySize);
822   return *this;
823 }
824 
825 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
826   unsigned SrcTySize = getBitWidth();
827   if (SrcTySize > DstTySize)
828     return truncate(DstTySize);
829   if (SrcTySize < DstTySize)
830     return signExtend(DstTySize);
831   return *this;
832 }
833 
834 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
835                                       const ConstantRange &Other) const {
836   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
837 
838   switch (BinOp) {
839   case Instruction::Add:
840     return add(Other);
841   case Instruction::Sub:
842     return sub(Other);
843   case Instruction::Mul:
844     return multiply(Other);
845   case Instruction::UDiv:
846     return udiv(Other);
847   case Instruction::SDiv:
848     return sdiv(Other);
849   case Instruction::URem:
850     return urem(Other);
851   case Instruction::SRem:
852     return srem(Other);
853   case Instruction::Shl:
854     return shl(Other);
855   case Instruction::LShr:
856     return lshr(Other);
857   case Instruction::AShr:
858     return ashr(Other);
859   case Instruction::And:
860     return binaryAnd(Other);
861   case Instruction::Or:
862     return binaryOr(Other);
863   case Instruction::Xor:
864     return binaryXor(Other);
865   // Note: floating point operations applied to abstract ranges are just
866   // ideal integer operations with a lossy representation
867   case Instruction::FAdd:
868     return add(Other);
869   case Instruction::FSub:
870     return sub(Other);
871   case Instruction::FMul:
872     return multiply(Other);
873   default:
874     // Conservatively return getFull set.
875     return getFull();
876   }
877 }
878 
879 ConstantRange ConstantRange::overflowingBinaryOp(Instruction::BinaryOps BinOp,
880                                                  const ConstantRange &Other,
881                                                  unsigned NoWrapKind) const {
882   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
883 
884   switch (BinOp) {
885   case Instruction::Add:
886     return addWithNoWrap(Other, NoWrapKind);
887   case Instruction::Sub:
888     return subWithNoWrap(Other, NoWrapKind);
889   default:
890     // Don't know about this Overflowing Binary Operation.
891     // Conservatively fallback to plain binop handling.
892     return binaryOp(BinOp, Other);
893   }
894 }
895 
896 bool ConstantRange::isIntrinsicSupported(Intrinsic::ID IntrinsicID) {
897   switch (IntrinsicID) {
898   case Intrinsic::uadd_sat:
899   case Intrinsic::usub_sat:
900   case Intrinsic::sadd_sat:
901   case Intrinsic::ssub_sat:
902   case Intrinsic::umin:
903   case Intrinsic::umax:
904   case Intrinsic::smin:
905   case Intrinsic::smax:
906   case Intrinsic::abs:
907     return true;
908   default:
909     return false;
910   }
911 }
912 
913 ConstantRange ConstantRange::intrinsic(Intrinsic::ID IntrinsicID,
914                                        ArrayRef<ConstantRange> Ops) {
915   switch (IntrinsicID) {
916   case Intrinsic::uadd_sat:
917     return Ops[0].uadd_sat(Ops[1]);
918   case Intrinsic::usub_sat:
919     return Ops[0].usub_sat(Ops[1]);
920   case Intrinsic::sadd_sat:
921     return Ops[0].sadd_sat(Ops[1]);
922   case Intrinsic::ssub_sat:
923     return Ops[0].ssub_sat(Ops[1]);
924   case Intrinsic::umin:
925     return Ops[0].umin(Ops[1]);
926   case Intrinsic::umax:
927     return Ops[0].umax(Ops[1]);
928   case Intrinsic::smin:
929     return Ops[0].smin(Ops[1]);
930   case Intrinsic::smax:
931     return Ops[0].smax(Ops[1]);
932   case Intrinsic::abs: {
933     const APInt *IntMinIsPoison = Ops[1].getSingleElement();
934     assert(IntMinIsPoison && "Must be known (immarg)");
935     assert(IntMinIsPoison->getBitWidth() == 1 && "Must be boolean");
936     return Ops[0].abs(IntMinIsPoison->getBoolValue());
937   }
938   default:
939     assert(!isIntrinsicSupported(IntrinsicID) && "Shouldn't be supported");
940     llvm_unreachable("Unsupported intrinsic");
941   }
942 }
943 
944 ConstantRange
945 ConstantRange::add(const ConstantRange &Other) const {
946   if (isEmptySet() || Other.isEmptySet())
947     return getEmpty();
948   if (isFullSet() || Other.isFullSet())
949     return getFull();
950 
951   APInt NewLower = getLower() + Other.getLower();
952   APInt NewUpper = getUpper() + Other.getUpper() - 1;
953   if (NewLower == NewUpper)
954     return getFull();
955 
956   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
957   if (X.isSizeStrictlySmallerThan(*this) ||
958       X.isSizeStrictlySmallerThan(Other))
959     // We've wrapped, therefore, full set.
960     return getFull();
961   return X;
962 }
963 
964 ConstantRange ConstantRange::addWithNoWrap(const ConstantRange &Other,
965                                            unsigned NoWrapKind,
966                                            PreferredRangeType RangeType) const {
967   // Calculate the range for "X + Y" which is guaranteed not to wrap(overflow).
968   // (X is from this, and Y is from Other)
969   if (isEmptySet() || Other.isEmptySet())
970     return getEmpty();
971   if (isFullSet() && Other.isFullSet())
972     return getFull();
973 
974   using OBO = OverflowingBinaryOperator;
975   ConstantRange Result = add(Other);
976 
977   // If an overflow happens for every value pair in these two constant ranges,
978   // we must return Empty set. In this case, we get that for free, because we
979   // get lucky that intersection of add() with uadd_sat()/sadd_sat() results
980   // in an empty set.
981 
982   if (NoWrapKind & OBO::NoSignedWrap)
983     Result = Result.intersectWith(sadd_sat(Other), RangeType);
984 
985   if (NoWrapKind & OBO::NoUnsignedWrap)
986     Result = Result.intersectWith(uadd_sat(Other), RangeType);
987 
988   return Result;
989 }
990 
991 ConstantRange
992 ConstantRange::sub(const ConstantRange &Other) const {
993   if (isEmptySet() || Other.isEmptySet())
994     return getEmpty();
995   if (isFullSet() || Other.isFullSet())
996     return getFull();
997 
998   APInt NewLower = getLower() - Other.getUpper() + 1;
999   APInt NewUpper = getUpper() - Other.getLower();
1000   if (NewLower == NewUpper)
1001     return getFull();
1002 
1003   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
1004   if (X.isSizeStrictlySmallerThan(*this) ||
1005       X.isSizeStrictlySmallerThan(Other))
1006     // We've wrapped, therefore, full set.
1007     return getFull();
1008   return X;
1009 }
1010 
1011 ConstantRange ConstantRange::subWithNoWrap(const ConstantRange &Other,
1012                                            unsigned NoWrapKind,
1013                                            PreferredRangeType RangeType) const {
1014   // Calculate the range for "X - Y" which is guaranteed not to wrap(overflow).
1015   // (X is from this, and Y is from Other)
1016   if (isEmptySet() || Other.isEmptySet())
1017     return getEmpty();
1018   if (isFullSet() && Other.isFullSet())
1019     return getFull();
1020 
1021   using OBO = OverflowingBinaryOperator;
1022   ConstantRange Result = sub(Other);
1023 
1024   // If an overflow happens for every value pair in these two constant ranges,
1025   // we must return Empty set. In signed case, we get that for free, because we
1026   // get lucky that intersection of sub() with ssub_sat() results in an
1027   // empty set. But for unsigned we must perform the overflow check manually.
1028 
1029   if (NoWrapKind & OBO::NoSignedWrap)
1030     Result = Result.intersectWith(ssub_sat(Other), RangeType);
1031 
1032   if (NoWrapKind & OBO::NoUnsignedWrap) {
1033     if (getUnsignedMax().ult(Other.getUnsignedMin()))
1034       return getEmpty(); // Always overflows.
1035     Result = Result.intersectWith(usub_sat(Other), RangeType);
1036   }
1037 
1038   return Result;
1039 }
1040 
1041 ConstantRange
1042 ConstantRange::multiply(const ConstantRange &Other) const {
1043   // TODO: If either operand is a single element and the multiply is known to
1044   // be non-wrapping, round the result min and max value to the appropriate
1045   // multiple of that element. If wrapping is possible, at least adjust the
1046   // range according to the greatest power-of-two factor of the single element.
1047 
1048   if (isEmptySet() || Other.isEmptySet())
1049     return getEmpty();
1050 
1051   // Multiplication is signedness-independent. However different ranges can be
1052   // obtained depending on how the input ranges are treated. These different
1053   // ranges are all conservatively correct, but one might be better than the
1054   // other. We calculate two ranges; one treating the inputs as unsigned
1055   // and the other signed, then return the smallest of these ranges.
1056 
1057   // Unsigned range first.
1058   APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
1059   APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
1060   APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
1061   APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
1062 
1063   ConstantRange Result_zext = ConstantRange(this_min * Other_min,
1064                                             this_max * Other_max + 1);
1065   ConstantRange UR = Result_zext.truncate(getBitWidth());
1066 
1067   // If the unsigned range doesn't wrap, and isn't negative then it's a range
1068   // from one positive number to another which is as good as we can generate.
1069   // In this case, skip the extra work of generating signed ranges which aren't
1070   // going to be better than this range.
1071   if (!UR.isUpperWrapped() &&
1072       (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
1073     return UR;
1074 
1075   // Now the signed range. Because we could be dealing with negative numbers
1076   // here, the lower bound is the smallest of the cartesian product of the
1077   // lower and upper ranges; for example:
1078   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1079   // Similarly for the upper bound, swapping min for max.
1080 
1081   this_min = getSignedMin().sext(getBitWidth() * 2);
1082   this_max = getSignedMax().sext(getBitWidth() * 2);
1083   Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
1084   Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
1085 
1086   auto L = {this_min * Other_min, this_min * Other_max,
1087             this_max * Other_min, this_max * Other_max};
1088   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1089   ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
1090   ConstantRange SR = Result_sext.truncate(getBitWidth());
1091 
1092   return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
1093 }
1094 
1095 ConstantRange ConstantRange::smul_fast(const ConstantRange &Other) const {
1096   if (isEmptySet() || Other.isEmptySet())
1097     return getEmpty();
1098 
1099   APInt Min = getSignedMin();
1100   APInt Max = getSignedMax();
1101   APInt OtherMin = Other.getSignedMin();
1102   APInt OtherMax = Other.getSignedMax();
1103 
1104   bool O1, O2, O3, O4;
1105   auto Muls = {Min.smul_ov(OtherMin, O1), Min.smul_ov(OtherMax, O2),
1106                Max.smul_ov(OtherMin, O3), Max.smul_ov(OtherMax, O4)};
1107   if (O1 || O2 || O3 || O4)
1108     return getFull();
1109 
1110   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1111   return getNonEmpty(std::min(Muls, Compare), std::max(Muls, Compare) + 1);
1112 }
1113 
1114 ConstantRange
1115 ConstantRange::smax(const ConstantRange &Other) const {
1116   // X smax Y is: range(smax(X_smin, Y_smin),
1117   //                    smax(X_smax, Y_smax))
1118   if (isEmptySet() || Other.isEmptySet())
1119     return getEmpty();
1120   APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
1121   APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
1122   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1123   if (isSignWrappedSet() || Other.isSignWrappedSet())
1124     return Res.intersectWith(unionWith(Other, Signed), Signed);
1125   return Res;
1126 }
1127 
1128 ConstantRange
1129 ConstantRange::umax(const ConstantRange &Other) const {
1130   // X umax Y is: range(umax(X_umin, Y_umin),
1131   //                    umax(X_umax, Y_umax))
1132   if (isEmptySet() || Other.isEmptySet())
1133     return getEmpty();
1134   APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1135   APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1136   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1137   if (isWrappedSet() || Other.isWrappedSet())
1138     return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
1139   return Res;
1140 }
1141 
1142 ConstantRange
1143 ConstantRange::smin(const ConstantRange &Other) const {
1144   // X smin Y is: range(smin(X_smin, Y_smin),
1145   //                    smin(X_smax, Y_smax))
1146   if (isEmptySet() || Other.isEmptySet())
1147     return getEmpty();
1148   APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
1149   APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
1150   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1151   if (isSignWrappedSet() || Other.isSignWrappedSet())
1152     return Res.intersectWith(unionWith(Other, Signed), Signed);
1153   return Res;
1154 }
1155 
1156 ConstantRange
1157 ConstantRange::umin(const ConstantRange &Other) const {
1158   // X umin Y is: range(umin(X_umin, Y_umin),
1159   //                    umin(X_umax, Y_umax))
1160   if (isEmptySet() || Other.isEmptySet())
1161     return getEmpty();
1162   APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
1163   APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
1164   ConstantRange Res = getNonEmpty(std::move(NewL), std::move(NewU));
1165   if (isWrappedSet() || Other.isWrappedSet())
1166     return Res.intersectWith(unionWith(Other, Unsigned), Unsigned);
1167   return Res;
1168 }
1169 
1170 ConstantRange
1171 ConstantRange::udiv(const ConstantRange &RHS) const {
1172   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1173     return getEmpty();
1174 
1175   APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
1176 
1177   APInt RHS_umin = RHS.getUnsignedMin();
1178   if (RHS_umin.isZero()) {
1179     // We want the lowest value in RHS excluding zero. Usually that would be 1
1180     // except for a range in the form of [X, 1) in which case it would be X.
1181     if (RHS.getUpper() == 1)
1182       RHS_umin = RHS.getLower();
1183     else
1184       RHS_umin = 1;
1185   }
1186 
1187   APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
1188   return getNonEmpty(std::move(Lower), std::move(Upper));
1189 }
1190 
1191 ConstantRange ConstantRange::sdiv(const ConstantRange &RHS) const {
1192   // We split up the LHS and RHS into positive and negative components
1193   // and then also compute the positive and negative components of the result
1194   // separately by combining division results with the appropriate signs.
1195   APInt Zero = APInt::getZero(getBitWidth());
1196   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1197   ConstantRange PosFilter(APInt(getBitWidth(), 1), SignedMin);
1198   ConstantRange NegFilter(SignedMin, Zero);
1199   ConstantRange PosL = intersectWith(PosFilter);
1200   ConstantRange NegL = intersectWith(NegFilter);
1201   ConstantRange PosR = RHS.intersectWith(PosFilter);
1202   ConstantRange NegR = RHS.intersectWith(NegFilter);
1203 
1204   ConstantRange PosRes = getEmpty();
1205   if (!PosL.isEmptySet() && !PosR.isEmptySet())
1206     // pos / pos = pos.
1207     PosRes = ConstantRange(PosL.Lower.sdiv(PosR.Upper - 1),
1208                            (PosL.Upper - 1).sdiv(PosR.Lower) + 1);
1209 
1210   if (!NegL.isEmptySet() && !NegR.isEmptySet()) {
1211     // neg / neg = pos.
1212     //
1213     // We need to deal with one tricky case here: SignedMin / -1 is UB on the
1214     // IR level, so we'll want to exclude this case when calculating bounds.
1215     // (For APInts the operation is well-defined and yields SignedMin.) We
1216     // handle this by dropping either SignedMin from the LHS or -1 from the RHS.
1217     APInt Lo = (NegL.Upper - 1).sdiv(NegR.Lower);
1218     if (NegL.Lower.isMinSignedValue() && NegR.Upper.isZero()) {
1219       // Remove -1 from the LHS. Skip if it's the only element, as this would
1220       // leave us with an empty set.
1221       if (!NegR.Lower.isAllOnes()) {
1222         APInt AdjNegRUpper;
1223         if (RHS.Lower.isAllOnes())
1224           // Negative part of [-1, X] without -1 is [SignedMin, X].
1225           AdjNegRUpper = RHS.Upper;
1226         else
1227           // [X, -1] without -1 is [X, -2].
1228           AdjNegRUpper = NegR.Upper - 1;
1229 
1230         PosRes = PosRes.unionWith(
1231             ConstantRange(Lo, NegL.Lower.sdiv(AdjNegRUpper - 1) + 1));
1232       }
1233 
1234       // Remove SignedMin from the RHS. Skip if it's the only element, as this
1235       // would leave us with an empty set.
1236       if (NegL.Upper != SignedMin + 1) {
1237         APInt AdjNegLLower;
1238         if (Upper == SignedMin + 1)
1239           // Negative part of [X, SignedMin] without SignedMin is [X, -1].
1240           AdjNegLLower = Lower;
1241         else
1242           // [SignedMin, X] without SignedMin is [SignedMin + 1, X].
1243           AdjNegLLower = NegL.Lower + 1;
1244 
1245         PosRes = PosRes.unionWith(
1246             ConstantRange(std::move(Lo),
1247                           AdjNegLLower.sdiv(NegR.Upper - 1) + 1));
1248       }
1249     } else {
1250       PosRes = PosRes.unionWith(
1251           ConstantRange(std::move(Lo), NegL.Lower.sdiv(NegR.Upper - 1) + 1));
1252     }
1253   }
1254 
1255   ConstantRange NegRes = getEmpty();
1256   if (!PosL.isEmptySet() && !NegR.isEmptySet())
1257     // pos / neg = neg.
1258     NegRes = ConstantRange((PosL.Upper - 1).sdiv(NegR.Upper - 1),
1259                            PosL.Lower.sdiv(NegR.Lower) + 1);
1260 
1261   if (!NegL.isEmptySet() && !PosR.isEmptySet())
1262     // neg / pos = neg.
1263     NegRes = NegRes.unionWith(
1264         ConstantRange(NegL.Lower.sdiv(PosR.Lower),
1265                       (NegL.Upper - 1).sdiv(PosR.Upper - 1) + 1));
1266 
1267   // Prefer a non-wrapping signed range here.
1268   ConstantRange Res = NegRes.unionWith(PosRes, PreferredRangeType::Signed);
1269 
1270   // Preserve the zero that we dropped when splitting the LHS by sign.
1271   if (contains(Zero) && (!PosR.isEmptySet() || !NegR.isEmptySet()))
1272     Res = Res.unionWith(ConstantRange(Zero));
1273   return Res;
1274 }
1275 
1276 ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
1277   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isZero())
1278     return getEmpty();
1279 
1280   if (const APInt *RHSInt = RHS.getSingleElement()) {
1281     // UREM by null is UB.
1282     if (RHSInt->isZero())
1283       return getEmpty();
1284     // Use APInt's implementation of UREM for single element ranges.
1285     if (const APInt *LHSInt = getSingleElement())
1286       return {LHSInt->urem(*RHSInt)};
1287   }
1288 
1289   // L % R for L < R is L.
1290   if (getUnsignedMax().ult(RHS.getUnsignedMin()))
1291     return *this;
1292 
1293   // L % R is <= L and < R.
1294   APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
1295   return getNonEmpty(APInt::getZero(getBitWidth()), std::move(Upper));
1296 }
1297 
1298 ConstantRange ConstantRange::srem(const ConstantRange &RHS) const {
1299   if (isEmptySet() || RHS.isEmptySet())
1300     return getEmpty();
1301 
1302   if (const APInt *RHSInt = RHS.getSingleElement()) {
1303     // SREM by null is UB.
1304     if (RHSInt->isZero())
1305       return getEmpty();
1306     // Use APInt's implementation of SREM for single element ranges.
1307     if (const APInt *LHSInt = getSingleElement())
1308       return {LHSInt->srem(*RHSInt)};
1309   }
1310 
1311   ConstantRange AbsRHS = RHS.abs();
1312   APInt MinAbsRHS = AbsRHS.getUnsignedMin();
1313   APInt MaxAbsRHS = AbsRHS.getUnsignedMax();
1314 
1315   // Modulus by zero is UB.
1316   if (MaxAbsRHS.isZero())
1317     return getEmpty();
1318 
1319   if (MinAbsRHS.isZero())
1320     ++MinAbsRHS;
1321 
1322   APInt MinLHS = getSignedMin(), MaxLHS = getSignedMax();
1323 
1324   if (MinLHS.isNonNegative()) {
1325     // L % R for L < R is L.
1326     if (MaxLHS.ult(MinAbsRHS))
1327       return *this;
1328 
1329     // L % R is <= L and < R.
1330     APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1331     return ConstantRange(APInt::getZero(getBitWidth()), std::move(Upper));
1332   }
1333 
1334   // Same basic logic as above, but the result is negative.
1335   if (MaxLHS.isNegative()) {
1336     if (MinLHS.ugt(-MinAbsRHS))
1337       return *this;
1338 
1339     APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1340     return ConstantRange(std::move(Lower), APInt(getBitWidth(), 1));
1341   }
1342 
1343   // LHS range crosses zero.
1344   APInt Lower = APIntOps::umax(MinLHS, -MaxAbsRHS + 1);
1345   APInt Upper = APIntOps::umin(MaxLHS, MaxAbsRHS - 1) + 1;
1346   return ConstantRange(std::move(Lower), std::move(Upper));
1347 }
1348 
1349 ConstantRange ConstantRange::binaryNot() const {
1350   return ConstantRange(APInt::getAllOnes(getBitWidth())).sub(*this);
1351 }
1352 
1353 ConstantRange
1354 ConstantRange::binaryAnd(const ConstantRange &Other) const {
1355   if (isEmptySet() || Other.isEmptySet())
1356     return getEmpty();
1357 
1358   // Use APInt's implementation of AND for single element ranges.
1359   if (isSingleElement() && Other.isSingleElement())
1360     return {*getSingleElement() & *Other.getSingleElement()};
1361 
1362   // TODO: replace this with something less conservative
1363 
1364   APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
1365   return getNonEmpty(APInt::getZero(getBitWidth()), std::move(umin) + 1);
1366 }
1367 
1368 ConstantRange
1369 ConstantRange::binaryOr(const ConstantRange &Other) const {
1370   if (isEmptySet() || Other.isEmptySet())
1371     return getEmpty();
1372 
1373   // Use APInt's implementation of OR for single element ranges.
1374   if (isSingleElement() && Other.isSingleElement())
1375     return {*getSingleElement() | *Other.getSingleElement()};
1376 
1377   // TODO: replace this with something less conservative
1378 
1379   APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1380   return getNonEmpty(std::move(umax), APInt::getZero(getBitWidth()));
1381 }
1382 
1383 ConstantRange ConstantRange::binaryXor(const ConstantRange &Other) const {
1384   if (isEmptySet() || Other.isEmptySet())
1385     return getEmpty();
1386 
1387   // Use APInt's implementation of XOR for single element ranges.
1388   if (isSingleElement() && Other.isSingleElement())
1389     return {*getSingleElement() ^ *Other.getSingleElement()};
1390 
1391   // Special-case binary complement, since we can give a precise answer.
1392   if (Other.isSingleElement() && Other.getSingleElement()->isAllOnes())
1393     return binaryNot();
1394   if (isSingleElement() && getSingleElement()->isAllOnes())
1395     return Other.binaryNot();
1396 
1397   // TODO: replace this with something less conservative
1398   return getFull();
1399 }
1400 
1401 ConstantRange
1402 ConstantRange::shl(const ConstantRange &Other) const {
1403   if (isEmptySet() || Other.isEmptySet())
1404     return getEmpty();
1405 
1406   APInt Min = getUnsignedMin();
1407   APInt Max = getUnsignedMax();
1408   if (const APInt *RHS = Other.getSingleElement()) {
1409     unsigned BW = getBitWidth();
1410     if (RHS->uge(BW))
1411       return getEmpty();
1412 
1413     unsigned EqualLeadingBits = (Min ^ Max).countLeadingZeros();
1414     if (RHS->ule(EqualLeadingBits))
1415       return getNonEmpty(Min << *RHS, (Max << *RHS) + 1);
1416 
1417     return getNonEmpty(APInt::getZero(BW),
1418                        APInt::getBitsSetFrom(BW, RHS->getZExtValue()) + 1);
1419   }
1420 
1421   APInt OtherMax = Other.getUnsignedMax();
1422 
1423   // There's overflow!
1424   if (OtherMax.ugt(Max.countLeadingZeros()))
1425     return getFull();
1426 
1427   // FIXME: implement the other tricky cases
1428 
1429   Min <<= Other.getUnsignedMin();
1430   Max <<= OtherMax;
1431 
1432   return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);
1433 }
1434 
1435 ConstantRange
1436 ConstantRange::lshr(const ConstantRange &Other) const {
1437   if (isEmptySet() || Other.isEmptySet())
1438     return getEmpty();
1439 
1440   APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
1441   APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
1442   return getNonEmpty(std::move(min), std::move(max));
1443 }
1444 
1445 ConstantRange
1446 ConstantRange::ashr(const ConstantRange &Other) const {
1447   if (isEmptySet() || Other.isEmptySet())
1448     return getEmpty();
1449 
1450   // May straddle zero, so handle both positive and negative cases.
1451   // 'PosMax' is the upper bound of the result of the ashr
1452   // operation, when Upper of the LHS of ashr is a non-negative.
1453   // number. Since ashr of a non-negative number will result in a
1454   // smaller number, the Upper value of LHS is shifted right with
1455   // the minimum value of 'Other' instead of the maximum value.
1456   APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
1457 
1458   // 'PosMin' is the lower bound of the result of the ashr
1459   // operation, when Lower of the LHS is a non-negative number.
1460   // Since ashr of a non-negative number will result in a smaller
1461   // number, the Lower value of LHS is shifted right with the
1462   // maximum value of 'Other'.
1463   APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
1464 
1465   // 'NegMax' is the upper bound of the result of the ashr
1466   // operation, when Upper of the LHS of ashr is a negative number.
1467   // Since 'ashr' of a negative number will result in a bigger
1468   // number, the Upper value of LHS is shifted right with the
1469   // maximum value of 'Other'.
1470   APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
1471 
1472   // 'NegMin' is the lower bound of the result of the ashr
1473   // operation, when Lower of the LHS of ashr is a negative number.
1474   // Since 'ashr' of a negative number will result in a bigger
1475   // number, the Lower value of LHS is shifted right with the
1476   // minimum value of 'Other'.
1477   APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
1478 
1479   APInt max, min;
1480   if (getSignedMin().isNonNegative()) {
1481     // Upper and Lower of LHS are non-negative.
1482     min = PosMin;
1483     max = PosMax;
1484   } else if (getSignedMax().isNegative()) {
1485     // Upper and Lower of LHS are negative.
1486     min = NegMin;
1487     max = NegMax;
1488   } else {
1489     // Upper is non-negative and Lower is negative.
1490     min = NegMin;
1491     max = PosMax;
1492   }
1493   return getNonEmpty(std::move(min), std::move(max));
1494 }
1495 
1496 ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
1497   if (isEmptySet() || Other.isEmptySet())
1498     return getEmpty();
1499 
1500   APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
1501   APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
1502   return getNonEmpty(std::move(NewL), std::move(NewU));
1503 }
1504 
1505 ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
1506   if (isEmptySet() || Other.isEmptySet())
1507     return getEmpty();
1508 
1509   APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
1510   APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
1511   return getNonEmpty(std::move(NewL), std::move(NewU));
1512 }
1513 
1514 ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
1515   if (isEmptySet() || Other.isEmptySet())
1516     return getEmpty();
1517 
1518   APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
1519   APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
1520   return getNonEmpty(std::move(NewL), std::move(NewU));
1521 }
1522 
1523 ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
1524   if (isEmptySet() || Other.isEmptySet())
1525     return getEmpty();
1526 
1527   APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
1528   APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
1529   return getNonEmpty(std::move(NewL), std::move(NewU));
1530 }
1531 
1532 ConstantRange ConstantRange::umul_sat(const ConstantRange &Other) const {
1533   if (isEmptySet() || Other.isEmptySet())
1534     return getEmpty();
1535 
1536   APInt NewL = getUnsignedMin().umul_sat(Other.getUnsignedMin());
1537   APInt NewU = getUnsignedMax().umul_sat(Other.getUnsignedMax()) + 1;
1538   return getNonEmpty(std::move(NewL), std::move(NewU));
1539 }
1540 
1541 ConstantRange ConstantRange::smul_sat(const ConstantRange &Other) const {
1542   if (isEmptySet() || Other.isEmptySet())
1543     return getEmpty();
1544 
1545   // Because we could be dealing with negative numbers here, the lower bound is
1546   // the smallest of the cartesian product of the lower and upper ranges;
1547   // for example:
1548   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
1549   // Similarly for the upper bound, swapping min for max.
1550 
1551   APInt Min = getSignedMin();
1552   APInt Max = getSignedMax();
1553   APInt OtherMin = Other.getSignedMin();
1554   APInt OtherMax = Other.getSignedMax();
1555 
1556   auto L = {Min.smul_sat(OtherMin), Min.smul_sat(OtherMax),
1557             Max.smul_sat(OtherMin), Max.smul_sat(OtherMax)};
1558   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
1559   return getNonEmpty(std::min(L, Compare), std::max(L, Compare) + 1);
1560 }
1561 
1562 ConstantRange ConstantRange::ushl_sat(const ConstantRange &Other) const {
1563   if (isEmptySet() || Other.isEmptySet())
1564     return getEmpty();
1565 
1566   APInt NewL = getUnsignedMin().ushl_sat(Other.getUnsignedMin());
1567   APInt NewU = getUnsignedMax().ushl_sat(Other.getUnsignedMax()) + 1;
1568   return getNonEmpty(std::move(NewL), std::move(NewU));
1569 }
1570 
1571 ConstantRange ConstantRange::sshl_sat(const ConstantRange &Other) const {
1572   if (isEmptySet() || Other.isEmptySet())
1573     return getEmpty();
1574 
1575   APInt Min = getSignedMin(), Max = getSignedMax();
1576   APInt ShAmtMin = Other.getUnsignedMin(), ShAmtMax = Other.getUnsignedMax();
1577   APInt NewL = Min.sshl_sat(Min.isNonNegative() ? ShAmtMin : ShAmtMax);
1578   APInt NewU = Max.sshl_sat(Max.isNegative() ? ShAmtMin : ShAmtMax) + 1;
1579   return getNonEmpty(std::move(NewL), std::move(NewU));
1580 }
1581 
1582 ConstantRange ConstantRange::inverse() const {
1583   if (isFullSet())
1584     return getEmpty();
1585   if (isEmptySet())
1586     return getFull();
1587   return ConstantRange(Upper, Lower);
1588 }
1589 
1590 ConstantRange ConstantRange::abs(bool IntMinIsPoison) const {
1591   if (isEmptySet())
1592     return getEmpty();
1593 
1594   if (isSignWrappedSet()) {
1595     APInt Lo;
1596     // Check whether the range crosses zero.
1597     if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
1598       Lo = APInt::getZero(getBitWidth());
1599     else
1600       Lo = APIntOps::umin(Lower, -Upper + 1);
1601 
1602     // If SignedMin is not poison, then it is included in the result range.
1603     if (IntMinIsPoison)
1604       return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()));
1605     else
1606       return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);
1607   }
1608 
1609   APInt SMin = getSignedMin(), SMax = getSignedMax();
1610 
1611   // Skip SignedMin if it is poison.
1612   if (IntMinIsPoison && SMin.isMinSignedValue()) {
1613     // The range may become empty if it *only* contains SignedMin.
1614     if (SMax.isMinSignedValue())
1615       return getEmpty();
1616     ++SMin;
1617   }
1618 
1619   // All non-negative.
1620   if (SMin.isNonNegative())
1621     return *this;
1622 
1623   // All negative.
1624   if (SMax.isNegative())
1625     return ConstantRange(-SMax, -SMin + 1);
1626 
1627   // Range crosses zero.
1628   return ConstantRange(APInt::getZero(getBitWidth()),
1629                        APIntOps::umax(-SMin, SMax) + 1);
1630 }
1631 
1632 ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
1633     const ConstantRange &Other) const {
1634   if (isEmptySet() || Other.isEmptySet())
1635     return OverflowResult::MayOverflow;
1636 
1637   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1638   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1639 
1640   // a u+ b overflows high iff a u> ~b.
1641   if (Min.ugt(~OtherMin))
1642     return OverflowResult::AlwaysOverflowsHigh;
1643   if (Max.ugt(~OtherMax))
1644     return OverflowResult::MayOverflow;
1645   return OverflowResult::NeverOverflows;
1646 }
1647 
1648 ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
1649     const ConstantRange &Other) const {
1650   if (isEmptySet() || Other.isEmptySet())
1651     return OverflowResult::MayOverflow;
1652 
1653   APInt Min = getSignedMin(), Max = getSignedMax();
1654   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1655 
1656   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1657   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1658 
1659   // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
1660   // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
1661   if (Min.isNonNegative() && OtherMin.isNonNegative() &&
1662       Min.sgt(SignedMax - OtherMin))
1663     return OverflowResult::AlwaysOverflowsHigh;
1664   if (Max.isNegative() && OtherMax.isNegative() &&
1665       Max.slt(SignedMin - OtherMax))
1666     return OverflowResult::AlwaysOverflowsLow;
1667 
1668   if (Max.isNonNegative() && OtherMax.isNonNegative() &&
1669       Max.sgt(SignedMax - OtherMax))
1670     return OverflowResult::MayOverflow;
1671   if (Min.isNegative() && OtherMin.isNegative() &&
1672       Min.slt(SignedMin - OtherMin))
1673     return OverflowResult::MayOverflow;
1674 
1675   return OverflowResult::NeverOverflows;
1676 }
1677 
1678 ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
1679     const ConstantRange &Other) const {
1680   if (isEmptySet() || Other.isEmptySet())
1681     return OverflowResult::MayOverflow;
1682 
1683   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1684   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1685 
1686   // a u- b overflows low iff a u< b.
1687   if (Max.ult(OtherMin))
1688     return OverflowResult::AlwaysOverflowsLow;
1689   if (Min.ult(OtherMax))
1690     return OverflowResult::MayOverflow;
1691   return OverflowResult::NeverOverflows;
1692 }
1693 
1694 ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
1695     const ConstantRange &Other) const {
1696   if (isEmptySet() || Other.isEmptySet())
1697     return OverflowResult::MayOverflow;
1698 
1699   APInt Min = getSignedMin(), Max = getSignedMax();
1700   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1701 
1702   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1703   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1704 
1705   // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
1706   // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
1707   if (Min.isNonNegative() && OtherMax.isNegative() &&
1708       Min.sgt(SignedMax + OtherMax))
1709     return OverflowResult::AlwaysOverflowsHigh;
1710   if (Max.isNegative() && OtherMin.isNonNegative() &&
1711       Max.slt(SignedMin + OtherMin))
1712     return OverflowResult::AlwaysOverflowsLow;
1713 
1714   if (Max.isNonNegative() && OtherMin.isNegative() &&
1715       Max.sgt(SignedMax + OtherMin))
1716     return OverflowResult::MayOverflow;
1717   if (Min.isNegative() && OtherMax.isNonNegative() &&
1718       Min.slt(SignedMin + OtherMax))
1719     return OverflowResult::MayOverflow;
1720 
1721   return OverflowResult::NeverOverflows;
1722 }
1723 
1724 ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
1725     const ConstantRange &Other) const {
1726   if (isEmptySet() || Other.isEmptySet())
1727     return OverflowResult::MayOverflow;
1728 
1729   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1730   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1731   bool Overflow;
1732 
1733   (void) Min.umul_ov(OtherMin, Overflow);
1734   if (Overflow)
1735     return OverflowResult::AlwaysOverflowsHigh;
1736 
1737   (void) Max.umul_ov(OtherMax, Overflow);
1738   if (Overflow)
1739     return OverflowResult::MayOverflow;
1740 
1741   return OverflowResult::NeverOverflows;
1742 }
1743 
1744 void ConstantRange::print(raw_ostream &OS) const {
1745   if (isFullSet())
1746     OS << "full-set";
1747   else if (isEmptySet())
1748     OS << "empty-set";
1749   else
1750     OS << "[" << Lower << "," << Upper << ")";
1751 }
1752 
1753 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1754 LLVM_DUMP_METHOD void ConstantRange::dump() const {
1755   print(dbgs());
1756 }
1757 #endif
1758 
1759 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
1760   const unsigned NumRanges = Ranges.getNumOperands() / 2;
1761   assert(NumRanges >= 1 && "Must have at least one range!");
1762   assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
1763 
1764   auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
1765   auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
1766 
1767   ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
1768 
1769   for (unsigned i = 1; i < NumRanges; ++i) {
1770     auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
1771     auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
1772 
1773     // Note: unionWith will potentially create a range that contains values not
1774     // contained in any of the original N ranges.
1775     CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
1776   }
1777 
1778   return CR;
1779 }
1780