[Support] Add KnownBits::getSignedMinValue/getSignedMaxValue helpers.
authorSimon Pilgrim <llvm-dev@redking.me.uk>
Thu, 24 Dec 2020 12:07:55 +0000 (12:07 +0000)
committerSimon Pilgrim <llvm-dev@redking.me.uk>
Thu, 24 Dec 2020 14:10:12 +0000 (14:10 +0000)
Add unit test coverage - a followup will update InstCombineCompares.cpp to use this and could be used by D86578 as well.

llvm/include/llvm/Support/KnownBits.h
llvm/unittests/Support/KnownBitsTest.cpp

index 2acaecfc344020034309549dbcbbdbb1843d53c9..ec88b9807174ae2a4cd4c767f4bf25760ea3e351 100644 (file)
@@ -119,12 +119,32 @@ public:
     return One;
   }
 
+  /// Return the minimal signed value possible given these KnownBits.
+  APInt getSignedMinValue() const {
+    // Assume that all bits that aren't known-ones are zeros.
+    APInt Min = One;
+    // Sign bit is unknown.
+    if (Zero.isSignBitClear() && One.isSignBitClear())
+      Min.setSignBit();
+    return Min;
+  }
+
   /// Return the maximal unsigned value possible given these KnownBits.
   APInt getMaxValue() const {
     // Assume that all bits that aren't known-zeros are ones.
     return ~Zero;
   }
 
+  /// Return the maximal signed value possible given these KnownBits.
+  APInt getSignedMaxValue() const {
+    // Assume that all bits that aren't known-zeros are ones.
+    APInt Max = ~Zero;
+    // Sign bit is unknown.
+    if (Zero.isSignBitClear() && One.isSignBitClear())
+      Max.clearSignBit();
+    return Max;
+  }
+
   /// Return known bits for a truncation of the value we're tracking.
   KnownBits trunc(unsigned BitWidth) const {
     return KnownBits(Zero.trunc(BitWidth), One.trunc(BitWidth));
index c5eb96efc85eed3a3797b5b494ac8ee23e1f5361..528a645ec51ad7e851ef81a96808822d67cd5bae 100644 (file)
@@ -295,6 +295,20 @@ TEST(KnownBitsTest, GetMinMaxVal) {
   });
 }
 
+TEST(KnownBitsTest, GetSignedMinMaxVal) {
+  unsigned Bits = 4;
+  ForeachKnownBits(Bits, [&](const KnownBits &Known) {
+    APInt Min = APInt::getSignedMaxValue(Bits);
+    APInt Max = APInt::getSignedMinValue(Bits);
+    ForeachNumInKnownBits(Known, [&](const APInt &N) {
+      Min = APIntOps::smin(Min, N);
+      Max = APIntOps::smax(Max, N);
+    });
+    EXPECT_EQ(Min, Known.getSignedMinValue());
+    EXPECT_EQ(Max, Known.getSignedMaxValue());
+  });
+}
+
 TEST(KnownBitsTest, SExtOrTrunc) {
   const unsigned NarrowerSize = 4;
   const unsigned BaseSize = 6;