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, smul_fast) {
1085   TestBinaryOpExhaustive(
1086       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1087         return CR1.smul_fast(CR2);
1088       },
1089       [](const APInt &N1, const APInt &N2) {
1090         return N1 * N2;
1091       },
1092       PreferSmallest,
1093       [](const ConstantRange &, const ConstantRange &) {
1094         return false; // Check correctness only.
1095       });
1096 }
1097 
1098 TEST_F(ConstantRangeTest, UMax) {
1099   EXPECT_EQ(Full.umax(Full), Full);
1100   EXPECT_EQ(Full.umax(Empty), Empty);
1101   EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1102   EXPECT_EQ(Full.umax(Wrap), Full);
1103   EXPECT_EQ(Full.umax(Some), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1104   EXPECT_EQ(Empty.umax(Empty), Empty);
1105   EXPECT_EQ(Empty.umax(Some), Empty);
1106   EXPECT_EQ(Empty.umax(Wrap), Empty);
1107   EXPECT_EQ(Empty.umax(One), Empty);
1108   EXPECT_EQ(Some.umax(Some), Some);
1109   EXPECT_EQ(Some.umax(Wrap), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1110   EXPECT_EQ(Some.umax(One), Some);
1111   EXPECT_EQ(Wrap.umax(Wrap), Wrap);
1112   EXPECT_EQ(Wrap.umax(One), ConstantRange(APInt(16, 0xa), APInt(16, 0)));
1113   EXPECT_EQ(One.umax(One), One);
1114 
1115   TestBinaryOpExhaustive(
1116       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1117         return CR1.umax(CR2);
1118       },
1119       [](const APInt &N1, const APInt &N2) {
1120         return APIntOps::umax(N1, N2);
1121       },
1122       PreferSmallestNonFullUnsigned);
1123 }
1124 
1125 TEST_F(ConstantRangeTest, SMax) {
1126   EXPECT_EQ(Full.smax(Full), Full);
1127   EXPECT_EQ(Full.smax(Empty), Empty);
1128   EXPECT_EQ(Full.smax(Some), ConstantRange(APInt(16, 0xa),
1129                                            APInt::getSignedMinValue(16)));
1130   EXPECT_EQ(Full.smax(Wrap), Full);
1131   EXPECT_EQ(Full.smax(One), ConstantRange(APInt(16, 0xa),
1132                                           APInt::getSignedMinValue(16)));
1133   EXPECT_EQ(Empty.smax(Empty), Empty);
1134   EXPECT_EQ(Empty.smax(Some), Empty);
1135   EXPECT_EQ(Empty.smax(Wrap), Empty);
1136   EXPECT_EQ(Empty.smax(One), Empty);
1137   EXPECT_EQ(Some.smax(Some), Some);
1138   EXPECT_EQ(Some.smax(Wrap), ConstantRange(APInt(16, 0xa),
1139                                            APInt(16, (uint64_t)INT16_MIN)));
1140   EXPECT_EQ(Some.smax(One), Some);
1141   EXPECT_EQ(Wrap.smax(One), ConstantRange(APInt(16, 0xa),
1142                                           APInt(16, (uint64_t)INT16_MIN)));
1143   EXPECT_EQ(One.smax(One), One);
1144 
1145   TestBinaryOpExhaustive(
1146       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1147         return CR1.smax(CR2);
1148       },
1149       [](const APInt &N1, const APInt &N2) {
1150         return APIntOps::smax(N1, N2);
1151       },
1152       PreferSmallestNonFullSigned);
1153 }
1154 
1155 TEST_F(ConstantRangeTest, UMin) {
1156   EXPECT_EQ(Full.umin(Full), Full);
1157   EXPECT_EQ(Full.umin(Empty), Empty);
1158   EXPECT_EQ(Full.umin(Some), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1159   EXPECT_EQ(Full.umin(Wrap), Full);
1160   EXPECT_EQ(Empty.umin(Empty), Empty);
1161   EXPECT_EQ(Empty.umin(Some), Empty);
1162   EXPECT_EQ(Empty.umin(Wrap), Empty);
1163   EXPECT_EQ(Empty.umin(One), Empty);
1164   EXPECT_EQ(Some.umin(Some), Some);
1165   EXPECT_EQ(Some.umin(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1166   EXPECT_EQ(Some.umin(One), One);
1167   EXPECT_EQ(Wrap.umin(Wrap), Wrap);
1168   EXPECT_EQ(Wrap.umin(One), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1169   EXPECT_EQ(One.umin(One), One);
1170 
1171   TestBinaryOpExhaustive(
1172       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1173         return CR1.umin(CR2);
1174       },
1175       [](const APInt &N1, const APInt &N2) {
1176         return APIntOps::umin(N1, N2);
1177       },
1178       PreferSmallestNonFullUnsigned);
1179 }
1180 
1181 TEST_F(ConstantRangeTest, SMin) {
1182   EXPECT_EQ(Full.smin(Full), Full);
1183   EXPECT_EQ(Full.smin(Empty), Empty);
1184   EXPECT_EQ(Full.smin(Some), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1185                                            APInt(16, 0xaaa)));
1186   EXPECT_EQ(Full.smin(Wrap), Full);
1187   EXPECT_EQ(Empty.smin(Empty), Empty);
1188   EXPECT_EQ(Empty.smin(Some), Empty);
1189   EXPECT_EQ(Empty.smin(Wrap), Empty);
1190   EXPECT_EQ(Empty.smin(One), Empty);
1191   EXPECT_EQ(Some.smin(Some), Some);
1192   EXPECT_EQ(Some.smin(Wrap), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1193                                            APInt(16, 0xaaa)));
1194   EXPECT_EQ(Some.smin(One), One);
1195   EXPECT_EQ(Wrap.smin(Wrap), Wrap);
1196   EXPECT_EQ(Wrap.smin(One), ConstantRange(APInt(16, (uint64_t)INT16_MIN),
1197                                           APInt(16, 0xb)));
1198   EXPECT_EQ(One.smin(One), One);
1199 
1200   TestBinaryOpExhaustive(
1201       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1202         return CR1.smin(CR2);
1203       },
1204       [](const APInt &N1, const APInt &N2) {
1205         return APIntOps::smin(N1, N2);
1206       },
1207       PreferSmallestNonFullSigned);
1208 }
1209 
1210 TEST_F(ConstantRangeTest, UDiv) {
1211   EXPECT_EQ(Full.udiv(Full), Full);
1212   EXPECT_EQ(Full.udiv(Empty), Empty);
1213   EXPECT_EQ(Full.udiv(One), ConstantRange(APInt(16, 0),
1214                                           APInt(16, 0xffff / 0xa + 1)));
1215   EXPECT_EQ(Full.udiv(Some), ConstantRange(APInt(16, 0),
1216                                            APInt(16, 0xffff / 0xa + 1)));
1217   EXPECT_EQ(Full.udiv(Wrap), Full);
1218   EXPECT_EQ(Empty.udiv(Empty), Empty);
1219   EXPECT_EQ(Empty.udiv(One), Empty);
1220   EXPECT_EQ(Empty.udiv(Some), Empty);
1221   EXPECT_EQ(Empty.udiv(Wrap), Empty);
1222   EXPECT_EQ(One.udiv(One), ConstantRange(APInt(16, 1)));
1223   EXPECT_EQ(One.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 2)));
1224   EXPECT_EQ(One.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1225   EXPECT_EQ(Some.udiv(Some), ConstantRange(APInt(16, 0), APInt(16, 0x111)));
1226   EXPECT_EQ(Some.udiv(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1227   EXPECT_EQ(Wrap.udiv(Wrap), Full);
1228 
1229 
1230   ConstantRange Zero(APInt(16, 0));
1231   EXPECT_EQ(Zero.udiv(One), Zero);
1232   EXPECT_EQ(Zero.udiv(Full), Zero);
1233 
1234   EXPECT_EQ(ConstantRange(APInt(16, 0), APInt(16, 99)).udiv(Full),
1235             ConstantRange(APInt(16, 0), APInt(16, 99)));
1236   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 99)).udiv(Full),
1237             ConstantRange(APInt(16, 0), APInt(16, 99)));
1238 }
1239 
1240 TEST_F(ConstantRangeTest, SDiv) {
1241   unsigned Bits = 4;
1242   EnumerateTwoConstantRanges(Bits, [&](const ConstantRange &CR1,
1243                                        const ConstantRange &CR2) {
1244     // Collect possible results in a bit vector. We store the signed value plus
1245     // a bias to make it unsigned.
1246     int Bias = 1 << (Bits - 1);
1247     BitVector Results(1 << Bits);
1248     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
1249       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
1250         // Division by zero is UB.
1251         if (N2 == 0)
1252           return;
1253 
1254         // SignedMin / -1 is UB.
1255         if (N1.isMinSignedValue() && N2.isAllOnes())
1256           return;
1257 
1258         APInt N = N1.sdiv(N2);
1259         Results.set(N.getSExtValue() + Bias);
1260       });
1261     });
1262 
1263     ConstantRange CR = CR1.sdiv(CR2);
1264     if (Results.none()) {
1265       EXPECT_TRUE(CR.isEmptySet());
1266       return;
1267     }
1268 
1269     // If there is a non-full signed envelope, that should be the result.
1270     APInt SMin(Bits, Results.find_first() - Bias);
1271     APInt SMax(Bits, Results.find_last() - Bias);
1272     ConstantRange Envelope = ConstantRange::getNonEmpty(SMin, SMax + 1);
1273     if (!Envelope.isFullSet()) {
1274       EXPECT_EQ(Envelope, CR);
1275       return;
1276     }
1277 
1278     // If the signed envelope is a full set, try to find a smaller sign wrapped
1279     // set that is separated in negative and positive components (or one which
1280     // can also additionally contain zero).
1281     int LastNeg = Results.find_last_in(0, Bias) - Bias;
1282     int LastPos = Results.find_next(Bias) - Bias;
1283     if (Results[Bias]) {
1284       if (LastNeg == -1)
1285         ++LastNeg;
1286       else if (LastPos == 1)
1287         --LastPos;
1288     }
1289 
1290     APInt WMax(Bits, LastNeg);
1291     APInt WMin(Bits, LastPos);
1292     ConstantRange Wrapped = ConstantRange::getNonEmpty(WMin, WMax + 1);
1293     EXPECT_EQ(Wrapped, CR);
1294   });
1295 }
1296 
1297 TEST_F(ConstantRangeTest, URem) {
1298   EXPECT_EQ(Full.urem(Empty), Empty);
1299   EXPECT_EQ(Empty.urem(Full), Empty);
1300   // urem by zero is poison.
1301   EXPECT_EQ(Full.urem(ConstantRange(APInt(16, 0))), Empty);
1302   // urem by full range doesn't contain MaxValue.
1303   EXPECT_EQ(Full.urem(Full), ConstantRange(APInt(16, 0), APInt(16, 0xffff)));
1304   // urem is upper bounded by maximum RHS minus one.
1305   EXPECT_EQ(Full.urem(ConstantRange(APInt(16, 0), APInt(16, 123))),
1306             ConstantRange(APInt(16, 0), APInt(16, 122)));
1307   // urem is upper bounded by maximum LHS.
1308   EXPECT_EQ(ConstantRange(APInt(16, 0), APInt(16, 123)).urem(Full),
1309             ConstantRange(APInt(16, 0), APInt(16, 123)));
1310   // If the LHS is always lower than the RHS, the result is the LHS.
1311   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 20))
1312                 .urem(ConstantRange(APInt(16, 20), APInt(16, 30))),
1313             ConstantRange(APInt(16, 10), APInt(16, 20)));
1314   // It has to be strictly lower, otherwise the top value may wrap to zero.
1315   EXPECT_EQ(ConstantRange(APInt(16, 10), APInt(16, 20))
1316                 .urem(ConstantRange(APInt(16, 19), APInt(16, 30))),
1317             ConstantRange(APInt(16, 0), APInt(16, 20)));
1318   // [12, 14] % 10 is [2, 4], but we conservatively compute [0, 9].
1319   EXPECT_EQ(ConstantRange(APInt(16, 12), APInt(16, 15))
1320                 .urem(ConstantRange(APInt(16, 10))),
1321             ConstantRange(APInt(16, 0), APInt(16, 10)));
1322 
1323   TestBinaryOpExhaustive(
1324       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1325         return CR1.urem(CR2);
1326       },
1327       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1328         if (N2.isZero())
1329           return None;
1330         return N1.urem(N2);
1331       },
1332       PreferSmallest,
1333       CheckSingleElementsOnly);
1334 }
1335 
1336 TEST_F(ConstantRangeTest, SRem) {
1337   EXPECT_EQ(Full.srem(Empty), Empty);
1338   EXPECT_EQ(Empty.srem(Full), Empty);
1339   // srem by zero is UB.
1340   EXPECT_EQ(Full.srem(ConstantRange(APInt(16, 0))), Empty);
1341   // srem by full range doesn't contain SignedMinValue.
1342   EXPECT_EQ(Full.srem(Full), ConstantRange(APInt::getSignedMinValue(16) + 1,
1343                                            APInt::getSignedMinValue(16)));
1344 
1345   ConstantRange PosMod(APInt(16, 10), APInt(16, 21));  // [10, 20]
1346   ConstantRange NegMod(APInt(16, -20), APInt(16, -9)); // [-20, -10]
1347   ConstantRange IntMinMod(APInt::getSignedMinValue(16));
1348 
1349   ConstantRange Expected(16, true);
1350 
1351   // srem is bounded by abs(RHS) minus one.
1352   ConstantRange PosLargeLHS(APInt(16, 0), APInt(16, 41));
1353   Expected = ConstantRange(APInt(16, 0), APInt(16, 20));
1354   EXPECT_EQ(PosLargeLHS.srem(PosMod), Expected);
1355   EXPECT_EQ(PosLargeLHS.srem(NegMod), Expected);
1356   ConstantRange NegLargeLHS(APInt(16, -40), APInt(16, 1));
1357   Expected = ConstantRange(APInt(16, -19), APInt(16, 1));
1358   EXPECT_EQ(NegLargeLHS.srem(PosMod), Expected);
1359   EXPECT_EQ(NegLargeLHS.srem(NegMod), Expected);
1360   ConstantRange PosNegLargeLHS(APInt(16, -32), APInt(16, 38));
1361   Expected = ConstantRange(APInt(16, -19), APInt(16, 20));
1362   EXPECT_EQ(PosNegLargeLHS.srem(PosMod), Expected);
1363   EXPECT_EQ(PosNegLargeLHS.srem(NegMod), Expected);
1364 
1365   // srem is bounded by LHS.
1366   ConstantRange PosLHS(APInt(16, 0), APInt(16, 16));
1367   EXPECT_EQ(PosLHS.srem(PosMod), PosLHS);
1368   EXPECT_EQ(PosLHS.srem(NegMod), PosLHS);
1369   EXPECT_EQ(PosLHS.srem(IntMinMod), PosLHS);
1370   ConstantRange NegLHS(APInt(16, -15), APInt(16, 1));
1371   EXPECT_EQ(NegLHS.srem(PosMod), NegLHS);
1372   EXPECT_EQ(NegLHS.srem(NegMod), NegLHS);
1373   EXPECT_EQ(NegLHS.srem(IntMinMod), NegLHS);
1374   ConstantRange PosNegLHS(APInt(16, -12), APInt(16, 18));
1375   EXPECT_EQ(PosNegLHS.srem(PosMod), PosNegLHS);
1376   EXPECT_EQ(PosNegLHS.srem(NegMod), PosNegLHS);
1377   EXPECT_EQ(PosNegLHS.srem(IntMinMod), PosNegLHS);
1378 
1379   // srem is LHS if it is smaller than RHS.
1380   ConstantRange PosSmallLHS(APInt(16, 3), APInt(16, 8));
1381   EXPECT_EQ(PosSmallLHS.srem(PosMod), PosSmallLHS);
1382   EXPECT_EQ(PosSmallLHS.srem(NegMod), PosSmallLHS);
1383   EXPECT_EQ(PosSmallLHS.srem(IntMinMod), PosSmallLHS);
1384   ConstantRange NegSmallLHS(APInt(16, -7), APInt(16, -2));
1385   EXPECT_EQ(NegSmallLHS.srem(PosMod), NegSmallLHS);
1386   EXPECT_EQ(NegSmallLHS.srem(NegMod), NegSmallLHS);
1387   EXPECT_EQ(NegSmallLHS.srem(IntMinMod), NegSmallLHS);
1388   ConstantRange PosNegSmallLHS(APInt(16, -3), APInt(16, 8));
1389   EXPECT_EQ(PosNegSmallLHS.srem(PosMod), PosNegSmallLHS);
1390   EXPECT_EQ(PosNegSmallLHS.srem(NegMod), PosNegSmallLHS);
1391   EXPECT_EQ(PosNegSmallLHS.srem(IntMinMod), PosNegSmallLHS);
1392 
1393   // Example of a suboptimal result:
1394   // [12, 14] srem 10 is [2, 4], but we conservatively compute [0, 9].
1395   EXPECT_EQ(ConstantRange(APInt(16, 12), APInt(16, 15))
1396                 .srem(ConstantRange(APInt(16, 10))),
1397             ConstantRange(APInt(16, 0), APInt(16, 10)));
1398 
1399   TestBinaryOpExhaustive(
1400       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1401         return CR1.srem(CR2);
1402       },
1403       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1404         if (N2.isZero())
1405           return None;
1406         return N1.srem(N2);
1407       },
1408       PreferSmallest,
1409       CheckSingleElementsOnly);
1410 }
1411 
1412 TEST_F(ConstantRangeTest, Shl) {
1413   ConstantRange Some2(APInt(16, 0xfff), APInt(16, 0x8000));
1414   ConstantRange WrapNullMax(APInt(16, 0x1), APInt(16, 0x0));
1415   EXPECT_EQ(Full.shl(Full), Full);
1416   EXPECT_EQ(Full.shl(Empty), Empty);
1417   EXPECT_EQ(Full.shl(One), ConstantRange(APInt(16, 0),
1418                                          APInt(16, 0xfc00) + 1));
1419   EXPECT_EQ(Full.shl(Some), Full);   // TODO: [0, (-1 << 0xa) + 1)
1420   EXPECT_EQ(Full.shl(Wrap), Full);
1421   EXPECT_EQ(Empty.shl(Empty), Empty);
1422   EXPECT_EQ(Empty.shl(One), Empty);
1423   EXPECT_EQ(Empty.shl(Some), Empty);
1424   EXPECT_EQ(Empty.shl(Wrap), Empty);
1425   EXPECT_EQ(One.shl(One), ConstantRange(APInt(16, 0xa << 0xa),
1426                                         APInt(16, (0xa << 0xa) + 1)));
1427   EXPECT_EQ(One.shl(Some), Full);    // TODO: [0xa << 0xa, 0)
1428   EXPECT_EQ(One.shl(Wrap), Full);    // TODO: [0xa, 0xa << 14 + 1)
1429   EXPECT_EQ(Some.shl(Some), Full);   // TODO: [0xa << 0xa, 0xfc01)
1430   EXPECT_EQ(Some.shl(Wrap), Full);   // TODO: [0xa, 0x7ff << 0x5 + 1)
1431   EXPECT_EQ(Wrap.shl(Wrap), Full);
1432   EXPECT_EQ(
1433       Some2.shl(ConstantRange(APInt(16, 0x1))),
1434       ConstantRange(APInt(16, 0xfff << 0x1), APInt(16, 0x7fff << 0x1) + 1));
1435   EXPECT_EQ(One.shl(WrapNullMax), Full);
1436 
1437   TestBinaryOpExhaustive(
1438       [](const ConstantRange &CR1, const ConstantRange &CR2) {
1439         return CR1.shl(CR2);
1440       },
1441       [](const APInt &N1, const APInt &N2) -> Optional<APInt> {
1442         if (N2.uge(N2.getBitWidth()))
1443           return None;
1444         return N1.shl(N2);
1445       },
1446       PreferSmallestUnsigned,
1447       [](const ConstantRange &, const ConstantRange &CR2) {
1448         // We currently only produce precise results for single element RHS.
1449         return CR2.isSingleElement();
1450       });
1451 }
1452 
1453 TEST_F(ConstantRangeTest, Lshr) {
1454   EXPECT_EQ(Full.lshr(Full), Full);
1455   EXPECT_EQ(Full.lshr(Empty), Empty);
1456   EXPECT_EQ(Full.lshr(One), ConstantRange(APInt(16, 0),
1457                                           APInt(16, (0xffff >> 0xa) + 1)));
1458   EXPECT_EQ(Full.lshr(Some), ConstantRange(APInt(16, 0),
1459                                            APInt(16, (0xffff >> 0xa) + 1)));
1460   EXPECT_EQ(Full.lshr(Wrap), Full);
1461   EXPECT_EQ(Empty.lshr(Empty), Empty);
1462   EXPECT_EQ(Empty.lshr(One), Empty);
1463   EXPECT_EQ(Empty.lshr(Some), Empty);
1464   EXPECT_EQ(Empty.lshr(Wrap), Empty);
1465   EXPECT_EQ(One.lshr(One), ConstantRange(APInt(16, 0)));
1466   EXPECT_EQ(One.lshr(Some), ConstantRange(APInt(16, 0)));
1467   EXPECT_EQ(One.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1468   EXPECT_EQ(Some.lshr(Some), ConstantRange(APInt(16, 0),
1469                                            APInt(16, (0xaaa >> 0xa) + 1)));
1470   EXPECT_EQ(Some.lshr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1471   EXPECT_EQ(Wrap.lshr(Wrap), Full);
1472 }
1473 
1474 TEST_F(ConstantRangeTest, Ashr) {
1475   EXPECT_EQ(Full.ashr(Full), Full);
1476   EXPECT_EQ(Full.ashr(Empty), Empty);
1477   EXPECT_EQ(Full.ashr(One), ConstantRange(APInt(16, 0xffe0),
1478                                           APInt(16, (0x7fff >> 0xa) + 1 )));
1479   ConstantRange Small(APInt(16, 0xa), APInt(16, 0xb));
1480   EXPECT_EQ(Full.ashr(Small), ConstantRange(APInt(16, 0xffe0),
1481                                            APInt(16, (0x7fff >> 0xa) + 1 )));
1482   EXPECT_EQ(Full.ashr(Some), ConstantRange(APInt(16, 0xffe0),
1483                                            APInt(16, (0x7fff >> 0xa) + 1 )));
1484   EXPECT_EQ(Full.ashr(Wrap), Full);
1485   EXPECT_EQ(Empty.ashr(Empty), Empty);
1486   EXPECT_EQ(Empty.ashr(One), Empty);
1487   EXPECT_EQ(Empty.ashr(Some), Empty);
1488   EXPECT_EQ(Empty.ashr(Wrap), Empty);
1489   EXPECT_EQ(One.ashr(One), ConstantRange(APInt(16, 0)));
1490   EXPECT_EQ(One.ashr(Some), ConstantRange(APInt(16, 0)));
1491   EXPECT_EQ(One.ashr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xb)));
1492   EXPECT_EQ(Some.ashr(Some), ConstantRange(APInt(16, 0),
1493                                            APInt(16, (0xaaa >> 0xa) + 1)));
1494   EXPECT_EQ(Some.ashr(Wrap), ConstantRange(APInt(16, 0), APInt(16, 0xaaa)));
1495   EXPECT_EQ(Wrap.ashr(Wrap), Full);
1496   ConstantRange Neg(APInt(16, 0xf3f0, true), APInt(16, 0xf7f8, true));
1497   EXPECT_EQ(Neg.ashr(Small), ConstantRange(APInt(16, 0xfffc, true),
1498                                            APInt(16, 0xfffe, true)));
1499 }
1500 
1501 TEST(ConstantRange, MakeAllowedICmpRegion) {
1502   // PR8250
1503   ConstantRange SMax = ConstantRange(APInt::getSignedMaxValue(32));
1504   EXPECT_TRUE(ConstantRange::makeAllowedICmpRegion(ICmpInst::ICMP_SGT, SMax)
1505                   .isEmptySet());
1506 }
1507 
1508 TEST(ConstantRange, MakeSatisfyingICmpRegion) {
1509   ConstantRange LowHalf(APInt(8, 0), APInt(8, 128));
1510   ConstantRange HighHalf(APInt(8, 128), APInt(8, 0));
1511   ConstantRange EmptySet(8, /* isFullSet = */ false);
1512 
1513   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, LowHalf),
1514             HighHalf);
1515 
1516   EXPECT_EQ(
1517       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_NE, HighHalf),
1518       LowHalf);
1519 
1520   EXPECT_TRUE(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_EQ,
1521                                                       HighHalf).isEmptySet());
1522 
1523   ConstantRange UnsignedSample(APInt(8, 5), APInt(8, 200));
1524 
1525   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULT,
1526                                                     UnsignedSample),
1527             ConstantRange(APInt(8, 0), APInt(8, 5)));
1528 
1529   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_ULE,
1530                                                     UnsignedSample),
1531             ConstantRange(APInt(8, 0), APInt(8, 6)));
1532 
1533   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGT,
1534                                                     UnsignedSample),
1535             ConstantRange(APInt(8, 200), APInt(8, 0)));
1536 
1537   EXPECT_EQ(ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_UGE,
1538                                                     UnsignedSample),
1539             ConstantRange(APInt(8, 199), APInt(8, 0)));
1540 
1541   ConstantRange SignedSample(APInt(8, -5), APInt(8, 5));
1542 
1543   EXPECT_EQ(
1544       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLT, SignedSample),
1545       ConstantRange(APInt(8, -128), APInt(8, -5)));
1546 
1547   EXPECT_EQ(
1548       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SLE, SignedSample),
1549       ConstantRange(APInt(8, -128), APInt(8, -4)));
1550 
1551   EXPECT_EQ(
1552       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGT, SignedSample),
1553       ConstantRange(APInt(8, 5), APInt(8, -128)));
1554 
1555   EXPECT_EQ(
1556       ConstantRange::makeSatisfyingICmpRegion(ICmpInst::ICMP_SGE, SignedSample),
1557       ConstantRange(APInt(8, 4), APInt(8, -128)));
1558 }
1559 
1560 static bool icmp(CmpInst::Predicate Pred, const APInt &LHS, const APInt &RHS) {
1561   switch (Pred) {
1562   case CmpInst::Predicate::ICMP_EQ:
1563     return LHS.eq(RHS);
1564   case CmpInst::Predicate::ICMP_NE:
1565     return LHS.ne(RHS);
1566   case CmpInst::Predicate::ICMP_UGT:
1567     return LHS.ugt(RHS);
1568   case CmpInst::Predicate::ICMP_UGE:
1569     return LHS.uge(RHS);
1570   case CmpInst::Predicate::ICMP_ULT:
1571     return LHS.ult(RHS);
1572   case CmpInst::Predicate::ICMP_ULE:
1573     return LHS.ule(RHS);
1574   case CmpInst::Predicate::ICMP_SGT:
1575     return LHS.sgt(RHS);
1576   case CmpInst::Predicate::ICMP_SGE:
1577     return LHS.sge(RHS);
1578   case CmpInst::Predicate::ICMP_SLT:
1579     return LHS.slt(RHS);
1580   case CmpInst::Predicate::ICMP_SLE:
1581     return LHS.sle(RHS);
1582   default:
1583     llvm_unreachable("Not an ICmp predicate!");
1584   }
1585 }
1586 
1587 void ICmpTestImpl(CmpInst::Predicate Pred) {
1588   unsigned Bits = 4;
1589   EnumerateTwoConstantRanges(
1590       Bits, [&](const ConstantRange &CR1, const ConstantRange &CR2) {
1591         bool Exhaustive = true;
1592         ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
1593           ForeachNumInConstantRange(
1594               CR2, [&](const APInt &N2) { Exhaustive &= icmp(Pred, N1, N2); });
1595         });
1596         EXPECT_EQ(CR1.icmp(Pred, CR2), Exhaustive);
1597       });
1598 }
1599 
1600 TEST(ConstantRange, ICmp) {
1601   for (auto Pred : seq_inclusive(CmpInst::Predicate::FIRST_ICMP_PREDICATE,
1602                                  CmpInst::Predicate::LAST_ICMP_PREDICATE))
1603     ICmpTestImpl(Pred);
1604 }
1605 
1606 TEST(ConstantRange, MakeGuaranteedNoWrapRegion) {
1607   const int IntMin4Bits = 8;
1608   const int IntMax4Bits = 7;
1609   typedef OverflowingBinaryOperator OBO;
1610 
1611   for (int Const : {0, -1, -2, 1, 2, IntMin4Bits, IntMax4Bits}) {
1612     APInt C(4, Const, true /* = isSigned */);
1613 
1614     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1615         Instruction::Add, C, OBO::NoUnsignedWrap);
1616 
1617     EXPECT_FALSE(NUWRegion.isEmptySet());
1618 
1619     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1620         Instruction::Add, C, OBO::NoSignedWrap);
1621 
1622     EXPECT_FALSE(NSWRegion.isEmptySet());
1623 
1624     for (APInt I = NUWRegion.getLower(), E = NUWRegion.getUpper(); I != E;
1625          ++I) {
1626       bool Overflow = false;
1627       (void)I.uadd_ov(C, Overflow);
1628       EXPECT_FALSE(Overflow);
1629     }
1630 
1631     for (APInt I = NSWRegion.getLower(), E = NSWRegion.getUpper(); I != E;
1632          ++I) {
1633       bool Overflow = false;
1634       (void)I.sadd_ov(C, Overflow);
1635       EXPECT_FALSE(Overflow);
1636     }
1637   }
1638 
1639   for (int Const : {0, -1, -2, 1, 2, IntMin4Bits, IntMax4Bits}) {
1640     APInt C(4, Const, true /* = isSigned */);
1641 
1642     auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1643         Instruction::Sub, C, OBO::NoUnsignedWrap);
1644 
1645     EXPECT_FALSE(NUWRegion.isEmptySet());
1646 
1647     auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1648         Instruction::Sub, C, OBO::NoSignedWrap);
1649 
1650     EXPECT_FALSE(NSWRegion.isEmptySet());
1651 
1652     for (APInt I = NUWRegion.getLower(), E = NUWRegion.getUpper(); I != E;
1653          ++I) {
1654       bool Overflow = false;
1655       (void)I.usub_ov(C, Overflow);
1656       EXPECT_FALSE(Overflow);
1657     }
1658 
1659     for (APInt I = NSWRegion.getLower(), E = NSWRegion.getUpper(); I != E;
1660          ++I) {
1661       bool Overflow = false;
1662       (void)I.ssub_ov(C, Overflow);
1663       EXPECT_FALSE(Overflow);
1664     }
1665   }
1666 
1667   auto NSWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1668       Instruction::Add, ConstantRange(32, /* isFullSet = */ true),
1669       OBO::NoSignedWrap);
1670   EXPECT_TRUE(NSWForAllValues.isSingleElement() &&
1671               NSWForAllValues.getSingleElement()->isMinValue());
1672 
1673   NSWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1674       Instruction::Sub, ConstantRange(32, /* isFullSet = */ true),
1675       OBO::NoSignedWrap);
1676   EXPECT_TRUE(NSWForAllValues.isSingleElement() &&
1677               NSWForAllValues.getSingleElement()->isMaxValue());
1678 
1679   auto NUWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1680       Instruction::Add, ConstantRange(32, /* isFullSet = */ true),
1681       OBO::NoUnsignedWrap);
1682   EXPECT_TRUE(NUWForAllValues.isSingleElement() &&
1683               NUWForAllValues.getSingleElement()->isMinValue());
1684 
1685   NUWForAllValues = ConstantRange::makeGuaranteedNoWrapRegion(
1686       Instruction::Sub, ConstantRange(32, /* isFullSet = */ true),
1687       OBO::NoUnsignedWrap);
1688   EXPECT_TRUE(NUWForAllValues.isSingleElement() &&
1689               NUWForAllValues.getSingleElement()->isMaxValue());
1690 
1691   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1692       Instruction::Add, APInt(32, 0), OBO::NoUnsignedWrap).isFullSet());
1693   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1694       Instruction::Add, APInt(32, 0), OBO::NoSignedWrap).isFullSet());
1695   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1696       Instruction::Sub, APInt(32, 0), OBO::NoUnsignedWrap).isFullSet());
1697   EXPECT_TRUE(ConstantRange::makeGuaranteedNoWrapRegion(
1698       Instruction::Sub, APInt(32, 0), OBO::NoSignedWrap).isFullSet());
1699 
1700   ConstantRange OneToFive(APInt(32, 1), APInt(32, 6));
1701   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1702                 Instruction::Add, OneToFive, OBO::NoSignedWrap),
1703             ConstantRange(APInt::getSignedMinValue(32),
1704                           APInt::getSignedMaxValue(32) - 4));
1705   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1706                 Instruction::Add, OneToFive, OBO::NoUnsignedWrap),
1707             ConstantRange(APInt::getMinValue(32), APInt::getMinValue(32) - 5));
1708   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1709                 Instruction::Sub, OneToFive, OBO::NoSignedWrap),
1710             ConstantRange(APInt::getSignedMinValue(32) + 5,
1711                           APInt::getSignedMinValue(32)));
1712   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1713                 Instruction::Sub, OneToFive, OBO::NoUnsignedWrap),
1714             ConstantRange(APInt::getMinValue(32) + 5, APInt::getMinValue(32)));
1715 
1716   ConstantRange MinusFiveToMinusTwo(APInt(32, -5), APInt(32, -1));
1717   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1718                 Instruction::Add, MinusFiveToMinusTwo, OBO::NoSignedWrap),
1719             ConstantRange(APInt::getSignedMinValue(32) + 5,
1720                           APInt::getSignedMinValue(32)));
1721   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1722                 Instruction::Add, MinusFiveToMinusTwo, OBO::NoUnsignedWrap),
1723             ConstantRange(APInt(32, 0), APInt(32, 2)));
1724   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1725                 Instruction::Sub, MinusFiveToMinusTwo, OBO::NoSignedWrap),
1726             ConstantRange(APInt::getSignedMinValue(32),
1727                           APInt::getSignedMaxValue(32) - 4));
1728   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1729                 Instruction::Sub, MinusFiveToMinusTwo, OBO::NoUnsignedWrap),
1730             ConstantRange(APInt::getMaxValue(32) - 1,
1731                           APInt::getMinValue(32)));
1732 
1733   ConstantRange MinusOneToOne(APInt(32, -1), APInt(32, 2));
1734   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1735                 Instruction::Add, MinusOneToOne, OBO::NoSignedWrap),
1736             ConstantRange(APInt::getSignedMinValue(32) + 1,
1737                           APInt::getSignedMinValue(32) - 1));
1738   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1739                 Instruction::Add, MinusOneToOne, OBO::NoUnsignedWrap),
1740             ConstantRange(APInt(32, 0), APInt(32, 1)));
1741   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1742                 Instruction::Sub, MinusOneToOne, OBO::NoSignedWrap),
1743             ConstantRange(APInt::getSignedMinValue(32) + 1,
1744                           APInt::getSignedMinValue(32) - 1));
1745   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1746                 Instruction::Sub, MinusOneToOne, OBO::NoUnsignedWrap),
1747             ConstantRange(APInt::getMaxValue(32),
1748                           APInt::getMinValue(32)));
1749 
1750   ConstantRange One(APInt(32, 1), APInt(32, 2));
1751   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1752                 Instruction::Add, One, OBO::NoSignedWrap),
1753             ConstantRange(APInt::getSignedMinValue(32),
1754                           APInt::getSignedMaxValue(32)));
1755   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1756                 Instruction::Add, One, OBO::NoUnsignedWrap),
1757             ConstantRange(APInt::getMinValue(32), APInt::getMaxValue(32)));
1758   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1759                 Instruction::Sub, One, OBO::NoSignedWrap),
1760             ConstantRange(APInt::getSignedMinValue(32) + 1,
1761                           APInt::getSignedMinValue(32)));
1762   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1763                 Instruction::Sub, One, OBO::NoUnsignedWrap),
1764             ConstantRange(APInt::getMinValue(32) + 1, APInt::getMinValue(32)));
1765 
1766   ConstantRange OneLessThanBitWidth(APInt(32, 0), APInt(32, 31) + 1);
1767   ConstantRange UpToBitWidth(APInt(32, 0), APInt(32, 32) + 1);
1768   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1769                 Instruction::Shl, UpToBitWidth, OBO::NoUnsignedWrap),
1770             ConstantRange::makeGuaranteedNoWrapRegion(
1771                 Instruction::Shl, OneLessThanBitWidth, OBO::NoUnsignedWrap));
1772   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1773                 Instruction::Shl, UpToBitWidth, OBO::NoSignedWrap),
1774             ConstantRange::makeGuaranteedNoWrapRegion(
1775                 Instruction::Shl, OneLessThanBitWidth, OBO::NoSignedWrap));
1776   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1777                 Instruction::Shl, UpToBitWidth, OBO::NoUnsignedWrap),
1778             ConstantRange(APInt(32, 0), APInt(32, 1) + 1));
1779   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1780                 Instruction::Shl, UpToBitWidth, OBO::NoSignedWrap),
1781             ConstantRange(APInt(32, -1), APInt(32, 0) + 1));
1782 
1783   EXPECT_EQ(
1784       ConstantRange::makeGuaranteedNoWrapRegion(
1785           Instruction::Shl, ConstantRange::getFull(32), OBO::NoUnsignedWrap),
1786       ConstantRange::makeGuaranteedNoWrapRegion(
1787           Instruction::Shl, OneLessThanBitWidth, OBO::NoUnsignedWrap));
1788   EXPECT_EQ(
1789       ConstantRange::makeGuaranteedNoWrapRegion(
1790           Instruction::Shl, ConstantRange::getFull(32), OBO::NoSignedWrap),
1791       ConstantRange::makeGuaranteedNoWrapRegion(
1792           Instruction::Shl, OneLessThanBitWidth, OBO::NoSignedWrap));
1793 
1794   ConstantRange IllegalShAmt(APInt(32, 32), APInt(32, 0) + 1);
1795   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1796                 Instruction::Shl, IllegalShAmt, OBO::NoUnsignedWrap),
1797             ConstantRange::getFull(32));
1798   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1799                 Instruction::Shl, IllegalShAmt, OBO::NoSignedWrap),
1800             ConstantRange::getFull(32));
1801 
1802   EXPECT_EQ(
1803       ConstantRange::makeGuaranteedNoWrapRegion(
1804           Instruction::Shl, ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1805           OBO::NoUnsignedWrap),
1806       ConstantRange::makeGuaranteedNoWrapRegion(
1807           Instruction::Shl, ConstantRange(APInt(32, 0), APInt(32, 16) + 1),
1808           OBO::NoUnsignedWrap));
1809   EXPECT_EQ(
1810       ConstantRange::makeGuaranteedNoWrapRegion(
1811           Instruction::Shl, ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1812           OBO::NoSignedWrap),
1813       ConstantRange::makeGuaranteedNoWrapRegion(
1814           Instruction::Shl, ConstantRange(APInt(32, 0), APInt(32, 16) + 1),
1815           OBO::NoSignedWrap));
1816 
1817   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1818                 Instruction::Shl,
1819                 ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1820                 OBO::NoUnsignedWrap),
1821             ConstantRange(APInt(32, 0), APInt(32, 65535) + 1));
1822   EXPECT_EQ(ConstantRange::makeGuaranteedNoWrapRegion(
1823                 Instruction::Shl,
1824                 ConstantRange(APInt(32, -32), APInt(32, 16) + 1),
1825                 OBO::NoSignedWrap),
1826             ConstantRange(APInt(32, -32768), APInt(32, 32767) + 1));
1827 }
1828 
1829 template<typename Fn>
1830 void TestNoWrapRegionExhaustive(Instruction::BinaryOps BinOp,
1831                                 unsigned NoWrapKind, Fn OverflowFn) {
1832   unsigned Bits = 5;
1833   EnumerateConstantRanges(Bits, [&](const ConstantRange &CR) {
1834     if (CR.isEmptySet())
1835       return;
1836     if (Instruction::isShift(BinOp) && CR.getUnsignedMax().uge(Bits))
1837       return;
1838 
1839     ConstantRange NoWrap =
1840         ConstantRange::makeGuaranteedNoWrapRegion(BinOp, CR, NoWrapKind);
1841     ConstantRange Full = ConstantRange::getFull(Bits);
1842     ForeachNumInConstantRange(Full, [&](const APInt &N1) {
1843       bool NoOverflow = true;
1844       bool Overflow = true;
1845       ForeachNumInConstantRange(CR, [&](const APInt &N2) {
1846         if (OverflowFn(N1, N2))
1847           NoOverflow = false;
1848         else
1849           Overflow = false;
1850       });
1851       EXPECT_EQ(NoOverflow, NoWrap.contains(N1));
1852 
1853       // The no-wrap range is exact for single-element ranges.
1854       if (CR.isSingleElement()) {
1855         EXPECT_EQ(Overflow, !NoWrap.contains(N1));
1856       }
1857     });
1858   });
1859 }
1860 
1861 // Show that makeGuaranteedNoWrapRegion() is maximal, and for single-element
1862 // ranges also exact.
1863 TEST(ConstantRange, NoWrapRegionExhaustive) {
1864   TestNoWrapRegionExhaustive(
1865       Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap,
1866       [](const APInt &N1, const APInt &N2) {
1867         bool Overflow;
1868         (void) N1.uadd_ov(N2, Overflow);
1869         return Overflow;
1870       });
1871   TestNoWrapRegionExhaustive(
1872       Instruction::Add, OverflowingBinaryOperator::NoSignedWrap,
1873       [](const APInt &N1, const APInt &N2) {
1874         bool Overflow;
1875         (void) N1.sadd_ov(N2, Overflow);
1876         return Overflow;
1877       });
1878   TestNoWrapRegionExhaustive(
1879       Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap,
1880       [](const APInt &N1, const APInt &N2) {
1881         bool Overflow;
1882         (void) N1.usub_ov(N2, Overflow);
1883         return Overflow;
1884       });
1885   TestNoWrapRegionExhaustive(
1886       Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap,
1887       [](const APInt &N1, const APInt &N2) {
1888         bool Overflow;
1889         (void) N1.ssub_ov(N2, Overflow);
1890         return Overflow;
1891       });
1892   TestNoWrapRegionExhaustive(
1893       Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap,
1894       [](const APInt &N1, const APInt &N2) {
1895         bool Overflow;
1896         (void) N1.umul_ov(N2, Overflow);
1897         return Overflow;
1898       });
1899   TestNoWrapRegionExhaustive(
1900       Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap,
1901       [](const APInt &N1, const APInt &N2) {
1902         bool Overflow;
1903         (void) N1.smul_ov(N2, Overflow);
1904         return Overflow;
1905       });
1906   TestNoWrapRegionExhaustive(Instruction::Shl,
1907                              OverflowingBinaryOperator::NoUnsignedWrap,
1908                              [](const APInt &N1, const APInt &N2) {
1909                                bool Overflow;
1910                                (void)N1.ushl_ov(N2, Overflow);
1911                                return Overflow;
1912                              });
1913   TestNoWrapRegionExhaustive(Instruction::Shl,
1914                              OverflowingBinaryOperator::NoSignedWrap,
1915                              [](const APInt &N1, const APInt &N2) {
1916                                bool Overflow;
1917                                (void)N1.sshl_ov(N2, Overflow);
1918                                return Overflow;
1919                              });
1920 }
1921 
1922 TEST(ConstantRange, GetEquivalentICmp) {
1923   APInt RHS;
1924   CmpInst::Predicate Pred;
1925 
1926   EXPECT_TRUE(ConstantRange(APInt::getMinValue(32), APInt(32, 100))
1927                   .getEquivalentICmp(Pred, RHS));
1928   EXPECT_EQ(Pred, CmpInst::ICMP_ULT);
1929   EXPECT_EQ(RHS, APInt(32, 100));
1930 
1931   EXPECT_TRUE(ConstantRange(APInt::getSignedMinValue(32), APInt(32, 100))
1932                   .getEquivalentICmp(Pred, RHS));
1933   EXPECT_EQ(Pred, CmpInst::ICMP_SLT);
1934   EXPECT_EQ(RHS, APInt(32, 100));
1935 
1936   EXPECT_TRUE(ConstantRange(APInt(32, 100), APInt::getMinValue(32))
1937                   .getEquivalentICmp(Pred, RHS));
1938   EXPECT_EQ(Pred, CmpInst::ICMP_UGE);
1939   EXPECT_EQ(RHS, APInt(32, 100));
1940 
1941   EXPECT_TRUE(ConstantRange(APInt(32, 100), APInt::getSignedMinValue(32))
1942                   .getEquivalentICmp(Pred, RHS));
1943   EXPECT_EQ(Pred, CmpInst::ICMP_SGE);
1944   EXPECT_EQ(RHS, APInt(32, 100));
1945 
1946   EXPECT_TRUE(
1947       ConstantRange(32, /*isFullSet=*/true).getEquivalentICmp(Pred, RHS));
1948   EXPECT_EQ(Pred, CmpInst::ICMP_UGE);
1949   EXPECT_EQ(RHS, APInt(32, 0));
1950 
1951   EXPECT_TRUE(
1952       ConstantRange(32, /*isFullSet=*/false).getEquivalentICmp(Pred, RHS));
1953   EXPECT_EQ(Pred, CmpInst::ICMP_ULT);
1954   EXPECT_EQ(RHS, APInt(32, 0));
1955 
1956   EXPECT_FALSE(ConstantRange(APInt(32, 100), APInt(32, 200))
1957                    .getEquivalentICmp(Pred, RHS));
1958 
1959   EXPECT_FALSE(ConstantRange(APInt::getSignedMinValue(32) - APInt(32, 100),
1960                              APInt::getSignedMinValue(32) + APInt(32, 100))
1961                    .getEquivalentICmp(Pred, RHS));
1962 
1963   EXPECT_FALSE(ConstantRange(APInt::getMinValue(32) - APInt(32, 100),
1964                              APInt::getMinValue(32) + APInt(32, 100))
1965                    .getEquivalentICmp(Pred, RHS));
1966 
1967   EXPECT_TRUE(ConstantRange(APInt(32, 100)).getEquivalentICmp(Pred, RHS));
1968   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1969   EXPECT_EQ(RHS, APInt(32, 100));
1970 
1971   EXPECT_TRUE(
1972       ConstantRange(APInt(32, 100)).inverse().getEquivalentICmp(Pred, RHS));
1973   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1974   EXPECT_EQ(RHS, APInt(32, 100));
1975 
1976   EXPECT_TRUE(
1977       ConstantRange(APInt(512, 100)).inverse().getEquivalentICmp(Pred, RHS));
1978   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1979   EXPECT_EQ(RHS, APInt(512, 100));
1980 
1981   // NB!  It would be correct for the following four calls to getEquivalentICmp
1982   // to return ordered predicates like CmpInst::ICMP_ULT or CmpInst::ICMP_UGT.
1983   // However, that's not the case today.
1984 
1985   EXPECT_TRUE(ConstantRange(APInt(32, 0)).getEquivalentICmp(Pred, RHS));
1986   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1987   EXPECT_EQ(RHS, APInt(32, 0));
1988 
1989   EXPECT_TRUE(
1990       ConstantRange(APInt(32, 0)).inverse().getEquivalentICmp(Pred, RHS));
1991   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
1992   EXPECT_EQ(RHS, APInt(32, 0));
1993 
1994   EXPECT_TRUE(ConstantRange(APInt(32, -1)).getEquivalentICmp(Pred, RHS));
1995   EXPECT_EQ(Pred, CmpInst::ICMP_EQ);
1996   EXPECT_EQ(RHS, APInt(32, -1));
1997 
1998   EXPECT_TRUE(
1999       ConstantRange(APInt(32, -1)).inverse().getEquivalentICmp(Pred, RHS));
2000   EXPECT_EQ(Pred, CmpInst::ICMP_NE);
2001   EXPECT_EQ(RHS, APInt(32, -1));
2002 }
2003 
2004 #define EXPECT_MAY_OVERFLOW(op) \
2005   EXPECT_EQ(ConstantRange::OverflowResult::MayOverflow, (op))
2006 #define EXPECT_ALWAYS_OVERFLOWS_LOW(op) \
2007   EXPECT_EQ(ConstantRange::OverflowResult::AlwaysOverflowsLow, (op))
2008 #define EXPECT_ALWAYS_OVERFLOWS_HIGH(op) \
2009   EXPECT_EQ(ConstantRange::OverflowResult::AlwaysOverflowsHigh, (op))
2010 #define EXPECT_NEVER_OVERFLOWS(op) \
2011   EXPECT_EQ(ConstantRange::OverflowResult::NeverOverflows, (op))
2012 
2013 TEST_F(ConstantRangeTest, UnsignedAddOverflow) {
2014   // Ill-defined - may overflow is a conservative result.
2015   EXPECT_MAY_OVERFLOW(Some.unsignedAddMayOverflow(Empty));
2016   EXPECT_MAY_OVERFLOW(Empty.unsignedAddMayOverflow(Some));
2017 
2018   // Never overflow despite one full/wrap set.
2019   ConstantRange Zero(APInt::getZero(16));
2020   EXPECT_NEVER_OVERFLOWS(Full.unsignedAddMayOverflow(Zero));
2021   EXPECT_NEVER_OVERFLOWS(Wrap.unsignedAddMayOverflow(Zero));
2022   EXPECT_NEVER_OVERFLOWS(Zero.unsignedAddMayOverflow(Full));
2023   EXPECT_NEVER_OVERFLOWS(Zero.unsignedAddMayOverflow(Wrap));
2024 
2025   // But usually full/wrap always may overflow.
2026   EXPECT_MAY_OVERFLOW(Full.unsignedAddMayOverflow(One));
2027   EXPECT_MAY_OVERFLOW(Wrap.unsignedAddMayOverflow(One));
2028   EXPECT_MAY_OVERFLOW(One.unsignedAddMayOverflow(Full));
2029   EXPECT_MAY_OVERFLOW(One.unsignedAddMayOverflow(Wrap));
2030 
2031   ConstantRange A(APInt(16, 0xfd00), APInt(16, 0xfe00));
2032   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2033   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2034   EXPECT_NEVER_OVERFLOWS(A.unsignedAddMayOverflow(B1));
2035   EXPECT_MAY_OVERFLOW(A.unsignedAddMayOverflow(B2));
2036   EXPECT_NEVER_OVERFLOWS(B1.unsignedAddMayOverflow(A));
2037   EXPECT_MAY_OVERFLOW(B2.unsignedAddMayOverflow(A));
2038 
2039   ConstantRange C1(APInt(16, 0x0299), APInt(16, 0x0400));
2040   ConstantRange C2(APInt(16, 0x0300), APInt(16, 0x0400));
2041   EXPECT_MAY_OVERFLOW(A.unsignedAddMayOverflow(C1));
2042   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.unsignedAddMayOverflow(C2));
2043   EXPECT_MAY_OVERFLOW(C1.unsignedAddMayOverflow(A));
2044   EXPECT_ALWAYS_OVERFLOWS_HIGH(C2.unsignedAddMayOverflow(A));
2045 }
2046 
2047 TEST_F(ConstantRangeTest, UnsignedSubOverflow) {
2048   // Ill-defined - may overflow is a conservative result.
2049   EXPECT_MAY_OVERFLOW(Some.unsignedSubMayOverflow(Empty));
2050   EXPECT_MAY_OVERFLOW(Empty.unsignedSubMayOverflow(Some));
2051 
2052   // Never overflow despite one full/wrap set.
2053   ConstantRange Zero(APInt::getZero(16));
2054   ConstantRange Max(APInt::getAllOnes(16));
2055   EXPECT_NEVER_OVERFLOWS(Full.unsignedSubMayOverflow(Zero));
2056   EXPECT_NEVER_OVERFLOWS(Wrap.unsignedSubMayOverflow(Zero));
2057   EXPECT_NEVER_OVERFLOWS(Max.unsignedSubMayOverflow(Full));
2058   EXPECT_NEVER_OVERFLOWS(Max.unsignedSubMayOverflow(Wrap));
2059 
2060   // But usually full/wrap always may overflow.
2061   EXPECT_MAY_OVERFLOW(Full.unsignedSubMayOverflow(One));
2062   EXPECT_MAY_OVERFLOW(Wrap.unsignedSubMayOverflow(One));
2063   EXPECT_MAY_OVERFLOW(One.unsignedSubMayOverflow(Full));
2064   EXPECT_MAY_OVERFLOW(One.unsignedSubMayOverflow(Wrap));
2065 
2066   ConstantRange A(APInt(16, 0x0000), APInt(16, 0x0100));
2067   ConstantRange B(APInt(16, 0x0100), APInt(16, 0x0200));
2068   EXPECT_NEVER_OVERFLOWS(B.unsignedSubMayOverflow(A));
2069   EXPECT_ALWAYS_OVERFLOWS_LOW(A.unsignedSubMayOverflow(B));
2070 
2071   ConstantRange A1(APInt(16, 0x0000), APInt(16, 0x0101));
2072   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2073   EXPECT_NEVER_OVERFLOWS(B1.unsignedSubMayOverflow(A1));
2074   EXPECT_MAY_OVERFLOW(A1.unsignedSubMayOverflow(B1));
2075 
2076   ConstantRange A2(APInt(16, 0x0000), APInt(16, 0x0102));
2077   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2078   EXPECT_MAY_OVERFLOW(B2.unsignedSubMayOverflow(A2));
2079   EXPECT_MAY_OVERFLOW(A2.unsignedSubMayOverflow(B2));
2080 }
2081 
2082 TEST_F(ConstantRangeTest, SignedAddOverflow) {
2083   // Ill-defined - may overflow is a conservative result.
2084   EXPECT_MAY_OVERFLOW(Some.signedAddMayOverflow(Empty));
2085   EXPECT_MAY_OVERFLOW(Empty.signedAddMayOverflow(Some));
2086 
2087   // Never overflow despite one full/wrap set.
2088   ConstantRange Zero(APInt::getZero(16));
2089   EXPECT_NEVER_OVERFLOWS(Full.signedAddMayOverflow(Zero));
2090   EXPECT_NEVER_OVERFLOWS(Wrap.signedAddMayOverflow(Zero));
2091   EXPECT_NEVER_OVERFLOWS(Zero.signedAddMayOverflow(Full));
2092   EXPECT_NEVER_OVERFLOWS(Zero.signedAddMayOverflow(Wrap));
2093 
2094   // But usually full/wrap always may overflow.
2095   EXPECT_MAY_OVERFLOW(Full.signedAddMayOverflow(One));
2096   EXPECT_MAY_OVERFLOW(Wrap.signedAddMayOverflow(One));
2097   EXPECT_MAY_OVERFLOW(One.signedAddMayOverflow(Full));
2098   EXPECT_MAY_OVERFLOW(One.signedAddMayOverflow(Wrap));
2099 
2100   ConstantRange A(APInt(16, 0x7d00), APInt(16, 0x7e00));
2101   ConstantRange B1(APInt(16, 0x0100), APInt(16, 0x0201));
2102   ConstantRange B2(APInt(16, 0x0100), APInt(16, 0x0202));
2103   EXPECT_NEVER_OVERFLOWS(A.signedAddMayOverflow(B1));
2104   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B2));
2105   ConstantRange B3(APInt(16, 0x8000), APInt(16, 0x0201));
2106   ConstantRange B4(APInt(16, 0x8000), APInt(16, 0x0202));
2107   EXPECT_NEVER_OVERFLOWS(A.signedAddMayOverflow(B3));
2108   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B4));
2109   ConstantRange B5(APInt(16, 0x0299), APInt(16, 0x0400));
2110   ConstantRange B6(APInt(16, 0x0300), APInt(16, 0x0400));
2111   EXPECT_MAY_OVERFLOW(A.signedAddMayOverflow(B5));
2112   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.signedAddMayOverflow(B6));
2113 
2114   ConstantRange C(APInt(16, 0x8200), APInt(16, 0x8300));
2115   ConstantRange D1(APInt(16, 0xfe00), APInt(16, 0xff00));
2116   ConstantRange D2(APInt(16, 0xfd99), APInt(16, 0xff00));
2117   EXPECT_NEVER_OVERFLOWS(C.signedAddMayOverflow(D1));
2118   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D2));
2119   ConstantRange D3(APInt(16, 0xfe00), APInt(16, 0x8000));
2120   ConstantRange D4(APInt(16, 0xfd99), APInt(16, 0x8000));
2121   EXPECT_NEVER_OVERFLOWS(C.signedAddMayOverflow(D3));
2122   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D4));
2123   ConstantRange D5(APInt(16, 0xfc00), APInt(16, 0xfd02));
2124   ConstantRange D6(APInt(16, 0xfc00), APInt(16, 0xfd01));
2125   EXPECT_MAY_OVERFLOW(C.signedAddMayOverflow(D5));
2126   EXPECT_ALWAYS_OVERFLOWS_LOW(C.signedAddMayOverflow(D6));
2127 
2128   ConstantRange E(APInt(16, 0xff00), APInt(16, 0x0100));
2129   EXPECT_NEVER_OVERFLOWS(E.signedAddMayOverflow(E));
2130   ConstantRange F(APInt(16, 0xf000), APInt(16, 0x7000));
2131   EXPECT_MAY_OVERFLOW(F.signedAddMayOverflow(F));
2132 }
2133 
2134 TEST_F(ConstantRangeTest, SignedSubOverflow) {
2135   // Ill-defined - may overflow is a conservative result.
2136   EXPECT_MAY_OVERFLOW(Some.signedSubMayOverflow(Empty));
2137   EXPECT_MAY_OVERFLOW(Empty.signedSubMayOverflow(Some));
2138 
2139   // Never overflow despite one full/wrap set.
2140   ConstantRange Zero(APInt::getZero(16));
2141   EXPECT_NEVER_OVERFLOWS(Full.signedSubMayOverflow(Zero));
2142   EXPECT_NEVER_OVERFLOWS(Wrap.signedSubMayOverflow(Zero));
2143 
2144   // But usually full/wrap always may overflow.
2145   EXPECT_MAY_OVERFLOW(Full.signedSubMayOverflow(One));
2146   EXPECT_MAY_OVERFLOW(Wrap.signedSubMayOverflow(One));
2147   EXPECT_MAY_OVERFLOW(One.signedSubMayOverflow(Full));
2148   EXPECT_MAY_OVERFLOW(One.signedSubMayOverflow(Wrap));
2149 
2150   ConstantRange A(APInt(16, 0x7d00), APInt(16, 0x7e00));
2151   ConstantRange B1(APInt(16, 0xfe00), APInt(16, 0xff00));
2152   ConstantRange B2(APInt(16, 0xfd99), APInt(16, 0xff00));
2153   EXPECT_NEVER_OVERFLOWS(A.signedSubMayOverflow(B1));
2154   EXPECT_MAY_OVERFLOW(A.signedSubMayOverflow(B2));
2155   ConstantRange B3(APInt(16, 0xfc00), APInt(16, 0xfd02));
2156   ConstantRange B4(APInt(16, 0xfc00), APInt(16, 0xfd01));
2157   EXPECT_MAY_OVERFLOW(A.signedSubMayOverflow(B3));
2158   EXPECT_ALWAYS_OVERFLOWS_HIGH(A.signedSubMayOverflow(B4));
2159 
2160   ConstantRange C(APInt(16, 0x8200), APInt(16, 0x8300));
2161   ConstantRange D1(APInt(16, 0x0100), APInt(16, 0x0201));
2162   ConstantRange D2(APInt(16, 0x0100), APInt(16, 0x0202));
2163   EXPECT_NEVER_OVERFLOWS(C.signedSubMayOverflow(D1));
2164   EXPECT_MAY_OVERFLOW(C.signedSubMayOverflow(D2));
2165   ConstantRange D3(APInt(16, 0x0299), APInt(16, 0x0400));
2166   ConstantRange D4(APInt(16, 0x0300), APInt(16, 0x0400));
2167   EXPECT_MAY_OVERFLOW(C.signedSubMayOverflow(D3));
2168   EXPECT_ALWAYS_OVERFLOWS_LOW(C.signedSubMayOverflow(D4));
2169 
2170   ConstantRange E(APInt(16, 0xff00), APInt(16, 0x0100));
2171   EXPECT_NEVER_OVERFLOWS(E.signedSubMayOverflow(E));
2172   ConstantRange F(APInt(16, 0xf000), APInt(16, 0x7001));
2173   EXPECT_MAY_OVERFLOW(F.signedSubMayOverflow(F));
2174 }
2175 
2176 template<typename Fn1, typename Fn2>
2177 static void TestOverflowExhaustive(Fn1 OverflowFn, Fn2 MayOverflowFn) {
2178   // Constant range overflow checks are tested exhaustively on 4-bit numbers.
2179   unsigned Bits = 4;
2180   EnumerateTwoConstantRanges(Bits, [=](const ConstantRange &CR1,
2181                                        const ConstantRange &CR2) {
2182     // Loop over all N1 in CR1 and N2 in CR2 and check whether any of the
2183     // operations have overflow / have no overflow.
2184     bool RangeHasOverflowLow = false;
2185     bool RangeHasOverflowHigh = false;
2186     bool RangeHasNoOverflow = false;
2187     ForeachNumInConstantRange(CR1, [&](const APInt &N1) {
2188       ForeachNumInConstantRange(CR2, [&](const APInt &N2) {
2189         bool IsOverflowHigh;
2190         if (!OverflowFn(IsOverflowHigh, N1, N2)) {
2191           RangeHasNoOverflow = true;
2192           return;
2193         }
2194 
2195         if (IsOverflowHigh)
2196           RangeHasOverflowHigh = true;
2197         else
2198           RangeHasOverflowLow = true;
2199       });
2200     });
2201 
2202     ConstantRange::OverflowResult OR = MayOverflowFn(CR1, CR2);
2203     switch (OR) {
2204     case ConstantRange::OverflowResult::AlwaysOverflowsLow:
2205       EXPECT_TRUE(RangeHasOverflowLow);
2206       EXPECT_FALSE(RangeHasOverflowHigh);
2207       EXPECT_FALSE(RangeHasNoOverflow);
2208       break;
2209     case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
2210       EXPECT_TRUE(RangeHasOverflowHigh);
2211       EXPECT_FALSE(RangeHasOverflowLow);
2212       EXPECT_FALSE(RangeHasNoOverflow);
2213       break;
2214     case ConstantRange::OverflowResult::NeverOverflows:
2215       EXPECT_FALSE(RangeHasOverflowLow);
2216       EXPECT_FALSE(RangeHasOverflowHigh);
2217       EXPECT_TRUE(RangeHasNoOverflow);
2218       break;
2219     case ConstantRange::OverflowResult::MayOverflow:
2220       // We return MayOverflow for empty sets as a conservative result,
2221       // but of course neither the RangeHasOverflow nor the
2222       // RangeHasNoOverflow flags will be set.
2223       if (CR1.isEmptySet() || CR2.isEmptySet())
2224         break;
2225 
2226       EXPECT_TRUE(RangeHasOverflowLow || RangeHasOverflowHigh);
2227       EXPECT_TRUE(RangeHasNoOverflow);
2228       break;
2229     }
2230   });
2231 }
2232 
2233 TEST_F(ConstantRangeTest, UnsignedAddOverflowExhaustive) {
2234   TestOverflowExhaustive(
2235       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2236         bool Overflow;
2237         (void) N1.uadd_ov(N2, Overflow);
2238         IsOverflowHigh = true;
2239         return Overflow;
2240       },
2241       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2242         return CR1.unsignedAddMayOverflow(CR2);
2243       });
2244 }
2245 
2246 TEST_F(ConstantRangeTest, UnsignedSubOverflowExhaustive) {
2247   TestOverflowExhaustive(
2248       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2249         bool Overflow;
2250         (void) N1.usub_ov(N2, Overflow);
2251         IsOverflowHigh = false;
2252         return Overflow;
2253       },
2254       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2255         return CR1.unsignedSubMayOverflow(CR2);
2256       });
2257 }
2258 
2259 TEST_F(ConstantRangeTest, UnsignedMulOverflowExhaustive) {
2260   TestOverflowExhaustive(
2261       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2262         bool Overflow;
2263         (void) N1.umul_ov(N2, Overflow);
2264         IsOverflowHigh = true;
2265         return Overflow;
2266       },
2267       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2268         return CR1.unsignedMulMayOverflow(CR2);
2269       });
2270 }
2271 
2272 TEST_F(ConstantRangeTest, SignedAddOverflowExhaustive) {
2273   TestOverflowExhaustive(
2274       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2275         bool Overflow;
2276         (void) N1.sadd_ov(N2, Overflow);
2277         IsOverflowHigh = N1.isNonNegative();
2278         return Overflow;
2279       },
2280       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2281         return CR1.signedAddMayOverflow(CR2);
2282       });
2283 }
2284 
2285 TEST_F(ConstantRangeTest, SignedSubOverflowExhaustive) {
2286   TestOverflowExhaustive(
2287       [](bool &IsOverflowHigh, const APInt &N1, const APInt &N2) {
2288         bool Overflow;
2289         (void) N1.ssub_ov(N2, Overflow);
2290         IsOverflowHigh = N1.isNonNegative();
2291         return Overflow;
2292       },
2293       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2294         return CR1.signedSubMayOverflow(CR2);
2295       });
2296 }
2297 
2298 TEST_F(ConstantRangeTest, FromKnownBits) {
2299   KnownBits Unknown(16);
2300   EXPECT_EQ(Full, ConstantRange::fromKnownBits(Unknown, /*signed*/false));
2301   EXPECT_EQ(Full, ConstantRange::fromKnownBits(Unknown, /*signed*/true));
2302 
2303   // .10..01. -> unsigned 01000010 (66)  to 11011011 (219)
2304   //          -> signed   11000010 (194) to 01011011 (91)
2305   KnownBits Known(8);
2306   Known.Zero = 36;
2307   Known.One = 66;
2308   ConstantRange Unsigned(APInt(8, 66), APInt(8, 219 + 1));
2309   ConstantRange Signed(APInt(8, 194), APInt(8, 91 + 1));
2310   EXPECT_EQ(Unsigned, ConstantRange::fromKnownBits(Known, /*signed*/false));
2311   EXPECT_EQ(Signed, ConstantRange::fromKnownBits(Known, /*signed*/true));
2312 
2313   // 1.10.10. -> 10100100 (164) to 11101101 (237)
2314   Known.Zero = 18;
2315   Known.One = 164;
2316   ConstantRange CR1(APInt(8, 164), APInt(8, 237 + 1));
2317   EXPECT_EQ(CR1, ConstantRange::fromKnownBits(Known, /*signed*/false));
2318   EXPECT_EQ(CR1, ConstantRange::fromKnownBits(Known, /*signed*/true));
2319 
2320   // 01.0.1.0 -> 01000100 (68) to 01101110 (110)
2321   Known.Zero = 145;
2322   Known.One = 68;
2323   ConstantRange CR2(APInt(8, 68), APInt(8, 110 + 1));
2324   EXPECT_EQ(CR2, ConstantRange::fromKnownBits(Known, /*signed*/false));
2325   EXPECT_EQ(CR2, ConstantRange::fromKnownBits(Known, /*signed*/true));
2326 }
2327 
2328 TEST_F(ConstantRangeTest, FromKnownBitsExhaustive) {
2329   unsigned Bits = 4;
2330   unsigned Max = 1 << Bits;
2331   KnownBits Known(Bits);
2332   for (unsigned Zero = 0; Zero < Max; ++Zero) {
2333     for (unsigned One = 0; One < Max; ++One) {
2334       Known.Zero = Zero;
2335       Known.One = One;
2336       if (Known.hasConflict() || Known.isUnknown())
2337         continue;
2338 
2339       UnsignedOpRangeGatherer UR(Bits);
2340       SignedOpRangeGatherer SR(Bits);
2341       for (unsigned N = 0; N < Max; ++N) {
2342         APInt Num(Bits, N);
2343         if ((Num & Known.Zero) != 0 || (~Num & Known.One) != 0)
2344           continue;
2345 
2346         UR.account(Num);
2347         SR.account(Num);
2348       }
2349 
2350       ConstantRange UnsignedCR = UR.getRange();
2351       ConstantRange SignedCR = SR.getRange();
2352       EXPECT_EQ(UnsignedCR, ConstantRange::fromKnownBits(Known, false));
2353       EXPECT_EQ(SignedCR, ConstantRange::fromKnownBits(Known, true));
2354     }
2355   }
2356 }
2357 
2358 TEST_F(ConstantRangeTest, Negative) {
2359   // All elements in an empty set (of which there are none) are both negative
2360   // and non-negative. Empty & full sets checked explicitly for clarity, but
2361   // they are also covered by the exhaustive test below.
2362   EXPECT_TRUE(Empty.isAllNegative());
2363   EXPECT_TRUE(Empty.isAllNonNegative());
2364   EXPECT_FALSE(Full.isAllNegative());
2365   EXPECT_FALSE(Full.isAllNonNegative());
2366 
2367   unsigned Bits = 4;
2368   EnumerateConstantRanges(Bits, [](const ConstantRange &CR) {
2369     bool AllNegative = true;
2370     bool AllNonNegative = true;
2371     ForeachNumInConstantRange(CR, [&](const APInt &N) {
2372       if (!N.isNegative())
2373         AllNegative = false;
2374       if (!N.isNonNegative())
2375         AllNonNegative = false;
2376     });
2377     assert((CR.isEmptySet() || !AllNegative || !AllNonNegative) &&
2378            "Only empty set can be both all negative and all non-negative");
2379 
2380     EXPECT_EQ(AllNegative, CR.isAllNegative());
2381     EXPECT_EQ(AllNonNegative, CR.isAllNonNegative());
2382   });
2383 }
2384 
2385 TEST_F(ConstantRangeTest, UAddSat) {
2386   TestBinaryOpExhaustive(
2387       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2388         return CR1.uadd_sat(CR2);
2389       },
2390       [](const APInt &N1, const APInt &N2) {
2391         return N1.uadd_sat(N2);
2392       },
2393       PreferSmallestUnsigned);
2394 }
2395 
2396 TEST_F(ConstantRangeTest, USubSat) {
2397   TestBinaryOpExhaustive(
2398       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2399         return CR1.usub_sat(CR2);
2400       },
2401       [](const APInt &N1, const APInt &N2) {
2402         return N1.usub_sat(N2);
2403       },
2404       PreferSmallestUnsigned);
2405 }
2406 
2407 TEST_F(ConstantRangeTest, UMulSat) {
2408   TestBinaryOpExhaustive(
2409       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2410         return CR1.umul_sat(CR2);
2411       },
2412       [](const APInt &N1, const APInt &N2) { return N1.umul_sat(N2); },
2413       PreferSmallestUnsigned);
2414 }
2415 
2416 TEST_F(ConstantRangeTest, UShlSat) {
2417   TestBinaryOpExhaustive(
2418       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2419         return CR1.ushl_sat(CR2);
2420       },
2421       [](const APInt &N1, const APInt &N2) { return N1.ushl_sat(N2); },
2422       PreferSmallestUnsigned);
2423 }
2424 
2425 TEST_F(ConstantRangeTest, SAddSat) {
2426   TestBinaryOpExhaustive(
2427       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2428         return CR1.sadd_sat(CR2);
2429       },
2430       [](const APInt &N1, const APInt &N2) {
2431         return N1.sadd_sat(N2);
2432       },
2433       PreferSmallestSigned);
2434 }
2435 
2436 TEST_F(ConstantRangeTest, SSubSat) {
2437   TestBinaryOpExhaustive(
2438       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2439         return CR1.ssub_sat(CR2);
2440       },
2441       [](const APInt &N1, const APInt &N2) {
2442         return N1.ssub_sat(N2);
2443       },
2444       PreferSmallestSigned);
2445 }
2446 
2447 TEST_F(ConstantRangeTest, SMulSat) {
2448   TestBinaryOpExhaustive(
2449       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2450         return CR1.smul_sat(CR2);
2451       },
2452       [](const APInt &N1, const APInt &N2) { return N1.smul_sat(N2); },
2453       PreferSmallestSigned);
2454 }
2455 
2456 TEST_F(ConstantRangeTest, SShlSat) {
2457   TestBinaryOpExhaustive(
2458       [](const ConstantRange &CR1, const ConstantRange &CR2) {
2459         return CR1.sshl_sat(CR2);
2460       },
2461       [](const APInt &N1, const APInt &N2) { return N1.sshl_sat(N2); },
2462       PreferSmallestSigned);
2463 }
2464 
2465 TEST_F(ConstantRangeTest, Abs) {
2466   TestUnaryOpExhaustive(
2467       [](const ConstantRange &CR) { return CR.abs(); },
2468       [](const APInt &N) { return N.abs(); });
2469 
2470   TestUnaryOpExhaustive(
2471       [](const ConstantRange &CR) { return CR.abs(/*IntMinIsPoison=*/true); },
2472       [](const APInt &N) -> Optional<APInt> {
2473         if (N.isMinSignedValue())
2474           return None;
2475         return N.abs();
2476       });
2477 }
2478 
2479 TEST_F(ConstantRangeTest, castOps) {
2480   ConstantRange A(APInt(16, 66), APInt(16, 128));
2481   ConstantRange FpToI8 = A.castOp(Instruction::FPToSI, 8);
2482   EXPECT_EQ(8u, FpToI8.getBitWidth());
2483   EXPECT_TRUE(FpToI8.isFullSet());
2484 
2485   ConstantRange FpToI16 = A.castOp(Instruction::FPToSI, 16);
2486   EXPECT_EQ(16u, FpToI16.getBitWidth());
2487   EXPECT_EQ(A, FpToI16);
2488 
2489   ConstantRange FPExtToDouble = A.castOp(Instruction::FPExt, 64);
2490   EXPECT_EQ(64u, FPExtToDouble.getBitWidth());
2491   EXPECT_TRUE(FPExtToDouble.isFullSet());
2492 
2493   ConstantRange PtrToInt = A.castOp(Instruction::PtrToInt, 64);
2494   EXPECT_EQ(64u, PtrToInt.getBitWidth());
2495   EXPECT_TRUE(PtrToInt.isFullSet());
2496 
2497   ConstantRange IntToPtr = A.castOp(Instruction::IntToPtr, 64);
2498   EXPECT_EQ(64u, IntToPtr.getBitWidth());
2499   EXPECT_TRUE(IntToPtr.isFullSet());
2500 }
2501 
2502 TEST_F(ConstantRangeTest, binaryXor) {
2503   // Single element ranges.
2504   ConstantRange R16(APInt(8, 16));
2505   ConstantRange R20(APInt(8, 20));
2506   EXPECT_EQ(*R16.binaryXor(R16).getSingleElement(), APInt(8, 0));
2507   EXPECT_EQ(*R16.binaryXor(R20).getSingleElement(), APInt(8, 16 ^ 20));
2508 
2509   // Ranges with more than a single element. Handled conservatively for now.
2510   ConstantRange R16_35(APInt(8, 16), APInt(8, 35));
2511   ConstantRange R0_99(APInt(8, 0), APInt(8, 99));
2512   EXPECT_TRUE(R16_35.binaryXor(R16_35).isFullSet());
2513   EXPECT_TRUE(R16_35.binaryXor(R0_99).isFullSet());
2514   EXPECT_TRUE(R0_99.binaryXor(R16_35).isFullSet());
2515 }
2516 
2517 TEST_F(ConstantRangeTest, binaryNot) {
2518   TestUnaryOpExhaustive(
2519       [](const ConstantRange &CR) { return CR.binaryNot(); },
2520       [](const APInt &N) { return ~N; },
2521       PreferSmallest);
2522   TestUnaryOpExhaustive(
2523       [](const ConstantRange &CR) {
2524         return CR.binaryXor(ConstantRange(APInt::getAllOnes(CR.getBitWidth())));
2525       },
2526       [](const APInt &N) { return ~N; }, PreferSmallest);
2527   TestUnaryOpExhaustive(
2528       [](const ConstantRange &CR) {
2529         return ConstantRange(APInt::getAllOnes(CR.getBitWidth())).binaryXor(CR);
2530       },
2531       [](const APInt &N) { return ~N; }, PreferSmallest);
2532 }
2533 
2534 }  // anonymous namespace
2535