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