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/Metadata.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/KnownBits.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <cstdint>
39 
40 using namespace llvm;
41 
42 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full)
43     : Lower(Full ? APInt::getMaxValue(BitWidth) : APInt::getMinValue(BitWidth)),
44       Upper(Lower) {}
45 
46 ConstantRange::ConstantRange(APInt V)
47     : Lower(std::move(V)), Upper(Lower + 1) {}
48 
49 ConstantRange::ConstantRange(APInt L, APInt U)
50     : Lower(std::move(L)), Upper(std::move(U)) {
51   assert(Lower.getBitWidth() == Upper.getBitWidth() &&
52          "ConstantRange with unequal bit widths");
53   assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
54          "Lower == Upper, but they aren't min or max value!");
55 }
56 
57 ConstantRange ConstantRange::fromKnownBits(const KnownBits &Known,
58                                            bool IsSigned) {
59   assert(!Known.hasConflict() && "Expected valid KnownBits");
60 
61   if (Known.isUnknown())
62     return getFull(Known.getBitWidth());
63 
64   // For unsigned ranges, or signed ranges with known sign bit, create a simple
65   // range between the smallest and largest possible value.
66   if (!IsSigned || Known.isNegative() || Known.isNonNegative())
67     return ConstantRange(Known.One, ~Known.Zero + 1);
68 
69   // If we don't know the sign bit, pick the lower bound as a negative number
70   // and the upper bound as a non-negative one.
71   APInt Lower = Known.One, Upper = ~Known.Zero;
72   Lower.setSignBit();
73   Upper.clearSignBit();
74   return ConstantRange(Lower, Upper + 1);
75 }
76 
77 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
78                                                    const ConstantRange &CR) {
79   if (CR.isEmptySet())
80     return CR;
81 
82   uint32_t W = CR.getBitWidth();
83   switch (Pred) {
84   default:
85     llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
86   case CmpInst::ICMP_EQ:
87     return CR;
88   case CmpInst::ICMP_NE:
89     if (CR.isSingleElement())
90       return ConstantRange(CR.getUpper(), CR.getLower());
91     return getFull(W);
92   case CmpInst::ICMP_ULT: {
93     APInt UMax(CR.getUnsignedMax());
94     if (UMax.isMinValue())
95       return getEmpty(W);
96     return ConstantRange(APInt::getMinValue(W), std::move(UMax));
97   }
98   case CmpInst::ICMP_SLT: {
99     APInt SMax(CR.getSignedMax());
100     if (SMax.isMinSignedValue())
101       return getEmpty(W);
102     return ConstantRange(APInt::getSignedMinValue(W), std::move(SMax));
103   }
104   case CmpInst::ICMP_ULE:
105     return getNonEmpty(APInt::getMinValue(W), CR.getUnsignedMax() + 1);
106   case CmpInst::ICMP_SLE:
107     return getNonEmpty(APInt::getSignedMinValue(W), CR.getSignedMax() + 1);
108   case CmpInst::ICMP_UGT: {
109     APInt UMin(CR.getUnsignedMin());
110     if (UMin.isMaxValue())
111       return getEmpty(W);
112     return ConstantRange(std::move(UMin) + 1, APInt::getNullValue(W));
113   }
114   case CmpInst::ICMP_SGT: {
115     APInt SMin(CR.getSignedMin());
116     if (SMin.isMaxSignedValue())
117       return getEmpty(W);
118     return ConstantRange(std::move(SMin) + 1, APInt::getSignedMinValue(W));
119   }
120   case CmpInst::ICMP_UGE:
121     return getNonEmpty(CR.getUnsignedMin(), APInt::getNullValue(W));
122   case CmpInst::ICMP_SGE:
123     return getNonEmpty(CR.getSignedMin(), APInt::getSignedMinValue(W));
124   }
125 }
126 
127 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
128                                                       const ConstantRange &CR) {
129   // Follows from De-Morgan's laws:
130   //
131   // ~(~A union ~B) == A intersect B.
132   //
133   return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
134       .inverse();
135 }
136 
137 ConstantRange ConstantRange::makeExactICmpRegion(CmpInst::Predicate Pred,
138                                                  const APInt &C) {
139   // Computes the exact range that is equal to both the constant ranges returned
140   // by makeAllowedICmpRegion and makeSatisfyingICmpRegion. This is always true
141   // when RHS is a singleton such as an APInt and so the assert is valid.
142   // However for non-singleton RHS, for example ult [2,5) makeAllowedICmpRegion
143   // returns [0,4) but makeSatisfyICmpRegion returns [0,2).
144   //
145   assert(makeAllowedICmpRegion(Pred, C) == makeSatisfyingICmpRegion(Pred, C));
146   return makeAllowedICmpRegion(Pred, C);
147 }
148 
149 bool ConstantRange::getEquivalentICmp(CmpInst::Predicate &Pred,
150                                       APInt &RHS) const {
151   bool Success = false;
152 
153   if (isFullSet() || isEmptySet()) {
154     Pred = isEmptySet() ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
155     RHS = APInt(getBitWidth(), 0);
156     Success = true;
157   } else if (auto *OnlyElt = getSingleElement()) {
158     Pred = CmpInst::ICMP_EQ;
159     RHS = *OnlyElt;
160     Success = true;
161   } else if (auto *OnlyMissingElt = getSingleMissingElement()) {
162     Pred = CmpInst::ICMP_NE;
163     RHS = *OnlyMissingElt;
164     Success = true;
165   } else if (getLower().isMinSignedValue() || getLower().isMinValue()) {
166     Pred =
167         getLower().isMinSignedValue() ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
168     RHS = getUpper();
169     Success = true;
170   } else if (getUpper().isMinSignedValue() || getUpper().isMinValue()) {
171     Pred =
172         getUpper().isMinSignedValue() ? CmpInst::ICMP_SGE : CmpInst::ICMP_UGE;
173     RHS = getLower();
174     Success = true;
175   }
176 
177   assert((!Success || ConstantRange::makeExactICmpRegion(Pred, RHS) == *this) &&
178          "Bad result!");
179 
180   return Success;
181 }
182 
183 ConstantRange
184 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
185                                           const ConstantRange &Other,
186                                           unsigned NoWrapKind) {
187   using OBO = OverflowingBinaryOperator;
188 
189   // Computes the intersection of CR0 and CR1.  It is different from
190   // intersectWith in that the ConstantRange returned will only contain elements
191   // in both CR0 and CR1 (i.e. SubsetIntersect(X, Y) is a *subset*, proper or
192   // not, of both X and Y).
193   auto SubsetIntersect =
194       [](const ConstantRange &CR0, const ConstantRange &CR1) {
195     return CR0.inverse().unionWith(CR1.inverse()).inverse();
196   };
197 
198   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
199 
200   assert((NoWrapKind == OBO::NoSignedWrap ||
201           NoWrapKind == OBO::NoUnsignedWrap) &&
202          "NoWrapKind invalid!");
203 
204   unsigned BitWidth = Other.getBitWidth();
205   ConstantRange Result(BitWidth, /* full */ true);
206 
207   switch (BinOp) {
208   default:
209     // Conservative answer: empty set
210     return getEmpty(BitWidth);
211 
212   case Instruction::Add:
213     if (auto *C = Other.getSingleElement())
214       if (C->isNullValue())
215         // Full set: nothing signed / unsigned wraps when added to 0.
216         return getFull(BitWidth);
217 
218     if (NoWrapKind == OBO::NoUnsignedWrap)
219       return ConstantRange(APInt::getNullValue(BitWidth),
220                            -Other.getUnsignedMax());
221 
222     if (NoWrapKind == OBO::NoSignedWrap) {
223       const APInt &SignedMin = Other.getSignedMin();
224       const APInt &SignedMax = Other.getSignedMax();
225       if (SignedMax.isStrictlyPositive())
226         Result = SubsetIntersect(
227             Result,
228             ConstantRange(APInt::getSignedMinValue(BitWidth),
229                           APInt::getSignedMinValue(BitWidth) - SignedMax));
230       if (SignedMin.isNegative())
231         Result = SubsetIntersect(
232             Result,
233             ConstantRange(APInt::getSignedMinValue(BitWidth) - SignedMin,
234                           APInt::getSignedMinValue(BitWidth)));
235     }
236     return Result;
237 
238   case Instruction::Sub:
239     if (auto *C = Other.getSingleElement())
240       if (C->isNullValue())
241         // Full set: nothing signed / unsigned wraps when subtracting 0.
242         return getFull(BitWidth);
243 
244     if (NoWrapKind == OBO::NoUnsignedWrap)
245       return ConstantRange(Other.getUnsignedMax(),
246                            APInt::getMinValue(BitWidth));
247 
248     if (NoWrapKind == OBO::NoSignedWrap) {
249       const APInt &SignedMin = Other.getSignedMin();
250       const APInt &SignedMax = Other.getSignedMax();
251       if (SignedMax.isStrictlyPositive())
252         Result = SubsetIntersect(
253             Result,
254             ConstantRange(APInt::getSignedMinValue(BitWidth) + SignedMax,
255                           APInt::getSignedMinValue(BitWidth)));
256       if (SignedMin.isNegative())
257         Result = SubsetIntersect(
258             Result,
259             ConstantRange(APInt::getSignedMinValue(BitWidth),
260                           APInt::getSignedMinValue(BitWidth) + SignedMin));
261     }
262     return Result;
263 
264   case Instruction::Mul: {
265     // Equivalent to calling makeGuaranteedNoWrapRegion() on [V, V+1).
266     const bool Unsigned = NoWrapKind == OBO::NoUnsignedWrap;
267     const auto makeSingleValueRegion = [Unsigned,
268                                         BitWidth](APInt V) -> ConstantRange {
269       // Handle special case for 0, -1 and 1. See the last for reason why we
270       // specialize -1 and 1.
271       if (V == 0 || V.isOneValue())
272         return getFull(BitWidth);
273 
274       APInt MinValue, MaxValue;
275       if (Unsigned) {
276         MinValue = APInt::getMinValue(BitWidth);
277         MaxValue = APInt::getMaxValue(BitWidth);
278       } else {
279         MinValue = APInt::getSignedMinValue(BitWidth);
280         MaxValue = APInt::getSignedMaxValue(BitWidth);
281       }
282       // e.g. Returning [-127, 127], represented as [-127, -128).
283       if (!Unsigned && V.isAllOnesValue())
284         return ConstantRange(-MaxValue, MinValue);
285 
286       APInt Lower, Upper;
287       if (!Unsigned && V.isNegative()) {
288         Lower = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::UP);
289         Upper = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::DOWN);
290       } else if (Unsigned) {
291         Lower = APIntOps::RoundingUDiv(MinValue, V, APInt::Rounding::UP);
292         Upper = APIntOps::RoundingUDiv(MaxValue, V, APInt::Rounding::DOWN);
293       } else {
294         Lower = APIntOps::RoundingSDiv(MinValue, V, APInt::Rounding::UP);
295         Upper = APIntOps::RoundingSDiv(MaxValue, V, APInt::Rounding::DOWN);
296       }
297       // ConstantRange ctor take a half inclusive interval [Lower, Upper + 1).
298       // Upper + 1 is guanranteed not to overflow, because |divisor| > 1. 0, -1,
299       // and 1 are already handled as special cases.
300       return ConstantRange(Lower, Upper + 1);
301     };
302 
303     if (Unsigned)
304       return makeSingleValueRegion(Other.getUnsignedMax());
305 
306     return SubsetIntersect(makeSingleValueRegion(Other.getSignedMin()),
307                            makeSingleValueRegion(Other.getSignedMax()));
308   }
309   }
310 }
311 
312 bool ConstantRange::isFullSet() const {
313   return Lower == Upper && Lower.isMaxValue();
314 }
315 
316 bool ConstantRange::isEmptySet() const {
317   return Lower == Upper && Lower.isMinValue();
318 }
319 
320 bool ConstantRange::isWrappedSet() const {
321   return Lower.ugt(Upper) && !Upper.isNullValue();
322 }
323 
324 bool ConstantRange::isUpperWrapped() const {
325   return Lower.ugt(Upper);
326 }
327 
328 bool ConstantRange::isSignWrappedSet() const {
329   return Lower.sgt(Upper) && !Upper.isMinSignedValue();
330 }
331 
332 bool ConstantRange::isUpperSignWrapped() const {
333   return Lower.sgt(Upper);
334 }
335 
336 bool
337 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
338   assert(getBitWidth() == Other.getBitWidth());
339   if (isFullSet())
340     return false;
341   if (Other.isFullSet())
342     return true;
343   return (Upper - Lower).ult(Other.Upper - Other.Lower);
344 }
345 
346 bool
347 ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
348   assert(MaxSize && "MaxSize can't be 0.");
349   // If this a full set, we need special handling to avoid needing an extra bit
350   // to represent the size.
351   if (isFullSet())
352     return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
353 
354   return (Upper - Lower).ugt(MaxSize);
355 }
356 
357 bool ConstantRange::isAllNegative() const {
358   // Empty set is all negative, full set is not.
359   if (isEmptySet())
360     return true;
361   if (isFullSet())
362     return false;
363 
364   return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
365 }
366 
367 bool ConstantRange::isAllNonNegative() const {
368   // Empty and full set are automatically treated correctly.
369   return !isSignWrappedSet() && Lower.isNonNegative();
370 }
371 
372 APInt ConstantRange::getUnsignedMax() const {
373   if (isFullSet() || isUpperWrapped())
374     return APInt::getMaxValue(getBitWidth());
375   return getUpper() - 1;
376 }
377 
378 APInt ConstantRange::getUnsignedMin() const {
379   if (isFullSet() || isWrappedSet())
380     return APInt::getMinValue(getBitWidth());
381   return getLower();
382 }
383 
384 APInt ConstantRange::getSignedMax() const {
385   if (isFullSet() || isUpperSignWrapped())
386     return APInt::getSignedMaxValue(getBitWidth());
387   return getUpper() - 1;
388 }
389 
390 APInt ConstantRange::getSignedMin() const {
391   if (isFullSet() || isSignWrappedSet())
392     return APInt::getSignedMinValue(getBitWidth());
393   return getLower();
394 }
395 
396 bool ConstantRange::contains(const APInt &V) const {
397   if (Lower == Upper)
398     return isFullSet();
399 
400   if (!isUpperWrapped())
401     return Lower.ule(V) && V.ult(Upper);
402   return Lower.ule(V) || V.ult(Upper);
403 }
404 
405 bool ConstantRange::contains(const ConstantRange &Other) const {
406   if (isFullSet() || Other.isEmptySet()) return true;
407   if (isEmptySet() || Other.isFullSet()) return false;
408 
409   if (!isUpperWrapped()) {
410     if (Other.isUpperWrapped())
411       return false;
412 
413     return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
414   }
415 
416   if (!Other.isUpperWrapped())
417     return Other.getUpper().ule(Upper) ||
418            Lower.ule(Other.getLower());
419 
420   return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
421 }
422 
423 ConstantRange ConstantRange::subtract(const APInt &Val) const {
424   assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
425   // If the set is empty or full, don't modify the endpoints.
426   if (Lower == Upper)
427     return *this;
428   return ConstantRange(Lower - Val, Upper - Val);
429 }
430 
431 ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
432   return intersectWith(CR.inverse());
433 }
434 
435 static ConstantRange getPreferredRange(
436     const ConstantRange &CR1, const ConstantRange &CR2,
437     ConstantRange::PreferredRangeType Type) {
438   if (Type == ConstantRange::Unsigned) {
439     if (!CR1.isWrappedSet() && CR2.isWrappedSet())
440       return CR1;
441     if (CR1.isWrappedSet() && !CR2.isWrappedSet())
442       return CR2;
443   } else if (Type == ConstantRange::Signed) {
444     if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
445       return CR1;
446     if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
447       return CR2;
448   }
449 
450   if (CR1.isSizeStrictlySmallerThan(CR2))
451     return CR1;
452   return CR2;
453 }
454 
455 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
456                                            PreferredRangeType Type) const {
457   assert(getBitWidth() == CR.getBitWidth() &&
458          "ConstantRange types don't agree!");
459 
460   // Handle common cases.
461   if (   isEmptySet() || CR.isFullSet()) return *this;
462   if (CR.isEmptySet() ||    isFullSet()) return CR;
463 
464   if (!isUpperWrapped() && CR.isUpperWrapped())
465     return CR.intersectWith(*this, Type);
466 
467   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
468     if (Lower.ult(CR.Lower)) {
469       // L---U       : this
470       //       L---U : CR
471       if (Upper.ule(CR.Lower))
472         return getEmpty();
473 
474       // L---U       : this
475       //   L---U     : CR
476       if (Upper.ult(CR.Upper))
477         return ConstantRange(CR.Lower, Upper);
478 
479       // L-------U   : this
480       //   L---U     : CR
481       return CR;
482     }
483     //   L---U     : this
484     // L-------U   : CR
485     if (Upper.ult(CR.Upper))
486       return *this;
487 
488     //   L-----U   : this
489     // L-----U     : CR
490     if (Lower.ult(CR.Upper))
491       return ConstantRange(Lower, CR.Upper);
492 
493     //       L---U : this
494     // L---U       : CR
495     return getEmpty();
496   }
497 
498   if (isUpperWrapped() && !CR.isUpperWrapped()) {
499     if (CR.Lower.ult(Upper)) {
500       // ------U   L--- : this
501       //  L--U          : CR
502       if (CR.Upper.ult(Upper))
503         return CR;
504 
505       // ------U   L--- : this
506       //  L------U      : CR
507       if (CR.Upper.ule(Lower))
508         return ConstantRange(CR.Lower, Upper);
509 
510       // ------U   L--- : this
511       //  L----------U  : CR
512       return getPreferredRange(*this, CR, Type);
513     }
514     if (CR.Lower.ult(Lower)) {
515       // --U      L---- : this
516       //     L--U       : CR
517       if (CR.Upper.ule(Lower))
518         return getEmpty();
519 
520       // --U      L---- : this
521       //     L------U   : CR
522       return ConstantRange(Lower, CR.Upper);
523     }
524 
525     // --U  L------ : this
526     //        L--U  : CR
527     return CR;
528   }
529 
530   if (CR.Upper.ult(Upper)) {
531     // ------U L-- : this
532     // --U L------ : CR
533     if (CR.Lower.ult(Upper))
534       return getPreferredRange(*this, CR, Type);
535 
536     // ----U   L-- : this
537     // --U   L---- : CR
538     if (CR.Lower.ult(Lower))
539       return ConstantRange(Lower, CR.Upper);
540 
541     // ----U L---- : this
542     // --U     L-- : CR
543     return CR;
544   }
545   if (CR.Upper.ule(Lower)) {
546     // --U     L-- : this
547     // ----U L---- : CR
548     if (CR.Lower.ult(Lower))
549       return *this;
550 
551     // --U   L---- : this
552     // ----U   L-- : CR
553     return ConstantRange(CR.Lower, Upper);
554   }
555 
556   // --U L------ : this
557   // ------U L-- : CR
558   return getPreferredRange(*this, CR, Type);
559 }
560 
561 ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
562                                        PreferredRangeType Type) const {
563   assert(getBitWidth() == CR.getBitWidth() &&
564          "ConstantRange types don't agree!");
565 
566   if (   isFullSet() || CR.isEmptySet()) return *this;
567   if (CR.isFullSet() ||    isEmptySet()) return CR;
568 
569   if (!isUpperWrapped() && CR.isUpperWrapped())
570     return CR.unionWith(*this, Type);
571 
572   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
573     //        L---U  and  L---U        : this
574     //  L---U                   L---U  : CR
575     // result in one of
576     //  L---------U
577     // -----U L-----
578     if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
579       return getPreferredRange(
580           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
581 
582     APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
583     APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
584 
585     if (L.isNullValue() && U.isNullValue())
586       return getFull();
587 
588     return ConstantRange(std::move(L), std::move(U));
589   }
590 
591   if (!CR.isUpperWrapped()) {
592     // ------U   L-----  and  ------U   L----- : this
593     //   L--U                            L--U  : CR
594     if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
595       return *this;
596 
597     // ------U   L----- : this
598     //    L---------U   : CR
599     if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
600       return getFull();
601 
602     // ----U       L---- : this
603     //       L---U       : CR
604     // results in one of
605     // ----------U L----
606     // ----U L----------
607     if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
608       return getPreferredRange(
609           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
610 
611     // ----U     L----- : this
612     //        L----U    : CR
613     if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
614       return ConstantRange(CR.Lower, Upper);
615 
616     // ------U    L---- : this
617     //    L-----U       : CR
618     assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
619            "ConstantRange::unionWith missed a case with one range wrapped");
620     return ConstantRange(Lower, CR.Upper);
621   }
622 
623   // ------U    L----  and  ------U    L---- : this
624   // -U  L-----------  and  ------------U  L : CR
625   if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
626     return getFull();
627 
628   APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
629   APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
630 
631   return ConstantRange(std::move(L), std::move(U));
632 }
633 
634 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
635                                     uint32_t ResultBitWidth) const {
636   switch (CastOp) {
637   default:
638     llvm_unreachable("unsupported cast type");
639   case Instruction::Trunc:
640     return truncate(ResultBitWidth);
641   case Instruction::SExt:
642     return signExtend(ResultBitWidth);
643   case Instruction::ZExt:
644     return zeroExtend(ResultBitWidth);
645   case Instruction::BitCast:
646     return *this;
647   case Instruction::FPToUI:
648   case Instruction::FPToSI:
649     if (getBitWidth() == ResultBitWidth)
650       return *this;
651     else
652       return getFull();
653   case Instruction::UIToFP: {
654     // TODO: use input range if available
655     auto BW = getBitWidth();
656     APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
657     APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
658     return ConstantRange(std::move(Min), std::move(Max));
659   }
660   case Instruction::SIToFP: {
661     // TODO: use input range if available
662     auto BW = getBitWidth();
663     APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
664     APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
665     return ConstantRange(std::move(SMin), std::move(SMax));
666   }
667   case Instruction::FPTrunc:
668   case Instruction::FPExt:
669   case Instruction::IntToPtr:
670   case Instruction::PtrToInt:
671   case Instruction::AddrSpaceCast:
672     // Conservatively return getFull set.
673     return getFull();
674   };
675 }
676 
677 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
678   if (isEmptySet()) return getEmpty(DstTySize);
679 
680   unsigned SrcTySize = getBitWidth();
681   assert(SrcTySize < DstTySize && "Not a value extension");
682   if (isFullSet() || isUpperWrapped()) {
683     // Change into [0, 1 << src bit width)
684     APInt LowerExt(DstTySize, 0);
685     if (!Upper) // special case: [X, 0) -- not really wrapping around
686       LowerExt = Lower.zext(DstTySize);
687     return ConstantRange(std::move(LowerExt),
688                          APInt::getOneBitSet(DstTySize, SrcTySize));
689   }
690 
691   return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
692 }
693 
694 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
695   if (isEmptySet()) return getEmpty(DstTySize);
696 
697   unsigned SrcTySize = getBitWidth();
698   assert(SrcTySize < DstTySize && "Not a value extension");
699 
700   // special case: [X, INT_MIN) -- not really wrapping around
701   if (Upper.isMinSignedValue())
702     return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
703 
704   if (isFullSet() || isSignWrappedSet()) {
705     return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
706                          APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
707   }
708 
709   return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
710 }
711 
712 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
713   assert(getBitWidth() > DstTySize && "Not a value truncation");
714   if (isEmptySet())
715     return getEmpty(DstTySize);
716   if (isFullSet())
717     return getFull(DstTySize);
718 
719   APInt LowerDiv(Lower), UpperDiv(Upper);
720   ConstantRange Union(DstTySize, /*isFullSet=*/false);
721 
722   // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
723   // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
724   // then we do the union with [MaxValue, Upper)
725   if (isUpperWrapped()) {
726     // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
727     // truncated range.
728     if (Upper.getActiveBits() > DstTySize ||
729         Upper.countTrailingOnes() == DstTySize)
730       return getFull(DstTySize);
731 
732     Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
733     UpperDiv.setAllBits();
734 
735     // Union covers the MaxValue case, so return if the remaining range is just
736     // MaxValue(DstTy).
737     if (LowerDiv == UpperDiv)
738       return Union;
739   }
740 
741   // Chop off the most significant bits that are past the destination bitwidth.
742   if (LowerDiv.getActiveBits() > DstTySize) {
743     // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
744     APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
745     LowerDiv -= Adjust;
746     UpperDiv -= Adjust;
747   }
748 
749   unsigned UpperDivWidth = UpperDiv.getActiveBits();
750   if (UpperDivWidth <= DstTySize)
751     return ConstantRange(LowerDiv.trunc(DstTySize),
752                          UpperDiv.trunc(DstTySize)).unionWith(Union);
753 
754   // The truncated value wraps around. Check if we can do better than fullset.
755   if (UpperDivWidth == DstTySize + 1) {
756     // Clear the MSB so that UpperDiv wraps around.
757     UpperDiv.clearBit(DstTySize);
758     if (UpperDiv.ult(LowerDiv))
759       return ConstantRange(LowerDiv.trunc(DstTySize),
760                            UpperDiv.trunc(DstTySize)).unionWith(Union);
761   }
762 
763   return getFull(DstTySize);
764 }
765 
766 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
767   unsigned SrcTySize = getBitWidth();
768   if (SrcTySize > DstTySize)
769     return truncate(DstTySize);
770   if (SrcTySize < DstTySize)
771     return zeroExtend(DstTySize);
772   return *this;
773 }
774 
775 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
776   unsigned SrcTySize = getBitWidth();
777   if (SrcTySize > DstTySize)
778     return truncate(DstTySize);
779   if (SrcTySize < DstTySize)
780     return signExtend(DstTySize);
781   return *this;
782 }
783 
784 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
785                                       const ConstantRange &Other) const {
786   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
787 
788   switch (BinOp) {
789   case Instruction::Add:
790     return add(Other);
791   case Instruction::Sub:
792     return sub(Other);
793   case Instruction::Mul:
794     return multiply(Other);
795   case Instruction::UDiv:
796     return udiv(Other);
797   case Instruction::URem:
798     return urem(Other);
799   case Instruction::Shl:
800     return shl(Other);
801   case Instruction::LShr:
802     return lshr(Other);
803   case Instruction::AShr:
804     return ashr(Other);
805   case Instruction::And:
806     return binaryAnd(Other);
807   case Instruction::Or:
808     return binaryOr(Other);
809   // Note: floating point operations applied to abstract ranges are just
810   // ideal integer operations with a lossy representation
811   case Instruction::FAdd:
812     return add(Other);
813   case Instruction::FSub:
814     return sub(Other);
815   case Instruction::FMul:
816     return multiply(Other);
817   default:
818     // Conservatively return getFull set.
819     return getFull();
820   }
821 }
822 
823 ConstantRange
824 ConstantRange::add(const ConstantRange &Other) const {
825   if (isEmptySet() || Other.isEmptySet())
826     return getEmpty();
827   if (isFullSet() || Other.isFullSet())
828     return getFull();
829 
830   APInt NewLower = getLower() + Other.getLower();
831   APInt NewUpper = getUpper() + Other.getUpper() - 1;
832   if (NewLower == NewUpper)
833     return getFull();
834 
835   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
836   if (X.isSizeStrictlySmallerThan(*this) ||
837       X.isSizeStrictlySmallerThan(Other))
838     // We've wrapped, therefore, full set.
839     return getFull();
840   return X;
841 }
842 
843 ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const {
844   // Calculate the subset of this range such that "X + Other" is
845   // guaranteed not to wrap (overflow) for all X in this subset.
846   // makeGuaranteedNoWrapRegion will produce an exact NSW range.
847   auto NSWRange = ConstantRange::makeGuaranteedNoWrapRegion(BinaryOperator::Add,
848                                       ConstantRange(Other),
849                                       OverflowingBinaryOperator::NoSignedWrap);
850   auto NSWConstrainedRange = intersectWith(NSWRange);
851 
852   return NSWConstrainedRange.add(ConstantRange(Other));
853 }
854 
855 ConstantRange
856 ConstantRange::sub(const ConstantRange &Other) const {
857   if (isEmptySet() || Other.isEmptySet())
858     return getEmpty();
859   if (isFullSet() || Other.isFullSet())
860     return getFull();
861 
862   APInt NewLower = getLower() - Other.getUpper() + 1;
863   APInt NewUpper = getUpper() - Other.getLower();
864   if (NewLower == NewUpper)
865     return getFull();
866 
867   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
868   if (X.isSizeStrictlySmallerThan(*this) ||
869       X.isSizeStrictlySmallerThan(Other))
870     // We've wrapped, therefore, full set.
871     return getFull();
872   return X;
873 }
874 
875 ConstantRange
876 ConstantRange::multiply(const ConstantRange &Other) const {
877   // TODO: If either operand is a single element and the multiply is known to
878   // be non-wrapping, round the result min and max value to the appropriate
879   // multiple of that element. If wrapping is possible, at least adjust the
880   // range according to the greatest power-of-two factor of the single element.
881 
882   if (isEmptySet() || Other.isEmptySet())
883     return getEmpty();
884 
885   // Multiplication is signedness-independent. However different ranges can be
886   // obtained depending on how the input ranges are treated. These different
887   // ranges are all conservatively correct, but one might be better than the
888   // other. We calculate two ranges; one treating the inputs as unsigned
889   // and the other signed, then return the smallest of these ranges.
890 
891   // Unsigned range first.
892   APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
893   APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
894   APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
895   APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
896 
897   ConstantRange Result_zext = ConstantRange(this_min * Other_min,
898                                             this_max * Other_max + 1);
899   ConstantRange UR = Result_zext.truncate(getBitWidth());
900 
901   // If the unsigned range doesn't wrap, and isn't negative then it's a range
902   // from one positive number to another which is as good as we can generate.
903   // In this case, skip the extra work of generating signed ranges which aren't
904   // going to be better than this range.
905   if (!UR.isUpperWrapped() &&
906       (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
907     return UR;
908 
909   // Now the signed range. Because we could be dealing with negative numbers
910   // here, the lower bound is the smallest of the cartesian product of the
911   // lower and upper ranges; for example:
912   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
913   // Similarly for the upper bound, swapping min for max.
914 
915   this_min = getSignedMin().sext(getBitWidth() * 2);
916   this_max = getSignedMax().sext(getBitWidth() * 2);
917   Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
918   Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
919 
920   auto L = {this_min * Other_min, this_min * Other_max,
921             this_max * Other_min, this_max * Other_max};
922   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
923   ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
924   ConstantRange SR = Result_sext.truncate(getBitWidth());
925 
926   return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
927 }
928 
929 ConstantRange
930 ConstantRange::smax(const ConstantRange &Other) const {
931   // X smax Y is: range(smax(X_smin, Y_smin),
932   //                    smax(X_smax, Y_smax))
933   if (isEmptySet() || Other.isEmptySet())
934     return getEmpty();
935   APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
936   APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
937   return getNonEmpty(std::move(NewL), std::move(NewU));
938 }
939 
940 ConstantRange
941 ConstantRange::umax(const ConstantRange &Other) const {
942   // X umax Y is: range(umax(X_umin, Y_umin),
943   //                    umax(X_umax, Y_umax))
944   if (isEmptySet() || Other.isEmptySet())
945     return getEmpty();
946   APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
947   APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
948   return getNonEmpty(std::move(NewL), std::move(NewU));
949 }
950 
951 ConstantRange
952 ConstantRange::smin(const ConstantRange &Other) const {
953   // X smin Y is: range(smin(X_smin, Y_smin),
954   //                    smin(X_smax, Y_smax))
955   if (isEmptySet() || Other.isEmptySet())
956     return getEmpty();
957   APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
958   APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
959   return getNonEmpty(std::move(NewL), std::move(NewU));
960 }
961 
962 ConstantRange
963 ConstantRange::umin(const ConstantRange &Other) const {
964   // X umin Y is: range(umin(X_umin, Y_umin),
965   //                    umin(X_umax, Y_umax))
966   if (isEmptySet() || Other.isEmptySet())
967     return getEmpty();
968   APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
969   APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
970   return getNonEmpty(std::move(NewL), std::move(NewU));
971 }
972 
973 ConstantRange
974 ConstantRange::udiv(const ConstantRange &RHS) const {
975   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
976     return getEmpty();
977 
978   APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
979 
980   APInt RHS_umin = RHS.getUnsignedMin();
981   if (RHS_umin.isNullValue()) {
982     // We want the lowest value in RHS excluding zero. Usually that would be 1
983     // except for a range in the form of [X, 1) in which case it would be X.
984     if (RHS.getUpper() == 1)
985       RHS_umin = RHS.getLower();
986     else
987       RHS_umin = 1;
988   }
989 
990   APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
991   return getNonEmpty(std::move(Lower), std::move(Upper));
992 }
993 
994 ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
995   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
996     return getEmpty();
997 
998   // L % R for L < R is L.
999   if (getUnsignedMax().ult(RHS.getUnsignedMin()))
1000     return *this;
1001 
1002   // L % R is <= L and < R.
1003   APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
1004   return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(Upper));
1005 }
1006 
1007 ConstantRange
1008 ConstantRange::binaryAnd(const ConstantRange &Other) const {
1009   if (isEmptySet() || Other.isEmptySet())
1010     return getEmpty();
1011 
1012   // TODO: replace this with something less conservative
1013 
1014   APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
1015   return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(umin) + 1);
1016 }
1017 
1018 ConstantRange
1019 ConstantRange::binaryOr(const ConstantRange &Other) const {
1020   if (isEmptySet() || Other.isEmptySet())
1021     return getEmpty();
1022 
1023   // TODO: replace this with something less conservative
1024 
1025   APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1026   return getNonEmpty(std::move(umax), APInt::getNullValue(getBitWidth()));
1027 }
1028 
1029 ConstantRange
1030 ConstantRange::shl(const ConstantRange &Other) const {
1031   if (isEmptySet() || Other.isEmptySet())
1032     return getEmpty();
1033 
1034   APInt max = getUnsignedMax();
1035   APInt Other_umax = Other.getUnsignedMax();
1036 
1037   // If we are shifting by maximum amount of
1038   // zero return return the original range.
1039   if (Other_umax.isNullValue())
1040     return *this;
1041   // there's overflow!
1042   if (Other_umax.ugt(max.countLeadingZeros()))
1043     return getFull();
1044 
1045   // FIXME: implement the other tricky cases
1046 
1047   APInt min = getUnsignedMin();
1048   min <<= Other.getUnsignedMin();
1049   max <<= Other_umax;
1050 
1051   return ConstantRange(std::move(min), std::move(max) + 1);
1052 }
1053 
1054 ConstantRange
1055 ConstantRange::lshr(const ConstantRange &Other) const {
1056   if (isEmptySet() || Other.isEmptySet())
1057     return getEmpty();
1058 
1059   APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
1060   APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
1061   return getNonEmpty(std::move(min), std::move(max));
1062 }
1063 
1064 ConstantRange
1065 ConstantRange::ashr(const ConstantRange &Other) const {
1066   if (isEmptySet() || Other.isEmptySet())
1067     return getEmpty();
1068 
1069   // May straddle zero, so handle both positive and negative cases.
1070   // 'PosMax' is the upper bound of the result of the ashr
1071   // operation, when Upper of the LHS of ashr is a non-negative.
1072   // number. Since ashr of a non-negative number will result in a
1073   // smaller number, the Upper value of LHS is shifted right with
1074   // the minimum value of 'Other' instead of the maximum value.
1075   APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
1076 
1077   // 'PosMin' is the lower bound of the result of the ashr
1078   // operation, when Lower of the LHS is a non-negative number.
1079   // Since ashr of a non-negative number will result in a smaller
1080   // number, the Lower value of LHS is shifted right with the
1081   // maximum value of 'Other'.
1082   APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
1083 
1084   // 'NegMax' is the upper bound of the result of the ashr
1085   // operation, when Upper of the LHS of ashr is a negative number.
1086   // Since 'ashr' of a negative number will result in a bigger
1087   // number, the Upper value of LHS is shifted right with the
1088   // maximum value of 'Other'.
1089   APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
1090 
1091   // 'NegMin' is the lower bound of the result of the ashr
1092   // operation, when Lower of the LHS of ashr is a negative number.
1093   // Since 'ashr' of a negative number will result in a bigger
1094   // number, the Lower value of LHS is shifted right with the
1095   // minimum value of 'Other'.
1096   APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
1097 
1098   APInt max, min;
1099   if (getSignedMin().isNonNegative()) {
1100     // Upper and Lower of LHS are non-negative.
1101     min = PosMin;
1102     max = PosMax;
1103   } else if (getSignedMax().isNegative()) {
1104     // Upper and Lower of LHS are negative.
1105     min = NegMin;
1106     max = NegMax;
1107   } else {
1108     // Upper is non-negative and Lower is negative.
1109     min = NegMin;
1110     max = PosMax;
1111   }
1112   return getNonEmpty(std::move(min), std::move(max));
1113 }
1114 
1115 ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
1116   if (isEmptySet() || Other.isEmptySet())
1117     return getEmpty();
1118 
1119   APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
1120   APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
1121   return getNonEmpty(std::move(NewL), std::move(NewU));
1122 }
1123 
1124 ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
1125   if (isEmptySet() || Other.isEmptySet())
1126     return getEmpty();
1127 
1128   APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
1129   APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
1130   return getNonEmpty(std::move(NewL), std::move(NewU));
1131 }
1132 
1133 ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
1134   if (isEmptySet() || Other.isEmptySet())
1135     return getEmpty();
1136 
1137   APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
1138   APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
1139   return getNonEmpty(std::move(NewL), std::move(NewU));
1140 }
1141 
1142 ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
1143   if (isEmptySet() || Other.isEmptySet())
1144     return getEmpty();
1145 
1146   APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
1147   APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
1148   return getNonEmpty(std::move(NewL), std::move(NewU));
1149 }
1150 
1151 ConstantRange ConstantRange::inverse() const {
1152   if (isFullSet())
1153     return getEmpty();
1154   if (isEmptySet())
1155     return getFull();
1156   return ConstantRange(Upper, Lower);
1157 }
1158 
1159 ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
1160     const ConstantRange &Other) const {
1161   if (isEmptySet() || Other.isEmptySet())
1162     return OverflowResult::MayOverflow;
1163 
1164   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1165   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1166 
1167   // a u+ b overflows iff a u> ~b.
1168   if (Min.ugt(~OtherMin))
1169     return OverflowResult::AlwaysOverflows;
1170   if (Max.ugt(~OtherMax))
1171     return OverflowResult::MayOverflow;
1172   return OverflowResult::NeverOverflows;
1173 }
1174 
1175 ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
1176     const ConstantRange &Other) const {
1177   if (isEmptySet() || Other.isEmptySet())
1178     return OverflowResult::MayOverflow;
1179 
1180   APInt Min = getSignedMin(), Max = getSignedMax();
1181   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1182 
1183   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1184   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1185 
1186   // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
1187   // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
1188   if (Min.isNonNegative() && OtherMin.isNonNegative() &&
1189       Min.sgt(SignedMax - OtherMin))
1190     return OverflowResult::AlwaysOverflows;
1191   if (Max.isNegative() && OtherMax.isNegative() &&
1192       Max.slt(SignedMin - OtherMax))
1193     return OverflowResult::AlwaysOverflows;
1194 
1195   if (Max.isNonNegative() && OtherMax.isNonNegative() &&
1196       Max.sgt(SignedMax - OtherMax))
1197     return OverflowResult::MayOverflow;
1198   if (Min.isNegative() && OtherMin.isNegative() &&
1199       Min.slt(SignedMin - OtherMin))
1200     return OverflowResult::MayOverflow;
1201 
1202   return OverflowResult::NeverOverflows;
1203 }
1204 
1205 ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
1206     const ConstantRange &Other) const {
1207   if (isEmptySet() || Other.isEmptySet())
1208     return OverflowResult::MayOverflow;
1209 
1210   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1211   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1212 
1213   // a u- b overflows iff a u< b.
1214   if (Max.ult(OtherMin))
1215     return OverflowResult::AlwaysOverflows;
1216   if (Min.ult(OtherMax))
1217     return OverflowResult::MayOverflow;
1218   return OverflowResult::NeverOverflows;
1219 }
1220 
1221 ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
1222     const ConstantRange &Other) const {
1223   if (isEmptySet() || Other.isEmptySet())
1224     return OverflowResult::MayOverflow;
1225 
1226   APInt Min = getSignedMin(), Max = getSignedMax();
1227   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1228 
1229   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1230   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1231 
1232   // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
1233   // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
1234   if (Min.isNonNegative() && OtherMax.isNegative() &&
1235       Min.sgt(SignedMax + OtherMax))
1236     return OverflowResult::AlwaysOverflows;
1237   if (Max.isNegative() && OtherMin.isNonNegative() &&
1238       Max.slt(SignedMin + OtherMin))
1239     return OverflowResult::AlwaysOverflows;
1240 
1241   if (Max.isNonNegative() && OtherMin.isNegative() &&
1242       Max.sgt(SignedMax + OtherMin))
1243     return OverflowResult::MayOverflow;
1244   if (Min.isNegative() && OtherMax.isNonNegative() &&
1245       Min.slt(SignedMin + OtherMax))
1246     return OverflowResult::MayOverflow;
1247 
1248   return OverflowResult::NeverOverflows;
1249 }
1250 
1251 ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
1252     const ConstantRange &Other) const {
1253   if (isEmptySet() || Other.isEmptySet())
1254     return OverflowResult::MayOverflow;
1255 
1256   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1257   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1258   bool Overflow;
1259 
1260   (void) Min.umul_ov(OtherMin, Overflow);
1261   if (Overflow)
1262     return OverflowResult::AlwaysOverflows;
1263 
1264   (void) Max.umul_ov(OtherMax, Overflow);
1265   if (Overflow)
1266     return OverflowResult::MayOverflow;
1267 
1268   return OverflowResult::NeverOverflows;
1269 }
1270 
1271 void ConstantRange::print(raw_ostream &OS) const {
1272   if (isFullSet())
1273     OS << "full-set";
1274   else if (isEmptySet())
1275     OS << "empty-set";
1276   else
1277     OS << "[" << Lower << "," << Upper << ")";
1278 }
1279 
1280 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1281 LLVM_DUMP_METHOD void ConstantRange::dump() const {
1282   print(dbgs());
1283 }
1284 #endif
1285 
1286 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
1287   const unsigned NumRanges = Ranges.getNumOperands() / 2;
1288   assert(NumRanges >= 1 && "Must have at least one range!");
1289   assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
1290 
1291   auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
1292   auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
1293 
1294   ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
1295 
1296   for (unsigned i = 1; i < NumRanges; ++i) {
1297     auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
1298     auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
1299 
1300     // Note: unionWith will potentially create a range that contains values not
1301     // contained in any of the original N ranges.
1302     CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
1303   }
1304 
1305   return CR;
1306 }
1307