xref: /llvm-project/llvm/unittests/Support/KnownBitsTest.cpp (revision 4aba595f092e8e05e92656b23944ce6619465a78)
1 //===- llvm/unittest/Support/KnownBitsTest.cpp - KnownBits 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 // This file implements unit tests for KnownBits functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/Support/KnownBits.h"
15 #include "KnownBitsTest.h"
16 #include "gtest/gtest.h"
17 
18 using namespace llvm;
19 
20 using UnaryBitsFn = llvm::function_ref<KnownBits(const KnownBits &)>;
21 using UnaryIntFn = llvm::function_ref<std::optional<APInt>(const APInt &)>;
22 using UnaryCheckFn = llvm::function_ref<bool(const KnownBits &)>;
23 
24 using BinaryBitsFn =
25     llvm::function_ref<KnownBits(const KnownBits &, const KnownBits &)>;
26 using BinaryIntFn =
27     llvm::function_ref<std::optional<APInt>(const APInt &, const APInt &)>;
28 using BinaryCheckFn =
29     llvm::function_ref<bool(const KnownBits &, const KnownBits &)>;
30 
31 static bool checkOptimalityUnary(const KnownBits &) { return true; }
32 static bool checkCorrectnessOnlyUnary(const KnownBits &) { return false; }
33 static bool checkOptimalityBinary(const KnownBits &, const KnownBits &) {
34   return true;
35 }
36 static bool checkCorrectnessOnlyBinary(const KnownBits &, const KnownBits &) {
37   return false;
38 }
39 
40 static testing::AssertionResult isCorrect(const KnownBits &Exact,
41                                           const KnownBits &Computed,
42                                           ArrayRef<KnownBits> Inputs) {
43   if (Computed.Zero.isSubsetOf(Exact.Zero) &&
44       Computed.One.isSubsetOf(Exact.One))
45     return testing::AssertionSuccess();
46 
47   testing::AssertionResult Result = testing::AssertionFailure();
48   Result << "Inputs = ";
49   for (const KnownBits &Input : Inputs)
50     Result << Input << ", ";
51   Result << "Computed = " << Computed << ", Exact = " << Exact;
52   return Result;
53 }
54 
55 static testing::AssertionResult isOptimal(const KnownBits &Exact,
56                                           const KnownBits &Computed,
57                                           ArrayRef<KnownBits> Inputs) {
58   if (Computed == Exact)
59     return testing::AssertionSuccess();
60 
61   testing::AssertionResult Result = testing::AssertionFailure();
62   Result << "Inputs = ";
63   for (const KnownBits &Input : Inputs)
64     Result << Input << ", ";
65   Result << "Computed = " << Computed << ", Exact = " << Exact;
66   return Result;
67 }
68 
69 static void
70 testUnaryOpExhaustive(UnaryBitsFn BitsFn, UnaryIntFn IntFn,
71                       UnaryCheckFn CheckOptimalityFn = checkOptimalityUnary) {
72   for (unsigned Bits : {1, 4}) {
73     ForeachKnownBits(Bits, [&](const KnownBits &Known) {
74       KnownBits Computed = BitsFn(Known);
75       KnownBits Exact(Bits);
76       Exact.Zero.setAllBits();
77       Exact.One.setAllBits();
78 
79       ForeachNumInKnownBits(Known, [&](const APInt &N) {
80         if (std::optional<APInt> Res = IntFn(N)) {
81           Exact.One &= *Res;
82           Exact.Zero &= ~*Res;
83         }
84       });
85 
86       EXPECT_TRUE(!Computed.hasConflict());
87       EXPECT_TRUE(isCorrect(Exact, Computed, Known));
88       // We generally don't want to return conflicting known bits, even if it is
89       // legal for always poison results.
90       if (CheckOptimalityFn(Known) && !Exact.hasConflict()) {
91         EXPECT_TRUE(isOptimal(Exact, Computed, Known));
92       }
93     });
94   }
95 }
96 
97 static void
98 testBinaryOpExhaustive(BinaryBitsFn BitsFn, BinaryIntFn IntFn,
99                        BinaryCheckFn CheckOptimalityFn = checkOptimalityBinary,
100                        bool RefinePoisonToZero = false) {
101   for (unsigned Bits : {1, 4}) {
102     ForeachKnownBits(Bits, [&](const KnownBits &Known1) {
103       ForeachKnownBits(Bits, [&](const KnownBits &Known2) {
104         KnownBits Computed = BitsFn(Known1, Known2);
105         KnownBits Exact(Bits);
106         Exact.Zero.setAllBits();
107         Exact.One.setAllBits();
108 
109         ForeachNumInKnownBits(Known1, [&](const APInt &N1) {
110           ForeachNumInKnownBits(Known2, [&](const APInt &N2) {
111             if (std::optional<APInt> Res = IntFn(N1, N2)) {
112               Exact.One &= *Res;
113               Exact.Zero &= ~*Res;
114             }
115           });
116         });
117 
118         EXPECT_TRUE(!Computed.hasConflict());
119         EXPECT_TRUE(isCorrect(Exact, Computed, {Known1, Known2}));
120         // We generally don't want to return conflicting known bits, even if it
121         // is legal for always poison results.
122         if (CheckOptimalityFn(Known1, Known2) && !Exact.hasConflict()) {
123           EXPECT_TRUE(isOptimal(Exact, Computed, {Known1, Known2}));
124         }
125         // In some cases we choose to return zero if the result is always
126         // poison.
127         if (RefinePoisonToZero && Exact.hasConflict()) {
128           EXPECT_TRUE(Computed.isZero());
129         }
130       });
131     });
132   }
133 }
134 
135 namespace {
136 
137 TEST(KnownBitsTest, AddCarryExhaustive) {
138   unsigned Bits = 4;
139   ForeachKnownBits(Bits, [&](const KnownBits &Known1) {
140     ForeachKnownBits(Bits, [&](const KnownBits &Known2) {
141       ForeachKnownBits(1, [&](const KnownBits &KnownCarry) {
142         // Explicitly compute known bits of the addition by trying all
143         // possibilities.
144         KnownBits Known(Bits);
145         Known.Zero.setAllBits();
146         Known.One.setAllBits();
147         ForeachNumInKnownBits(Known1, [&](const APInt &N1) {
148           ForeachNumInKnownBits(Known2, [&](const APInt &N2) {
149             ForeachNumInKnownBits(KnownCarry, [&](const APInt &Carry) {
150               APInt Add = N1 + N2;
151               if (Carry.getBoolValue())
152                 ++Add;
153 
154               Known.One &= Add;
155               Known.Zero &= ~Add;
156             });
157           });
158         });
159 
160         KnownBits KnownComputed =
161             KnownBits::computeForAddCarry(Known1, Known2, KnownCarry);
162         EXPECT_EQ(Known, KnownComputed);
163       });
164     });
165   });
166 }
167 
168 static void TestAddSubExhaustive(bool IsAdd) {
169   unsigned Bits = 4;
170   ForeachKnownBits(Bits, [&](const KnownBits &Known1) {
171     ForeachKnownBits(Bits, [&](const KnownBits &Known2) {
172       KnownBits Known(Bits), KnownNSW(Bits), KnownNUW(Bits),
173           KnownNSWAndNUW(Bits);
174       Known.Zero.setAllBits();
175       Known.One.setAllBits();
176       KnownNSW.Zero.setAllBits();
177       KnownNSW.One.setAllBits();
178       KnownNUW.Zero.setAllBits();
179       KnownNUW.One.setAllBits();
180       KnownNSWAndNUW.Zero.setAllBits();
181       KnownNSWAndNUW.One.setAllBits();
182 
183       ForeachNumInKnownBits(Known1, [&](const APInt &N1) {
184         ForeachNumInKnownBits(Known2, [&](const APInt &N2) {
185           bool SignedOverflow;
186           bool UnsignedOverflow;
187           APInt Res;
188           if (IsAdd) {
189             Res = N1.uadd_ov(N2, UnsignedOverflow);
190             Res = N1.sadd_ov(N2, SignedOverflow);
191           } else {
192             Res = N1.usub_ov(N2, UnsignedOverflow);
193             Res = N1.ssub_ov(N2, SignedOverflow);
194           }
195 
196           Known.One &= Res;
197           Known.Zero &= ~Res;
198 
199           if (!SignedOverflow) {
200             KnownNSW.One &= Res;
201             KnownNSW.Zero &= ~Res;
202           }
203 
204           if (!UnsignedOverflow) {
205             KnownNUW.One &= Res;
206             KnownNUW.Zero &= ~Res;
207           }
208 
209           if (!UnsignedOverflow && !SignedOverflow) {
210             KnownNSWAndNUW.One &= Res;
211             KnownNSWAndNUW.Zero &= ~Res;
212           }
213         });
214       });
215 
216       KnownBits KnownComputed = KnownBits::computeForAddSub(
217           IsAdd, /*NSW=*/false, /*NUW=*/false, Known1, Known2);
218       EXPECT_TRUE(isOptimal(Known, KnownComputed, {Known1, Known2}));
219 
220       KnownBits KnownNSWComputed = KnownBits::computeForAddSub(
221           IsAdd, /*NSW=*/true, /*NUW=*/false, Known1, Known2);
222       if (!KnownNSW.hasConflict())
223         EXPECT_TRUE(isOptimal(KnownNSW, KnownNSWComputed, {Known1, Known2}));
224 
225       KnownBits KnownNUWComputed = KnownBits::computeForAddSub(
226           IsAdd, /*NSW=*/false, /*NUW=*/true, Known1, Known2);
227       if (!KnownNUW.hasConflict())
228         EXPECT_TRUE(isOptimal(KnownNUW, KnownNUWComputed, {Known1, Known2}));
229 
230       KnownBits KnownNSWAndNUWComputed = KnownBits::computeForAddSub(
231           IsAdd, /*NSW=*/true, /*NUW=*/true, Known1, Known2);
232       if (!KnownNSWAndNUW.hasConflict())
233         EXPECT_TRUE(isOptimal(KnownNSWAndNUW, KnownNSWAndNUWComputed,
234                               {Known1, Known2}));
235     });
236   });
237 }
238 
239 TEST(KnownBitsTest, AddSubExhaustive) {
240   TestAddSubExhaustive(true);
241   TestAddSubExhaustive(false);
242 }
243 
244 TEST(KnownBitsTest, SubBorrowExhaustive) {
245   unsigned Bits = 4;
246   ForeachKnownBits(Bits, [&](const KnownBits &Known1) {
247     ForeachKnownBits(Bits, [&](const KnownBits &Known2) {
248       ForeachKnownBits(1, [&](const KnownBits &KnownBorrow) {
249         // Explicitly compute known bits of the subtraction by trying all
250         // possibilities.
251         KnownBits Known(Bits);
252         Known.Zero.setAllBits();
253         Known.One.setAllBits();
254         ForeachNumInKnownBits(Known1, [&](const APInt &N1) {
255           ForeachNumInKnownBits(Known2, [&](const APInt &N2) {
256             ForeachNumInKnownBits(KnownBorrow, [&](const APInt &Borrow) {
257               APInt Sub = N1 - N2;
258               if (Borrow.getBoolValue())
259                 --Sub;
260 
261               Known.One &= Sub;
262               Known.Zero &= ~Sub;
263             });
264           });
265         });
266 
267         KnownBits KnownComputed =
268             KnownBits::computeForSubBorrow(Known1, Known2, KnownBorrow);
269         EXPECT_EQ(Known, KnownComputed);
270       });
271     });
272   });
273 }
274 
275 TEST(KnownBitsTest, SignBitUnknown) {
276   KnownBits Known(2);
277   EXPECT_TRUE(Known.isSignUnknown());
278   Known.Zero.setBit(0);
279   EXPECT_TRUE(Known.isSignUnknown());
280   Known.Zero.setBit(1);
281   EXPECT_FALSE(Known.isSignUnknown());
282   Known.Zero.clearBit(0);
283   EXPECT_FALSE(Known.isSignUnknown());
284   Known.Zero.clearBit(1);
285   EXPECT_TRUE(Known.isSignUnknown());
286 
287   Known.One.setBit(0);
288   EXPECT_TRUE(Known.isSignUnknown());
289   Known.One.setBit(1);
290   EXPECT_FALSE(Known.isSignUnknown());
291   Known.One.clearBit(0);
292   EXPECT_FALSE(Known.isSignUnknown());
293   Known.One.clearBit(1);
294   EXPECT_TRUE(Known.isSignUnknown());
295 }
296 
297 TEST(KnownBitsTest, ABDUSpecialCase) {
298   // There are 2 implementations of abdu - both are currently needed to cover
299   // extra cases.
300   KnownBits LHS, RHS, Res;
301 
302   // abdu(LHS,RHS) = sub(umax(LHS,RHS), umin(LHS,RHS)).
303   // Actual: false (Inputs = 1011, 101?, Computed = 000?, Exact = 000?)
304   LHS.One = APInt(4, 0b1011);
305   RHS.One = APInt(4, 0b1010);
306   LHS.Zero = APInt(4, 0b0100);
307   RHS.Zero = APInt(4, 0b0100);
308   Res = KnownBits::abdu(LHS, RHS);
309   EXPECT_EQ(0b0000ul, Res.One.getZExtValue());
310   EXPECT_EQ(0b1110ul, Res.Zero.getZExtValue());
311 
312   // find the common bits between sub(LHS,RHS) and sub(RHS,LHS).
313   // Actual: false (Inputs = ???1, 1000, Computed = ???1, Exact = 0??1)
314   LHS.One = APInt(4, 0b0001);
315   RHS.One = APInt(4, 0b1000);
316   LHS.Zero = APInt(4, 0b0000);
317   RHS.Zero = APInt(4, 0b0111);
318   Res = KnownBits::abdu(LHS, RHS);
319   EXPECT_EQ(0b0001ul, Res.One.getZExtValue());
320   EXPECT_EQ(0b0000ul, Res.Zero.getZExtValue());
321 }
322 
323 TEST(KnownBitsTest, ABDSSpecialCase) {
324   // There are 2 implementations of abds - both are currently needed to cover
325   // extra cases.
326   KnownBits LHS, RHS, Res;
327 
328   // abds(LHS,RHS) = sub(smax(LHS,RHS), smin(LHS,RHS)).
329   // Actual: false (Inputs = 1011, 10??, Computed = ????, Exact = 00??)
330   LHS.One = APInt(4, 0b1011);
331   RHS.One = APInt(4, 0b1000);
332   LHS.Zero = APInt(4, 0b0100);
333   RHS.Zero = APInt(4, 0b0100);
334   Res = KnownBits::abds(LHS, RHS);
335   EXPECT_EQ(0, Res.One.getSExtValue());
336   EXPECT_EQ(-4, Res.Zero.getSExtValue());
337 
338   // find the common bits between sub(LHS,RHS) and sub(RHS,LHS).
339   // Actual: false (Inputs = ???1, 1000, Computed = ???1, Exact = 0??1)
340   LHS.One = APInt(4, 0b0001);
341   RHS.One = APInt(4, 0b1000);
342   LHS.Zero = APInt(4, 0b0000);
343   RHS.Zero = APInt(4, 0b0111);
344   Res = KnownBits::abds(LHS, RHS);
345   EXPECT_EQ(1, Res.One.getSExtValue());
346   EXPECT_EQ(0, Res.Zero.getSExtValue());
347 }
348 
349 TEST(KnownBitsTest, BinaryExhaustive) {
350   testBinaryOpExhaustive(
351       [](const KnownBits &Known1, const KnownBits &Known2) {
352         return Known1 & Known2;
353       },
354       [](const APInt &N1, const APInt &N2) { return N1 & N2; });
355   testBinaryOpExhaustive(
356       [](const KnownBits &Known1, const KnownBits &Known2) {
357         return Known1 | Known2;
358       },
359       [](const APInt &N1, const APInt &N2) { return N1 | N2; });
360   testBinaryOpExhaustive(
361       [](const KnownBits &Known1, const KnownBits &Known2) {
362         return Known1 ^ Known2;
363       },
364       [](const APInt &N1, const APInt &N2) { return N1 ^ N2; });
365   testBinaryOpExhaustive(KnownBits::umax, APIntOps::umax);
366   testBinaryOpExhaustive(KnownBits::umin, APIntOps::umin);
367   testBinaryOpExhaustive(KnownBits::smax, APIntOps::smax);
368   testBinaryOpExhaustive(KnownBits::smin, APIntOps::smin);
369   testBinaryOpExhaustive(KnownBits::abdu, APIntOps::abdu,
370                          checkCorrectnessOnlyBinary);
371   testBinaryOpExhaustive(KnownBits::abds, APIntOps::abds,
372                          checkCorrectnessOnlyBinary);
373   testBinaryOpExhaustive(
374       [](const KnownBits &Known1, const KnownBits &Known2) {
375         return KnownBits::udiv(Known1, Known2);
376       },
377       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
378         if (N2.isZero())
379           return std::nullopt;
380         return N1.udiv(N2);
381       },
382       checkCorrectnessOnlyBinary);
383   testBinaryOpExhaustive(
384       [](const KnownBits &Known1, const KnownBits &Known2) {
385         return KnownBits::udiv(Known1, Known2, /*Exact*/ true);
386       },
387       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
388         if (N2.isZero() || !N1.urem(N2).isZero())
389           return std::nullopt;
390         return N1.udiv(N2);
391       },
392       checkCorrectnessOnlyBinary);
393   testBinaryOpExhaustive(
394       [](const KnownBits &Known1, const KnownBits &Known2) {
395         return KnownBits::sdiv(Known1, Known2);
396       },
397       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
398         if (N2.isZero() || (N1.isMinSignedValue() && N2.isAllOnes()))
399           return std::nullopt;
400         return N1.sdiv(N2);
401       },
402       checkCorrectnessOnlyBinary);
403   testBinaryOpExhaustive(
404       [](const KnownBits &Known1, const KnownBits &Known2) {
405         return KnownBits::sdiv(Known1, Known2, /*Exact*/ true);
406       },
407       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
408         if (N2.isZero() || (N1.isMinSignedValue() && N2.isAllOnes()) ||
409             !N1.srem(N2).isZero())
410           return std::nullopt;
411         return N1.sdiv(N2);
412       },
413       checkCorrectnessOnlyBinary);
414   testBinaryOpExhaustive(
415       KnownBits::urem,
416       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
417         if (N2.isZero())
418           return std::nullopt;
419         return N1.urem(N2);
420       },
421       checkCorrectnessOnlyBinary);
422   testBinaryOpExhaustive(
423       KnownBits::srem,
424       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
425         if (N2.isZero())
426           return std::nullopt;
427         return N1.srem(N2);
428       },
429       checkCorrectnessOnlyBinary);
430   testBinaryOpExhaustive(
431       KnownBits::sadd_sat,
432       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
433         return N1.sadd_sat(N2);
434       },
435       checkCorrectnessOnlyBinary);
436   testBinaryOpExhaustive(
437       KnownBits::uadd_sat,
438       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
439         return N1.uadd_sat(N2);
440       },
441       checkCorrectnessOnlyBinary);
442   testBinaryOpExhaustive(
443       KnownBits::ssub_sat,
444       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
445         return N1.ssub_sat(N2);
446       },
447       checkCorrectnessOnlyBinary);
448   testBinaryOpExhaustive(
449       KnownBits::usub_sat,
450       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
451         return N1.usub_sat(N2);
452       },
453       checkCorrectnessOnlyBinary);
454   testBinaryOpExhaustive(
455       [](const KnownBits &Known1, const KnownBits &Known2) {
456         return KnownBits::shl(Known1, Known2);
457       },
458       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
459         if (N2.uge(N2.getBitWidth()))
460           return std::nullopt;
461         return N1.shl(N2);
462       },
463       checkOptimalityBinary, /* RefinePoisonToZero */ true);
464   testBinaryOpExhaustive(
465       [](const KnownBits &Known1, const KnownBits &Known2) {
466         return KnownBits::shl(Known1, Known2, /* NUW */ true);
467       },
468       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
469         bool Overflow;
470         APInt Res = N1.ushl_ov(N2, Overflow);
471         if (Overflow)
472           return std::nullopt;
473         return Res;
474       },
475       checkOptimalityBinary, /* RefinePoisonToZero */ true);
476   testBinaryOpExhaustive(
477       [](const KnownBits &Known1, const KnownBits &Known2) {
478         return KnownBits::shl(Known1, Known2, /* NUW */ false, /* NSW */ true);
479       },
480       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
481         bool Overflow;
482         APInt Res = N1.sshl_ov(N2, Overflow);
483         if (Overflow)
484           return std::nullopt;
485         return Res;
486       },
487       checkOptimalityBinary, /* RefinePoisonToZero */ true);
488   testBinaryOpExhaustive(
489       [](const KnownBits &Known1, const KnownBits &Known2) {
490         return KnownBits::shl(Known1, Known2, /* NUW */ true, /* NSW */ true);
491       },
492       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
493         bool OverflowUnsigned, OverflowSigned;
494         APInt Res = N1.ushl_ov(N2, OverflowUnsigned);
495         (void)N1.sshl_ov(N2, OverflowSigned);
496         if (OverflowUnsigned || OverflowSigned)
497           return std::nullopt;
498         return Res;
499       },
500       checkOptimalityBinary, /* RefinePoisonToZero */ true);
501 
502   testBinaryOpExhaustive(
503       [](const KnownBits &Known1, const KnownBits &Known2) {
504         return KnownBits::lshr(Known1, Known2);
505       },
506       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
507         if (N2.uge(N2.getBitWidth()))
508           return std::nullopt;
509         return N1.lshr(N2);
510       },
511       checkOptimalityBinary, /* RefinePoisonToZero */ true);
512   testBinaryOpExhaustive(
513       [](const KnownBits &Known1, const KnownBits &Known2) {
514         return KnownBits::lshr(Known1, Known2, /*ShAmtNonZero=*/false,
515                                /*Exact=*/true);
516       },
517       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
518         if (N2.uge(N2.getBitWidth()))
519           return std::nullopt;
520         if (!N1.extractBits(N2.getZExtValue(), 0).isZero())
521           return std::nullopt;
522         return N1.lshr(N2);
523       },
524       checkOptimalityBinary, /* RefinePoisonToZero */ true);
525   testBinaryOpExhaustive(
526       [](const KnownBits &Known1, const KnownBits &Known2) {
527         return KnownBits::ashr(Known1, Known2);
528       },
529       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
530         if (N2.uge(N2.getBitWidth()))
531           return std::nullopt;
532         return N1.ashr(N2);
533       },
534       checkOptimalityBinary, /* RefinePoisonToZero */ true);
535   testBinaryOpExhaustive(
536       [](const KnownBits &Known1, const KnownBits &Known2) {
537         return KnownBits::ashr(Known1, Known2, /*ShAmtNonZero=*/false,
538                                /*Exact=*/true);
539       },
540       [](const APInt &N1, const APInt &N2) -> std::optional<APInt> {
541         if (N2.uge(N2.getBitWidth()))
542           return std::nullopt;
543         if (!N1.extractBits(N2.getZExtValue(), 0).isZero())
544           return std::nullopt;
545         return N1.ashr(N2);
546       },
547       checkOptimalityBinary, /* RefinePoisonToZero */ true);
548   testBinaryOpExhaustive(
549       [](const KnownBits &Known1, const KnownBits &Known2) {
550         return KnownBits::mul(Known1, Known2);
551       },
552       [](const APInt &N1, const APInt &N2) { return N1 * N2; },
553       checkCorrectnessOnlyBinary);
554   testBinaryOpExhaustive(
555       KnownBits::mulhs,
556       [](const APInt &N1, const APInt &N2) { return APIntOps::mulhs(N1, N2); },
557       checkCorrectnessOnlyBinary);
558   testBinaryOpExhaustive(
559       KnownBits::mulhu,
560       [](const APInt &N1, const APInt &N2) { return APIntOps::mulhu(N1, N2); },
561       checkCorrectnessOnlyBinary);
562 }
563 
564 TEST(KnownBitsTest, UnaryExhaustive) {
565   testUnaryOpExhaustive([](const KnownBits &Known) { return Known.abs(); },
566                         [](const APInt &N) { return N.abs(); });
567 
568   testUnaryOpExhaustive([](const KnownBits &Known) { return Known.abs(true); },
569                         [](const APInt &N) -> std::optional<APInt> {
570                           if (N.isMinSignedValue())
571                             return std::nullopt;
572                           return N.abs();
573                         });
574 
575   testUnaryOpExhaustive([](const KnownBits &Known) { return Known.blsi(); },
576                         [](const APInt &N) { return N & -N; });
577   testUnaryOpExhaustive([](const KnownBits &Known) { return Known.blsmsk(); },
578                         [](const APInt &N) { return N ^ (N - 1); });
579 
580   testUnaryOpExhaustive(
581       [](const KnownBits &Known) {
582         return KnownBits::mul(Known, Known, /*SelfMultiply*/ true);
583       },
584       [](const APInt &N) { return N * N; }, checkCorrectnessOnlyUnary);
585 }
586 
587 TEST(KnownBitsTest, WideShifts) {
588   unsigned BitWidth = 128;
589   KnownBits Unknown(BitWidth);
590   KnownBits AllOnes = KnownBits::makeConstant(APInt::getAllOnes(BitWidth));
591 
592   KnownBits ShlResult(BitWidth);
593   ShlResult.makeNegative();
594   EXPECT_EQ(KnownBits::shl(AllOnes, Unknown), ShlResult);
595   KnownBits LShrResult(BitWidth);
596   LShrResult.One.setBit(0);
597   EXPECT_EQ(KnownBits::lshr(AllOnes, Unknown), LShrResult);
598   EXPECT_EQ(KnownBits::ashr(AllOnes, Unknown), AllOnes);
599 }
600 
601 TEST(KnownBitsTest, ICmpExhaustive) {
602   unsigned Bits = 4;
603   ForeachKnownBits(Bits, [&](const KnownBits &Known1) {
604     ForeachKnownBits(Bits, [&](const KnownBits &Known2) {
605       bool AllEQ = true, NoneEQ = true;
606       bool AllNE = true, NoneNE = true;
607       bool AllUGT = true, NoneUGT = true;
608       bool AllUGE = true, NoneUGE = true;
609       bool AllULT = true, NoneULT = true;
610       bool AllULE = true, NoneULE = true;
611       bool AllSGT = true, NoneSGT = true;
612       bool AllSGE = true, NoneSGE = true;
613       bool AllSLT = true, NoneSLT = true;
614       bool AllSLE = true, NoneSLE = true;
615 
616       ForeachNumInKnownBits(Known1, [&](const APInt &N1) {
617         ForeachNumInKnownBits(Known2, [&](const APInt &N2) {
618           AllEQ &= N1.eq(N2);
619           AllNE &= N1.ne(N2);
620           AllUGT &= N1.ugt(N2);
621           AllUGE &= N1.uge(N2);
622           AllULT &= N1.ult(N2);
623           AllULE &= N1.ule(N2);
624           AllSGT &= N1.sgt(N2);
625           AllSGE &= N1.sge(N2);
626           AllSLT &= N1.slt(N2);
627           AllSLE &= N1.sle(N2);
628           NoneEQ &= !N1.eq(N2);
629           NoneNE &= !N1.ne(N2);
630           NoneUGT &= !N1.ugt(N2);
631           NoneUGE &= !N1.uge(N2);
632           NoneULT &= !N1.ult(N2);
633           NoneULE &= !N1.ule(N2);
634           NoneSGT &= !N1.sgt(N2);
635           NoneSGE &= !N1.sge(N2);
636           NoneSLT &= !N1.slt(N2);
637           NoneSLE &= !N1.sle(N2);
638         });
639       });
640 
641       std::optional<bool> KnownEQ = KnownBits::eq(Known1, Known2);
642       std::optional<bool> KnownNE = KnownBits::ne(Known1, Known2);
643       std::optional<bool> KnownUGT = KnownBits::ugt(Known1, Known2);
644       std::optional<bool> KnownUGE = KnownBits::uge(Known1, Known2);
645       std::optional<bool> KnownULT = KnownBits::ult(Known1, Known2);
646       std::optional<bool> KnownULE = KnownBits::ule(Known1, Known2);
647       std::optional<bool> KnownSGT = KnownBits::sgt(Known1, Known2);
648       std::optional<bool> KnownSGE = KnownBits::sge(Known1, Known2);
649       std::optional<bool> KnownSLT = KnownBits::slt(Known1, Known2);
650       std::optional<bool> KnownSLE = KnownBits::sle(Known1, Known2);
651 
652       EXPECT_EQ(AllEQ || NoneEQ, KnownEQ.has_value());
653       EXPECT_EQ(AllNE || NoneNE, KnownNE.has_value());
654       EXPECT_EQ(AllUGT || NoneUGT, KnownUGT.has_value());
655       EXPECT_EQ(AllUGE || NoneUGE, KnownUGE.has_value());
656       EXPECT_EQ(AllULT || NoneULT, KnownULT.has_value());
657       EXPECT_EQ(AllULE || NoneULE, KnownULE.has_value());
658       EXPECT_EQ(AllSGT || NoneSGT, KnownSGT.has_value());
659       EXPECT_EQ(AllSGE || NoneSGE, KnownSGE.has_value());
660       EXPECT_EQ(AllSLT || NoneSLT, KnownSLT.has_value());
661       EXPECT_EQ(AllSLE || NoneSLE, KnownSLE.has_value());
662 
663       EXPECT_EQ(AllEQ, KnownEQ.has_value() && *KnownEQ);
664       EXPECT_EQ(AllNE, KnownNE.has_value() && *KnownNE);
665       EXPECT_EQ(AllUGT, KnownUGT.has_value() && *KnownUGT);
666       EXPECT_EQ(AllUGE, KnownUGE.has_value() && *KnownUGE);
667       EXPECT_EQ(AllULT, KnownULT.has_value() && *KnownULT);
668       EXPECT_EQ(AllULE, KnownULE.has_value() && *KnownULE);
669       EXPECT_EQ(AllSGT, KnownSGT.has_value() && *KnownSGT);
670       EXPECT_EQ(AllSGE, KnownSGE.has_value() && *KnownSGE);
671       EXPECT_EQ(AllSLT, KnownSLT.has_value() && *KnownSLT);
672       EXPECT_EQ(AllSLE, KnownSLE.has_value() && *KnownSLE);
673 
674       EXPECT_EQ(NoneEQ, KnownEQ.has_value() && !*KnownEQ);
675       EXPECT_EQ(NoneNE, KnownNE.has_value() && !*KnownNE);
676       EXPECT_EQ(NoneUGT, KnownUGT.has_value() && !*KnownUGT);
677       EXPECT_EQ(NoneUGE, KnownUGE.has_value() && !*KnownUGE);
678       EXPECT_EQ(NoneULT, KnownULT.has_value() && !*KnownULT);
679       EXPECT_EQ(NoneULE, KnownULE.has_value() && !*KnownULE);
680       EXPECT_EQ(NoneSGT, KnownSGT.has_value() && !*KnownSGT);
681       EXPECT_EQ(NoneSGE, KnownSGE.has_value() && !*KnownSGE);
682       EXPECT_EQ(NoneSLT, KnownSLT.has_value() && !*KnownSLT);
683       EXPECT_EQ(NoneSLE, KnownSLE.has_value() && !*KnownSLE);
684     });
685   });
686 }
687 
688 TEST(KnownBitsTest, GetMinMaxVal) {
689   unsigned Bits = 4;
690   ForeachKnownBits(Bits, [&](const KnownBits &Known) {
691     APInt Min = APInt::getMaxValue(Bits);
692     APInt Max = APInt::getMinValue(Bits);
693     ForeachNumInKnownBits(Known, [&](const APInt &N) {
694       Min = APIntOps::umin(Min, N);
695       Max = APIntOps::umax(Max, N);
696     });
697     EXPECT_EQ(Min, Known.getMinValue());
698     EXPECT_EQ(Max, Known.getMaxValue());
699   });
700 }
701 
702 TEST(KnownBitsTest, GetSignedMinMaxVal) {
703   unsigned Bits = 4;
704   ForeachKnownBits(Bits, [&](const KnownBits &Known) {
705     APInt Min = APInt::getSignedMaxValue(Bits);
706     APInt Max = APInt::getSignedMinValue(Bits);
707     ForeachNumInKnownBits(Known, [&](const APInt &N) {
708       Min = APIntOps::smin(Min, N);
709       Max = APIntOps::smax(Max, N);
710     });
711     EXPECT_EQ(Min, Known.getSignedMinValue());
712     EXPECT_EQ(Max, Known.getSignedMaxValue());
713   });
714 }
715 
716 TEST(KnownBitsTest, CountMaxActiveBits) {
717   unsigned Bits = 4;
718   ForeachKnownBits(Bits, [&](const KnownBits &Known) {
719     unsigned Expected = 0;
720     ForeachNumInKnownBits(Known, [&](const APInt &N) {
721       Expected = std::max(Expected, N.getActiveBits());
722     });
723     EXPECT_EQ(Expected, Known.countMaxActiveBits());
724   });
725 }
726 
727 TEST(KnownBitsTest, CountMaxSignificantBits) {
728   unsigned Bits = 4;
729   ForeachKnownBits(Bits, [&](const KnownBits &Known) {
730     unsigned Expected = 0;
731     ForeachNumInKnownBits(Known, [&](const APInt &N) {
732       Expected = std::max(Expected, N.getSignificantBits());
733     });
734     EXPECT_EQ(Expected, Known.countMaxSignificantBits());
735   });
736 }
737 
738 TEST(KnownBitsTest, SExtOrTrunc) {
739   const unsigned NarrowerSize = 4;
740   const unsigned BaseSize = 6;
741   const unsigned WiderSize = 8;
742   APInt NegativeFitsNarrower(BaseSize, -4, /*isSigned*/ true);
743   APInt NegativeDoesntFitNarrower(BaseSize, -28, /*isSigned*/ true);
744   APInt PositiveFitsNarrower(BaseSize, 14);
745   APInt PositiveDoesntFitNarrower(BaseSize, 36);
746   auto InitKnownBits = [&](KnownBits &Res, const APInt &Input) {
747     Res = KnownBits(Input.getBitWidth());
748     Res.One = Input;
749     Res.Zero = ~Input;
750   };
751 
752   for (unsigned Size : {NarrowerSize, BaseSize, WiderSize}) {
753     for (const APInt &Input :
754          {NegativeFitsNarrower, NegativeDoesntFitNarrower, PositiveFitsNarrower,
755           PositiveDoesntFitNarrower}) {
756       KnownBits Test;
757       InitKnownBits(Test, Input);
758       KnownBits Baseline;
759       InitKnownBits(Baseline, Input.sextOrTrunc(Size));
760       Test = Test.sextOrTrunc(Size);
761       EXPECT_EQ(Test, Baseline);
762     }
763   }
764 }
765 
766 TEST(KnownBitsTest, SExtInReg) {
767   unsigned Bits = 4;
768   for (unsigned FromBits = 1; FromBits <= Bits; ++FromBits) {
769     ForeachKnownBits(Bits, [&](const KnownBits &Known) {
770       APInt CommonOne = APInt::getAllOnes(Bits);
771       APInt CommonZero = APInt::getAllOnes(Bits);
772       unsigned ExtBits = Bits - FromBits;
773       ForeachNumInKnownBits(Known, [&](const APInt &N) {
774         APInt Ext = N << ExtBits;
775         Ext.ashrInPlace(ExtBits);
776         CommonOne &= Ext;
777         CommonZero &= ~Ext;
778       });
779       KnownBits KnownSExtInReg = Known.sextInReg(FromBits);
780       EXPECT_EQ(CommonOne, KnownSExtInReg.One);
781       EXPECT_EQ(CommonZero, KnownSExtInReg.Zero);
782     });
783   }
784 }
785 
786 TEST(KnownBitsTest, CommonBitsSet) {
787   unsigned Bits = 4;
788   ForeachKnownBits(Bits, [&](const KnownBits &Known1) {
789     ForeachKnownBits(Bits, [&](const KnownBits &Known2) {
790       bool HasCommonBitsSet = false;
791       ForeachNumInKnownBits(Known1, [&](const APInt &N1) {
792         ForeachNumInKnownBits(Known2, [&](const APInt &N2) {
793           HasCommonBitsSet |= N1.intersects(N2);
794         });
795       });
796       EXPECT_EQ(!HasCommonBitsSet,
797                 KnownBits::haveNoCommonBitsSet(Known1, Known2));
798     });
799   });
800 }
801 
802 TEST(KnownBitsTest, ConcatBits) {
803   unsigned Bits = 4;
804   for (unsigned LoBits = 1; LoBits < Bits; ++LoBits) {
805     unsigned HiBits = Bits - LoBits;
806     ForeachKnownBits(LoBits, [&](const KnownBits &KnownLo) {
807       ForeachKnownBits(HiBits, [&](const KnownBits &KnownHi) {
808         KnownBits KnownAll = KnownHi.concat(KnownLo);
809 
810         EXPECT_EQ(KnownLo.countMinPopulation() + KnownHi.countMinPopulation(),
811                   KnownAll.countMinPopulation());
812         EXPECT_EQ(KnownLo.countMaxPopulation() + KnownHi.countMaxPopulation(),
813                   KnownAll.countMaxPopulation());
814 
815         KnownBits ExtractLo = KnownAll.extractBits(LoBits, 0);
816         KnownBits ExtractHi = KnownAll.extractBits(HiBits, LoBits);
817 
818         EXPECT_EQ(KnownLo.One.getZExtValue(), ExtractLo.One.getZExtValue());
819         EXPECT_EQ(KnownHi.One.getZExtValue(), ExtractHi.One.getZExtValue());
820         EXPECT_EQ(KnownLo.Zero.getZExtValue(), ExtractLo.Zero.getZExtValue());
821         EXPECT_EQ(KnownHi.Zero.getZExtValue(), ExtractHi.Zero.getZExtValue());
822       });
823     });
824   }
825 }
826 
827 } // end anonymous namespace
828