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 ConstantRange ConstantRange::makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
313                                                    const APInt &Other,
314                                                    unsigned NoWrapKind) {
315   // makeGuaranteedNoWrapRegion() is exact for single-element ranges, as
316   // "for all" and "for any" coincide in this case.
317   return makeGuaranteedNoWrapRegion(BinOp, ConstantRange(Other), NoWrapKind);
318 }
319 
320 bool ConstantRange::isFullSet() const {
321   return Lower == Upper && Lower.isMaxValue();
322 }
323 
324 bool ConstantRange::isEmptySet() const {
325   return Lower == Upper && Lower.isMinValue();
326 }
327 
328 bool ConstantRange::isWrappedSet() const {
329   return Lower.ugt(Upper) && !Upper.isNullValue();
330 }
331 
332 bool ConstantRange::isUpperWrapped() const {
333   return Lower.ugt(Upper);
334 }
335 
336 bool ConstantRange::isSignWrappedSet() const {
337   return Lower.sgt(Upper) && !Upper.isMinSignedValue();
338 }
339 
340 bool ConstantRange::isUpperSignWrapped() const {
341   return Lower.sgt(Upper);
342 }
343 
344 bool
345 ConstantRange::isSizeStrictlySmallerThan(const ConstantRange &Other) const {
346   assert(getBitWidth() == Other.getBitWidth());
347   if (isFullSet())
348     return false;
349   if (Other.isFullSet())
350     return true;
351   return (Upper - Lower).ult(Other.Upper - Other.Lower);
352 }
353 
354 bool
355 ConstantRange::isSizeLargerThan(uint64_t MaxSize) const {
356   assert(MaxSize && "MaxSize can't be 0.");
357   // If this a full set, we need special handling to avoid needing an extra bit
358   // to represent the size.
359   if (isFullSet())
360     return APInt::getMaxValue(getBitWidth()).ugt(MaxSize - 1);
361 
362   return (Upper - Lower).ugt(MaxSize);
363 }
364 
365 bool ConstantRange::isAllNegative() const {
366   // Empty set is all negative, full set is not.
367   if (isEmptySet())
368     return true;
369   if (isFullSet())
370     return false;
371 
372   return !isUpperSignWrapped() && !Upper.isStrictlyPositive();
373 }
374 
375 bool ConstantRange::isAllNonNegative() const {
376   // Empty and full set are automatically treated correctly.
377   return !isSignWrappedSet() && Lower.isNonNegative();
378 }
379 
380 APInt ConstantRange::getUnsignedMax() const {
381   if (isFullSet() || isUpperWrapped())
382     return APInt::getMaxValue(getBitWidth());
383   return getUpper() - 1;
384 }
385 
386 APInt ConstantRange::getUnsignedMin() const {
387   if (isFullSet() || isWrappedSet())
388     return APInt::getMinValue(getBitWidth());
389   return getLower();
390 }
391 
392 APInt ConstantRange::getSignedMax() const {
393   if (isFullSet() || isUpperSignWrapped())
394     return APInt::getSignedMaxValue(getBitWidth());
395   return getUpper() - 1;
396 }
397 
398 APInt ConstantRange::getSignedMin() const {
399   if (isFullSet() || isSignWrappedSet())
400     return APInt::getSignedMinValue(getBitWidth());
401   return getLower();
402 }
403 
404 bool ConstantRange::contains(const APInt &V) const {
405   if (Lower == Upper)
406     return isFullSet();
407 
408   if (!isUpperWrapped())
409     return Lower.ule(V) && V.ult(Upper);
410   return Lower.ule(V) || V.ult(Upper);
411 }
412 
413 bool ConstantRange::contains(const ConstantRange &Other) const {
414   if (isFullSet() || Other.isEmptySet()) return true;
415   if (isEmptySet() || Other.isFullSet()) return false;
416 
417   if (!isUpperWrapped()) {
418     if (Other.isUpperWrapped())
419       return false;
420 
421     return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
422   }
423 
424   if (!Other.isUpperWrapped())
425     return Other.getUpper().ule(Upper) ||
426            Lower.ule(Other.getLower());
427 
428   return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
429 }
430 
431 ConstantRange ConstantRange::subtract(const APInt &Val) const {
432   assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
433   // If the set is empty or full, don't modify the endpoints.
434   if (Lower == Upper)
435     return *this;
436   return ConstantRange(Lower - Val, Upper - Val);
437 }
438 
439 ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
440   return intersectWith(CR.inverse());
441 }
442 
443 static ConstantRange getPreferredRange(
444     const ConstantRange &CR1, const ConstantRange &CR2,
445     ConstantRange::PreferredRangeType Type) {
446   if (Type == ConstantRange::Unsigned) {
447     if (!CR1.isWrappedSet() && CR2.isWrappedSet())
448       return CR1;
449     if (CR1.isWrappedSet() && !CR2.isWrappedSet())
450       return CR2;
451   } else if (Type == ConstantRange::Signed) {
452     if (!CR1.isSignWrappedSet() && CR2.isSignWrappedSet())
453       return CR1;
454     if (CR1.isSignWrappedSet() && !CR2.isSignWrappedSet())
455       return CR2;
456   }
457 
458   if (CR1.isSizeStrictlySmallerThan(CR2))
459     return CR1;
460   return CR2;
461 }
462 
463 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
464                                            PreferredRangeType Type) const {
465   assert(getBitWidth() == CR.getBitWidth() &&
466          "ConstantRange types don't agree!");
467 
468   // Handle common cases.
469   if (   isEmptySet() || CR.isFullSet()) return *this;
470   if (CR.isEmptySet() ||    isFullSet()) return CR;
471 
472   if (!isUpperWrapped() && CR.isUpperWrapped())
473     return CR.intersectWith(*this, Type);
474 
475   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
476     if (Lower.ult(CR.Lower)) {
477       // L---U       : this
478       //       L---U : CR
479       if (Upper.ule(CR.Lower))
480         return getEmpty();
481 
482       // L---U       : this
483       //   L---U     : CR
484       if (Upper.ult(CR.Upper))
485         return ConstantRange(CR.Lower, Upper);
486 
487       // L-------U   : this
488       //   L---U     : CR
489       return CR;
490     }
491     //   L---U     : this
492     // L-------U   : CR
493     if (Upper.ult(CR.Upper))
494       return *this;
495 
496     //   L-----U   : this
497     // L-----U     : CR
498     if (Lower.ult(CR.Upper))
499       return ConstantRange(Lower, CR.Upper);
500 
501     //       L---U : this
502     // L---U       : CR
503     return getEmpty();
504   }
505 
506   if (isUpperWrapped() && !CR.isUpperWrapped()) {
507     if (CR.Lower.ult(Upper)) {
508       // ------U   L--- : this
509       //  L--U          : CR
510       if (CR.Upper.ult(Upper))
511         return CR;
512 
513       // ------U   L--- : this
514       //  L------U      : CR
515       if (CR.Upper.ule(Lower))
516         return ConstantRange(CR.Lower, Upper);
517 
518       // ------U   L--- : this
519       //  L----------U  : CR
520       return getPreferredRange(*this, CR, Type);
521     }
522     if (CR.Lower.ult(Lower)) {
523       // --U      L---- : this
524       //     L--U       : CR
525       if (CR.Upper.ule(Lower))
526         return getEmpty();
527 
528       // --U      L---- : this
529       //     L------U   : CR
530       return ConstantRange(Lower, CR.Upper);
531     }
532 
533     // --U  L------ : this
534     //        L--U  : CR
535     return CR;
536   }
537 
538   if (CR.Upper.ult(Upper)) {
539     // ------U L-- : this
540     // --U L------ : CR
541     if (CR.Lower.ult(Upper))
542       return getPreferredRange(*this, CR, Type);
543 
544     // ----U   L-- : this
545     // --U   L---- : CR
546     if (CR.Lower.ult(Lower))
547       return ConstantRange(Lower, CR.Upper);
548 
549     // ----U L---- : this
550     // --U     L-- : CR
551     return CR;
552   }
553   if (CR.Upper.ule(Lower)) {
554     // --U     L-- : this
555     // ----U L---- : CR
556     if (CR.Lower.ult(Lower))
557       return *this;
558 
559     // --U   L---- : this
560     // ----U   L-- : CR
561     return ConstantRange(CR.Lower, Upper);
562   }
563 
564   // --U L------ : this
565   // ------U L-- : CR
566   return getPreferredRange(*this, CR, Type);
567 }
568 
569 ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
570                                        PreferredRangeType Type) const {
571   assert(getBitWidth() == CR.getBitWidth() &&
572          "ConstantRange types don't agree!");
573 
574   if (   isFullSet() || CR.isEmptySet()) return *this;
575   if (CR.isFullSet() ||    isEmptySet()) return CR;
576 
577   if (!isUpperWrapped() && CR.isUpperWrapped())
578     return CR.unionWith(*this, Type);
579 
580   if (!isUpperWrapped() && !CR.isUpperWrapped()) {
581     //        L---U  and  L---U        : this
582     //  L---U                   L---U  : CR
583     // result in one of
584     //  L---------U
585     // -----U L-----
586     if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower))
587       return getPreferredRange(
588           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
589 
590     APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
591     APInt U = (CR.Upper - 1).ugt(Upper - 1) ? CR.Upper : Upper;
592 
593     if (L.isNullValue() && U.isNullValue())
594       return getFull();
595 
596     return ConstantRange(std::move(L), std::move(U));
597   }
598 
599   if (!CR.isUpperWrapped()) {
600     // ------U   L-----  and  ------U   L----- : this
601     //   L--U                            L--U  : CR
602     if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
603       return *this;
604 
605     // ------U   L----- : this
606     //    L---------U   : CR
607     if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
608       return getFull();
609 
610     // ----U       L---- : this
611     //       L---U       : CR
612     // results in one of
613     // ----------U L----
614     // ----U L----------
615     if (Upper.ult(CR.Lower) && CR.Upper.ult(Lower))
616       return getPreferredRange(
617           ConstantRange(Lower, CR.Upper), ConstantRange(CR.Lower, Upper), Type);
618 
619     // ----U     L----- : this
620     //        L----U    : CR
621     if (Upper.ult(CR.Lower) && Lower.ule(CR.Upper))
622       return ConstantRange(CR.Lower, Upper);
623 
624     // ------U    L---- : this
625     //    L-----U       : CR
626     assert(CR.Lower.ule(Upper) && CR.Upper.ult(Lower) &&
627            "ConstantRange::unionWith missed a case with one range wrapped");
628     return ConstantRange(Lower, CR.Upper);
629   }
630 
631   // ------U    L----  and  ------U    L---- : this
632   // -U  L-----------  and  ------------U  L : CR
633   if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
634     return getFull();
635 
636   APInt L = CR.Lower.ult(Lower) ? CR.Lower : Lower;
637   APInt U = CR.Upper.ugt(Upper) ? CR.Upper : Upper;
638 
639   return ConstantRange(std::move(L), std::move(U));
640 }
641 
642 ConstantRange ConstantRange::castOp(Instruction::CastOps CastOp,
643                                     uint32_t ResultBitWidth) const {
644   switch (CastOp) {
645   default:
646     llvm_unreachable("unsupported cast type");
647   case Instruction::Trunc:
648     return truncate(ResultBitWidth);
649   case Instruction::SExt:
650     return signExtend(ResultBitWidth);
651   case Instruction::ZExt:
652     return zeroExtend(ResultBitWidth);
653   case Instruction::BitCast:
654     return *this;
655   case Instruction::FPToUI:
656   case Instruction::FPToSI:
657     if (getBitWidth() == ResultBitWidth)
658       return *this;
659     else
660       return getFull();
661   case Instruction::UIToFP: {
662     // TODO: use input range if available
663     auto BW = getBitWidth();
664     APInt Min = APInt::getMinValue(BW).zextOrSelf(ResultBitWidth);
665     APInt Max = APInt::getMaxValue(BW).zextOrSelf(ResultBitWidth);
666     return ConstantRange(std::move(Min), std::move(Max));
667   }
668   case Instruction::SIToFP: {
669     // TODO: use input range if available
670     auto BW = getBitWidth();
671     APInt SMin = APInt::getSignedMinValue(BW).sextOrSelf(ResultBitWidth);
672     APInt SMax = APInt::getSignedMaxValue(BW).sextOrSelf(ResultBitWidth);
673     return ConstantRange(std::move(SMin), std::move(SMax));
674   }
675   case Instruction::FPTrunc:
676   case Instruction::FPExt:
677   case Instruction::IntToPtr:
678   case Instruction::PtrToInt:
679   case Instruction::AddrSpaceCast:
680     // Conservatively return getFull set.
681     return getFull();
682   };
683 }
684 
685 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
686   if (isEmptySet()) return getEmpty(DstTySize);
687 
688   unsigned SrcTySize = getBitWidth();
689   assert(SrcTySize < DstTySize && "Not a value extension");
690   if (isFullSet() || isUpperWrapped()) {
691     // Change into [0, 1 << src bit width)
692     APInt LowerExt(DstTySize, 0);
693     if (!Upper) // special case: [X, 0) -- not really wrapping around
694       LowerExt = Lower.zext(DstTySize);
695     return ConstantRange(std::move(LowerExt),
696                          APInt::getOneBitSet(DstTySize, SrcTySize));
697   }
698 
699   return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
700 }
701 
702 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
703   if (isEmptySet()) return getEmpty(DstTySize);
704 
705   unsigned SrcTySize = getBitWidth();
706   assert(SrcTySize < DstTySize && "Not a value extension");
707 
708   // special case: [X, INT_MIN) -- not really wrapping around
709   if (Upper.isMinSignedValue())
710     return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
711 
712   if (isFullSet() || isSignWrappedSet()) {
713     return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
714                          APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
715   }
716 
717   return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
718 }
719 
720 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
721   assert(getBitWidth() > DstTySize && "Not a value truncation");
722   if (isEmptySet())
723     return getEmpty(DstTySize);
724   if (isFullSet())
725     return getFull(DstTySize);
726 
727   APInt LowerDiv(Lower), UpperDiv(Upper);
728   ConstantRange Union(DstTySize, /*isFullSet=*/false);
729 
730   // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
731   // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
732   // then we do the union with [MaxValue, Upper)
733   if (isUpperWrapped()) {
734     // If Upper is greater than or equal to MaxValue(DstTy), it covers the whole
735     // truncated range.
736     if (Upper.getActiveBits() > DstTySize ||
737         Upper.countTrailingOnes() == DstTySize)
738       return getFull(DstTySize);
739 
740     Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
741     UpperDiv.setAllBits();
742 
743     // Union covers the MaxValue case, so return if the remaining range is just
744     // MaxValue(DstTy).
745     if (LowerDiv == UpperDiv)
746       return Union;
747   }
748 
749   // Chop off the most significant bits that are past the destination bitwidth.
750   if (LowerDiv.getActiveBits() > DstTySize) {
751     // Mask to just the signficant bits and subtract from LowerDiv/UpperDiv.
752     APInt Adjust = LowerDiv & APInt::getBitsSetFrom(getBitWidth(), DstTySize);
753     LowerDiv -= Adjust;
754     UpperDiv -= Adjust;
755   }
756 
757   unsigned UpperDivWidth = UpperDiv.getActiveBits();
758   if (UpperDivWidth <= DstTySize)
759     return ConstantRange(LowerDiv.trunc(DstTySize),
760                          UpperDiv.trunc(DstTySize)).unionWith(Union);
761 
762   // The truncated value wraps around. Check if we can do better than fullset.
763   if (UpperDivWidth == DstTySize + 1) {
764     // Clear the MSB so that UpperDiv wraps around.
765     UpperDiv.clearBit(DstTySize);
766     if (UpperDiv.ult(LowerDiv))
767       return ConstantRange(LowerDiv.trunc(DstTySize),
768                            UpperDiv.trunc(DstTySize)).unionWith(Union);
769   }
770 
771   return getFull(DstTySize);
772 }
773 
774 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
775   unsigned SrcTySize = getBitWidth();
776   if (SrcTySize > DstTySize)
777     return truncate(DstTySize);
778   if (SrcTySize < DstTySize)
779     return zeroExtend(DstTySize);
780   return *this;
781 }
782 
783 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
784   unsigned SrcTySize = getBitWidth();
785   if (SrcTySize > DstTySize)
786     return truncate(DstTySize);
787   if (SrcTySize < DstTySize)
788     return signExtend(DstTySize);
789   return *this;
790 }
791 
792 ConstantRange ConstantRange::binaryOp(Instruction::BinaryOps BinOp,
793                                       const ConstantRange &Other) const {
794   assert(Instruction::isBinaryOp(BinOp) && "Binary operators only!");
795 
796   switch (BinOp) {
797   case Instruction::Add:
798     return add(Other);
799   case Instruction::Sub:
800     return sub(Other);
801   case Instruction::Mul:
802     return multiply(Other);
803   case Instruction::UDiv:
804     return udiv(Other);
805   case Instruction::URem:
806     return urem(Other);
807   case Instruction::Shl:
808     return shl(Other);
809   case Instruction::LShr:
810     return lshr(Other);
811   case Instruction::AShr:
812     return ashr(Other);
813   case Instruction::And:
814     return binaryAnd(Other);
815   case Instruction::Or:
816     return binaryOr(Other);
817   // Note: floating point operations applied to abstract ranges are just
818   // ideal integer operations with a lossy representation
819   case Instruction::FAdd:
820     return add(Other);
821   case Instruction::FSub:
822     return sub(Other);
823   case Instruction::FMul:
824     return multiply(Other);
825   default:
826     // Conservatively return getFull set.
827     return getFull();
828   }
829 }
830 
831 ConstantRange
832 ConstantRange::add(const ConstantRange &Other) const {
833   if (isEmptySet() || Other.isEmptySet())
834     return getEmpty();
835   if (isFullSet() || Other.isFullSet())
836     return getFull();
837 
838   APInt NewLower = getLower() + Other.getLower();
839   APInt NewUpper = getUpper() + Other.getUpper() - 1;
840   if (NewLower == NewUpper)
841     return getFull();
842 
843   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
844   if (X.isSizeStrictlySmallerThan(*this) ||
845       X.isSizeStrictlySmallerThan(Other))
846     // We've wrapped, therefore, full set.
847     return getFull();
848   return X;
849 }
850 
851 ConstantRange ConstantRange::addWithNoSignedWrap(const APInt &Other) const {
852   // Calculate the subset of this range such that "X + Other" is
853   // guaranteed not to wrap (overflow) for all X in this subset.
854   auto NSWRange = ConstantRange::makeExactNoWrapRegion(
855       BinaryOperator::Add, Other, OverflowingBinaryOperator::NoSignedWrap);
856   auto NSWConstrainedRange = intersectWith(NSWRange);
857 
858   return NSWConstrainedRange.add(ConstantRange(Other));
859 }
860 
861 ConstantRange
862 ConstantRange::sub(const ConstantRange &Other) const {
863   if (isEmptySet() || Other.isEmptySet())
864     return getEmpty();
865   if (isFullSet() || Other.isFullSet())
866     return getFull();
867 
868   APInt NewLower = getLower() - Other.getUpper() + 1;
869   APInt NewUpper = getUpper() - Other.getLower();
870   if (NewLower == NewUpper)
871     return getFull();
872 
873   ConstantRange X = ConstantRange(std::move(NewLower), std::move(NewUpper));
874   if (X.isSizeStrictlySmallerThan(*this) ||
875       X.isSizeStrictlySmallerThan(Other))
876     // We've wrapped, therefore, full set.
877     return getFull();
878   return X;
879 }
880 
881 ConstantRange
882 ConstantRange::multiply(const ConstantRange &Other) const {
883   // TODO: If either operand is a single element and the multiply is known to
884   // be non-wrapping, round the result min and max value to the appropriate
885   // multiple of that element. If wrapping is possible, at least adjust the
886   // range according to the greatest power-of-two factor of the single element.
887 
888   if (isEmptySet() || Other.isEmptySet())
889     return getEmpty();
890 
891   // Multiplication is signedness-independent. However different ranges can be
892   // obtained depending on how the input ranges are treated. These different
893   // ranges are all conservatively correct, but one might be better than the
894   // other. We calculate two ranges; one treating the inputs as unsigned
895   // and the other signed, then return the smallest of these ranges.
896 
897   // Unsigned range first.
898   APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
899   APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
900   APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
901   APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
902 
903   ConstantRange Result_zext = ConstantRange(this_min * Other_min,
904                                             this_max * Other_max + 1);
905   ConstantRange UR = Result_zext.truncate(getBitWidth());
906 
907   // If the unsigned range doesn't wrap, and isn't negative then it's a range
908   // from one positive number to another which is as good as we can generate.
909   // In this case, skip the extra work of generating signed ranges which aren't
910   // going to be better than this range.
911   if (!UR.isUpperWrapped() &&
912       (UR.getUpper().isNonNegative() || UR.getUpper().isMinSignedValue()))
913     return UR;
914 
915   // Now the signed range. Because we could be dealing with negative numbers
916   // here, the lower bound is the smallest of the cartesian product of the
917   // lower and upper ranges; for example:
918   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
919   // Similarly for the upper bound, swapping min for max.
920 
921   this_min = getSignedMin().sext(getBitWidth() * 2);
922   this_max = getSignedMax().sext(getBitWidth() * 2);
923   Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
924   Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
925 
926   auto L = {this_min * Other_min, this_min * Other_max,
927             this_max * Other_min, this_max * Other_max};
928   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
929   ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
930   ConstantRange SR = Result_sext.truncate(getBitWidth());
931 
932   return UR.isSizeStrictlySmallerThan(SR) ? UR : SR;
933 }
934 
935 ConstantRange
936 ConstantRange::smax(const ConstantRange &Other) const {
937   // X smax Y is: range(smax(X_smin, Y_smin),
938   //                    smax(X_smax, Y_smax))
939   if (isEmptySet() || Other.isEmptySet())
940     return getEmpty();
941   APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
942   APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
943   return getNonEmpty(std::move(NewL), std::move(NewU));
944 }
945 
946 ConstantRange
947 ConstantRange::umax(const ConstantRange &Other) const {
948   // X umax Y is: range(umax(X_umin, Y_umin),
949   //                    umax(X_umax, Y_umax))
950   if (isEmptySet() || Other.isEmptySet())
951     return getEmpty();
952   APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
953   APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
954   return getNonEmpty(std::move(NewL), std::move(NewU));
955 }
956 
957 ConstantRange
958 ConstantRange::smin(const ConstantRange &Other) const {
959   // X smin Y is: range(smin(X_smin, Y_smin),
960   //                    smin(X_smax, Y_smax))
961   if (isEmptySet() || Other.isEmptySet())
962     return getEmpty();
963   APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
964   APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
965   return getNonEmpty(std::move(NewL), std::move(NewU));
966 }
967 
968 ConstantRange
969 ConstantRange::umin(const ConstantRange &Other) const {
970   // X umin Y is: range(umin(X_umin, Y_umin),
971   //                    umin(X_umax, Y_umax))
972   if (isEmptySet() || Other.isEmptySet())
973     return getEmpty();
974   APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
975   APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
976   return getNonEmpty(std::move(NewL), std::move(NewU));
977 }
978 
979 ConstantRange
980 ConstantRange::udiv(const ConstantRange &RHS) const {
981   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
982     return getEmpty();
983 
984   APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
985 
986   APInt RHS_umin = RHS.getUnsignedMin();
987   if (RHS_umin.isNullValue()) {
988     // We want the lowest value in RHS excluding zero. Usually that would be 1
989     // except for a range in the form of [X, 1) in which case it would be X.
990     if (RHS.getUpper() == 1)
991       RHS_umin = RHS.getLower();
992     else
993       RHS_umin = 1;
994   }
995 
996   APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
997   return getNonEmpty(std::move(Lower), std::move(Upper));
998 }
999 
1000 ConstantRange ConstantRange::urem(const ConstantRange &RHS) const {
1001   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax().isNullValue())
1002     return getEmpty();
1003 
1004   // L % R for L < R is L.
1005   if (getUnsignedMax().ult(RHS.getUnsignedMin()))
1006     return *this;
1007 
1008   // L % R is <= L and < R.
1009   APInt Upper = APIntOps::umin(getUnsignedMax(), RHS.getUnsignedMax() - 1) + 1;
1010   return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(Upper));
1011 }
1012 
1013 ConstantRange
1014 ConstantRange::binaryAnd(const ConstantRange &Other) const {
1015   if (isEmptySet() || Other.isEmptySet())
1016     return getEmpty();
1017 
1018   // TODO: replace this with something less conservative
1019 
1020   APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
1021   return getNonEmpty(APInt::getNullValue(getBitWidth()), std::move(umin) + 1);
1022 }
1023 
1024 ConstantRange
1025 ConstantRange::binaryOr(const ConstantRange &Other) const {
1026   if (isEmptySet() || Other.isEmptySet())
1027     return getEmpty();
1028 
1029   // TODO: replace this with something less conservative
1030 
1031   APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
1032   return getNonEmpty(std::move(umax), APInt::getNullValue(getBitWidth()));
1033 }
1034 
1035 ConstantRange
1036 ConstantRange::shl(const ConstantRange &Other) const {
1037   if (isEmptySet() || Other.isEmptySet())
1038     return getEmpty();
1039 
1040   APInt max = getUnsignedMax();
1041   APInt Other_umax = Other.getUnsignedMax();
1042 
1043   // If we are shifting by maximum amount of
1044   // zero return return the original range.
1045   if (Other_umax.isNullValue())
1046     return *this;
1047   // there's overflow!
1048   if (Other_umax.ugt(max.countLeadingZeros()))
1049     return getFull();
1050 
1051   // FIXME: implement the other tricky cases
1052 
1053   APInt min = getUnsignedMin();
1054   min <<= Other.getUnsignedMin();
1055   max <<= Other_umax;
1056 
1057   return ConstantRange(std::move(min), std::move(max) + 1);
1058 }
1059 
1060 ConstantRange
1061 ConstantRange::lshr(const ConstantRange &Other) const {
1062   if (isEmptySet() || Other.isEmptySet())
1063     return getEmpty();
1064 
1065   APInt max = getUnsignedMax().lshr(Other.getUnsignedMin()) + 1;
1066   APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
1067   return getNonEmpty(std::move(min), std::move(max));
1068 }
1069 
1070 ConstantRange
1071 ConstantRange::ashr(const ConstantRange &Other) const {
1072   if (isEmptySet() || Other.isEmptySet())
1073     return getEmpty();
1074 
1075   // May straddle zero, so handle both positive and negative cases.
1076   // 'PosMax' is the upper bound of the result of the ashr
1077   // operation, when Upper of the LHS of ashr is a non-negative.
1078   // number. Since ashr of a non-negative number will result in a
1079   // smaller number, the Upper value of LHS is shifted right with
1080   // the minimum value of 'Other' instead of the maximum value.
1081   APInt PosMax = getSignedMax().ashr(Other.getUnsignedMin()) + 1;
1082 
1083   // 'PosMin' is the lower bound of the result of the ashr
1084   // operation, when Lower of the LHS is a non-negative number.
1085   // Since ashr of a non-negative number will result in a smaller
1086   // number, the Lower value of LHS is shifted right with the
1087   // maximum value of 'Other'.
1088   APInt PosMin = getSignedMin().ashr(Other.getUnsignedMax());
1089 
1090   // 'NegMax' is the upper bound of the result of the ashr
1091   // operation, when Upper of the LHS of ashr is a negative number.
1092   // Since 'ashr' of a negative number will result in a bigger
1093   // number, the Upper value of LHS is shifted right with the
1094   // maximum value of 'Other'.
1095   APInt NegMax = getSignedMax().ashr(Other.getUnsignedMax()) + 1;
1096 
1097   // 'NegMin' is the lower bound of the result of the ashr
1098   // operation, when Lower of the LHS of ashr is a negative number.
1099   // Since 'ashr' of a negative number will result in a bigger
1100   // number, the Lower value of LHS is shifted right with the
1101   // minimum value of 'Other'.
1102   APInt NegMin = getSignedMin().ashr(Other.getUnsignedMin());
1103 
1104   APInt max, min;
1105   if (getSignedMin().isNonNegative()) {
1106     // Upper and Lower of LHS are non-negative.
1107     min = PosMin;
1108     max = PosMax;
1109   } else if (getSignedMax().isNegative()) {
1110     // Upper and Lower of LHS are negative.
1111     min = NegMin;
1112     max = NegMax;
1113   } else {
1114     // Upper is non-negative and Lower is negative.
1115     min = NegMin;
1116     max = PosMax;
1117   }
1118   return getNonEmpty(std::move(min), std::move(max));
1119 }
1120 
1121 ConstantRange ConstantRange::uadd_sat(const ConstantRange &Other) const {
1122   if (isEmptySet() || Other.isEmptySet())
1123     return getEmpty();
1124 
1125   APInt NewL = getUnsignedMin().uadd_sat(Other.getUnsignedMin());
1126   APInt NewU = getUnsignedMax().uadd_sat(Other.getUnsignedMax()) + 1;
1127   return getNonEmpty(std::move(NewL), std::move(NewU));
1128 }
1129 
1130 ConstantRange ConstantRange::sadd_sat(const ConstantRange &Other) const {
1131   if (isEmptySet() || Other.isEmptySet())
1132     return getEmpty();
1133 
1134   APInt NewL = getSignedMin().sadd_sat(Other.getSignedMin());
1135   APInt NewU = getSignedMax().sadd_sat(Other.getSignedMax()) + 1;
1136   return getNonEmpty(std::move(NewL), std::move(NewU));
1137 }
1138 
1139 ConstantRange ConstantRange::usub_sat(const ConstantRange &Other) const {
1140   if (isEmptySet() || Other.isEmptySet())
1141     return getEmpty();
1142 
1143   APInt NewL = getUnsignedMin().usub_sat(Other.getUnsignedMax());
1144   APInt NewU = getUnsignedMax().usub_sat(Other.getUnsignedMin()) + 1;
1145   return getNonEmpty(std::move(NewL), std::move(NewU));
1146 }
1147 
1148 ConstantRange ConstantRange::ssub_sat(const ConstantRange &Other) const {
1149   if (isEmptySet() || Other.isEmptySet())
1150     return getEmpty();
1151 
1152   APInt NewL = getSignedMin().ssub_sat(Other.getSignedMax());
1153   APInt NewU = getSignedMax().ssub_sat(Other.getSignedMin()) + 1;
1154   return getNonEmpty(std::move(NewL), std::move(NewU));
1155 }
1156 
1157 ConstantRange ConstantRange::inverse() const {
1158   if (isFullSet())
1159     return getEmpty();
1160   if (isEmptySet())
1161     return getFull();
1162   return ConstantRange(Upper, Lower);
1163 }
1164 
1165 ConstantRange ConstantRange::abs() const {
1166   if (isEmptySet())
1167     return getEmpty();
1168 
1169   if (isSignWrappedSet()) {
1170     APInt Lo;
1171     // Check whether the range crosses zero.
1172     if (Upper.isStrictlyPositive() || !Lower.isStrictlyPositive())
1173       Lo = APInt::getNullValue(getBitWidth());
1174     else
1175       Lo = APIntOps::umin(Lower, -Upper + 1);
1176 
1177     // SignedMin is included in the result range.
1178     return ConstantRange(Lo, APInt::getSignedMinValue(getBitWidth()) + 1);
1179   }
1180 
1181   APInt SMin = getSignedMin(), SMax = getSignedMax();
1182 
1183   // All non-negative.
1184   if (SMin.isNonNegative())
1185     return *this;
1186 
1187   // All negative.
1188   if (SMax.isNegative())
1189     return ConstantRange(-SMax, -SMin + 1);
1190 
1191   // Range crosses zero.
1192   return ConstantRange(APInt::getNullValue(getBitWidth()),
1193                        APIntOps::umax(-SMin, SMax) + 1);
1194 }
1195 
1196 ConstantRange::OverflowResult ConstantRange::unsignedAddMayOverflow(
1197     const ConstantRange &Other) const {
1198   if (isEmptySet() || Other.isEmptySet())
1199     return OverflowResult::MayOverflow;
1200 
1201   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1202   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1203 
1204   // a u+ b overflows iff a u> ~b.
1205   if (Min.ugt(~OtherMin))
1206     return OverflowResult::AlwaysOverflows;
1207   if (Max.ugt(~OtherMax))
1208     return OverflowResult::MayOverflow;
1209   return OverflowResult::NeverOverflows;
1210 }
1211 
1212 ConstantRange::OverflowResult ConstantRange::signedAddMayOverflow(
1213     const ConstantRange &Other) const {
1214   if (isEmptySet() || Other.isEmptySet())
1215     return OverflowResult::MayOverflow;
1216 
1217   APInt Min = getSignedMin(), Max = getSignedMax();
1218   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1219 
1220   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1221   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1222 
1223   // a s+ b overflows high iff a s>=0 && b s>= 0 && a s> smax - b.
1224   // a s+ b overflows low iff a s< 0 && b s< 0 && a s< smin - b.
1225   if (Min.isNonNegative() && OtherMin.isNonNegative() &&
1226       Min.sgt(SignedMax - OtherMin))
1227     return OverflowResult::AlwaysOverflows;
1228   if (Max.isNegative() && OtherMax.isNegative() &&
1229       Max.slt(SignedMin - OtherMax))
1230     return OverflowResult::AlwaysOverflows;
1231 
1232   if (Max.isNonNegative() && OtherMax.isNonNegative() &&
1233       Max.sgt(SignedMax - OtherMax))
1234     return OverflowResult::MayOverflow;
1235   if (Min.isNegative() && OtherMin.isNegative() &&
1236       Min.slt(SignedMin - OtherMin))
1237     return OverflowResult::MayOverflow;
1238 
1239   return OverflowResult::NeverOverflows;
1240 }
1241 
1242 ConstantRange::OverflowResult ConstantRange::unsignedSubMayOverflow(
1243     const ConstantRange &Other) const {
1244   if (isEmptySet() || Other.isEmptySet())
1245     return OverflowResult::MayOverflow;
1246 
1247   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1248   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1249 
1250   // a u- b overflows iff a u< b.
1251   if (Max.ult(OtherMin))
1252     return OverflowResult::AlwaysOverflows;
1253   if (Min.ult(OtherMax))
1254     return OverflowResult::MayOverflow;
1255   return OverflowResult::NeverOverflows;
1256 }
1257 
1258 ConstantRange::OverflowResult ConstantRange::signedSubMayOverflow(
1259     const ConstantRange &Other) const {
1260   if (isEmptySet() || Other.isEmptySet())
1261     return OverflowResult::MayOverflow;
1262 
1263   APInt Min = getSignedMin(), Max = getSignedMax();
1264   APInt OtherMin = Other.getSignedMin(), OtherMax = Other.getSignedMax();
1265 
1266   APInt SignedMin = APInt::getSignedMinValue(getBitWidth());
1267   APInt SignedMax = APInt::getSignedMaxValue(getBitWidth());
1268 
1269   // a s- b overflows high iff a s>=0 && b s< 0 && a s> smax + b.
1270   // a s- b overflows low iff a s< 0 && b s>= 0 && a s< smin + b.
1271   if (Min.isNonNegative() && OtherMax.isNegative() &&
1272       Min.sgt(SignedMax + OtherMax))
1273     return OverflowResult::AlwaysOverflows;
1274   if (Max.isNegative() && OtherMin.isNonNegative() &&
1275       Max.slt(SignedMin + OtherMin))
1276     return OverflowResult::AlwaysOverflows;
1277 
1278   if (Max.isNonNegative() && OtherMin.isNegative() &&
1279       Max.sgt(SignedMax + OtherMin))
1280     return OverflowResult::MayOverflow;
1281   if (Min.isNegative() && OtherMax.isNonNegative() &&
1282       Min.slt(SignedMin + OtherMax))
1283     return OverflowResult::MayOverflow;
1284 
1285   return OverflowResult::NeverOverflows;
1286 }
1287 
1288 ConstantRange::OverflowResult ConstantRange::unsignedMulMayOverflow(
1289     const ConstantRange &Other) const {
1290   if (isEmptySet() || Other.isEmptySet())
1291     return OverflowResult::MayOverflow;
1292 
1293   APInt Min = getUnsignedMin(), Max = getUnsignedMax();
1294   APInt OtherMin = Other.getUnsignedMin(), OtherMax = Other.getUnsignedMax();
1295   bool Overflow;
1296 
1297   (void) Min.umul_ov(OtherMin, Overflow);
1298   if (Overflow)
1299     return OverflowResult::AlwaysOverflows;
1300 
1301   (void) Max.umul_ov(OtherMax, Overflow);
1302   if (Overflow)
1303     return OverflowResult::MayOverflow;
1304 
1305   return OverflowResult::NeverOverflows;
1306 }
1307 
1308 void ConstantRange::print(raw_ostream &OS) const {
1309   if (isFullSet())
1310     OS << "full-set";
1311   else if (isEmptySet())
1312     OS << "empty-set";
1313   else
1314     OS << "[" << Lower << "," << Upper << ")";
1315 }
1316 
1317 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1318 LLVM_DUMP_METHOD void ConstantRange::dump() const {
1319   print(dbgs());
1320 }
1321 #endif
1322 
1323 ConstantRange llvm::getConstantRangeFromMetadata(const MDNode &Ranges) {
1324   const unsigned NumRanges = Ranges.getNumOperands() / 2;
1325   assert(NumRanges >= 1 && "Must have at least one range!");
1326   assert(Ranges.getNumOperands() % 2 == 0 && "Must be a sequence of pairs");
1327 
1328   auto *FirstLow = mdconst::extract<ConstantInt>(Ranges.getOperand(0));
1329   auto *FirstHigh = mdconst::extract<ConstantInt>(Ranges.getOperand(1));
1330 
1331   ConstantRange CR(FirstLow->getValue(), FirstHigh->getValue());
1332 
1333   for (unsigned i = 1; i < NumRanges; ++i) {
1334     auto *Low = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
1335     auto *High = mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
1336 
1337     // Note: unionWith will potentially create a range that contains values not
1338     // contained in any of the original N ranges.
1339     CR = CR.unionWith(ConstantRange(Low->getValue(), High->getValue()));
1340   }
1341 
1342   return CR;
1343 }
1344