1 //===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Represent a range of possible values that may occur when the program is run
11 // for an integral value.  This keeps track of a lower and upper bound for the
12 // constant, which MAY wrap around the end of the numeric range.  To do this, it
13 // keeps track of a [lower, upper) bound, which specifies an interval just like
14 // STL iterators.  When used with boolean values, the following are important
15 // ranges (other integral ranges use min/max values for special range values):
16 //
17 //  [F, F) = {}     = Empty set
18 //  [T, F) = {T}
19 //  [F, T) = {F}
20 //  [T, T) = {F, T} = Full set
21 //
22 //===----------------------------------------------------------------------===//
23 
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/InstrTypes.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 using namespace llvm;
31 
32 /// Initialize a full (the default) or empty set for the specified type.
33 ///
34 ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) {
35   if (Full)
36     Lower = Upper = APInt::getMaxValue(BitWidth);
37   else
38     Lower = Upper = APInt::getMinValue(BitWidth);
39 }
40 
41 /// Initialize a range to hold the single specified value.
42 ///
43 ConstantRange::ConstantRange(APIntMoveTy V)
44     : Lower(std::move(V)), Upper(Lower + 1) {}
45 
46 ConstantRange::ConstantRange(APIntMoveTy L, APIntMoveTy U)
47     : Lower(std::move(L)), Upper(std::move(U)) {
48   assert(Lower.getBitWidth() == Upper.getBitWidth() &&
49          "ConstantRange with unequal bit widths");
50   assert((Lower != Upper || (Lower.isMaxValue() || Lower.isMinValue())) &&
51          "Lower == Upper, but they aren't min or max value!");
52 }
53 
54 ConstantRange ConstantRange::makeAllowedICmpRegion(CmpInst::Predicate Pred,
55                                                    const ConstantRange &CR) {
56   if (CR.isEmptySet())
57     return CR;
58 
59   uint32_t W = CR.getBitWidth();
60   switch (Pred) {
61   default:
62     llvm_unreachable("Invalid ICmp predicate to makeAllowedICmpRegion()");
63     case CmpInst::ICMP_EQ:
64       return CR;
65     case CmpInst::ICMP_NE:
66       if (CR.isSingleElement())
67         return ConstantRange(CR.getUpper(), CR.getLower());
68       return ConstantRange(W);
69     case CmpInst::ICMP_ULT: {
70       APInt UMax(CR.getUnsignedMax());
71       if (UMax.isMinValue())
72         return ConstantRange(W, /* empty */ false);
73       return ConstantRange(APInt::getMinValue(W), UMax);
74     }
75     case CmpInst::ICMP_SLT: {
76       APInt SMax(CR.getSignedMax());
77       if (SMax.isMinSignedValue())
78         return ConstantRange(W, /* empty */ false);
79       return ConstantRange(APInt::getSignedMinValue(W), SMax);
80     }
81     case CmpInst::ICMP_ULE: {
82       APInt UMax(CR.getUnsignedMax());
83       if (UMax.isMaxValue())
84         return ConstantRange(W);
85       return ConstantRange(APInt::getMinValue(W), UMax + 1);
86     }
87     case CmpInst::ICMP_SLE: {
88       APInt SMax(CR.getSignedMax());
89       if (SMax.isMaxSignedValue())
90         return ConstantRange(W);
91       return ConstantRange(APInt::getSignedMinValue(W), SMax + 1);
92     }
93     case CmpInst::ICMP_UGT: {
94       APInt UMin(CR.getUnsignedMin());
95       if (UMin.isMaxValue())
96         return ConstantRange(W, /* empty */ false);
97       return ConstantRange(UMin + 1, APInt::getNullValue(W));
98     }
99     case CmpInst::ICMP_SGT: {
100       APInt SMin(CR.getSignedMin());
101       if (SMin.isMaxSignedValue())
102         return ConstantRange(W, /* empty */ false);
103       return ConstantRange(SMin + 1, APInt::getSignedMinValue(W));
104     }
105     case CmpInst::ICMP_UGE: {
106       APInt UMin(CR.getUnsignedMin());
107       if (UMin.isMinValue())
108         return ConstantRange(W);
109       return ConstantRange(UMin, APInt::getNullValue(W));
110     }
111     case CmpInst::ICMP_SGE: {
112       APInt SMin(CR.getSignedMin());
113       if (SMin.isMinSignedValue())
114         return ConstantRange(W);
115       return ConstantRange(SMin, APInt::getSignedMinValue(W));
116     }
117   }
118 }
119 
120 ConstantRange ConstantRange::makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
121                                                       const ConstantRange &CR) {
122   // Follows from De-Morgan's laws:
123   //
124   // ~(~A union ~B) == A intersect B.
125   //
126   return makeAllowedICmpRegion(CmpInst::getInversePredicate(Pred), CR)
127       .inverse();
128 }
129 
130 ConstantRange
131 ConstantRange::makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
132                                           const ConstantRange &Other,
133                                           unsigned NoWrapKind) {
134   typedef OverflowingBinaryOperator OBO;
135 
136   // Computes the intersection of CR0 and CR1.  It is different from
137   // intersectWith in that the ConstantRange returned will only contain elements
138   // in both CR0 and CR1 (i.e. SubsetIntersect(X, Y) is a *subset*, proper or
139   // not, of both X and Y).
140   auto SubsetIntersect =
141       [](const ConstantRange &CR0, const ConstantRange &CR1) {
142     return CR0.inverse().unionWith(CR1.inverse()).inverse();
143   };
144 
145   assert(BinOp >= Instruction::BinaryOpsBegin &&
146          BinOp < Instruction::BinaryOpsEnd && "Binary operators only!");
147 
148   assert((NoWrapKind == OBO::NoSignedWrap ||
149           NoWrapKind == OBO::NoUnsignedWrap ||
150           NoWrapKind == (OBO::NoUnsignedWrap | OBO::NoSignedWrap)) &&
151          "NoWrapKind invalid!");
152 
153   unsigned BitWidth = Other.getBitWidth();
154   if (BinOp != Instruction::Add)
155     // Conservative answer: empty set
156     return ConstantRange(BitWidth, false);
157 
158   if (auto *C = Other.getSingleElement())
159     if (C->isMinValue())
160       // Full set: nothing signed / unsigned wraps when added to 0.
161       return ConstantRange(BitWidth);
162 
163   ConstantRange Result(BitWidth);
164 
165   if (NoWrapKind & OBO::NoUnsignedWrap)
166     Result =
167         SubsetIntersect(Result, ConstantRange(APInt::getNullValue(BitWidth),
168                                               -Other.getUnsignedMax()));
169 
170   if (NoWrapKind & OBO::NoSignedWrap) {
171     APInt SignedMin = Other.getSignedMin();
172     APInt SignedMax = Other.getSignedMax();
173 
174     if (SignedMax.isStrictlyPositive())
175       Result = SubsetIntersect(
176           Result,
177           ConstantRange(APInt::getSignedMinValue(BitWidth),
178                         APInt::getSignedMinValue(BitWidth) - SignedMax));
179 
180     if (SignedMin.isNegative())
181       Result = SubsetIntersect(
182           Result, ConstantRange(APInt::getSignedMinValue(BitWidth) - SignedMin,
183                                 APInt::getSignedMinValue(BitWidth)));
184   }
185 
186   return Result;
187 }
188 
189 /// isFullSet - Return true if this set contains all of the elements possible
190 /// for this data-type
191 bool ConstantRange::isFullSet() const {
192   return Lower == Upper && Lower.isMaxValue();
193 }
194 
195 /// isEmptySet - Return true if this set contains no members.
196 ///
197 bool ConstantRange::isEmptySet() const {
198   return Lower == Upper && Lower.isMinValue();
199 }
200 
201 /// isWrappedSet - Return true if this set wraps around the top of the range,
202 /// for example: [100, 8)
203 ///
204 bool ConstantRange::isWrappedSet() const {
205   return Lower.ugt(Upper);
206 }
207 
208 /// isSignWrappedSet - Return true if this set wraps around the INT_MIN of
209 /// its bitwidth, for example: i8 [120, 140).
210 ///
211 bool ConstantRange::isSignWrappedSet() const {
212   return contains(APInt::getSignedMaxValue(getBitWidth())) &&
213          contains(APInt::getSignedMinValue(getBitWidth()));
214 }
215 
216 /// getSetSize - Return the number of elements in this set.
217 ///
218 APInt ConstantRange::getSetSize() const {
219   if (isFullSet()) {
220     APInt Size(getBitWidth()+1, 0);
221     Size.setBit(getBitWidth());
222     return Size;
223   }
224 
225   // This is also correct for wrapped sets.
226   return (Upper - Lower).zext(getBitWidth()+1);
227 }
228 
229 /// getUnsignedMax - Return the largest unsigned value contained in the
230 /// ConstantRange.
231 ///
232 APInt ConstantRange::getUnsignedMax() const {
233   if (isFullSet() || isWrappedSet())
234     return APInt::getMaxValue(getBitWidth());
235   return getUpper() - 1;
236 }
237 
238 /// getUnsignedMin - Return the smallest unsigned value contained in the
239 /// ConstantRange.
240 ///
241 APInt ConstantRange::getUnsignedMin() const {
242   if (isFullSet() || (isWrappedSet() && getUpper() != 0))
243     return APInt::getMinValue(getBitWidth());
244   return getLower();
245 }
246 
247 /// getSignedMax - Return the largest signed value contained in the
248 /// ConstantRange.
249 ///
250 APInt ConstantRange::getSignedMax() const {
251   APInt SignedMax(APInt::getSignedMaxValue(getBitWidth()));
252   if (!isWrappedSet()) {
253     if (getLower().sle(getUpper() - 1))
254       return getUpper() - 1;
255     return SignedMax;
256   }
257   if (getLower().isNegative() == getUpper().isNegative())
258     return SignedMax;
259   return getUpper() - 1;
260 }
261 
262 /// getSignedMin - Return the smallest signed value contained in the
263 /// ConstantRange.
264 ///
265 APInt ConstantRange::getSignedMin() const {
266   APInt SignedMin(APInt::getSignedMinValue(getBitWidth()));
267   if (!isWrappedSet()) {
268     if (getLower().sle(getUpper() - 1))
269       return getLower();
270     return SignedMin;
271   }
272   if ((getUpper() - 1).slt(getLower())) {
273     if (getUpper() != SignedMin)
274       return SignedMin;
275   }
276   return getLower();
277 }
278 
279 /// contains - Return true if the specified value is in the set.
280 ///
281 bool ConstantRange::contains(const APInt &V) const {
282   if (Lower == Upper)
283     return isFullSet();
284 
285   if (!isWrappedSet())
286     return Lower.ule(V) && V.ult(Upper);
287   return Lower.ule(V) || V.ult(Upper);
288 }
289 
290 /// contains - Return true if the argument is a subset of this range.
291 /// Two equal sets contain each other. The empty set contained by all other
292 /// sets.
293 ///
294 bool ConstantRange::contains(const ConstantRange &Other) const {
295   if (isFullSet() || Other.isEmptySet()) return true;
296   if (isEmptySet() || Other.isFullSet()) return false;
297 
298   if (!isWrappedSet()) {
299     if (Other.isWrappedSet())
300       return false;
301 
302     return Lower.ule(Other.getLower()) && Other.getUpper().ule(Upper);
303   }
304 
305   if (!Other.isWrappedSet())
306     return Other.getUpper().ule(Upper) ||
307            Lower.ule(Other.getLower());
308 
309   return Other.getUpper().ule(Upper) && Lower.ule(Other.getLower());
310 }
311 
312 /// subtract - Subtract the specified constant from the endpoints of this
313 /// constant range.
314 ConstantRange ConstantRange::subtract(const APInt &Val) const {
315   assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
316   // If the set is empty or full, don't modify the endpoints.
317   if (Lower == Upper)
318     return *this;
319   return ConstantRange(Lower - Val, Upper - Val);
320 }
321 
322 /// \brief Subtract the specified range from this range (aka relative complement
323 /// of the sets).
324 ConstantRange ConstantRange::difference(const ConstantRange &CR) const {
325   return intersectWith(CR.inverse());
326 }
327 
328 /// intersectWith - Return the range that results from the intersection of this
329 /// range with another range.  The resultant range is guaranteed to include all
330 /// elements contained in both input ranges, and to have the smallest possible
331 /// set size that does so.  Because there may be two intersections with the
332 /// same set size, A.intersectWith(B) might not be equal to B.intersectWith(A).
333 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
334   assert(getBitWidth() == CR.getBitWidth() &&
335          "ConstantRange types don't agree!");
336 
337   // Handle common cases.
338   if (   isEmptySet() || CR.isFullSet()) return *this;
339   if (CR.isEmptySet() ||    isFullSet()) return CR;
340 
341   if (!isWrappedSet() && CR.isWrappedSet())
342     return CR.intersectWith(*this);
343 
344   if (!isWrappedSet() && !CR.isWrappedSet()) {
345     if (Lower.ult(CR.Lower)) {
346       if (Upper.ule(CR.Lower))
347         return ConstantRange(getBitWidth(), false);
348 
349       if (Upper.ult(CR.Upper))
350         return ConstantRange(CR.Lower, Upper);
351 
352       return CR;
353     }
354     if (Upper.ult(CR.Upper))
355       return *this;
356 
357     if (Lower.ult(CR.Upper))
358       return ConstantRange(Lower, CR.Upper);
359 
360     return ConstantRange(getBitWidth(), false);
361   }
362 
363   if (isWrappedSet() && !CR.isWrappedSet()) {
364     if (CR.Lower.ult(Upper)) {
365       if (CR.Upper.ult(Upper))
366         return CR;
367 
368       if (CR.Upper.ule(Lower))
369         return ConstantRange(CR.Lower, Upper);
370 
371       if (getSetSize().ult(CR.getSetSize()))
372         return *this;
373       return CR;
374     }
375     if (CR.Lower.ult(Lower)) {
376       if (CR.Upper.ule(Lower))
377         return ConstantRange(getBitWidth(), false);
378 
379       return ConstantRange(Lower, CR.Upper);
380     }
381     return CR;
382   }
383 
384   if (CR.Upper.ult(Upper)) {
385     if (CR.Lower.ult(Upper)) {
386       if (getSetSize().ult(CR.getSetSize()))
387         return *this;
388       return CR;
389     }
390 
391     if (CR.Lower.ult(Lower))
392       return ConstantRange(Lower, CR.Upper);
393 
394     return CR;
395   }
396   if (CR.Upper.ule(Lower)) {
397     if (CR.Lower.ult(Lower))
398       return *this;
399 
400     return ConstantRange(CR.Lower, Upper);
401   }
402   if (getSetSize().ult(CR.getSetSize()))
403     return *this;
404   return CR;
405 }
406 
407 
408 /// unionWith - Return the range that results from the union of this range with
409 /// another range.  The resultant range is guaranteed to include the elements of
410 /// both sets, but may contain more.  For example, [3, 9) union [12,15) is
411 /// [3, 15), which includes 9, 10, and 11, which were not included in either
412 /// set before.
413 ///
414 ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
415   assert(getBitWidth() == CR.getBitWidth() &&
416          "ConstantRange types don't agree!");
417 
418   if (   isFullSet() || CR.isEmptySet()) return *this;
419   if (CR.isFullSet() ||    isEmptySet()) return CR;
420 
421   if (!isWrappedSet() && CR.isWrappedSet()) return CR.unionWith(*this);
422 
423   if (!isWrappedSet() && !CR.isWrappedSet()) {
424     if (CR.Upper.ult(Lower) || Upper.ult(CR.Lower)) {
425       // If the two ranges are disjoint, find the smaller gap and bridge it.
426       APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
427       if (d1.ult(d2))
428         return ConstantRange(Lower, CR.Upper);
429       return ConstantRange(CR.Lower, Upper);
430     }
431 
432     APInt L = Lower, U = Upper;
433     if (CR.Lower.ult(L))
434       L = CR.Lower;
435     if ((CR.Upper - 1).ugt(U - 1))
436       U = CR.Upper;
437 
438     if (L == 0 && U == 0)
439       return ConstantRange(getBitWidth());
440 
441     return ConstantRange(L, U);
442   }
443 
444   if (!CR.isWrappedSet()) {
445     // ------U   L-----  and  ------U   L----- : this
446     //   L--U                            L--U  : CR
447     if (CR.Upper.ule(Upper) || CR.Lower.uge(Lower))
448       return *this;
449 
450     // ------U   L----- : this
451     //    L---------U   : CR
452     if (CR.Lower.ule(Upper) && Lower.ule(CR.Upper))
453       return ConstantRange(getBitWidth());
454 
455     // ----U       L---- : this
456     //       L---U       : CR
457     //    <d1>  <d2>
458     if (Upper.ule(CR.Lower) && CR.Upper.ule(Lower)) {
459       APInt d1 = CR.Lower - Upper, d2 = Lower - CR.Upper;
460       if (d1.ult(d2))
461         return ConstantRange(Lower, CR.Upper);
462       return ConstantRange(CR.Lower, Upper);
463     }
464 
465     // ----U     L----- : this
466     //        L----U    : CR
467     if (Upper.ult(CR.Lower) && Lower.ult(CR.Upper))
468       return ConstantRange(CR.Lower, Upper);
469 
470     // ------U    L---- : this
471     //    L-----U       : CR
472     assert(CR.Lower.ult(Upper) && CR.Upper.ult(Lower) &&
473            "ConstantRange::unionWith missed a case with one range wrapped");
474     return ConstantRange(Lower, CR.Upper);
475   }
476 
477   // ------U    L----  and  ------U    L---- : this
478   // -U  L-----------  and  ------------U  L : CR
479   if (CR.Lower.ule(Upper) || Lower.ule(CR.Upper))
480     return ConstantRange(getBitWidth());
481 
482   APInt L = Lower, U = Upper;
483   if (CR.Upper.ugt(U))
484     U = CR.Upper;
485   if (CR.Lower.ult(L))
486     L = CR.Lower;
487 
488   return ConstantRange(L, U);
489 }
490 
491 /// zeroExtend - Return a new range in the specified integer type, which must
492 /// be strictly larger than the current type.  The returned range will
493 /// correspond to the possible range of values as if the source range had been
494 /// zero extended.
495 ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
496   if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
497 
498   unsigned SrcTySize = getBitWidth();
499   assert(SrcTySize < DstTySize && "Not a value extension");
500   if (isFullSet() || isWrappedSet()) {
501     // Change into [0, 1 << src bit width)
502     APInt LowerExt(DstTySize, 0);
503     if (!Upper) // special case: [X, 0) -- not really wrapping around
504       LowerExt = Lower.zext(DstTySize);
505     return ConstantRange(LowerExt, APInt::getOneBitSet(DstTySize, SrcTySize));
506   }
507 
508   return ConstantRange(Lower.zext(DstTySize), Upper.zext(DstTySize));
509 }
510 
511 /// signExtend - Return a new range in the specified integer type, which must
512 /// be strictly larger than the current type.  The returned range will
513 /// correspond to the possible range of values as if the source range had been
514 /// sign extended.
515 ConstantRange ConstantRange::signExtend(uint32_t DstTySize) const {
516   if (isEmptySet()) return ConstantRange(DstTySize, /*isFullSet=*/false);
517 
518   unsigned SrcTySize = getBitWidth();
519   assert(SrcTySize < DstTySize && "Not a value extension");
520 
521   // special case: [X, INT_MIN) -- not really wrapping around
522   if (Upper.isMinSignedValue())
523     return ConstantRange(Lower.sext(DstTySize), Upper.zext(DstTySize));
524 
525   if (isFullSet() || isSignWrappedSet()) {
526     return ConstantRange(APInt::getHighBitsSet(DstTySize,DstTySize-SrcTySize+1),
527                          APInt::getLowBitsSet(DstTySize, SrcTySize-1) + 1);
528   }
529 
530   return ConstantRange(Lower.sext(DstTySize), Upper.sext(DstTySize));
531 }
532 
533 /// truncate - Return a new range in the specified integer type, which must be
534 /// strictly smaller than the current type.  The returned range will
535 /// correspond to the possible range of values as if the source range had been
536 /// truncated to the specified type.
537 ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
538   assert(getBitWidth() > DstTySize && "Not a value truncation");
539   if (isEmptySet())
540     return ConstantRange(DstTySize, /*isFullSet=*/false);
541   if (isFullSet())
542     return ConstantRange(DstTySize, /*isFullSet=*/true);
543 
544   APInt MaxValue = APInt::getMaxValue(DstTySize).zext(getBitWidth());
545   APInt MaxBitValue(getBitWidth(), 0);
546   MaxBitValue.setBit(DstTySize);
547 
548   APInt LowerDiv(Lower), UpperDiv(Upper);
549   ConstantRange Union(DstTySize, /*isFullSet=*/false);
550 
551   // Analyze wrapped sets in their two parts: [0, Upper) \/ [Lower, MaxValue]
552   // We use the non-wrapped set code to analyze the [Lower, MaxValue) part, and
553   // then we do the union with [MaxValue, Upper)
554   if (isWrappedSet()) {
555     // if Upper is greater than Max Value, it covers the whole truncated range.
556     if (Upper.uge(MaxValue))
557       return ConstantRange(DstTySize, /*isFullSet=*/true);
558 
559     Union = ConstantRange(APInt::getMaxValue(DstTySize),Upper.trunc(DstTySize));
560     UpperDiv = APInt::getMaxValue(getBitWidth());
561 
562     // Union covers the MaxValue case, so return if the remaining range is just
563     // MaxValue.
564     if (LowerDiv == UpperDiv)
565       return Union;
566   }
567 
568   // Chop off the most significant bits that are past the destination bitwidth.
569   if (LowerDiv.uge(MaxValue)) {
570     APInt Div(getBitWidth(), 0);
571     APInt::udivrem(LowerDiv, MaxBitValue, Div, LowerDiv);
572     UpperDiv = UpperDiv - MaxBitValue * Div;
573   }
574 
575   if (UpperDiv.ule(MaxValue))
576     return ConstantRange(LowerDiv.trunc(DstTySize),
577                          UpperDiv.trunc(DstTySize)).unionWith(Union);
578 
579   // The truncated value wrapps around. Check if we can do better than fullset.
580   APInt UpperModulo = UpperDiv - MaxBitValue;
581   if (UpperModulo.ult(LowerDiv))
582     return ConstantRange(LowerDiv.trunc(DstTySize),
583                          UpperModulo.trunc(DstTySize)).unionWith(Union);
584 
585   return ConstantRange(DstTySize, /*isFullSet=*/true);
586 }
587 
588 /// zextOrTrunc - make this range have the bit width given by \p DstTySize. The
589 /// value is zero extended, truncated, or left alone to make it that width.
590 ConstantRange ConstantRange::zextOrTrunc(uint32_t DstTySize) const {
591   unsigned SrcTySize = getBitWidth();
592   if (SrcTySize > DstTySize)
593     return truncate(DstTySize);
594   if (SrcTySize < DstTySize)
595     return zeroExtend(DstTySize);
596   return *this;
597 }
598 
599 /// sextOrTrunc - make this range have the bit width given by \p DstTySize. The
600 /// value is sign extended, truncated, or left alone to make it that width.
601 ConstantRange ConstantRange::sextOrTrunc(uint32_t DstTySize) const {
602   unsigned SrcTySize = getBitWidth();
603   if (SrcTySize > DstTySize)
604     return truncate(DstTySize);
605   if (SrcTySize < DstTySize)
606     return signExtend(DstTySize);
607   return *this;
608 }
609 
610 ConstantRange
611 ConstantRange::add(const ConstantRange &Other) const {
612   if (isEmptySet() || Other.isEmptySet())
613     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
614   if (isFullSet() || Other.isFullSet())
615     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
616 
617   APInt Spread_X = getSetSize(), Spread_Y = Other.getSetSize();
618   APInt NewLower = getLower() + Other.getLower();
619   APInt NewUpper = getUpper() + Other.getUpper() - 1;
620   if (NewLower == NewUpper)
621     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
622 
623   ConstantRange X = ConstantRange(NewLower, NewUpper);
624   if (X.getSetSize().ult(Spread_X) || X.getSetSize().ult(Spread_Y))
625     // We've wrapped, therefore, full set.
626     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
627 
628   return X;
629 }
630 
631 ConstantRange
632 ConstantRange::sub(const ConstantRange &Other) const {
633   if (isEmptySet() || Other.isEmptySet())
634     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
635   if (isFullSet() || Other.isFullSet())
636     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
637 
638   APInt Spread_X = getSetSize(), Spread_Y = Other.getSetSize();
639   APInt NewLower = getLower() - Other.getUpper() + 1;
640   APInt NewUpper = getUpper() - Other.getLower();
641   if (NewLower == NewUpper)
642     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
643 
644   ConstantRange X = ConstantRange(NewLower, NewUpper);
645   if (X.getSetSize().ult(Spread_X) || X.getSetSize().ult(Spread_Y))
646     // We've wrapped, therefore, full set.
647     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
648 
649   return X;
650 }
651 
652 ConstantRange
653 ConstantRange::multiply(const ConstantRange &Other) const {
654   // TODO: If either operand is a single element and the multiply is known to
655   // be non-wrapping, round the result min and max value to the appropriate
656   // multiple of that element. If wrapping is possible, at least adjust the
657   // range according to the greatest power-of-two factor of the single element.
658 
659   if (isEmptySet() || Other.isEmptySet())
660     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
661 
662   // Multiplication is signedness-independent. However different ranges can be
663   // obtained depending on how the input ranges are treated. These different
664   // ranges are all conservatively correct, but one might be better than the
665   // other. We calculate two ranges; one treating the inputs as unsigned
666   // and the other signed, then return the smallest of these ranges.
667 
668   // Unsigned range first.
669   APInt this_min = getUnsignedMin().zext(getBitWidth() * 2);
670   APInt this_max = getUnsignedMax().zext(getBitWidth() * 2);
671   APInt Other_min = Other.getUnsignedMin().zext(getBitWidth() * 2);
672   APInt Other_max = Other.getUnsignedMax().zext(getBitWidth() * 2);
673 
674   ConstantRange Result_zext = ConstantRange(this_min * Other_min,
675                                             this_max * Other_max + 1);
676   ConstantRange UR = Result_zext.truncate(getBitWidth());
677 
678   // Now the signed range. Because we could be dealing with negative numbers
679   // here, the lower bound is the smallest of the cartesian product of the
680   // lower and upper ranges; for example:
681   //   [-1,4) * [-2,3) = min(-1*-2, -1*2, 3*-2, 3*2) = -6.
682   // Similarly for the upper bound, swapping min for max.
683 
684   this_min = getSignedMin().sext(getBitWidth() * 2);
685   this_max = getSignedMax().sext(getBitWidth() * 2);
686   Other_min = Other.getSignedMin().sext(getBitWidth() * 2);
687   Other_max = Other.getSignedMax().sext(getBitWidth() * 2);
688 
689   auto L = {this_min * Other_min, this_min * Other_max,
690             this_max * Other_min, this_max * Other_max};
691   auto Compare = [](const APInt &A, const APInt &B) { return A.slt(B); };
692   ConstantRange Result_sext(std::min(L, Compare), std::max(L, Compare) + 1);
693   ConstantRange SR = Result_sext.truncate(getBitWidth());
694 
695   return UR.getSetSize().ult(SR.getSetSize()) ? UR : SR;
696 }
697 
698 ConstantRange
699 ConstantRange::smax(const ConstantRange &Other) const {
700   // X smax Y is: range(smax(X_smin, Y_smin),
701   //                    smax(X_smax, Y_smax))
702   if (isEmptySet() || Other.isEmptySet())
703     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
704   APInt NewL = APIntOps::smax(getSignedMin(), Other.getSignedMin());
705   APInt NewU = APIntOps::smax(getSignedMax(), Other.getSignedMax()) + 1;
706   if (NewU == NewL)
707     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
708   return ConstantRange(NewL, NewU);
709 }
710 
711 ConstantRange
712 ConstantRange::umax(const ConstantRange &Other) const {
713   // X umax Y is: range(umax(X_umin, Y_umin),
714   //                    umax(X_umax, Y_umax))
715   if (isEmptySet() || Other.isEmptySet())
716     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
717   APInt NewL = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
718   APInt NewU = APIntOps::umax(getUnsignedMax(), Other.getUnsignedMax()) + 1;
719   if (NewU == NewL)
720     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
721   return ConstantRange(NewL, NewU);
722 }
723 
724 ConstantRange
725 ConstantRange::smin(const ConstantRange &Other) const {
726   // X smin Y is: range(smin(X_smin, Y_smin),
727   //                    smin(X_smax, Y_smax))
728   if (isEmptySet() || Other.isEmptySet())
729     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
730   APInt NewL = APIntOps::smin(getSignedMin(), Other.getSignedMin());
731   APInt NewU = APIntOps::smin(getSignedMax(), Other.getSignedMax()) + 1;
732   if (NewU == NewL)
733     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
734   return ConstantRange(NewL, NewU);
735 }
736 
737 ConstantRange
738 ConstantRange::umin(const ConstantRange &Other) const {
739   // X umin Y is: range(umin(X_umin, Y_umin),
740   //                    umin(X_umax, Y_umax))
741   if (isEmptySet() || Other.isEmptySet())
742     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
743   APInt NewL = APIntOps::umin(getUnsignedMin(), Other.getUnsignedMin());
744   APInt NewU = APIntOps::umin(getUnsignedMax(), Other.getUnsignedMax()) + 1;
745   if (NewU == NewL)
746     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
747   return ConstantRange(NewL, NewU);
748 }
749 
750 ConstantRange
751 ConstantRange::udiv(const ConstantRange &RHS) const {
752   if (isEmptySet() || RHS.isEmptySet() || RHS.getUnsignedMax() == 0)
753     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
754   if (RHS.isFullSet())
755     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
756 
757   APInt Lower = getUnsignedMin().udiv(RHS.getUnsignedMax());
758 
759   APInt RHS_umin = RHS.getUnsignedMin();
760   if (RHS_umin == 0) {
761     // We want the lowest value in RHS excluding zero. Usually that would be 1
762     // except for a range in the form of [X, 1) in which case it would be X.
763     if (RHS.getUpper() == 1)
764       RHS_umin = RHS.getLower();
765     else
766       RHS_umin = APInt(getBitWidth(), 1);
767   }
768 
769   APInt Upper = getUnsignedMax().udiv(RHS_umin) + 1;
770 
771   // If the LHS is Full and the RHS is a wrapped interval containing 1 then
772   // this could occur.
773   if (Lower == Upper)
774     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
775 
776   return ConstantRange(Lower, Upper);
777 }
778 
779 ConstantRange
780 ConstantRange::binaryAnd(const ConstantRange &Other) const {
781   if (isEmptySet() || Other.isEmptySet())
782     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
783 
784   // TODO: replace this with something less conservative
785 
786   APInt umin = APIntOps::umin(Other.getUnsignedMax(), getUnsignedMax());
787   if (umin.isAllOnesValue())
788     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
789   return ConstantRange(APInt::getNullValue(getBitWidth()), umin + 1);
790 }
791 
792 ConstantRange
793 ConstantRange::binaryOr(const ConstantRange &Other) const {
794   if (isEmptySet() || Other.isEmptySet())
795     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
796 
797   // TODO: replace this with something less conservative
798 
799   APInt umax = APIntOps::umax(getUnsignedMin(), Other.getUnsignedMin());
800   if (umax.isMinValue())
801     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
802   return ConstantRange(umax, APInt::getNullValue(getBitWidth()));
803 }
804 
805 ConstantRange
806 ConstantRange::shl(const ConstantRange &Other) const {
807   if (isEmptySet() || Other.isEmptySet())
808     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
809 
810   APInt min = getUnsignedMin().shl(Other.getUnsignedMin());
811   APInt max = getUnsignedMax().shl(Other.getUnsignedMax());
812 
813   // there's no overflow!
814   APInt Zeros(getBitWidth(), getUnsignedMax().countLeadingZeros());
815   if (Zeros.ugt(Other.getUnsignedMax()))
816     return ConstantRange(min, max + 1);
817 
818   // FIXME: implement the other tricky cases
819   return ConstantRange(getBitWidth(), /*isFullSet=*/true);
820 }
821 
822 ConstantRange
823 ConstantRange::lshr(const ConstantRange &Other) const {
824   if (isEmptySet() || Other.isEmptySet())
825     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
826 
827   APInt max = getUnsignedMax().lshr(Other.getUnsignedMin());
828   APInt min = getUnsignedMin().lshr(Other.getUnsignedMax());
829   if (min == max + 1)
830     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
831 
832   return ConstantRange(min, max + 1);
833 }
834 
835 ConstantRange ConstantRange::inverse() const {
836   if (isFullSet())
837     return ConstantRange(getBitWidth(), /*isFullSet=*/false);
838   if (isEmptySet())
839     return ConstantRange(getBitWidth(), /*isFullSet=*/true);
840   return ConstantRange(Upper, Lower);
841 }
842 
843 /// print - Print out the bounds to a stream...
844 ///
845 void ConstantRange::print(raw_ostream &OS) const {
846   if (isFullSet())
847     OS << "full-set";
848   else if (isEmptySet())
849     OS << "empty-set";
850   else
851     OS << "[" << Lower << "," << Upper << ")";
852 }
853 
854 /// dump - Allow printing from a debugger easily...
855 ///
856 LLVM_DUMP_METHOD void ConstantRange::dump() const {
857   print(dbgs());
858 }
859