1 //===- ConstantRangeTest.cpp - ConstantRange tests ------------------------===//
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 #include "llvm/IR/ConstantRange.h"
10 #include "llvm/ADT/BitVector.h"
11 #include "llvm/ADT/Sequence.h"
12 #include "llvm/ADT/SmallBitVector.h"
13 #include "llvm/IR/Instructions.h"
14 #include "llvm/IR/Operator.h"
15 #include "llvm/Support/KnownBits.h"
16 #include "gtest/gtest.h"
17 
18 using namespace llvm;
19 
20 namespace {
21 
22 class ConstantRangeTest : public ::testing::Test {
23 protected:
24   static ConstantRange Full;
25   static ConstantRange Empty;
26   static ConstantRange One;
27   static ConstantRange Some;
28   static ConstantRange Wrap;
29 };
30 
31 template<typename Fn>
32 static void EnumerateConstantRanges(unsigned Bits, Fn TestFn) {
33   unsigned Max = 1 << Bits;
34   for (unsigned Lo = 0; Lo < Max; Lo++) {
35     for (unsigned Hi = 0; Hi < Max; Hi++) {
36       // Enforce ConstantRange invariant.
37       if (Lo == Hi && Lo != 0 && Lo != Max - 1)
38         continue;
39 
40       ConstantRange CR(APInt(Bits, Lo), APInt(Bits, Hi));
41       TestFn(CR);
42     }
43   }
44 }
45 
46 template<typename Fn>
47 static void EnumerateTwoConstantRanges(unsigned Bits, Fn TestFn) {
48   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR1) {
49     EnumerateConstantRanges(Bits, [&](const ConstantRange &CR2) {
50       TestFn(CR1, CR2);
51     });
52   });
53 }
54 
55 template<typename Fn>
56 static void ForeachNumInConstantRange(const ConstantRange &CR, Fn TestFn) {
57   if (!CR.isEmptySet()) {
58     APInt N = CR.getLower();
59     do TestFn(N);
60     while (++N != CR.getUpper());
61   }
62 }
63 
64 using PreferFn = llvm::function_ref<bool(const ConstantRange &,
65                                          const ConstantRange &)>;
66 
67 bool PreferSmallest(const ConstantRange &CR1, const ConstantRange &CR2) {
68   return CR1.isSizeStrictlySmallerThan(CR2);
69 }
70 
71 bool PreferSmallestUnsigned(const ConstantRange &CR1,
72                             const ConstantRange &CR2) {
73   if (CR1.isWrappedSet() != CR2.isWrappedSet())
74     return CR1.isWrappedSet() < CR2.isWrappedSet();
75   return PreferSmallest(CR1, CR2);
76 }
77 
78 bool PreferSmallestSigned(const ConstantRange &CR1, const ConstantRange &CR2) {
79   if (CR1.isSignWrappedSet() != CR2.isSignWrappedSet())
80     return CR1.isSignWrappedSet() < CR2.isSignWrappedSet();
81   return PreferSmallest(CR1, CR2);
82 }
83 
84 bool PreferSmallestNonFullUnsigned(const ConstantRange &CR1,
85                                    const ConstantRange &CR2) {
86   if (CR1.isFullSet() != CR2.isFullSet())
87     return CR1.isFullSet() < CR2.isFullSet();
88   return PreferSmallestUnsigned(CR1, CR2);
89 }
90 
91 bool PreferSmallestNonFullSigned(const ConstantRange &CR1,
92                                  const ConstantRange &CR2) {
93   if (CR1.isFullSet() != CR2.isFullSet())
94     return CR1.isFullSet() < CR2.isFullSet();
95   return PreferSmallestSigned(CR1, CR2);
96 }
97 
98 testing::AssertionResult rangeContains(const ConstantRange &CR, const APInt &N,
99                                        ArrayRef<ConstantRange> Inputs) {
100   if (CR.contains(N))
101     return testing::AssertionSuccess();
102 
103   testing::AssertionResult Result = testing::AssertionFailure();
104   Result << CR << " does not contain " << N << " for inputs: ";
105   for (const ConstantRange &Input : Inputs)
106     Result << Input << ", ";
107   return Result;
108 }
109 
110 // Check whether constant range CR is an optimal approximation of the set
111 // Elems under the given PreferenceFn. The preference function should return
112 // true if the first range argument is strictly preferred to the second one.
113 static void TestRange(const ConstantRange &CR, const SmallBitVector &Elems,
114                       PreferFn PreferenceFn, ArrayRef<ConstantRange> Inputs,
115                       bool CheckOptimality = true) {
116   unsigned BitWidth = CR.getBitWidth();
117 
118   // Check conservative correctness.
119   for (unsigned Elem : Elems.set_bits()) {
120     EXPECT_TRUE(rangeContains(CR, APInt(BitWidth, Elem), Inputs));
121   }
122 
123   if (!CheckOptimality)
124     return;
125 
126   // Make sure we have at least one element for the code below.
127   if (Elems.none()) {
128     EXPECT_TRUE(CR.isEmptySet());
129     return;
130   }
131 
132   auto NotPreferred = [&](const ConstantRange &PossibleCR) {
133     if (!PreferenceFn(PossibleCR, CR))
134       return testing::AssertionSuccess();
135 
136     testing::AssertionResult Result = testing::AssertionFailure();
137     Result << "Inputs = ";
138     for (const ConstantRange &Input : Inputs)
139       Result << Input << ", ";
140     Result << "CR = " << CR << ", BetterCR = " << PossibleCR;
141     return Result;
142   };
143 
144   // Look at all pairs of adjacent elements and the slack-free ranges
145   // [Elem, PrevElem] they imply. Check that none of the ranges are strictly
146   // preferred over the computed range (they may have equal preference).
147   int FirstElem = Elems.find_first();
148   int PrevElem = FirstElem, Elem;
149   do {
150     Elem = Elems.find_next(PrevElem);
151     if (Elem < 0)
152       Elem = FirstElem; // Wrap around to first element.
153 
154     ConstantRange PossibleCR =
155         ConstantRange::getNonEmpty(APInt(BitWidth, Elem),
156                                    APInt(BitWidth, PrevElem) + 1);
157     // We get a full range any time PrevElem and Elem are adjacent. Avoid
158     // repeated checks by skipping here, and explicitly checking below instead.
159     if (!PossibleCR.isFullSet()) {
160       EXPECT_TRUE(NotPreferred(PossibleCR));
161     }
162 
163     PrevElem = Elem;
164   } while (Elem != FirstElem);
165 
166   EXPECT_TRUE(NotPreferred(ConstantRange::getFull(BitWidth)));
167 }
168 
169 using UnaryRangeFn = llvm::function_ref<ConstantRange(const ConstantRange &)>;
170 using UnaryIntFn = llvm::function_ref<Optional<APInt>(const APInt &)>;
171 
172 static void TestUnaryOpExhaustive(UnaryRangeFn RangeFn, UnaryIntFn IntFn,
173                                   PreferFn PreferenceFn = PreferSmallest) {
174   unsigned Bits = 4;
175   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
176     SmallBitVector Elems(1 << Bits);
177     ForeachNumInConstantRange(CR, [&](const APInt &N) {
178       if (Optional<APInt> ResultN = IntFn(N))
179         Elems.set(ResultN->getZExtValue());
180     });
181     TestRange(RangeFn(CR), Elems, PreferenceFn, {CR});
182   });
183 }
184 
185 using BinaryRangeFn = llvm::function_ref<ConstantRange(const ConstantRange &,
186                                                        const ConstantRange &)>;
187 using BinaryIntFn = llvm::function_ref<Optional<APInt>(const APInt &,
188                                                        const APInt &)>;
189 using BinaryCheckFn = llvm::function_ref<bool(const ConstantRange &,
190                                               const ConstantRange &)>;
191 
192 static bool CheckAll(const ConstantRange &, const ConstantRange &) {
193   return true;
194 }
195 
196 static bool CheckSingleElementsOnly(const ConstantRange &CR1,
197                                     const ConstantRange &CR2) {
198   return CR1.isSingleElement() && CR2.isSingleElement();
199 }
200 
201 // CheckFn determines whether optimality is checked for a given range pair.
202 // Correctness is always checked.
203 static void TestBinaryOpExhaustive(BinaryRangeFn RangeFn, BinaryIntFn IntFn,
204                                    PreferFn PreferenceFn = PreferSmallest,
205                                    BinaryCheckFn CheckFn = CheckAll) {
206   unsigned Bits = 4;
207   EnumerateTwoConstantRanges(
208       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
209         SmallBitVector Elems(1 << Bits);
210         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
211           ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
212             if (Optional<APInt> ResultN = IntFn(N1, N2))
213               Elems.set(ResultN->getZExtValue());
214           });
215         });
216         TestRange(RangeFn(CR1, CR2), Elems, PreferenceFn, {CR1, CR2},
217                   CheckFn(CR1, CR2));
218       });
219 }
220 
221 struct OpRangeGathererBase {
222   void account(const APInt &N);
223   ConstantRange getRange();
224 };
225 
226 struct UnsignedOpRangeGatherer : public OpRangeGathererBase {
227   APInt Min;
228   APInt Max;
229 
230   UnsignedOpRangeGatherer(unsigned Bits)
231       : Min(APInt::getMaxValue(Bits)), Max(APInt::getMinValue(Bits)) {}
232 
233   void account(const APInt &N) {
234     if (N.ult(Min))
235       Min = N;
236     if (N.ugt(Max))
237       Max = N;
238   }
239 
240   ConstantRange getRange() {
241     if (Min.ugt(Max))
242       return ConstantRange::getEmpty(Min.getBitWidth());
243     return ConstantRange::getNonEmpty(Min, Max + 1);
244   }
245 };
246 
247 struct SignedOpRangeGatherer : public OpRangeGathererBase {
248   APInt Min;
249   APInt Max;
250 
251   SignedOpRangeGatherer(unsigned Bits)
252       : Min(APInt::getSignedMaxValue(Bits)),
253         Max(APInt::getSignedMinValue(Bits)) {}
254 
255   void account(const APInt &N) {
256     if (N.slt(Min))
257       Min = N;
258     if (N.sgt(Max))
259       Max = N;
260   }
261 
262   ConstantRange getRange() {
263     if (Min.sgt(Max))
264       return ConstantRange::getEmpty(Min.getBitWidth());
265     return ConstantRange::getNonEmpty(Min, Max + 1);
266   }
267 };
268 
269 ConstantRange ConstantRangeTest::Full(16, true);
270 ConstantRange ConstantRangeTest::Empty(16, false);
271 ConstantRange ConstantRangeTest::One(APInt(16, 0xa));
272 ConstantRange ConstantRangeTest::Some(APInt(16, 0xa), APInt(16, 0xaaa));
273 ConstantRange ConstantRangeTest::Wrap(APInt(16, 0xaaa), APInt(16, 0xa));
274 
275 TEST_F(ConstantRangeTest, Basics) {
276   EXPECT_TRUE(Full.isFullSet());
277   EXPECT_FALSE(Full.isEmptySet());
278   EXPECT_TRUE(Full.inverse().isEmptySet());
279   EXPECT_FALSE(Full.isWrappedSet());
280   EXPECT_TRUE(Full.contains(APInt(16, 0x0)));
281   EXPECT_TRUE(Full.contains(APInt(16, 0x9)));
282   EXPECT_TRUE(Full.contains(APInt(16, 0xa)));
283   EXPECT_TRUE(Full.contains(APInt(16, 0xaa9)));
284   EXPECT_TRUE(Full.contains(APInt(16, 0xaaa)));
285 
286   EXPECT_FALSE(Empty.isFullSet());
287   EXPECT_TRUE(Empty.isEmptySet());
288   EXPECT_TRUE(Empty.inverse().isFullSet());
289   EXPECT_FALSE(Empty.isWrappedSet());
290   EXPECT_FALSE(Empty.contains(APInt(16, 0x0)));
291   EXPECT_FALSE(Empty.contains(APInt(16, 0x9)));
292   EXPECT_FALSE(Empty.contains(APInt(16, 0xa)));
293   EXPECT_FALSE(Empty.contains(APInt(16, 0xaa9)));
294   EXPECT_FALSE(Empty.contains(APInt(16, 0xaaa)));
295 
296   EXPECT_FALSE(One.isFullSet());
297   EXPECT_FALSE(One.isEmptySet());
298   EXPECT_FALSE(One.isWrappedSet());
299   EXPECT_FALSE(One.contains(APInt(16, 0x0)));
300   EXPECT_FALSE(One.contains(APInt(16, 0x9)));
301   EXPECT_TRUE(One.contains(APInt(16, 0xa)));
302   EXPECT_FALSE(One.contains(APInt(16, 0xaa9)));
303   EXPECT_FALSE(One.contains(APInt(16, 0xaaa)));
304   EXPECT_FALSE(One.inverse().contains(APInt(16, 0xa)));
305 
306   EXPECT_FALSE(Some.isFullSet());
307   EXPECT_FALSE(Some.isEmptySet());
308   EXPECT_FALSE(Some.isWrappedSet());
309   EXPECT_FALSE(Some.contains(APInt(16, 0x0)));
310   EXPECT_FALSE(Some.contains(APInt(16, 0x9)));
311   EXPECT_TRUE(Some.contains(APInt(16, 0xa)));
312   EXPECT_TRUE(Some.contains(APInt(16, 0xaa9)));
313   EXPECT_FALSE(Some.contains(APInt(16, 0xaaa)));
314 
315   EXPECT_FALSE(Wrap.isFullSet());
316   EXPECT_FALSE(Wrap.isEmptySet());
317   EXPECT_TRUE(Wrap.isWrappedSet());
318   EXPECT_TRUE(Wrap.contains(APInt(16, 0x0)));
319   EXPECT_TRUE(Wrap.contains(APInt(16, 0x9)));
320   EXPECT_FALSE(Wrap.contains(APInt(16, 0xa)));
321   EXPECT_FALSE(Wrap.contains(APInt(16, 0xaa9)));
322   EXPECT_TRUE(Wrap.contains(APInt(16, 0xaaa)));
323 }
324 
325 TEST_F(ConstantRangeTest, Equality) {
326   EXPECT_EQ(Full, Full);
327   EXPECT_EQ(Empty, Empty);
328   EXPECT_EQ(One, One);
329   EXPECT_EQ(Some, Some);
330   EXPECT_EQ(Wrap, Wrap);
331   EXPECT_NE(Full, Empty);
332   EXPECT_NE(Full, One);
333   EXPECT_NE(Full, Some);
334   EXPECT_NE(Full, Wrap);
335   EXPECT_NE(Empty, One);
336   EXPECT_NE(Empty, Some);
337   EXPECT_NE(Empty, Wrap);
338   EXPECT_NE(One, Some);
339   EXPECT_NE(One, Wrap);
340   EXPECT_NE(Some, Wrap);
341 }
342 
343 TEST_F(ConstantRangeTest, SingleElement) {
344   EXPECT_EQ(Full.getSingleElement(), static_cast<APInt *>(nullptr));
345   EXPECT_EQ(Empty.getSingleElement(), static_cast<APInt *>(nullptr));
346   EXPECT_EQ(Full.getSingleMissingElement(), static_cast<APInt *>(nullptr));
347   EXPECT_EQ(Empty.getSingleMissingElement(), static_cast<APInt *>(nullptr));
348 
349   EXPECT_EQ(*One.getSingleElement(), APInt(16, 0xa));
350   EXPECT_EQ(Some.getSingleElement(), static_cast<APInt *>(nullptr));
351   EXPECT_EQ(Wrap.getSingleElement(), static_cast<APInt *>(nullptr));
352 
353   EXPECT_EQ(One.getSingleMissingElement(), static_cast<APInt *>(nullptr));
354   EXPECT_EQ(Some.getSingleMissingElement(), static_cast<APInt *>(nullptr));
355 
356   ConstantRange OneInverse = One.inverse();
357   EXPECT_EQ(*OneInverse.getSingleMissingElement(), *One.getSingleElement());
358 
359   EXPECT_FALSE(Full.isSingleElement());
360   EXPECT_FALSE(Empty.isSingleElement());
361   EXPECT_TRUE(One.isSingleElement());
362   EXPECT_FALSE(Some.isSingleElement());
363   EXPECT_FALSE(Wrap.isSingleElement());
364 }
365 
366 TEST_F(ConstantRangeTest, GetMinsAndMaxes) {
367   EXPECT_EQ(Full.getUnsignedMax(), APInt(16, UINT16_MAX));
368   EXPECT_EQ(One.getUnsignedMax(), APInt(16, 0xa));
369   EXPECT_EQ(Some.getUnsignedMax(), APInt(16, 0xaa9));
370   EXPECT_EQ(Wrap.getUnsignedMax(), APInt(16, UINT16_MAX));
371 
372   EXPECT_EQ(Full.getUnsignedMin(), APInt(16, 0));
373   EXPECT_EQ(One.getUnsignedMin(), APInt(16, 0xa));
374   EXPECT_EQ(Some.getUnsignedMin(), APInt(16, 0xa));
375   EXPECT_EQ(Wrap.getUnsignedMin(), APInt(16, 0));
376 
377   EXPECT_EQ(Full.getSignedMax(), APInt(16, INT16_MAX));
378   EXPECT_EQ(One.getSignedMax(), APInt(16, 0xa));
379   EXPECT_EQ(Some.getSignedMax(), APInt(16, 0xaa9));
380   EXPECT_EQ(Wrap.getSignedMax(), APInt(16, INT16_MAX));
381 
382   EXPECT_EQ(Full.getSignedMin(), APInt(16, (uint64_t)INT16_MIN));
383   EXPECT_EQ(One.getSignedMin(), APInt(16, 0xa));
384   EXPECT_EQ(Some.getSignedMin(), APInt(16, 0xa));
385   EXPECT_EQ(Wrap.getSignedMin(), APInt(16, (uint64_t)INT16_MIN));
386 
387   // Found by Klee
388   EXPECT_EQ(ConstantRange(APInt(4, 7), APInt(4, 0)).getSignedMax(),
389             APInt(4, 7));
390 }
391 
392 TEST_F(ConstantRangeTest, SignWrapped) {
393   EXPECT_FALSE(Full.isSignWrappedSet());
394   EXPECT_FALSE(Empty.isSignWrappedSet());
395   EXPECT_FALSE(One.isSignWrappedSet());
396   EXPECT_FALSE(Some.isSignWrappedSet());
397   EXPECT_TRUE(Wrap.isSignWrappedSet());
398 
399   EXPECT_FALSE(ConstantRange(APInt(8, 127), APInt(8, 128)).isSignWrappedSet());
400   EXPECT_TRUE(ConstantRange(APInt(8, 127), APInt(8, 129)).isSignWrappedSet());
401   EXPECT_FALSE(ConstantRange(APInt(8, 128), APInt(8, 129)).isSignWrappedSet());
402   EXPECT_TRUE(ConstantRange(APInt(8, 10), APInt(8, 9)).isSignWrappedSet());
403   EXPECT_TRUE(ConstantRange(APInt(8, 10), APInt(8, 250)).isSignWrappedSet());
404   EXPECT_FALSE(ConstantRange(APInt(8, 250), APInt(8, 10)).isSignWrappedSet());
405   EXPECT_FALSE(ConstantRange(APInt(8, 250), APInt(8, 251)).isSignWrappedSet());
406 }
407 
408 TEST_F(ConstantRangeTest, UpperWrapped) {
409   // The behavior here is the same as for isWrappedSet() / isSignWrappedSet().
410   EXPECT_FALSE(Full.isUpperWrapped());
411   EXPECT_FALSE(Empty.isUpperWrapped());
412   EXPECT_FALSE(One.isUpperWrapped());
413   EXPECT_FALSE(Some.isUpperWrapped());
414   EXPECT_TRUE(Wrap.isUpperWrapped());
415   EXPECT_FALSE(Full.isUpperSignWrapped());
416   EXPECT_FALSE(Empty.isUpperSignWrapped());
417   EXPECT_FALSE(One.isUpperSignWrapped());
418   EXPECT_FALSE(Some.isUpperSignWrapped());
419   EXPECT_TRUE(Wrap.isUpperSignWrapped());
420 
421   // The behavior differs if Upper is the Min/SignedMin value.
422   ConstantRange CR1(APInt(8, 42), APInt::getMinValue(8));
423   EXPECT_FALSE(CR1.isWrappedSet());
424   EXPECT_TRUE(CR1.isUpperWrapped());
425 
426   ConstantRange CR2(APInt(8, 42), APInt::getSignedMinValue(8));
427   EXPECT_FALSE(CR2.isSignWrappedSet());
428   EXPECT_TRUE(CR2.isUpperSignWrapped());
429 }
430 
431 TEST_F(ConstantRangeTest, Trunc) {
432   ConstantRange TFull = Full.truncate(10);
433   ConstantRange TEmpty = Empty.truncate(10);
434   ConstantRange TOne = One.truncate(10);
435   ConstantRange TSome = Some.truncate(10);
436   ConstantRange TWrap = Wrap.truncate(10);
437   EXPECT_TRUE(TFull.isFullSet());
438   EXPECT_TRUE(TEmpty.isEmptySet());
439   EXPECT_EQ(TOne, ConstantRange(One.getLower().trunc(10),
440                                 One.getUpper().trunc(10)));
441   EXPECT_TRUE(TSome.isFullSet());
442   EXPECT_TRUE(TWrap.isFullSet());
443 
444   // trunc([2, 5), 3->2) = [2, 1)
445   ConstantRange TwoFive(APInt(3, 2), APInt(3, 5));
446   EXPECT_EQ(TwoFive.truncate(2), ConstantRange(APInt(2, 2), APInt(2, 1)));
447 
448   // trunc([2, 6), 3->2) = full
449   ConstantRange TwoSix(APInt(3, 2), APInt(3, 6));
450   EXPECT_TRUE(TwoSix.truncate(2).isFullSet());
451 
452   // trunc([5, 7), 3->2) = [1, 3)
453   ConstantRange FiveSeven(APInt(3, 5), APInt(3, 7));
454   EXPECT_EQ(FiveSeven.truncate(2), ConstantRange(APInt(2, 1), APInt(2, 3)));
455 
456   // trunc([7, 1), 3->2) = [3, 1)
457   ConstantRange SevenOne(APInt(3, 7), APInt(3, 1));
458   EXPECT_EQ(SevenOne.truncate(2), ConstantRange(APInt(2, 3), APInt(2, 1)));
459 }
460 
461 TEST_F(ConstantRangeTest, ZExt) {
462   ConstantRange ZFull = Full.zeroExtend(20);
463   ConstantRange ZEmpty = Empty.zeroExtend(20);
464   ConstantRange ZOne = One.zeroExtend(20);
465   ConstantRange ZSome = Some.zeroExtend(20);
466   ConstantRange ZWrap = Wrap.zeroExtend(20);
467   EXPECT_EQ(ZFull, ConstantRange(APInt(20, 0), APInt(20, 0x10000)));
468   EXPECT_TRUE(ZEmpty.isEmptySet());
469   EXPECT_EQ(ZOne, ConstantRange(One.getLower().zext(20),
470                                 One.getUpper().zext(20)));
471   EXPECT_EQ(ZSome, ConstantRange(Some.getLower().zext(20),
472                                  Some.getUpper().zext(20)));
473   EXPECT_EQ(ZWrap, ConstantRange(APInt(20, 0), APInt(20, 0x10000)));
474 
475   // zext([5, 0), 3->7) = [5, 8)
476   ConstantRange FiveZero(APInt(3, 5), APInt(3, 0));
477   EXPECT_EQ(FiveZero.zeroExtend(7), ConstantRange(APInt(7, 5), APInt(7, 8)));
478 }
479 
480 TEST_F(ConstantRangeTest, SExt) {
481   ConstantRange SFull = Full.signExtend(20);
482   ConstantRange SEmpty = Empty.signExtend(20);
483   ConstantRange SOne = One.signExtend(20);
484   ConstantRange SSome = Some.signExtend(20);
485   ConstantRange SWrap = Wrap.signExtend(20);
486   EXPECT_EQ(SFull, ConstantRange(APInt(20, (uint64_t)INT16_MIN, true),
487                                  APInt(20, INT16_MAX + 1, true)));
488   EXPECT_TRUE(SEmpty.isEmptySet());
489   EXPECT_EQ(SOne, ConstantRange(One.getLower().sext(20),
490                                 One.getUpper().sext(20)));
491   EXPECT_EQ(SSome, ConstantRange(Some.getLower().sext(20),
492                                  Some.getUpper().sext(20)));
493   EXPECT_EQ(SWrap, ConstantRange(APInt(20, (uint64_t)INT16_MIN, true),
494                                  APInt(20, INT16_MAX + 1, true)));
495 
496   EXPECT_EQ(ConstantRange(APInt(8, 120), APInt(8, 140)).signExtend(16),
497             ConstantRange(APInt(16, -128), APInt(16, 128)));
498 
499   EXPECT_EQ(ConstantRange(APInt(16, 0x0200), APInt(16, 0x8000)).signExtend(19),
500             ConstantRange(APInt(19, 0x0200), APInt(19, 0x8000)));
501 }
502 
503 TEST_F(ConstantRangeTest, IntersectWith) {
504   EXPECT_EQ(Empty.intersectWith(Full), Empty);
505   EXPECT_EQ(Empty.intersectWith(Empty), Empty);
506   EXPECT_EQ(Empty.intersectWith(One), Empty);
507   EXPECT_EQ(Empty.intersectWith(Some), Empty);
508   EXPECT_EQ(Empty.intersectWith(Wrap), Empty);
509   EXPECT_EQ(Full.intersectWith(Full), Full);
510   EXPECT_EQ(Some.intersectWith(Some), Some);
511   EXPECT_EQ(Some.intersectWith(One), One);
512   EXPECT_EQ(Full.intersectWith(One), One);
513   EXPECT_EQ(Full.intersectWith(Some), Some);
514   EXPECT_EQ(Some.intersectWith(Wrap), Empty);
515   EXPECT_EQ(One.intersectWith(Wrap), Empty);
516   EXPECT_EQ(One.intersectWith(Wrap), Wrap.intersectWith(One));
517 
518   // Klee generated testcase from PR4545.
519   // The intersection of i16 [4, 2) and [6, 5) is disjoint, looking like
520   // 01..4.6789ABCDEF where the dots represent values not in the intersection.
521   ConstantRange LHS(APInt(16, 4), APInt(16, 2));
522   ConstantRange RHS(APInt(16, 6), APInt(16, 5));
523   EXPECT_TRUE(LHS.intersectWith(RHS) == LHS);
524 
525   // previous bug: intersection of [min, 3) and [2, max) should be 2
526   LHS = ConstantRange(APInt(32, -2147483646), APInt(32, 3));
527   RHS = ConstantRange(APInt(32, 2), APInt(32, 2147483646));
528   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 2)));
529 
530   // [2, 0) /\ [4, 3) = [2, 0)
531   LHS = ConstantRange(APInt(32, 2), APInt(32, 0));
532   RHS = ConstantRange(APInt(32, 4), APInt(32, 3));
533   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 2), APInt(32, 0)));
534 
535   // [2, 0) /\ [4, 2) = [4, 0)
536   LHS = ConstantRange(APInt(32, 2), APInt(32, 0));
537   RHS = ConstantRange(APInt(32, 4), APInt(32, 2));
538   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 4), APInt(32, 0)));
539 
540   // [4, 2) /\ [5, 1) = [5, 1)
541   LHS = ConstantRange(APInt(32, 4), APInt(32, 2));
542   RHS = ConstantRange(APInt(32, 5), APInt(32, 1));
543   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 5), APInt(32, 1)));
544 
545   // [2, 0) /\ [7, 4) = [7, 4)
546   LHS = ConstantRange(APInt(32, 2), APInt(32, 0));
547   RHS = ConstantRange(APInt(32, 7), APInt(32, 4));
548   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 7), APInt(32, 4)));
549 
550   // [4, 2) /\ [1, 0) = [1, 0)
551   LHS = ConstantRange(APInt(32, 4), APInt(32, 2));
552   RHS = ConstantRange(APInt(32, 1), APInt(32, 0));
553   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 4), APInt(32, 2)));
554 
555   // [15, 0) /\ [7, 6) = [15, 0)
556   LHS = ConstantRange(APInt(32, 15), APInt(32, 0));
557   RHS = ConstantRange(APInt(32, 7), APInt(32, 6));
558   EXPECT_EQ(LHS.intersectWith(RHS), ConstantRange(APInt(32, 15), APInt(32, 0)));
559 }
560 
561 template<typename Fn1, typename Fn2>
562 void testBinarySetOperationExhaustive(Fn1 OpFn, Fn2 InResultFn) {
563   unsigned Bits = 4;
564   EnumerateTwoConstantRanges(Bits,
565       [=](const ConstantRange &CR1, const ConstantRange &CR2) {
566         SmallBitVector Elems(1 << Bits);
567         APInt Num(Bits, 0);
568         for (unsigned I = 0, Limit = 1 << Bits; I < Limit; ++I, ++Num)
569           if (InResultFn(CR1, CR2, Num))
570             Elems.set(Num.getZExtValue());
571 
572         ConstantRange SmallestCR = OpFn(CR1, CR2, ConstantRange::Smallest);
573         TestRange(SmallestCR, Elems, PreferSmallest, {CR1, CR2});
574 
575         ConstantRange UnsignedCR = OpFn(CR1, CR2, ConstantRange::Unsigned);
576         TestRange(UnsignedCR, Elems, PreferSmallestNonFullUnsigned, {CR1, CR2});
577 
578         ConstantRange SignedCR = OpFn(CR1, CR2, ConstantRange::Signed);
579         TestRange(SignedCR, Elems, PreferSmallestNonFullSigned, {CR1, CR2});
580       });
581 }
582 
583 TEST_F(ConstantRangeTest, IntersectWithExhaustive) {
584   testBinarySetOperationExhaustive(
585       [](const ConstantRange &CR1, const ConstantRange &CR2,
586          ConstantRange::PreferredRangeType Type) {
587         return CR1.intersectWith(CR2, Type);
588       },
589       [](const ConstantRange &CR1, const ConstantRange &CR2, const APInt &N) {
590         return CR1.contains(N) && CR2.contains(N);
591       });
592 }
593 
594 TEST_F(ConstantRangeTest, UnionWithExhaustive) {
595   testBinarySetOperationExhaustive(
596       [](const ConstantRange &CR1, const ConstantRange &CR2,
597          ConstantRange::PreferredRangeType Type) {
598         return CR1.unionWith(CR2, Type);
599       },
600       [](const ConstantRange &CR1, const ConstantRange &CR2, const APInt &N) {
601         return CR1.contains(N) || CR2.contains(N);
602       });
603 }
604 
605 TEST_F(ConstantRangeTest, UnionWith) {
606   EXPECT_EQ(Wrap.unionWith(One),
607             ConstantRange(APInt(16, 0xaaa), APInt(16, 0xb)));
608   EXPECT_EQ(One.unionWith(Wrap), Wrap.unionWith(One));
609   EXPECT_EQ(Empty.unionWith(Empty), Empty);
610   EXPECT_EQ(Full.unionWith(Full), Full);
611   EXPECT_EQ(Some.unionWith(Wrap), Full);
612 
613   // PR4545
614   EXPECT_EQ(ConstantRange(APInt(16, 14), APInt(16, 1)).unionWith(
615                                     ConstantRange(APInt(16, 0), APInt(16, 8))),
616             ConstantRange(APInt(16, 14), APInt(16, 8)));
617   EXPECT_EQ(ConstantRange(APInt(16, 6), APInt(16, 4)).unionWith(
618                                     ConstantRange(APInt(16, 4), APInt(16, 0))),
619             ConstantRange::getFull(16));
620   EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 0)).unionWith(
621                                     ConstantRange(APInt(16, 2), APInt(16, 1))),
622             ConstantRange::getFull(16));
623 }
624 
625 TEST_F(ConstantRangeTest, SetDifference) {
626   EXPECT_EQ(Full.difference(Empty), Full);
627   EXPECT_EQ(Full.difference(Full), Empty);
628   EXPECT_EQ(Empty.difference(Empty), Empty);
629   EXPECT_EQ(Empty.difference(Full), Empty);
630 
631   ConstantRange A(APInt(16, 3), APInt(16, 7));
632   ConstantRange B(APInt(16, 5), APInt(16, 9));
633   ConstantRange C(APInt(16, 3), APInt(16, 5));
634   ConstantRange D(APInt(16, 7), APInt(16, 9));
635   ConstantRange E(APInt(16, 5), APInt(16, 4));
636   ConstantRange F(APInt(16, 7), APInt(16, 3));
637   EXPECT_EQ(A.difference(B), C);
638   EXPECT_EQ(B.difference(A), D);
639   EXPECT_EQ(E.difference(A), F);
640 }
641 
642 TEST_F(ConstantRangeTest, getActiveBits) {
643   unsigned Bits = 4;
644   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
645     unsigned Exact = 0;
646     ForeachNumInConstantRange(CR, [&](const APInt &N) {
647       Exact = std::max(Exact, N.getActiveBits());
648     });
649 
650     unsigned ResultCR = CR.getActiveBits();
651     EXPECT_EQ(Exact, ResultCR);
652   });
653 }
654 TEST_F(ConstantRangeTest, losslessUnsignedTruncationZeroext) {
655   unsigned Bits = 4;
656   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
657     unsigned MinBitWidth = CR.getActiveBits();
658     if (MinBitWidth == 0) {
659       EXPECT_TRUE(CR.isEmptySet() ||
660                   (CR.isSingleElement() && CR.getSingleElement()->isZero()));
661       return;
662     }
663     if (MinBitWidth == Bits)
664       return;
665     EXPECT_EQ(CR, CR.truncate(MinBitWidth).zeroExtend(Bits));
666   });
667 }
668 
669 TEST_F(ConstantRangeTest, getMinSignedBits) {
670   unsigned Bits = 4;
671   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
672     unsigned Exact = 0;
673     ForeachNumInConstantRange(CR, [&](const APInt &N) {
674       Exact = std::max(Exact, N.getMinSignedBits());
675     });
676 
677     unsigned ResultCR = CR.getMinSignedBits();
678     EXPECT_EQ(Exact, ResultCR);
679   });
680 }
681 TEST_F(ConstantRangeTest, losslessSignedTruncationSignext) {
682   unsigned Bits = 4;
683   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
684     unsigned MinBitWidth = CR.getMinSignedBits();
685     if (MinBitWidth == 0) {
686       EXPECT_TRUE(CR.isEmptySet());
687       return;
688     }
689     if (MinBitWidth == Bits)
690       return;
691     EXPECT_EQ(CR, CR.truncate(MinBitWidth).signExtend(Bits));
692   });
693 }
694 
695 TEST_F(ConstantRangeTest, SubtractAPInt) {
696   EXPECT_EQ(Full.subtract(APInt(16, 4)), Full);
697   EXPECT_EQ(Empty.subtract(APInt(16, 4)), Empty);
698   EXPECT_EQ(Some.subtract(APInt(16, 4)),
699             ConstantRange(APInt(16, 0x6), APInt(16, 0xaa6)));
700   EXPECT_EQ(Wrap.subtract(APInt(16, 4)),
701             ConstantRange(APInt(16, 0xaa6), APInt(16, 0x6)));
702   EXPECT_EQ(One.subtract(APInt(16, 4)),
703             ConstantRange(APInt(16, 0x6)));
704 }
705 
706 TEST_F(ConstantRangeTest, Add) {
707   EXPECT_EQ(Full.add(APInt(16, 4)), Full);
708   EXPECT_EQ(Full.add(Full), Full);
709   EXPECT_EQ(Full.add(Empty), Empty);
710   EXPECT_EQ(Full.add(One), Full);
711   EXPECT_EQ(Full.add(Some), Full);
712   EXPECT_EQ(Full.add(Wrap), Full);
713   EXPECT_EQ(Empty.add(Empty), Empty);
714   EXPECT_EQ(Empty.add(One), Empty);
715   EXPECT_EQ(Empty.add(Some), Empty);
716   EXPECT_EQ(Empty.add(Wrap), Empty);
717   EXPECT_EQ(Empty.add(APInt(16, 4)), Empty);
718   EXPECT_EQ(Some.add(APInt(16, 4)),
719             ConstantRange(APInt(16, 0xe), APInt(16, 0xaae)));
720   EXPECT_EQ(Wrap.add(APInt(16, 4)),
721             ConstantRange(APInt(16, 0xaae), APInt(16, 0xe)));
722   EXPECT_EQ(One.add(APInt(16, 4)),
723             ConstantRange(APInt(16, 0xe)));
724 
725   TestBinaryOpExhaustive(
726       [](const ConstantRange &CR1, const ConstantRange &CR2) {
727         return CR1.add(CR2);
728       },
729       [](const APInt &N1, const APInt &N2) {
730         return N1 + N2;
731       });
732 }
733 
734 template <typename Fn1, typename Fn2>
735 static void TestAddWithNoSignedWrapExhaustive(Fn1 RangeFn, Fn2 IntFn) {
736   unsigned Bits = 4;
737   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
738                                        const ConstantRange &CR2) {
739     ConstantRange CR = RangeFn(CR1, CR2);
740     SignedOpRangeGatherer R(CR.getBitWidth());
741     bool AllOverflow = true;
742     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
743       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
744         bool IsOverflow = false;
745         APInt N = IntFn(IsOverflow, N1, N2);
746         if (!IsOverflow) {
747           AllOverflow = false;
748           R.account(N);
749           EXPECT_TRUE(CR.contains(N));
750         }
751       });
752     });
753 
754     EXPECT_EQ(CR.isEmptySet(), AllOverflow);
755 
756     if (CR1.isSignWrappedSet() || CR2.isSignWrappedSet())
757       return;
758 
759     ConstantRange Exact = R.getRange();
760     EXPECT_EQ(Exact, CR);
761   });
762 }
763 
764 template <typename Fn1, typename Fn2>
765 static void TestAddWithNoUnsignedWrapExhaustive(Fn1 RangeFn, Fn2 IntFn) {
766   unsigned Bits = 4;
767   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
768                                        const ConstantRange &CR2) {
769     ConstantRange CR = RangeFn(CR1, CR2);
770     UnsignedOpRangeGatherer R(CR.getBitWidth());
771     bool AllOverflow = true;
772     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
773       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
774         bool IsOverflow = false;
775         APInt N = IntFn(IsOverflow, N1, N2);
776         if (!IsOverflow) {
777           AllOverflow = false;
778           R.account(N);
779           EXPECT_TRUE(CR.contains(N));
780         }
781       });
782     });
783 
784     EXPECT_EQ(CR.isEmptySet(), AllOverflow);
785 
786     if (CR1.isWrappedSet() || CR2.isWrappedSet())
787       return;
788 
789     ConstantRange Exact = R.getRange();
790     EXPECT_EQ(Exact, CR);
791   });
792 }
793 
794 template <typename Fn1, typename Fn2, typename Fn3>
795 static void TestAddWithNoSignedUnsignedWrapExhaustive(Fn1 RangeFn,
796                                                       Fn2 IntFnSigned,
797                                                       Fn3 IntFnUnsigned) {
798   unsigned Bits = 4;
799   EnumerateTwoConstantRanges(
800       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
801         ConstantRange CR = RangeFn(CR1, CR2);
802         UnsignedOpRangeGatherer UR(CR.getBitWidth());
803         SignedOpRangeGatherer SR(CR.getBitWidth());
804         bool AllOverflow = true;
805         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
806           ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
807             bool IsOverflow = false, IsSignedOverflow = false;
808             APInt N = IntFnSigned(IsSignedOverflow, N1, N2);
809             (void) IntFnUnsigned(IsOverflow, N1, N2);
810             if (!IsSignedOverflow && !IsOverflow) {
811               AllOverflow = false;
812               UR.account(N);
813               SR.account(N);
814               EXPECT_TRUE(CR.contains(N));
815             }
816           });
817         });
818 
819         EXPECT_EQ(CR.isEmptySet(), AllOverflow);
820 
821         if (CR1.isWrappedSet() || CR2.isWrappedSet() ||
822             CR1.isSignWrappedSet() || CR2.isSignWrappedSet())
823           return;
824 
825         ConstantRange ExactUnsignedCR = UR.getRange();
826         ConstantRange ExactSignedCR = SR.getRange();
827 
828         if (ExactUnsignedCR.isEmptySet() || ExactSignedCR.isEmptySet()) {
829           EXPECT_TRUE(CR.isEmptySet());
830           return;
831         }
832 
833         ConstantRange Exact = ExactSignedCR.intersectWith(ExactUnsignedCR);
834         EXPECT_EQ(Exact, CR);
835       });
836 }
837 
838 TEST_F(ConstantRangeTest, AddWithNoWrap) {
839   typedef OverflowingBinaryOperator OBO;
840   EXPECT_EQ(Empty.addWithNoWrap(Some, OBO::NoSignedWrap), Empty);
841   EXPECT_EQ(Some.addWithNoWrap(Empty, OBO::NoSignedWrap), Empty);
842   EXPECT_EQ(Full.addWithNoWrap(Full, OBO::NoSignedWrap), Full);
843   EXPECT_NE(Full.addWithNoWrap(Some, OBO::NoSignedWrap), Full);
844   EXPECT_NE(Some.addWithNoWrap(Full, OBO::NoSignedWrap), Full);
845   EXPECT_EQ(Full.addWithNoWrap(ConstantRange(APInt(16, 1), APInt(16, 2)),
846                                OBO::NoSignedWrap),
847             ConstantRange(APInt(16, INT16_MIN + 1), APInt(16, INT16_MIN)));
848   EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 2))
849                 .addWithNoWrap(Full, OBO::NoSignedWrap),
850             ConstantRange(APInt(16, INT16_MIN + 1), APInt(16, INT16_MIN)));
851   EXPECT_EQ(Full.addWithNoWrap(ConstantRange(APInt(16, -1), APInt(16, 0)),
852                                OBO::NoSignedWrap),
853             ConstantRange(APInt(16, INT16_MIN), APInt(16, INT16_MAX)));
854   EXPECT_EQ(ConstantRange(APInt(8, 100), APInt(8, 120))
855                 .addWithNoWrap(ConstantRange(APInt(8, 120), APInt(8, 123)),
856                                OBO::NoSignedWrap),
857             ConstantRange(8, false));
858   EXPECT_EQ(ConstantRange(APInt(8, -120), APInt(8, -100))
859                 .addWithNoWrap(ConstantRange(APInt(8, -110), APInt(8, -100)),
860                                OBO::NoSignedWrap),
861             ConstantRange(8, false));
862   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
863                 .addWithNoWrap(ConstantRange(APInt(8, -128), APInt(8, 28)),
864                                OBO::NoSignedWrap),
865             ConstantRange(8, true));
866   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
867                 .addWithNoWrap(ConstantRange(APInt(8, -120), APInt(8, 29)),
868                                OBO::NoSignedWrap),
869             ConstantRange(APInt(8, -120), APInt(8, -128)));
870   EXPECT_EQ(ConstantRange(APInt(8, -50), APInt(8, 50))
871                 .addWithNoWrap(ConstantRange(APInt(8, 10), APInt(8, 20)),
872                                OBO::NoSignedWrap),
873             ConstantRange(APInt(8, -40), APInt(8, 69)));
874   EXPECT_EQ(ConstantRange(APInt(8, 10), APInt(8, 20))
875                 .addWithNoWrap(ConstantRange(APInt(8, -50), APInt(8, 50)),
876                                OBO::NoSignedWrap),
877             ConstantRange(APInt(8, -40), APInt(8, 69)));
878   EXPECT_EQ(ConstantRange(APInt(8, 120), APInt(8, -10))
879                 .addWithNoWrap(ConstantRange(APInt(8, 5), APInt(8, 20)),
880                                OBO::NoSignedWrap),
881             ConstantRange(APInt(8, 125), APInt(8, 9)));
882   EXPECT_EQ(ConstantRange(APInt(8, 5), APInt(8, 20))
883                 .addWithNoWrap(ConstantRange(APInt(8, 120), APInt(8, -10)),
884                                OBO::NoSignedWrap),
885             ConstantRange(APInt(8, 125), APInt(8, 9)));
886 
887   TestAddWithNoSignedWrapExhaustive(
888       [](const ConstantRange &CR1, const ConstantRange &CR2) {
889         return CR1.addWithNoWrap(CR2, OBO::NoSignedWrap);
890       },
891       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
892         return N1.sadd_ov(N2, IsOverflow);
893       });
894 
895   EXPECT_EQ(Empty.addWithNoWrap(Some, OBO::NoUnsignedWrap), Empty);
896   EXPECT_EQ(Some.addWithNoWrap(Empty, OBO::NoUnsignedWrap), Empty);
897   EXPECT_EQ(Full.addWithNoWrap(Full, OBO::NoUnsignedWrap), Full);
898   EXPECT_NE(Full.addWithNoWrap(Some, OBO::NoUnsignedWrap), Full);
899   EXPECT_NE(Some.addWithNoWrap(Full, OBO::NoUnsignedWrap), Full);
900   EXPECT_EQ(Full.addWithNoWrap(ConstantRange(APInt(16, 1), APInt(16, 2)),
901                                OBO::NoUnsignedWrap),
902             ConstantRange(APInt(16, 1), APInt(16, 0)));
903   EXPECT_EQ(ConstantRange(APInt(16, 1), APInt(16, 2))
904                 .addWithNoWrap(Full, OBO::NoUnsignedWrap),
905             ConstantRange(APInt(16, 1), APInt(16, 0)));
906   EXPECT_EQ(ConstantRange(APInt(8, 200), APInt(8, 220))
907                 .addWithNoWrap(ConstantRange(APInt(8, 100), APInt(8, 123)),
908                                OBO::NoUnsignedWrap),
909             ConstantRange(8, false));
910   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
911                 .addWithNoWrap(ConstantRange(APInt(8, 0), APInt(8, 156)),
912                                OBO::NoUnsignedWrap),
913             ConstantRange(8, true));
914   EXPECT_EQ(ConstantRange(APInt(8, 0), APInt(8, 101))
915                 .addWithNoWrap(ConstantRange(APInt(8, 10), APInt(8, 29)),
916                                OBO::NoUnsignedWrap),
917             ConstantRange(APInt(8, 10), APInt(8, 129)));
918   EXPECT_EQ(ConstantRange(APInt(8, 20), APInt(8, 10))
919                 .addWithNoWrap(ConstantRange(APInt(8, 50), APInt(8, 200)),
920                                OBO::NoUnsignedWrap),
921             ConstantRange(APInt(8, 50), APInt(8, 0)));
922   EXPECT_EQ(ConstantRange(APInt(8, 10), APInt(8, 20))
923                 .addWithNoWrap(ConstantRange(APInt(8, 50), APInt(8, 200)),
924                                OBO::NoUnsignedWrap),
925             ConstantRange(APInt(8, 60), APInt(8, -37)));
926   EXPECT_EQ(ConstantRange(APInt(8, 20), APInt(8, -30))
927                 .addWithNoWrap(ConstantRange(APInt(8, 5), APInt(8, 20)),
928                                OBO::NoUnsignedWrap),
929             ConstantRange(APInt(8, 25), APInt(8, -11)));
930   EXPECT_EQ(ConstantRange(APInt(8, 5), APInt(8, 20))
931                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, -30)),
932                                OBO::NoUnsignedWrap),
933             ConstantRange(APInt(8, 25), APInt(8, -11)));
934 
935   TestAddWithNoUnsignedWrapExhaustive(
936       [](const ConstantRange &CR1, const ConstantRange &CR2) {
937         return CR1.addWithNoWrap(CR2, OBO::NoUnsignedWrap);
938       },
939       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
940         return N1.uadd_ov(N2, IsOverflow);
941       });
942 
943   EXPECT_EQ(ConstantRange(APInt(8, 50), APInt(8, 100))
944                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 70)),
945                                OBO::NoSignedWrap),
946             ConstantRange(APInt(8, 70), APInt(8, -128)));
947   EXPECT_EQ(ConstantRange(APInt(8, 50), APInt(8, 100))
948                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 70)),
949                                OBO::NoUnsignedWrap),
950             ConstantRange(APInt(8, 70), APInt(8, 169)));
951   EXPECT_EQ(ConstantRange(APInt(8, 50), APInt(8, 100))
952                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 70)),
953                                OBO::NoUnsignedWrap | OBO::NoSignedWrap),
954             ConstantRange(APInt(8, 70), APInt(8, -128)));
955 
956   EXPECT_EQ(ConstantRange(APInt(8, -100), APInt(8, -50))
957                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 30)),
958                                OBO::NoSignedWrap),
959             ConstantRange(APInt(8, -80), APInt(8, -21)));
960   EXPECT_EQ(ConstantRange(APInt(8, -100), APInt(8, -50))
961                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 30)),
962                                OBO::NoUnsignedWrap),
963             ConstantRange(APInt(8, 176), APInt(8, 235)));
964   EXPECT_EQ(ConstantRange(APInt(8, -100), APInt(8, -50))
965                 .addWithNoWrap(ConstantRange(APInt(8, 20), APInt(8, 30)),
966                                OBO::NoUnsignedWrap | OBO::NoSignedWrap),
967             ConstantRange(APInt(8, 176), APInt(8, 235)));
968 
969   TestAddWithNoSignedUnsignedWrapExhaustive(
970       [](const ConstantRange &CR1, const ConstantRange &CR2) {
971         return CR1.addWithNoWrap(CR2, OBO::NoUnsignedWrap | OBO::NoSignedWrap);
972       },
973       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
974         return N1.sadd_ov(N2, IsOverflow);
975       },
976       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
977         return N1.uadd_ov(N2, IsOverflow);
978       });
979 }
980 
981 TEST_F(ConstantRangeTest, Sub) {
982   EXPECT_EQ(Full.sub(APInt(16, 4)), Full);
983   EXPECT_EQ(Full.sub(Full), Full);
984   EXPECT_EQ(Full.sub(Empty), Empty);
985   EXPECT_EQ(Full.sub(One), Full);
986   EXPECT_EQ(Full.sub(Some), Full);
987   EXPECT_EQ(Full.sub(Wrap), Full);
988   EXPECT_EQ(Empty.sub(Empty), Empty);
989   EXPECT_EQ(Empty.sub(One), Empty);
990   EXPECT_EQ(Empty.sub(Some), Empty);
991   EXPECT_EQ(Empty.sub(Wrap), Empty);
992   EXPECT_EQ(Empty.sub(APInt(16, 4)), Empty);
993   EXPECT_EQ(Some.sub(APInt(16, 4)),
994             ConstantRange(APInt(16, 0x6), APInt(16, 0xaa6)));
995   EXPECT_EQ(Some.sub(Some),
996             ConstantRange(APInt(16, 0xf561), APInt(16, 0xaa0)));
997   EXPECT_EQ(Wrap.sub(APInt(16, 4)),
998             ConstantRange(APInt(16, 0xaa6), APInt(16, 0x6)));
999   EXPECT_EQ(One.sub(APInt(16, 4)),
1000             ConstantRange(APInt(16, 0x6)));
1001 
1002   TestBinaryOpExhaustive(
1003       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1004         return CR1.sub(CR2);
1005       },
1006       [](const APInt &N1, const APInt &N2) {
1007         return N1 - N2;
1008       });
1009 }
1010 
1011 TEST_F(ConstantRangeTest, SubWithNoWrap) {
1012   typedef OverflowingBinaryOperator OBO;
1013   TestAddWithNoSignedWrapExhaustive(
1014       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1015         return CR1.subWithNoWrap(CR2, OBO::NoSignedWrap);
1016       },
1017       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1018         return N1.ssub_ov(N2, IsOverflow);
1019       });
1020   TestAddWithNoUnsignedWrapExhaustive(
1021       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1022         return CR1.subWithNoWrap(CR2, OBO::NoUnsignedWrap);
1023       },
1024       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1025         return N1.usub_ov(N2, IsOverflow);
1026       });
1027   TestAddWithNoSignedUnsignedWrapExhaustive(
1028       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1029         return CR1.subWithNoWrap(CR2, OBO::NoUnsignedWrap | OBO::NoSignedWrap);
1030       },
1031       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1032         return N1.ssub_ov(N2, IsOverflow);
1033       },
1034       [](bool &IsOverflow, const APInt &N1, const APInt &N2) {
1035         return N1.usub_ov(N2, IsOverflow);
1036       });
1037 }
1038 
1039 TEST_F(ConstantRangeTest, Multiply) {
1040   EXPECT_EQ(Full.multiply(Full), Full);
1041   EXPECT_EQ(Full.multiply(Empty), Empty);
1042   EXPECT_EQ(Full.multiply(One), Full);
1043   EXPECT_EQ(Full.multiply(Some), Full);
1044   EXPECT_EQ(Full.multiply(Wrap), Full);
1045   EXPECT_EQ(Empty.multiply(Empty), Empty);
1046   EXPECT_EQ(Empty.multiply(One), Empty);
1047   EXPECT_EQ(Empty.multiply(Some), Empty);
1048   EXPECT_EQ(Empty.multiply(Wrap), Empty);
1049   EXPECT_EQ(One.multiply(One), ConstantRange(APInt(16, 0xa*0xa),
1050                                              APInt(16, 0xa*0xa + 1)));
1051   EXPECT_EQ(One.multiply(Some), ConstantRange(APInt(16, 0xa*0xa),
1052                                               APInt(16, 0xa*0xaa9 + 1)));
1053   EXPECT_EQ(One.multiply(Wrap), Full);
1054   EXPECT_EQ(Some.multiply(Some), Full);
1055   EXPECT_EQ(Some.multiply(Wrap), Full);
1056   EXPECT_EQ(Wrap.multiply(Wrap), Full);
1057 
1058   ConstantRange Zero(APInt(16, 0));
1059   EXPECT_EQ(Zero.multiply(Full), Zero);
1060   EXPECT_EQ(Zero.multiply(Some), Zero);
1061   EXPECT_EQ(Zero.multiply(Wrap), Zero);
1062   EXPECT_EQ(Full.multiply(Zero), Zero);
1063   EXPECT_EQ(Some.multiply(Zero), Zero);
1064   EXPECT_EQ(Wrap.multiply(Zero), Zero);
1065 
1066   // http://llvm.org/PR4545
1067   EXPECT_EQ(ConstantRange(APInt(4, 1), APInt(4, 6)).multiply(
1068                 ConstantRange(APInt(4, 6), APInt(4, 2))),
1069             ConstantRange(4, /*isFullSet=*/true));
1070 
1071   EXPECT_EQ(ConstantRange(APInt(8, 254), APInt(8, 0)).multiply(
1072               ConstantRange(APInt(8, 252), APInt(8, 4))),
1073             ConstantRange(APInt(8, 250), APInt(8, 9)));
1074   EXPECT_EQ(ConstantRange(APInt(8, 254), APInt(8, 255)).multiply(
1075               ConstantRange(APInt(8, 2), APInt(8, 4))),
1076             ConstantRange(APInt(8, 250), APInt(8, 253)));
1077 
1078   // TODO: This should be return [-2, 0]
1079   EXPECT_EQ(ConstantRange(APInt(8, -2)).multiply(
1080               ConstantRange(APInt(8, 0), APInt(8, 2))),
1081             ConstantRange(APInt(8, -2), APInt(8, 1)));
1082 }
1083 
1084 TEST_F(ConstantRangeTest, UMax) {
1085   EXPECT_EQ(Full.umax(Full), Full);
1086   EXPECT_EQ(Full.umax(Empty), Empty);
1087   EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1088   EXPECT_EQ(Full.umax(Wrap), Full);
1089   EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1090   EXPECT_EQ(Empty.umax(Empty), Empty);
1091   EXPECT_EQ(Empty.umax(Some), Empty);
1092   EXPECT_EQ(Empty.umax(Wrap), Empty);
1093   EXPECT_EQ(Empty.umax(One), Empty);
1094   EXPECT_EQ(Some.umax(Some), Some);
1095   EXPECT_EQ(Some.umax(Wrap), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1096   EXPECT_EQ(Some.umax(One), Some);
1097   EXPECT_EQ(Wrap.umax(Wrap), Wrap);
1098   EXPECT_EQ(Wrap.umax(One), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1099   EXPECT_EQ(One.umax(One), One);
1100 
1101   TestBinaryOpExhaustive(
1102       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1103         return CR1.umax(CR2);
1104       },
1105       [](const APInt &N1, const APInt &N2) {
1106         return APIntOps::umax(N1, N2);
1107       },
1108       PreferSmallestNonFullUnsigned);
1109 }
1110 
1111 TEST_F(ConstantRangeTest, SMax) {
1112   EXPECT_EQ(Full.smax(Full), Full);
1113   EXPECT_EQ(Full.smax(Empty), Empty);
1114   EXPECT_EQ(Full.smax(Some), ConstantRange(APInt(16, 0xa),
1115                                            APInt::getSignedMinValue(16)));
1116   EXPECT_EQ(Full.smax(Wrap), Full);
1117   EXPECT_EQ(Full.smax(One), ConstantRange(APInt(16, 0xa),
1118                                           APInt::getSignedMinValue(16)));
1119   EXPECT_EQ(Empty.smax(Empty), Empty);
1120   EXPECT_EQ(Empty.smax(Some), Empty);
1121   EXPECT_EQ(Empty.smax(Wrap), Empty);
1122   EXPECT_EQ(Empty.smax(One), Empty);
1123   EXPECT_EQ(Some.smax(Some), Some);
1124   EXPECT_EQ(Some.smax(Wrap), ConstantRange(APInt(16, 0xa),
1125                                            APInt(16, (uint64_t)INT16_MIN)));
1126   EXPECT_EQ(Some.smax(One), Some);
1127   EXPECT_EQ(Wrap.smax(One), ConstantRange(APInt(16, 0xa),
1128                                           APInt(16, (uint64_t)INT16_MIN)));
1129   EXPECT_EQ(One.smax(One), One);
1130 
1131   TestBinaryOpExhaustive(
1132       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1133         return CR1.smax(CR2);
1134       },
1135       [](const APInt &N1, const APInt &N2) {
1136         return APIntOps::smax(N1, N2);
1137       },
1138       PreferSmallestNonFullSigned);
1139 }
1140 
1141 TEST_F(ConstantRangeTest, UMin) {
1142   EXPECT_EQ(Full.umin(Full), Full);
1143   EXPECT_EQ(Full.umin(Empty), Empty);
1144   EXPECT_EQ(Full.umin(Some), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1145   EXPECT_EQ(Full.umin(Wrap), Full);
1146   EXPECT_EQ(Empty.umin(Empty), Empty);
1147   EXPECT_EQ(Empty.umin(Some), Empty);
1148   EXPECT_EQ(Empty.umin(Wrap), Empty);
1149   EXPECT_EQ(Empty.umin(One), Empty);
1150   EXPECT_EQ(Some.umin(Some), Some);
1151   EXPECT_EQ(Some.umin(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1152   EXPECT_EQ(Some.umin(One), One);
1153   EXPECT_EQ(Wrap.umin(Wrap), Wrap);
1154   EXPECT_EQ(Wrap.umin(One), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1155   EXPECT_EQ(One.umin(One), One);
1156 
1157   TestBinaryOpExhaustive(
1158       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1159         return CR1.umin(CR2);
1160       },
1161       [](const APInt &N1, const APInt &N2) {
1162         return APIntOps::umin(N1, N2);
1163       },
1164       PreferSmallestNonFullUnsigned);
1165 }
1166 
1167 TEST_F(ConstantRangeTest, SMin) {
1168   EXPECT_EQ(Full.smin(Full), Full);
1169   EXPECT_EQ(Full.smin(Empty), Empty);
1170   EXPECT_EQ(Full.smin(Some), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1171                                            APInt(16, 0xaaa)));
1172   EXPECT_EQ(Full.smin(Wrap), Full);
1173   EXPECT_EQ(Empty.smin(Empty), Empty);
1174   EXPECT_EQ(Empty.smin(Some), Empty);
1175   EXPECT_EQ(Empty.smin(Wrap), Empty);
1176   EXPECT_EQ(Empty.smin(One), Empty);
1177   EXPECT_EQ(Some.smin(Some), Some);
1178   EXPECT_EQ(Some.smin(Wrap), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1179                                            APInt(16, 0xaaa)));
1180   EXPECT_EQ(Some.smin(One), One);
1181   EXPECT_EQ(Wrap.smin(Wrap), Wrap);
1182   EXPECT_EQ(Wrap.smin(One), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1183                                           APInt(16, 0xb)));
1184   EXPECT_EQ(One.smin(One), One);
1185 
1186   TestBinaryOpExhaustive(
1187       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1188         return CR1.smin(CR2);
1189       },
1190       [](const APInt &N1, const APInt &N2) {
1191         return APIntOps::smin(N1, N2);
1192       },
1193       PreferSmallestNonFullSigned);
1194 }
1195 
1196 TEST_F(ConstantRangeTest, UDiv) {
1197   EXPECT_EQ(Full.udiv(Full), Full);
1198   EXPECT_EQ(Full.udiv(Empty), Empty);
1199   EXPECT_EQ(Full.udiv(One), ConstantRange(APInt(16, 0),
1200                                           APInt(16, 0xffff / 0xa + 1)));
1201   EXPECT_EQ(Full.udiv(Some), ConstantRange(APInt(16, 0),
1202                                            APInt(16, 0xffff / 0xa + 1)));
1203   EXPECT_EQ(Full.udiv(Wrap), Full);
1204   EXPECT_EQ(Empty.udiv(Empty), Empty);
1205   EXPECT_EQ(Empty.udiv(One), Empty);
1206   EXPECT_EQ(Empty.udiv(Some), Empty);
1207   EXPECT_EQ(Empty.udiv(Wrap), Empty);
1208   EXPECT_EQ(One.udiv(One), ConstantRange(APInt(16, 1)));
1209   EXPECT_EQ(One.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 2)));
1210   EXPECT_EQ(One.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1211   EXPECT_EQ(Some.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 0x111)));
1212   EXPECT_EQ(Some.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1213   EXPECT_EQ(Wrap.udiv(Wrap), Full);
1214 
1215 
1216   ConstantRange Zero(APInt(16, 0));
1217   EXPECT_EQ(Zero.udiv(One), Zero);
1218   EXPECT_EQ(Zero.udiv(Full), Zero);
1219 
1220   EXPECT_EQ(ConstantRange(APInt(16, 0), APInt(16, 99)).udiv(Full),
1221             ConstantRange(APInt(16, 0), APInt(16, 99)));
1222   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 99)).udiv(Full),
1223             ConstantRange(APInt(16, 0), APInt(16, 99)));
1224 }
1225 
1226 TEST_F(ConstantRangeTest, SDiv) {
1227   unsigned Bits = 4;
1228   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
1229                                        const ConstantRange &CR2) {
1230     // Collect possible results in a bit vector. We store the signed value plus
1231     // a bias to make it unsigned.
1232     int Bias = 1 << (Bits - 1);
1233     BitVector Results(1 << Bits);
1234     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
1235       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
1236         // Division by zero is UB.
1237         if (N2 == 0)
1238           return;
1239 
1240         // SignedMin / -1 is UB.
1241         if (N1.isMinSignedValue() && N2.isAllOnes())
1242           return;
1243 
1244         APInt N = N1.sdiv(N2);
1245         Results.set(N.getSExtValue() + Bias);
1246       });
1247     });
1248 
1249     ConstantRange CR = CR1.sdiv(CR2);
1250     if (Results.none()) {
1251       EXPECT_TRUE(CR.isEmptySet());
1252       return;
1253     }
1254 
1255     // If there is a non-full signed envelope, that should be the result.
1256     APInt SMin(Bits, Results.find_first() - Bias);
1257     APInt SMax(Bits, Results.find_last() - Bias);
1258     ConstantRange Envelope = ConstantRange::getNonEmpty(SMin, SMax + 1);
1259     if (!Envelope.isFullSet()) {
1260       EXPECT_EQ(Envelope, CR);
1261       return;
1262     }
1263 
1264     // If the signed envelope is a full set, try to find a smaller sign wrapped
1265     // set that is separated in negative and positive components (or one which
1266     // can also additionally contain zero).
1267     int LastNeg = Results.find_last_in(0, Bias) - Bias;
1268     int LastPos = Results.find_next(Bias) - Bias;
1269     if (Results[Bias]) {
1270       if (LastNeg == -1)
1271         ++LastNeg;
1272       else if (LastPos == 1)
1273         --LastPos;
1274     }
1275 
1276     APInt WMax(Bits, LastNeg);
1277     APInt WMin(Bits, LastPos);
1278     ConstantRange Wrapped = ConstantRange::getNonEmpty(WMin, WMax + 1);
1279     EXPECT_EQ(Wrapped, CR);
1280   });
1281 }
1282 
1283 TEST_F(ConstantRangeTest, URem) {
1284   EXPECT_EQ(Full.urem(Empty), Empty);
1285   EXPECT_EQ(Empty.urem(Full), Empty);
1286   // urem by zero is poison.
1287   EXPECT_EQ(Full.urem(ConstantRange(APInt(16, 0))), Empty);
1288   // urem by full range doesn't contain MaxValue.
1289   EXPECT_EQ(Full.urem(Full), ConstantRange(APInt(16, 0), APInt(16, 0xffff)));
1290   // urem is upper bounded by maximum RHS minus one.
1291   EXPECT_EQ(Full.urem(ConstantRange(APInt(16, 0), APInt(16, 123))),
1292             ConstantRange(APInt(16, 0), APInt(16, 122)));
1293   // urem is upper bounded by maximum LHS.
1294   EXPECT_EQ(ConstantRange(APInt(16, 0), APInt(16, 123)).urem(Full),
1295             ConstantRange(APInt(16, 0), APInt(16, 123)));
1296   // If the LHS is always lower than the RHS, the result is the LHS.
1297   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 20))
1298                 .urem(ConstantRange(APInt(16, 20), APInt(16, 30))),
1299             ConstantRange(APInt(16, 10), APInt(16, 20)));
1300   // It has to be strictly lower, otherwise the top value may wrap to zero.
1301   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 20))
1302                 .urem(ConstantRange(APInt(16, 19), APInt(16, 30))),
1303             ConstantRange(APInt(16, 0), APInt(16, 20)));
1304   // [12, 14] % 10 is [2, 4], but we conservatively compute [0, 9].
1305   EXPECT_EQ(ConstantRange(APInt(16, 12), APInt(16, 15))
1306                 .urem(ConstantRange(APInt(16, 10))),
1307             ConstantRange(APInt(16, 0), APInt(16, 10)));
1308 
1309   TestBinaryOpExhaustive(
1310       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1311         return CR1.urem(CR2);
1312       },
1313       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1314         if (N2.isZero())
1315           return None;
1316         return N1.urem(N2);
1317       },
1318       PreferSmallest,
1319       CheckSingleElementsOnly);
1320 }
1321 
1322 TEST_F(ConstantRangeTest, SRem) {
1323   EXPECT_EQ(Full.srem(Empty), Empty);
1324   EXPECT_EQ(Empty.srem(Full), Empty);
1325   // srem by zero is UB.
1326   EXPECT_EQ(Full.srem(ConstantRange(APInt(16, 0))), Empty);
1327   // srem by full range doesn't contain SignedMinValue.
1328   EXPECT_EQ(Full.srem(Full), ConstantRange(APInt::getSignedMinValue(16) + 1,
1329                                            APInt::getSignedMinValue(16)));
1330 
1331   ConstantRange PosMod(APInt(16, 10), APInt(16, 21));  // [10, 20]
1332   ConstantRange NegMod(APInt(16, -20), APInt(16, -9)); // [-20, -10]
1333   ConstantRange IntMinMod(APInt::getSignedMinValue(16));
1334 
1335   ConstantRange Expected(16, true);
1336 
1337   // srem is bounded by abs(RHS) minus one.
1338   ConstantRange PosLargeLHS(APInt(16, 0), APInt(16, 41));
1339   Expected = ConstantRange(APInt(16, 0), APInt(16, 20));
1340   EXPECT_EQ(PosLargeLHS.srem(PosMod), Expected);
1341   EXPECT_EQ(PosLargeLHS.srem(NegMod), Expected);
1342   ConstantRange NegLargeLHS(APInt(16, -40), APInt(16, 1));
1343   Expected = ConstantRange(APInt(16, -19), APInt(16, 1));
1344   EXPECT_EQ(NegLargeLHS.srem(PosMod), Expected);
1345   EXPECT_EQ(NegLargeLHS.srem(NegMod), Expected);
1346   ConstantRange PosNegLargeLHS(APInt(16, -32), APInt(16, 38));
1347   Expected = ConstantRange(APInt(16, -19), APInt(16, 20));
1348   EXPECT_EQ(PosNegLargeLHS.srem(PosMod), Expected);
1349   EXPECT_EQ(PosNegLargeLHS.srem(NegMod), Expected);
1350 
1351   // srem is bounded by LHS.
1352   ConstantRange PosLHS(APInt(16, 0), APInt(16, 16));
1353   EXPECT_EQ(PosLHS.srem(PosMod), PosLHS);
1354   EXPECT_EQ(PosLHS.srem(NegMod), PosLHS);
1355   EXPECT_EQ(PosLHS.srem(IntMinMod), PosLHS);
1356   ConstantRange NegLHS(APInt(16, -15), APInt(16, 1));
1357   EXPECT_EQ(NegLHS.srem(PosMod), NegLHS);
1358   EXPECT_EQ(NegLHS.srem(NegMod), NegLHS);
1359   EXPECT_EQ(NegLHS.srem(IntMinMod), NegLHS);
1360   ConstantRange PosNegLHS(APInt(16, -12), APInt(16, 18));
1361   EXPECT_EQ(PosNegLHS.srem(PosMod), PosNegLHS);
1362   EXPECT_EQ(PosNegLHS.srem(NegMod), PosNegLHS);
1363   EXPECT_EQ(PosNegLHS.srem(IntMinMod), PosNegLHS);
1364 
1365   // srem is LHS if it is smaller than RHS.
1366   ConstantRange PosSmallLHS(APInt(16, 3), APInt(16, 8));
1367   EXPECT_EQ(PosSmallLHS.srem(PosMod), PosSmallLHS);
1368   EXPECT_EQ(PosSmallLHS.srem(NegMod), PosSmallLHS);
1369   EXPECT_EQ(PosSmallLHS.srem(IntMinMod), PosSmallLHS);
1370   ConstantRange NegSmallLHS(APInt(16, -7), APInt(16, -2));
1371   EXPECT_EQ(NegSmallLHS.srem(PosMod), NegSmallLHS);
1372   EXPECT_EQ(NegSmallLHS.srem(NegMod), NegSmallLHS);
1373   EXPECT_EQ(NegSmallLHS.srem(IntMinMod), NegSmallLHS);
1374   ConstantRange PosNegSmallLHS(APInt(16, -3), APInt(16, 8));
1375   EXPECT_EQ(PosNegSmallLHS.srem(PosMod), PosNegSmallLHS);
1376   EXPECT_EQ(PosNegSmallLHS.srem(NegMod), PosNegSmallLHS);
1377   EXPECT_EQ(PosNegSmallLHS.srem(IntMinMod), PosNegSmallLHS);
1378 
1379   // Example of a suboptimal result:
1380   // [12, 14] srem 10 is [2, 4], but we conservatively compute [0, 9].
1381   EXPECT_EQ(ConstantRange(APInt(16, 12), APInt(16, 15))
1382                 .srem(ConstantRange(APInt(16, 10))),
1383             ConstantRange(APInt(16, 0), APInt(16, 10)));
1384 
1385   TestBinaryOpExhaustive(
1386       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1387         return CR1.srem(CR2);
1388       },
1389       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1390         if (N2.isZero())
1391           return None;
1392         return N1.srem(N2);
1393       },
1394       PreferSmallest,
1395       CheckSingleElementsOnly);
1396 }
1397 
1398 TEST_F(ConstantRangeTest, Shl) {
1399   ConstantRange Some2(APInt(16, 0xfff), APInt(16, 0x8000));
1400   ConstantRange WrapNullMax(APInt(16, 0x1), APInt(16, 0x0));
1401   EXPECT_EQ(Full.shl(Full), Full);
1402   EXPECT_EQ(Full.shl(Empty), Empty);
1403   EXPECT_EQ(Full.shl(One), ConstantRange(APInt(16, 0),
1404                                          APInt(16, 0xfc00) + 1));
1405   EXPECT_EQ(Full.shl(Some), Full);   // TODO: [0, (-1 << 0xa) + 1)
1406   EXPECT_EQ(Full.shl(Wrap), Full);
1407   EXPECT_EQ(Empty.shl(Empty), Empty);
1408   EXPECT_EQ(Empty.shl(One), Empty);
1409   EXPECT_EQ(Empty.shl(Some), Empty);
1410   EXPECT_EQ(Empty.shl(Wrap), Empty);
1411   EXPECT_EQ(One.shl(One), ConstantRange(APInt(16, 0xa << 0xa),
1412                                         APInt(16, (0xa << 0xa) + 1)));
1413   EXPECT_EQ(One.shl(Some), Full);    // TODO: [0xa << 0xa, 0)
1414   EXPECT_EQ(One.shl(Wrap), Full);    // TODO: [0xa, 0xa << 14 + 1)
1415   EXPECT_EQ(Some.shl(Some), Full);   // TODO: [0xa << 0xa, 0xfc01)
1416   EXPECT_EQ(Some.shl(Wrap), Full);   // TODO: [0xa, 0x7ff << 0x5 + 1)
1417   EXPECT_EQ(Wrap.shl(Wrap), Full);
1418   EXPECT_EQ(
1419       Some2.shl(ConstantRange(APInt(16, 0x1))),
1420       ConstantRange(APInt(16, 0xfff << 0x1), APInt(16, 0x7fff << 0x1) + 1));
1421   EXPECT_EQ(One.shl(WrapNullMax), Full);
1422 
1423   TestBinaryOpExhaustive(
1424       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1425         return CR1.shl(CR2);
1426       },
1427       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1428         if (N2.uge(N2.getBitWidth()))
1429           return None;
1430         return N1.shl(N2);
1431       },
1432       PreferSmallestUnsigned,
1433       [](const ConstantRange &, const ConstantRange &CR2) {
1434         // We currently only produce precise results for single element RHS.
1435         return CR2.isSingleElement();
1436       });
1437 }
1438 
1439 TEST_F(ConstantRangeTest, Lshr) {
1440   EXPECT_EQ(Full.lshr(Full), Full);
1441   EXPECT_EQ(Full.lshr(Empty), Empty);
1442   EXPECT_EQ(Full.lshr(One), ConstantRange(APInt(16, 0),
1443                                           APInt(16, (0xffff >> 0xa) + 1)));
1444   EXPECT_EQ(Full.lshr(Some), ConstantRange(APInt(16, 0),
1445                                            APInt(16, (0xffff >> 0xa) + 1)));
1446   EXPECT_EQ(Full.lshr(Wrap), Full);
1447   EXPECT_EQ(Empty.lshr(Empty), Empty);
1448   EXPECT_EQ(Empty.lshr(One), Empty);
1449   EXPECT_EQ(Empty.lshr(Some), Empty);
1450   EXPECT_EQ(Empty.lshr(Wrap), Empty);
1451   EXPECT_EQ(One.lshr(One), ConstantRange(APInt(16, 0)));
1452   EXPECT_EQ(One.lshr(Some), ConstantRange(APInt(16, 0)));
1453   EXPECT_EQ(One.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1454   EXPECT_EQ(Some.lshr(Some), ConstantRange(APInt(16, 0),
1455                                            APInt(16, (0xaaa >> 0xa) + 1)));
1456   EXPECT_EQ(Some.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1457   EXPECT_EQ(Wrap.lshr(Wrap), Full);
1458 }
1459 
1460 TEST_F(ConstantRangeTest, Ashr) {
1461   EXPECT_EQ(Full.ashr(Full), Full);
1462   EXPECT_EQ(Full.ashr(Empty), Empty);
1463   EXPECT_EQ(Full.ashr(One), ConstantRange(APInt(16, 0xffe0),
1464                                           APInt(16, (0x7fff >> 0xa) + 1 )));
1465   ConstantRange Small(APInt(16, 0xa), APInt(16, 0xb));
1466   EXPECT_EQ(Full.ashr(Small), ConstantRange(APInt(16, 0xffe0),
1467                                            APInt(16, (0x7fff >> 0xa) + 1 )));
1468   EXPECT_EQ(Full.ashr(Some), ConstantRange(APInt(16, 0xffe0),
1469                                            APInt(16, (0x7fff >> 0xa) + 1 )));
1470   EXPECT_EQ(Full.ashr(Wrap), Full);
1471   EXPECT_EQ(Empty.ashr(Empty), Empty);
1472   EXPECT_EQ(Empty.ashr(One), Empty);
1473   EXPECT_EQ(Empty.ashr(Some), Empty);
1474   EXPECT_EQ(Empty.ashr(Wrap), Empty);
1475   EXPECT_EQ(One.ashr(One), ConstantRange(APInt(16, 0)));
1476   EXPECT_EQ(One.ashr(Some), ConstantRange(APInt(16, 0)));
1477   EXPECT_EQ(One.ashr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1478   EXPECT_EQ(Some.ashr(Some), ConstantRange(APInt(16, 0),
1479                                            APInt(16, (0xaaa >> 0xa) + 1)));
1480   EXPECT_EQ(Some.ashr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1481   EXPECT_EQ(Wrap.ashr(Wrap), Full);
1482   ConstantRange Neg(APInt(16, 0xf3f0, true), APInt(16, 0xf7f8, true));
1483   EXPECT_EQ(Neg.ashr(Small), ConstantRange(APInt(16, 0xfffc, true),
1484                                            APInt(16, 0xfffe, true)));
1485 }
1486 
1487 TEST(ConstantRange, MakeAllowedICmpRegion) {
1488   // PR8250
1489   ConstantRange SMax = ConstantRange(APInt::getSignedMaxValue(32));
1490   EXPECT_TRUE(ConstantRange::makeAllowedICmpRegion(ICmpInst::ICMP_SGT, SMax)
1491                   .isEmptySet());
1492 }
1493 
1494 TEST(ConstantRange, MakeSatisfyingICmpRegion) {
1495   ConstantRange LowHalf(APInt(8, 0), APInt(8, 128));
1496   ConstantRange HighHalf(APInt(8, 128), APInt(8, 0));
1497   ConstantRange EmptySet(8, /* isFullSet = */ false);
1498 
1499   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, LowHalf),
1500             HighHalf);
1501 
1502   EXPECT_EQ(
1503       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, HighHalf),
1504       LowHalf);
1505 
1506   EXPECT_TRUE(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_EQ,
1507                                                       HighHalf).isEmptySet());
1508 
1509   ConstantRange UnsignedSample(APInt(8, 5), APInt(8, 200));
1510 
1511   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULT,
1512                                                     UnsignedSample),
1513             ConstantRange(APInt(8, 0), APInt(8, 5)));
1514 
1515   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULE,
1516                                                     UnsignedSample),
1517             ConstantRange(APInt(8, 0), APInt(8, 6)));
1518 
1519   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGT,
1520                                                     UnsignedSample),
1521             ConstantRange(APInt(8, 200), APInt(8, 0)));
1522 
1523   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGE,
1524                                                     UnsignedSample),
1525             ConstantRange(APInt(8, 199), APInt(8, 0)));
1526 
1527   ConstantRange SignedSample(APInt(8, -5), APInt(8, 5));
1528 
1529   EXPECT_EQ(
1530       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLT, SignedSample),
1531       ConstantRange(APInt(8, -128), APInt(8, -5)));
1532 
1533   EXPECT_EQ(
1534       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLE, SignedSample),
1535       ConstantRange(APInt(8, -128), APInt(8, -4)));
1536 
1537   EXPECT_EQ(
1538       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGT, SignedSample),
1539       ConstantRange(APInt(8, 5), APInt(8, -128)));
1540 
1541   EXPECT_EQ(
1542       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGE, SignedSample),
1543       ConstantRange(APInt(8, 4), APInt(8, -128)));
1544 }
1545 
1546 static bool icmp(CmpInst::Predicate Pred, const APInt &LHS, const APInt &RHS) {
1547   switch (Pred) {
1548   case CmpInst::Predicate::ICMP_EQ:
1549     return LHS.eq(RHS);
1550   case CmpInst::Predicate::ICMP_NE:
1551     return LHS.ne(RHS);
1552   case CmpInst::Predicate::ICMP_UGT:
1553     return LHS.ugt(RHS);
1554   case CmpInst::Predicate::ICMP_UGE:
1555     return LHS.uge(RHS);
1556   case CmpInst::Predicate::ICMP_ULT:
1557     return LHS.ult(RHS);
1558   case CmpInst::Predicate::ICMP_ULE:
1559     return LHS.ule(RHS);
1560   case CmpInst::Predicate::ICMP_SGT:
1561     return LHS.sgt(RHS);
1562   case CmpInst::Predicate::ICMP_SGE:
1563     return LHS.sge(RHS);
1564   case CmpInst::Predicate::ICMP_SLT:
1565     return LHS.slt(RHS);
1566   case CmpInst::Predicate::ICMP_SLE:
1567     return LHS.sle(RHS);
1568   default:
1569     llvm_unreachable("Not an ICmp predicate!");
1570   }
1571 }
1572 
1573 void ICmpTestImpl(CmpInst::Predicate Pred) {
1574   unsigned Bits = 4;
1575   EnumerateTwoConstantRanges(
1576       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
1577         bool Exhaustive = true;
1578         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
1579           ForeachNumInConstantRange(
1580               CR2, [&](const APInt &N2) { Exhaustive &= icmp(Pred, N1, N2); });
1581         });
1582         EXPECT_EQ(CR1.icmp(Pred, CR2), Exhaustive);
1583       });
1584 }
1585 
1586 TEST(ConstantRange, ICmp) {
1587   for (auto Pred : seq_inclusive(CmpInst::Predicate::FIRST_ICMP_PREDICATE,
1588                                  CmpInst::Predicate::LAST_ICMP_PREDICATE))
1589     ICmpTestImpl(Pred);
1590 }
1591 
1592 TEST(ConstantRange, MakeGuaranteedNoWrapRegion) {
1593   const int IntMin4Bits = 8;
1594   const int IntMax4Bits = 7;
1595   typedef OverflowingBinaryOperator OBO;
1596 
1597   for (int Const : {0, -1, -2, 1, 2, IntMin4Bits, IntMax4Bits}) {
1598     APInt C(4, Const, true /* = isSigned */);
1599 
1600     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1601         Instruction::Add, C, OBO::NoUnsignedWrap);
1602 
1603     EXPECT_FALSE(NUWRegion.isEmptySet());
1604 
1605     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1606         Instruction::Add, C, OBO::NoSignedWrap);
1607 
1608     EXPECT_FALSE(NSWRegion.isEmptySet());
1609 
1610     for (APInt I = NUWRegion.getLower(), E = NUWRegion.getUpper(); I != E;
1611          ++I) {
1612       bool Overflow = false;
1613       (void)I.uadd_ov(C, Overflow);
1614       EXPECT_FALSE(Overflow);
1615     }
1616 
1617     for (APInt I = NSWRegion.getLower(), E = NSWRegion.getUpper(); I != E;
1618          ++I) {
1619       bool Overflow = false;
1620       (void)I.sadd_ov(C, Overflow);
1621       EXPECT_FALSE(Overflow);
1622     }
1623   }
1624 
1625   for (int Const : {0, -1, -2, 1, 2, IntMin4Bits, IntMax4Bits}) {
1626     APInt C(4, Const, true /* = isSigned */);
1627 
1628     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1629         Instruction::Sub, C, OBO::NoUnsignedWrap);
1630 
1631     EXPECT_FALSE(NUWRegion.isEmptySet());
1632 
1633     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1634         Instruction::Sub, C, OBO::NoSignedWrap);
1635 
1636     EXPECT_FALSE(NSWRegion.isEmptySet());
1637 
1638     for (APInt I = NUWRegion.getLower(), E = NUWRegion.getUpper(); I != E;
1639          ++I) {
1640       bool Overflow = false;
1641       (void)I.usub_ov(C, Overflow);
1642       EXPECT_FALSE(Overflow);
1643     }
1644 
1645     for (APInt I = NSWRegion.getLower(), E = NSWRegion.getUpper(); I != E;
1646          ++I) {
1647       bool Overflow = false;
1648       (void)I.ssub_ov(C, Overflow);
1649       EXPECT_FALSE(Overflow);
1650     }
1651   }
1652 
1653   auto NSWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1654       Instruction::Add, ConstantRange(32, /* isFullSet = */ true),
1655       OBO::NoSignedWrap);
1656   EXPECT_TRUE(NSWForAllValues.isSingleElement() &&
1657               NSWForAllValues.getSingleElement()->isMinValue());
1658 
1659   NSWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1660       Instruction::Sub, ConstantRange(32, /* isFullSet = */ true),
1661       OBO::NoSignedWrap);
1662   EXPECT_TRUE(NSWForAllValues.isSingleElement() &&
1663               NSWForAllValues.getSingleElement()->isMaxValue());
1664 
1665   auto NUWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1666       Instruction::Add, ConstantRange(32, /* isFullSet = */ true),
1667       OBO::NoUnsignedWrap);
1668   EXPECT_TRUE(NUWForAllValues.isSingleElement() &&
1669               NUWForAllValues.getSingleElement()->isMinValue());
1670 
1671   NUWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1672       Instruction::Sub, ConstantRange(32, /* isFullSet = */ true),
1673       OBO::NoUnsignedWrap);
1674   EXPECT_TRUE(NUWForAllValues.isSingleElement() &&
1675               NUWForAllValues.getSingleElement()->isMaxValue());
1676 
1677   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1678       Instruction::Add, APInt(32, 0), OBO::NoUnsignedWrap).isFullSet());
1679   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1680       Instruction::Add, APInt(32, 0), OBO::NoSignedWrap).isFullSet());
1681   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1682       Instruction::Sub, APInt(32, 0), OBO::NoUnsignedWrap).isFullSet());
1683   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1684       Instruction::Sub, APInt(32, 0), OBO::NoSignedWrap).isFullSet());
1685 
1686   ConstantRange OneToFive(APInt(32, 1), APInt(32, 6));
1687   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1688                 Instruction::Add, OneToFive, OBO::NoSignedWrap),
1689             ConstantRange(APInt::getSignedMinValue(32),
1690                           APInt::getSignedMaxValue(32) - 4));
1691   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1692                 Instruction::Add, OneToFive, OBO::NoUnsignedWrap),
1693             ConstantRange(APInt::getMinValue(32), APInt::getMinValue(32) - 5));
1694   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1695                 Instruction::Sub, OneToFive, OBO::NoSignedWrap),
1696             ConstantRange(APInt::getSignedMinValue(32) + 5,
1697                           APInt::getSignedMinValue(32)));
1698   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1699                 Instruction::Sub, OneToFive, OBO::NoUnsignedWrap),
1700             ConstantRange(APInt::getMinValue(32) + 5, APInt::getMinValue(32)));
1701 
1702   ConstantRange MinusFiveToMinusTwo(APInt(32, -5), APInt(32, -1));
1703   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1704                 Instruction::Add, MinusFiveToMinusTwo, OBO::NoSignedWrap),
1705             ConstantRange(APInt::getSignedMinValue(32) + 5,
1706                           APInt::getSignedMinValue(32)));
1707   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1708                 Instruction::Add, MinusFiveToMinusTwo, OBO::NoUnsignedWrap),
1709             ConstantRange(APInt(32, 0), APInt(32, 2)));
1710   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1711                 Instruction::Sub, MinusFiveToMinusTwo, OBO::NoSignedWrap),
1712             ConstantRange(APInt::getSignedMinValue(32),
1713                           APInt::getSignedMaxValue(32) - 4));
1714   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1715                 Instruction::Sub, MinusFiveToMinusTwo, OBO::NoUnsignedWrap),
1716             ConstantRange(APInt::getMaxValue(32) - 1,
1717                           APInt::getMinValue(32)));
1718 
1719   ConstantRange MinusOneToOne(APInt(32, -1), APInt(32, 2));
1720   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1721                 Instruction::Add, MinusOneToOne, OBO::NoSignedWrap),
1722             ConstantRange(APInt::getSignedMinValue(32) + 1,
1723                           APInt::getSignedMinValue(32) - 1));
1724   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1725                 Instruction::Add, MinusOneToOne, OBO::NoUnsignedWrap),
1726             ConstantRange(APInt(32, 0), APInt(32, 1)));
1727   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1728                 Instruction::Sub, MinusOneToOne, OBO::NoSignedWrap),
1729             ConstantRange(APInt::getSignedMinValue(32) + 1,
1730                           APInt::getSignedMinValue(32) - 1));
1731   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1732                 Instruction::Sub, MinusOneToOne, OBO::NoUnsignedWrap),
1733             ConstantRange(APInt::getMaxValue(32),
1734                           APInt::getMinValue(32)));
1735 
1736   ConstantRange One(APInt(32, 1), APInt(32, 2));
1737   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1738                 Instruction::Add, One, OBO::NoSignedWrap),
1739             ConstantRange(APInt::getSignedMinValue(32),
1740                           APInt::getSignedMaxValue(32)));
1741   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1742                 Instruction::Add, One, OBO::NoUnsignedWrap),
1743             ConstantRange(APInt::getMinValue(32), APInt::getMaxValue(32)));
1744   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1745                 Instruction::Sub, One, OBO::NoSignedWrap),
1746             ConstantRange(APInt::getSignedMinValue(32) + 1,
1747                           APInt::getSignedMinValue(32)));
1748   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1749                 Instruction::Sub, One, OBO::NoUnsignedWrap),
1750             ConstantRange(APInt::getMinValue(32) + 1, APInt::getMinValue(32)));
1751 
1752   ConstantRange OneLessThanBitWidth(APInt(32, 0), APInt(32, 31) + 1);
1753   ConstantRange UpToBitWidth(APInt(32, 0), APInt(32, 32) + 1);
1754   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1755                 Instruction::Shl, UpToBitWidth, OBO::NoUnsignedWrap),
1756             ConstantRange::makeGuaranteedNoWrapRegion(
1757                 Instruction::Shl, OneLessThanBitWidth, OBO::NoUnsignedWrap));
1758   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1759                 Instruction::Shl, UpToBitWidth, OBO::NoSignedWrap),
1760             ConstantRange::makeGuaranteedNoWrapRegion(
1761                 Instruction::Shl, OneLessThanBitWidth, OBO::NoSignedWrap));
1762   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1763                 Instruction::Shl, UpToBitWidth, OBO::NoUnsignedWrap),
1764             ConstantRange(APInt(32, 0), APInt(32, 1) + 1));
1765   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1766                 Instruction::Shl, UpToBitWidth, OBO::NoSignedWrap),
1767             ConstantRange(APInt(32, -1), APInt(32, 0) + 1));
1768 
1769   EXPECT_EQ(
1770       ConstantRange::makeGuaranteedNoWrapRegion(
1771           Instruction::Shl, ConstantRange::getFull(32), OBO::NoUnsignedWrap),
1772       ConstantRange::makeGuaranteedNoWrapRegion(
1773           Instruction::Shl, OneLessThanBitWidth, OBO::NoUnsignedWrap));
1774   EXPECT_EQ(
1775       ConstantRange::makeGuaranteedNoWrapRegion(
1776           Instruction::Shl, ConstantRange::getFull(32), OBO::NoSignedWrap),
1777       ConstantRange::makeGuaranteedNoWrapRegion(
1778           Instruction::Shl, OneLessThanBitWidth, OBO::NoSignedWrap));
1779 
1780   ConstantRange IllegalShAmt(APInt(32, 32), APInt(32, 0) + 1);
1781   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1782                 Instruction::Shl, IllegalShAmt, OBO::NoUnsignedWrap),
1783             ConstantRange::getFull(32));
1784   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1785                 Instruction::Shl, IllegalShAmt, OBO::NoSignedWrap),
1786             ConstantRange::getFull(32));
1787 
1788   EXPECT_EQ(
1789       ConstantRange::makeGuaranteedNoWrapRegion(
1790           Instruction::Shl, ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1791           OBO::NoUnsignedWrap),
1792       ConstantRange::makeGuaranteedNoWrapRegion(
1793           Instruction::Shl, ConstantRange(APInt(32, 0), APInt(32, 16) + 1),
1794           OBO::NoUnsignedWrap));
1795   EXPECT_EQ(
1796       ConstantRange::makeGuaranteedNoWrapRegion(
1797           Instruction::Shl, ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1798           OBO::NoSignedWrap),
1799       ConstantRange::makeGuaranteedNoWrapRegion(
1800           Instruction::Shl, ConstantRange(APInt(32, 0), APInt(32, 16) + 1),
1801           OBO::NoSignedWrap));
1802 
1803   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1804                 Instruction::Shl,
1805                 ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1806                 OBO::NoUnsignedWrap),
1807             ConstantRange(APInt(32, 0), APInt(32, 65535) + 1));
1808   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1809                 Instruction::Shl,
1810                 ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1811                 OBO::NoSignedWrap),
1812             ConstantRange(APInt(32, -32768), APInt(32, 32767) + 1));
1813 }
1814 
1815 template<typename Fn>
1816 void TestNoWrapRegionExhaustive(Instruction::BinaryOps BinOp,
1817                                 unsigned NoWrapKind, Fn OverflowFn) {
1818   unsigned Bits = 5;
1819   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
1820     if (CR.isEmptySet())
1821       return;
1822     if (Instruction::isShift(BinOp) && CR.getUnsignedMax().uge(Bits))
1823       return;
1824 
1825     ConstantRange NoWrap =
1826         ConstantRange::makeGuaranteedNoWrapRegion(BinOp, CR, NoWrapKind);
1827     ConstantRange Full = ConstantRange::getFull(Bits);
1828     ForeachNumInConstantRange(Full, [&](const APInt &N1) {
1829       bool NoOverflow = true;
1830       bool Overflow = true;
1831       ForeachNumInConstantRange(CR, [&](const APInt &N2) {
1832         if (OverflowFn(N1, N2))
1833           NoOverflow = false;
1834         else
1835           Overflow = false;
1836       });
1837       EXPECT_EQ(NoOverflow, NoWrap.contains(N1));
1838 
1839       // The no-wrap range is exact for single-element ranges.
1840       if (CR.isSingleElement()) {
1841         EXPECT_EQ(Overflow, !NoWrap.contains(N1));
1842       }
1843     });
1844   });
1845 }
1846 
1847 // Show that makeGuaranteedNoWrapRegion() is maximal, and for single-element
1848 // ranges also exact.
1849 TEST(ConstantRange, NoWrapRegionExhaustive) {
1850   TestNoWrapRegionExhaustive(
1851       Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap,
1852       [](const APInt &N1, const APInt &N2) {
1853         bool Overflow;
1854         (void) N1.uadd_ov(N2, Overflow);
1855         return Overflow;
1856       });
1857   TestNoWrapRegionExhaustive(
1858       Instruction::Add, OverflowingBinaryOperator::NoSignedWrap,
1859       [](const APInt &N1, const APInt &N2) {
1860         bool Overflow;
1861         (void) N1.sadd_ov(N2, Overflow);
1862         return Overflow;
1863       });
1864   TestNoWrapRegionExhaustive(
1865       Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap,
1866       [](const APInt &N1, const APInt &N2) {
1867         bool Overflow;
1868         (void) N1.usub_ov(N2, Overflow);
1869         return Overflow;
1870       });
1871   TestNoWrapRegionExhaustive(
1872       Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap,
1873       [](const APInt &N1, const APInt &N2) {
1874         bool Overflow;
1875         (void) N1.ssub_ov(N2, Overflow);
1876         return Overflow;
1877       });
1878   TestNoWrapRegionExhaustive(
1879       Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap,
1880       [](const APInt &N1, const APInt &N2) {
1881         bool Overflow;
1882         (void) N1.umul_ov(N2, Overflow);
1883         return Overflow;
1884       });
1885   TestNoWrapRegionExhaustive(
1886       Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap,
1887       [](const APInt &N1, const APInt &N2) {
1888         bool Overflow;
1889         (void) N1.smul_ov(N2, Overflow);
1890         return Overflow;
1891       });
1892   TestNoWrapRegionExhaustive(Instruction::Shl,
1893                              OverflowingBinaryOperator::NoUnsignedWrap,
1894                              [](const APInt &N1, const APInt &N2) {
1895                                bool Overflow;
1896                                (void)N1.ushl_ov(N2, Overflow);
1897                                return Overflow;
1898                              });
1899   TestNoWrapRegionExhaustive(Instruction::Shl,
1900                              OverflowingBinaryOperator::NoSignedWrap,
1901                              [](const APInt &N1, const APInt &N2) {
1902                                bool Overflow;
1903                                (void)N1.sshl_ov(N2, Overflow);
1904                                return Overflow;
1905                              });
1906 }
1907 
1908 TEST(ConstantRange, GetEquivalentICmp) {
1909   APInt RHS;
1910   CmpInst::Predicate Pred;
1911 
1912   EXPECT_TRUE(ConstantRange(APInt::getMinValue(32), APInt(32, 100))
1913                   .getEquivalentICmp(Pred, RHS));
1914   EXPECT_EQ(Pred, CmpInst::ICMP_ULT);
1915   EXPECT_EQ(RHS, APInt(32, 100));
1916 
1917   EXPECT_TRUE(ConstantRange(APInt::getSignedMinValue(32), APInt(32, 100))
1918                   .getEquivalentICmp(Pred, RHS));
1919   EXPECT_EQ(Pred, CmpInst::ICMP_SLT);
1920   EXPECT_EQ(RHS, APInt(32, 100));
1921 
1922   EXPECT_TRUE(ConstantRange(APInt(32, 100), APInt::getMinValue(32))
1923                   .getEquivalentICmp(Pred, RHS));
1924   EXPECT_EQ(Pred, CmpInst::ICMP_UGE);
1925   EXPECT_EQ(RHS, APInt(32, 100));
1926 
1927   EXPECT_TRUE(ConstantRange(APInt(32, 100), APInt::getSignedMinValue(32))
1928                   .getEquivalentICmp(Pred, RHS));
1929   EXPECT_EQ(Pred, CmpInst::ICMP_SGE);
1930   EXPECT_EQ(RHS, APInt(32, 100));
1931 
1932   EXPECT_TRUE(
1933       ConstantRange(32, /*isFullSet=*/true).getEquivalentICmp(Pred, RHS));
1934   EXPECT_EQ(Pred, CmpInst::ICMP_UGE);
1935   EXPECT_EQ(RHS, APInt(32, 0));
1936 
1937   EXPECT_TRUE(
1938       ConstantRange(32, /*isFullSet=*/false).getEquivalentICmp(Pred, RHS));
1939   EXPECT_EQ(Pred, CmpInst::ICMP_ULT);
1940   EXPECT_EQ(RHS, APInt(32, 0));
1941 
1942   EXPECT_FALSE(ConstantRange(APInt(32, 100), APInt(32, 200))
1943                    .getEquivalentICmp(Pred, RHS));
1944 
1945   EXPECT_FALSE(ConstantRange(APInt::getSignedMinValue(32) - APInt(32, 100),
1946                              APInt::getSignedMinValue(32) + APInt(32, 100))
1947                    .getEquivalentICmp(Pred, RHS));
1948 
1949   EXPECT_FALSE(ConstantRange(APInt::getMinValue(32) - APInt(32, 100),
1950                              APInt::getMinValue(32) + APInt(32, 100))
1951                    .getEquivalentICmp(Pred, RHS));
1952 
1953   EXPECT_TRUE(ConstantRange(APInt(32, 100)).getEquivalentICmp(Pred, RHS));
1954   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1955   EXPECT_EQ(RHS, APInt(32, 100));
1956 
1957   EXPECT_TRUE(
1958       ConstantRange(APInt(32, 100)).inverse().getEquivalentICmp(Pred, RHS));
1959   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1960   EXPECT_EQ(RHS, APInt(32, 100));
1961 
1962   EXPECT_TRUE(
1963       ConstantRange(APInt(512, 100)).inverse().getEquivalentICmp(Pred, RHS));
1964   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1965   EXPECT_EQ(RHS, APInt(512, 100));
1966 
1967   // NB!  It would be correct for the following four calls to getEquivalentICmp
1968   // to return ordered predicates like CmpInst::ICMP_ULT or CmpInst::ICMP_UGT.
1969   // However, that's not the case today.
1970 
1971   EXPECT_TRUE(ConstantRange(APInt(32, 0)).getEquivalentICmp(Pred, RHS));
1972   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1973   EXPECT_EQ(RHS, APInt(32, 0));
1974 
1975   EXPECT_TRUE(
1976       ConstantRange(APInt(32, 0)).inverse().getEquivalentICmp(Pred, RHS));
1977   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1978   EXPECT_EQ(RHS, APInt(32, 0));
1979 
1980   EXPECT_TRUE(ConstantRange(APInt(32, -1)).getEquivalentICmp(Pred, RHS));
1981   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1982   EXPECT_EQ(RHS, APInt(32, -1));
1983 
1984   EXPECT_TRUE(
1985       ConstantRange(APInt(32, -1)).inverse().getEquivalentICmp(Pred, RHS));
1986   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1987   EXPECT_EQ(RHS, APInt(32, -1));
1988 }
1989 
1990 #define EXPECT_MAY_OVERFLOW(op) \
1991   EXPECT_EQ(ConstantRange::OverflowResult::MayOverflow, (op))
1992 #define EXPECT_ALWAYS_OVERFLOWS_LOW(op) \
1993   EXPECT_EQ(ConstantRange::OverflowResult::AlwaysOverflowsLow, (op))
1994 #define EXPECT_ALWAYS_OVERFLOWS_HIGH(op) \
1995   EXPECT_EQ(ConstantRange::OverflowResult::AlwaysOverflowsHigh, (op))
1996 #define EXPECT_NEVER_OVERFLOWS(op) \
1997   EXPECT_EQ(ConstantRange::OverflowResult::NeverOverflows, (op))
1998 
1999 TEST_F(ConstantRangeTest, UnsignedAddOverflow) {
2000   // Ill-defined - may overflow is a conservative result.
2001   EXPECT_MAY_OVERFLOW(Some.unsignedAddMayOverflow(Empty));
2002   EXPECT_MAY_OVERFLOW(Empty.unsignedAddMayOverflow(Some));
2003 
2004   // Never overflow despite one full/wrap set.
2005   ConstantRange Zero(APInt::getZero(16));
2006   EXPECT_NEVER_OVERFLOWS(Full.unsignedAddMayOverflow(Zero));
2007   EXPECT_NEVER_OVERFLOWS(Wrap.unsignedAddMayOverflow(Zero));
2008   EXPECT_NEVER_OVERFLOWS(Zero.unsignedAddMayOverflow(Full));
2009   EXPECT_NEVER_OVERFLOWS(Zero.unsignedAddMayOverflow(Wrap));
2010 
2011   // But usually full/wrap always may overflow.
2012   EXPECT_MAY_OVERFLOW(Full.unsignedAddMayOverflow(One));
2013   EXPECT_MAY_OVERFLOW(Wrap.unsignedAddMayOverflow(One));
2014   EXPECT_MAY_OVERFLOW(One.unsignedAddMayOverflow(Full));
2015   EXPECT_MAY_OVERFLOW(One.unsignedAddMayOverflow(Wrap));
2016 
2017   ConstantRange A(APInt(16, 0xfd00), APInt(16, 0xfe00));
2018   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2019   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2020   EXPECT_NEVER_OVERFLOWS(A.unsignedAddMayOverflow(B1));
2021   EXPECT_MAY_OVERFLOW(A.unsignedAddMayOverflow(B2));
2022   EXPECT_NEVER_OVERFLOWS(B1.unsignedAddMayOverflow(A));
2023   EXPECT_MAY_OVERFLOW(B2.unsignedAddMayOverflow(A));
2024 
2025   ConstantRange C1(APInt(16, 0x0299), APInt(16, 0x0400));
2026   ConstantRange C2(APInt(16, 0x0300), APInt(16, 0x0400));
2027   EXPECT_MAY_OVERFLOW(A.unsignedAddMayOverflow(C1));
2028   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.unsignedAddMayOverflow(C2));
2029   EXPECT_MAY_OVERFLOW(C1.unsignedAddMayOverflow(A));
2030   EXPECT_ALWAYS_OVERFLOWS_HIGH(C2.unsignedAddMayOverflow(A));
2031 }
2032 
2033 TEST_F(ConstantRangeTest, UnsignedSubOverflow) {
2034   // Ill-defined - may overflow is a conservative result.
2035   EXPECT_MAY_OVERFLOW(Some.unsignedSubMayOverflow(Empty));
2036   EXPECT_MAY_OVERFLOW(Empty.unsignedSubMayOverflow(Some));
2037 
2038   // Never overflow despite one full/wrap set.
2039   ConstantRange Zero(APInt::getZero(16));
2040   ConstantRange Max(APInt::getAllOnes(16));
2041   EXPECT_NEVER_OVERFLOWS(Full.unsignedSubMayOverflow(Zero));
2042   EXPECT_NEVER_OVERFLOWS(Wrap.unsignedSubMayOverflow(Zero));
2043   EXPECT_NEVER_OVERFLOWS(Max.unsignedSubMayOverflow(Full));
2044   EXPECT_NEVER_OVERFLOWS(Max.unsignedSubMayOverflow(Wrap));
2045 
2046   // But usually full/wrap always may overflow.
2047   EXPECT_MAY_OVERFLOW(Full.unsignedSubMayOverflow(One));
2048   EXPECT_MAY_OVERFLOW(Wrap.unsignedSubMayOverflow(One));
2049   EXPECT_MAY_OVERFLOW(One.unsignedSubMayOverflow(Full));
2050   EXPECT_MAY_OVERFLOW(One.unsignedSubMayOverflow(Wrap));
2051 
2052   ConstantRange A(APInt(16, 0x0000), APInt(16, 0x0100));
2053   ConstantRange B(APInt(16, 0x0100), APInt(16, 0x0200));
2054   EXPECT_NEVER_OVERFLOWS(B.unsignedSubMayOverflow(A));
2055   EXPECT_ALWAYS_OVERFLOWS_LOW(A.unsignedSubMayOverflow(B));
2056 
2057   ConstantRange A1(APInt(16, 0x0000), APInt(16, 0x0101));
2058   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2059   EXPECT_NEVER_OVERFLOWS(B1.unsignedSubMayOverflow(A1));
2060   EXPECT_MAY_OVERFLOW(A1.unsignedSubMayOverflow(B1));
2061 
2062   ConstantRange A2(APInt(16, 0x0000), APInt(16, 0x0102));
2063   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2064   EXPECT_MAY_OVERFLOW(B2.unsignedSubMayOverflow(A2));
2065   EXPECT_MAY_OVERFLOW(A2.unsignedSubMayOverflow(B2));
2066 }
2067 
2068 TEST_F(ConstantRangeTest, SignedAddOverflow) {
2069   // Ill-defined - may overflow is a conservative result.
2070   EXPECT_MAY_OVERFLOW(Some.signedAddMayOverflow(Empty));
2071   EXPECT_MAY_OVERFLOW(Empty.signedAddMayOverflow(Some));
2072 
2073   // Never overflow despite one full/wrap set.
2074   ConstantRange Zero(APInt::getZero(16));
2075   EXPECT_NEVER_OVERFLOWS(Full.signedAddMayOverflow(Zero));
2076   EXPECT_NEVER_OVERFLOWS(Wrap.signedAddMayOverflow(Zero));
2077   EXPECT_NEVER_OVERFLOWS(Zero.signedAddMayOverflow(Full));
2078   EXPECT_NEVER_OVERFLOWS(Zero.signedAddMayOverflow(Wrap));
2079 
2080   // But usually full/wrap always may overflow.
2081   EXPECT_MAY_OVERFLOW(Full.signedAddMayOverflow(One));
2082   EXPECT_MAY_OVERFLOW(Wrap.signedAddMayOverflow(One));
2083   EXPECT_MAY_OVERFLOW(One.signedAddMayOverflow(Full));
2084   EXPECT_MAY_OVERFLOW(One.signedAddMayOverflow(Wrap));
2085 
2086   ConstantRange A(APInt(16, 0x7d00), APInt(16, 0x7e00));
2087   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2088   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2089   EXPECT_NEVER_OVERFLOWS(A.signedAddMayOverflow(B1));
2090   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B2));
2091   ConstantRange B3(APInt(16, 0x8000), APInt(16, 0x0201));
2092   ConstantRange B4(APInt(16, 0x8000), APInt(16, 0x0202));
2093   EXPECT_NEVER_OVERFLOWS(A.signedAddMayOverflow(B3));
2094   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B4));
2095   ConstantRange B5(APInt(16, 0x0299), APInt(16, 0x0400));
2096   ConstantRange B6(APInt(16, 0x0300), APInt(16, 0x0400));
2097   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B5));
2098   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.signedAddMayOverflow(B6));
2099 
2100   ConstantRange C(APInt(16, 0x8200), APInt(16, 0x8300));
2101   ConstantRange D1(APInt(16, 0xfe00), APInt(16, 0xff00));
2102   ConstantRange D2(APInt(16, 0xfd99), APInt(16, 0xff00));
2103   EXPECT_NEVER_OVERFLOWS(C.signedAddMayOverflow(D1));
2104   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D2));
2105   ConstantRange D3(APInt(16, 0xfe00), APInt(16, 0x8000));
2106   ConstantRange D4(APInt(16, 0xfd99), APInt(16, 0x8000));
2107   EXPECT_NEVER_OVERFLOWS(C.signedAddMayOverflow(D3));
2108   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D4));
2109   ConstantRange D5(APInt(16, 0xfc00), APInt(16, 0xfd02));
2110   ConstantRange D6(APInt(16, 0xfc00), APInt(16, 0xfd01));
2111   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D5));
2112   EXPECT_ALWAYS_OVERFLOWS_LOW(C.signedAddMayOverflow(D6));
2113 
2114   ConstantRange E(APInt(16, 0xff00), APInt(16, 0x0100));
2115   EXPECT_NEVER_OVERFLOWS(E.signedAddMayOverflow(E));
2116   ConstantRange F(APInt(16, 0xf000), APInt(16, 0x7000));
2117   EXPECT_MAY_OVERFLOW(F.signedAddMayOverflow(F));
2118 }
2119 
2120 TEST_F(ConstantRangeTest, SignedSubOverflow) {
2121   // Ill-defined - may overflow is a conservative result.
2122   EXPECT_MAY_OVERFLOW(Some.signedSubMayOverflow(Empty));
2123   EXPECT_MAY_OVERFLOW(Empty.signedSubMayOverflow(Some));
2124 
2125   // Never overflow despite one full/wrap set.
2126   ConstantRange Zero(APInt::getZero(16));
2127   EXPECT_NEVER_OVERFLOWS(Full.signedSubMayOverflow(Zero));
2128   EXPECT_NEVER_OVERFLOWS(Wrap.signedSubMayOverflow(Zero));
2129 
2130   // But usually full/wrap always may overflow.
2131   EXPECT_MAY_OVERFLOW(Full.signedSubMayOverflow(One));
2132   EXPECT_MAY_OVERFLOW(Wrap.signedSubMayOverflow(One));
2133   EXPECT_MAY_OVERFLOW(One.signedSubMayOverflow(Full));
2134   EXPECT_MAY_OVERFLOW(One.signedSubMayOverflow(Wrap));
2135 
2136   ConstantRange A(APInt(16, 0x7d00), APInt(16, 0x7e00));
2137   ConstantRange B1(APInt(16, 0xfe00), APInt(16, 0xff00));
2138   ConstantRange B2(APInt(16, 0xfd99), APInt(16, 0xff00));
2139   EXPECT_NEVER_OVERFLOWS(A.signedSubMayOverflow(B1));
2140   EXPECT_MAY_OVERFLOW(A.signedSubMayOverflow(B2));
2141   ConstantRange B3(APInt(16, 0xfc00), APInt(16, 0xfd02));
2142   ConstantRange B4(APInt(16, 0xfc00), APInt(16, 0xfd01));
2143   EXPECT_MAY_OVERFLOW(A.signedSubMayOverflow(B3));
2144   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.signedSubMayOverflow(B4));
2145 
2146   ConstantRange C(APInt(16, 0x8200), APInt(16, 0x8300));
2147   ConstantRange D1(APInt(16, 0x0100), APInt(16, 0x0201));
2148   ConstantRange D2(APInt(16, 0x0100), APInt(16, 0x0202));
2149   EXPECT_NEVER_OVERFLOWS(C.signedSubMayOverflow(D1));
2150   EXPECT_MAY_OVERFLOW(C.signedSubMayOverflow(D2));
2151   ConstantRange D3(APInt(16, 0x0299), APInt(16, 0x0400));
2152   ConstantRange D4(APInt(16, 0x0300), APInt(16, 0x0400));
2153   EXPECT_MAY_OVERFLOW(C.signedSubMayOverflow(D3));
2154   EXPECT_ALWAYS_OVERFLOWS_LOW(C.signedSubMayOverflow(D4));
2155 
2156   ConstantRange E(APInt(16, 0xff00), APInt(16, 0x0100));
2157   EXPECT_NEVER_OVERFLOWS(E.signedSubMayOverflow(E));
2158   ConstantRange F(APInt(16, 0xf000), APInt(16, 0x7001));
2159   EXPECT_MAY_OVERFLOW(F.signedSubMayOverflow(F));
2160 }
2161 
2162 template<typename Fn1, typename Fn2>
2163 static void TestOverflowExhaustive(Fn1 OverflowFn, Fn2 MayOverflowFn) {
2164   // Constant range overflow checks are tested exhaustively on 4-bit numbers.
2165   unsigned Bits = 4;
2166   EnumerateTwoConstantRanges(Bits, [=](const ConstantRange &CR1,
2167                                        const ConstantRange &CR2) {
2168     // Loop over all N1 in CR1 and N2 in CR2 and check whether any of the
2169     // operations have overflow / have no overflow.
2170     bool RangeHasOverflowLow = false;
2171     bool RangeHasOverflowHigh = false;
2172     bool RangeHasNoOverflow = false;
2173     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
2174       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
2175         bool IsOverflowHigh;
2176         if (!OverflowFn(IsOverflowHigh, N1, N2)) {
2177           RangeHasNoOverflow = true;
2178           return;
2179         }
2180 
2181         if (IsOverflowHigh)
2182           RangeHasOverflowHigh = true;
2183         else
2184           RangeHasOverflowLow = true;
2185       });
2186     });
2187 
2188     ConstantRange::OverflowResult OR = MayOverflowFn(CR1, CR2);
2189     switch (OR) {
2190     case ConstantRange::OverflowResult::AlwaysOverflowsLow:
2191       EXPECT_TRUE(RangeHasOverflowLow);
2192       EXPECT_FALSE(RangeHasOverflowHigh);
2193       EXPECT_FALSE(RangeHasNoOverflow);
2194       break;
2195     case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
2196       EXPECT_TRUE(RangeHasOverflowHigh);
2197       EXPECT_FALSE(RangeHasOverflowLow);
2198       EXPECT_FALSE(RangeHasNoOverflow);
2199       break;
2200     case ConstantRange::OverflowResult::NeverOverflows:
2201       EXPECT_FALSE(RangeHasOverflowLow);
2202       EXPECT_FALSE(RangeHasOverflowHigh);
2203       EXPECT_TRUE(RangeHasNoOverflow);
2204       break;
2205     case ConstantRange::OverflowResult::MayOverflow:
2206       // We return MayOverflow for empty sets as a conservative result,
2207       // but of course neither the RangeHasOverflow nor the
2208       // RangeHasNoOverflow flags will be set.
2209       if (CR1.isEmptySet() || CR2.isEmptySet())
2210         break;
2211 
2212       EXPECT_TRUE(RangeHasOverflowLow || RangeHasOverflowHigh);
2213       EXPECT_TRUE(RangeHasNoOverflow);
2214       break;
2215     }
2216   });
2217 }
2218 
2219 TEST_F(ConstantRangeTest, UnsignedAddOverflowExhaustive) {
2220   TestOverflowExhaustive(
2221       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2222         bool Overflow;
2223         (void) N1.uadd_ov(N2, Overflow);
2224         IsOverflowHigh = true;
2225         return Overflow;
2226       },
2227       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2228         return CR1.unsignedAddMayOverflow(CR2);
2229       });
2230 }
2231 
2232 TEST_F(ConstantRangeTest, UnsignedSubOverflowExhaustive) {
2233   TestOverflowExhaustive(
2234       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2235         bool Overflow;
2236         (void) N1.usub_ov(N2, Overflow);
2237         IsOverflowHigh = false;
2238         return Overflow;
2239       },
2240       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2241         return CR1.unsignedSubMayOverflow(CR2);
2242       });
2243 }
2244 
2245 TEST_F(ConstantRangeTest, UnsignedMulOverflowExhaustive) {
2246   TestOverflowExhaustive(
2247       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2248         bool Overflow;
2249         (void) N1.umul_ov(N2, Overflow);
2250         IsOverflowHigh = true;
2251         return Overflow;
2252       },
2253       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2254         return CR1.unsignedMulMayOverflow(CR2);
2255       });
2256 }
2257 
2258 TEST_F(ConstantRangeTest, SignedAddOverflowExhaustive) {
2259   TestOverflowExhaustive(
2260       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2261         bool Overflow;
2262         (void) N1.sadd_ov(N2, Overflow);
2263         IsOverflowHigh = N1.isNonNegative();
2264         return Overflow;
2265       },
2266       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2267         return CR1.signedAddMayOverflow(CR2);
2268       });
2269 }
2270 
2271 TEST_F(ConstantRangeTest, SignedSubOverflowExhaustive) {
2272   TestOverflowExhaustive(
2273       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2274         bool Overflow;
2275         (void) N1.ssub_ov(N2, Overflow);
2276         IsOverflowHigh = N1.isNonNegative();
2277         return Overflow;
2278       },
2279       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2280         return CR1.signedSubMayOverflow(CR2);
2281       });
2282 }
2283 
2284 TEST_F(ConstantRangeTest, FromKnownBits) {
2285   KnownBits Unknown(16);
2286   EXPECT_EQ(Full, ConstantRange::fromKnownBits(Unknown, /*signed*/false));
2287   EXPECT_EQ(Full, ConstantRange::fromKnownBits(Unknown, /*signed*/true));
2288 
2289   // .10..01. -> unsigned 01000010 (66)  to 11011011 (219)
2290   //          -> signed   11000010 (194) to 01011011 (91)
2291   KnownBits Known(8);
2292   Known.Zero = 36;
2293   Known.One = 66;
2294   ConstantRange Unsigned(APInt(8, 66), APInt(8, 219 + 1));
2295   ConstantRange Signed(APInt(8, 194), APInt(8, 91 + 1));
2296   EXPECT_EQ(Unsigned, ConstantRange::fromKnownBits(Known, /*signed*/false));
2297   EXPECT_EQ(Signed, ConstantRange::fromKnownBits(Known, /*signed*/true));
2298 
2299   // 1.10.10. -> 10100100 (164) to 11101101 (237)
2300   Known.Zero = 18;
2301   Known.One = 164;
2302   ConstantRange CR1(APInt(8, 164), APInt(8, 237 + 1));
2303   EXPECT_EQ(CR1, ConstantRange::fromKnownBits(Known, /*signed*/false));
2304   EXPECT_EQ(CR1, ConstantRange::fromKnownBits(Known, /*signed*/true));
2305 
2306   // 01.0.1.0 -> 01000100 (68) to 01101110 (110)
2307   Known.Zero = 145;
2308   Known.One = 68;
2309   ConstantRange CR2(APInt(8, 68), APInt(8, 110 + 1));
2310   EXPECT_EQ(CR2, ConstantRange::fromKnownBits(Known, /*signed*/false));
2311   EXPECT_EQ(CR2, ConstantRange::fromKnownBits(Known, /*signed*/true));
2312 }
2313 
2314 TEST_F(ConstantRangeTest, FromKnownBitsExhaustive) {
2315   unsigned Bits = 4;
2316   unsigned Max = 1 << Bits;
2317   KnownBits Known(Bits);
2318   for (unsigned Zero = 0; Zero < Max; ++Zero) {
2319     for (unsigned One = 0; One < Max; ++One) {
2320       Known.Zero = Zero;
2321       Known.One = One;
2322       if (Known.hasConflict() || Known.isUnknown())
2323         continue;
2324 
2325       UnsignedOpRangeGatherer UR(Bits);
2326       SignedOpRangeGatherer SR(Bits);
2327       for (unsigned N = 0; N < Max; ++N) {
2328         APInt Num(Bits, N);
2329         if ((Num & Known.Zero) != 0 || (~Num & Known.One) != 0)
2330           continue;
2331 
2332         UR.account(Num);
2333         SR.account(Num);
2334       }
2335 
2336       ConstantRange UnsignedCR = UR.getRange();
2337       ConstantRange SignedCR = SR.getRange();
2338       EXPECT_EQ(UnsignedCR, ConstantRange::fromKnownBits(Known, false));
2339       EXPECT_EQ(SignedCR, ConstantRange::fromKnownBits(Known, true));
2340     }
2341   }
2342 }
2343 
2344 TEST_F(ConstantRangeTest, Negative) {
2345   // All elements in an empty set (of which there are none) are both negative
2346   // and non-negative. Empty & full sets checked explicitly for clarity, but
2347   // they are also covered by the exhaustive test below.
2348   EXPECT_TRUE(Empty.isAllNegative());
2349   EXPECT_TRUE(Empty.isAllNonNegative());
2350   EXPECT_FALSE(Full.isAllNegative());
2351   EXPECT_FALSE(Full.isAllNonNegative());
2352 
2353   unsigned Bits = 4;
2354   EnumerateConstantRanges(Bits, [](const ConstantRange &CR) {
2355     bool AllNegative = true;
2356     bool AllNonNegative = true;
2357     ForeachNumInConstantRange(CR, [&](const APInt &N) {
2358       if (!N.isNegative())
2359         AllNegative = false;
2360       if (!N.isNonNegative())
2361         AllNonNegative = false;
2362     });
2363     assert((CR.isEmptySet() || !AllNegative || !AllNonNegative) &&
2364            "Only empty set can be both all negative and all non-negative");
2365 
2366     EXPECT_EQ(AllNegative, CR.isAllNegative());
2367     EXPECT_EQ(AllNonNegative, CR.isAllNonNegative());
2368   });
2369 }
2370 
2371 TEST_F(ConstantRangeTest, UAddSat) {
2372   TestBinaryOpExhaustive(
2373       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2374         return CR1.uadd_sat(CR2);
2375       },
2376       [](const APInt &N1, const APInt &N2) {
2377         return N1.uadd_sat(N2);
2378       },
2379       PreferSmallestUnsigned);
2380 }
2381 
2382 TEST_F(ConstantRangeTest, USubSat) {
2383   TestBinaryOpExhaustive(
2384       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2385         return CR1.usub_sat(CR2);
2386       },
2387       [](const APInt &N1, const APInt &N2) {
2388         return N1.usub_sat(N2);
2389       },
2390       PreferSmallestUnsigned);
2391 }
2392 
2393 TEST_F(ConstantRangeTest, UMulSat) {
2394   TestBinaryOpExhaustive(
2395       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2396         return CR1.umul_sat(CR2);
2397       },
2398       [](const APInt &N1, const APInt &N2) { return N1.umul_sat(N2); },
2399       PreferSmallestUnsigned);
2400 }
2401 
2402 TEST_F(ConstantRangeTest, UShlSat) {
2403   TestBinaryOpExhaustive(
2404       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2405         return CR1.ushl_sat(CR2);
2406       },
2407       [](const APInt &N1, const APInt &N2) { return N1.ushl_sat(N2); },
2408       PreferSmallestUnsigned);
2409 }
2410 
2411 TEST_F(ConstantRangeTest, SAddSat) {
2412   TestBinaryOpExhaustive(
2413       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2414         return CR1.sadd_sat(CR2);
2415       },
2416       [](const APInt &N1, const APInt &N2) {
2417         return N1.sadd_sat(N2);
2418       },
2419       PreferSmallestSigned);
2420 }
2421 
2422 TEST_F(ConstantRangeTest, SSubSat) {
2423   TestBinaryOpExhaustive(
2424       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2425         return CR1.ssub_sat(CR2);
2426       },
2427       [](const APInt &N1, const APInt &N2) {
2428         return N1.ssub_sat(N2);
2429       },
2430       PreferSmallestSigned);
2431 }
2432 
2433 TEST_F(ConstantRangeTest, SMulSat) {
2434   TestBinaryOpExhaustive(
2435       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2436         return CR1.smul_sat(CR2);
2437       },
2438       [](const APInt &N1, const APInt &N2) { return N1.smul_sat(N2); },
2439       PreferSmallestSigned);
2440 }
2441 
2442 TEST_F(ConstantRangeTest, SShlSat) {
2443   TestBinaryOpExhaustive(
2444       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2445         return CR1.sshl_sat(CR2);
2446       },
2447       [](const APInt &N1, const APInt &N2) { return N1.sshl_sat(N2); },
2448       PreferSmallestSigned);
2449 }
2450 
2451 TEST_F(ConstantRangeTest, Abs) {
2452   TestUnaryOpExhaustive(
2453       [](const ConstantRange &CR) { return CR.abs(); },
2454       [](const APInt &N) { return N.abs(); });
2455 
2456   TestUnaryOpExhaustive(
2457       [](const ConstantRange &CR) { return CR.abs(/*IntMinIsPoison=*/true); },
2458       [](const APInt &N) -> Optional<APInt> {
2459         if (N.isMinSignedValue())
2460           return None;
2461         return N.abs();
2462       });
2463 }
2464 
2465 TEST_F(ConstantRangeTest, castOps) {
2466   ConstantRange A(APInt(16, 66), APInt(16, 128));
2467   ConstantRange FpToI8 = A.castOp(Instruction::FPToSI, 8);
2468   EXPECT_EQ(8u, FpToI8.getBitWidth());
2469   EXPECT_TRUE(FpToI8.isFullSet());
2470 
2471   ConstantRange FpToI16 = A.castOp(Instruction::FPToSI, 16);
2472   EXPECT_EQ(16u, FpToI16.getBitWidth());
2473   EXPECT_EQ(A, FpToI16);
2474 
2475   ConstantRange FPExtToDouble = A.castOp(Instruction::FPExt, 64);
2476   EXPECT_EQ(64u, FPExtToDouble.getBitWidth());
2477   EXPECT_TRUE(FPExtToDouble.isFullSet());
2478 
2479   ConstantRange PtrToInt = A.castOp(Instruction::PtrToInt, 64);
2480   EXPECT_EQ(64u, PtrToInt.getBitWidth());
2481   EXPECT_TRUE(PtrToInt.isFullSet());
2482 
2483   ConstantRange IntToPtr = A.castOp(Instruction::IntToPtr, 64);
2484   EXPECT_EQ(64u, IntToPtr.getBitWidth());
2485   EXPECT_TRUE(IntToPtr.isFullSet());
2486 }
2487 
2488 TEST_F(ConstantRangeTest, binaryXor) {
2489   // Single element ranges.
2490   ConstantRange R16(APInt(8, 16));
2491   ConstantRange R20(APInt(8, 20));
2492   EXPECT_EQ(*R16.binaryXor(R16).getSingleElement(), APInt(8, 0));
2493   EXPECT_EQ(*R16.binaryXor(R20).getSingleElement(), APInt(8, 16 ^ 20));
2494 
2495   // Ranges with more than a single element. Handled conservatively for now.
2496   ConstantRange R16_35(APInt(8, 16), APInt(8, 35));
2497   ConstantRange R0_99(APInt(8, 0), APInt(8, 99));
2498   EXPECT_TRUE(R16_35.binaryXor(R16_35).isFullSet());
2499   EXPECT_TRUE(R16_35.binaryXor(R0_99).isFullSet());
2500   EXPECT_TRUE(R0_99.binaryXor(R16_35).isFullSet());
2501 }
2502 
2503 TEST_F(ConstantRangeTest, binaryNot) {
2504   TestUnaryOpExhaustive(
2505       [](const ConstantRange &CR) { return CR.binaryNot(); },
2506       [](const APInt &N) { return ~N; },
2507       PreferSmallest);
2508   TestUnaryOpExhaustive(
2509       [](const ConstantRange &CR) {
2510         return CR.binaryXor(ConstantRange(APInt::getAllOnes(CR.getBitWidth())));
2511       },
2512       [](const APInt &N) { return ~N; }, PreferSmallest);
2513   TestUnaryOpExhaustive(
2514       [](const ConstantRange &CR) {
2515         return ConstantRange(APInt::getAllOnes(CR.getBitWidth())).binaryXor(CR);
2516       },
2517       [](const APInt &N) { return ~N; }, PreferSmallest);
2518 }
2519 
2520 }  // anonymous namespace
2521