[APInt] Add APInt::isOneBitSet helper.
authorSimon Pilgrim <llvm-dev@redking.me.uk>
Tue, 3 Jan 2023 16:10:06 +0000 (16:10 +0000)
committerSimon Pilgrim <llvm-dev@redking.me.uk>
Tue, 3 Jan 2023 16:10:29 +0000 (16:10 +0000)
Equivalent tester for the APInt::getOneBitSet builder.

This should allow us to remove a number of cases where we're doing "Val == (1 << BitNo)" style code patterns.

llvm/include/llvm/ADT/APInt.h
llvm/unittests/ADT/APIntTest.cpp

index ab8bf3e..4b08868 100644 (file)
@@ -343,6 +343,13 @@ public:
   /// \returns true if this APInt is non-positive.
   bool isNonPositive() const { return !isStrictlyPositive(); }
 
+  /// Determine if this APInt Value only has the specified bit set.
+  ///
+  /// \returns true if this APInt only has the specified bit set.
+  bool isOneBitSet(unsigned BitNo) const {
+    return (*this)[BitNo] && countPopulation() == 1;
+  }
+
   /// Determine if all bits are set.  This is true for zero-width values.
   bool isAllOnes() const {
     if (BitWidth == 0)
index e7632c0..0377e05 100644 (file)
@@ -1793,6 +1793,16 @@ TEST(APIntTest, isShiftedMask) {
   }
 }
 
+TEST(APIntTest, isOneBitSet) {
+  EXPECT_FALSE(APInt(5, 0x00).isOneBitSet(0));
+  EXPECT_FALSE(APInt(5, 0x02).isOneBitSet(0));
+  EXPECT_FALSE(APInt(5, 0x03).isOneBitSet(0));
+  EXPECT_TRUE(APInt(5, 0x02).isOneBitSet(1));
+  EXPECT_TRUE(APInt(32, (unsigned)(0xffu << 31)).isOneBitSet(31));
+
+  EXPECT_TRUE(APInt::getOneBitSet(255, 13).isOneBitSet(13));
+}
+
 TEST(APIntTest, isPowerOf2) {
   EXPECT_FALSE(APInt(5, 0x00).isPowerOf2());
   EXPECT_FALSE(APInt(32, 0x11).isPowerOf2());