From ad3e0e4b419461bbc56a79a33167e93141ba5859 Mon Sep 17 00:00:00 2001 From: Simon Pilgrim Date: Tue, 3 Jan 2023 16:10:06 +0000 Subject: [PATCH] [APInt] Add APInt::isOneBitSet helper. 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 | 7 +++++++ llvm/unittests/ADT/APIntTest.cpp | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/llvm/include/llvm/ADT/APInt.h b/llvm/include/llvm/ADT/APInt.h index ab8bf3e..4b08868 100644 --- a/llvm/include/llvm/ADT/APInt.h +++ b/llvm/include/llvm/ADT/APInt.h @@ -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) diff --git a/llvm/unittests/ADT/APIntTest.cpp b/llvm/unittests/ADT/APIntTest.cpp index e7632c0..0377e05 100644 --- a/llvm/unittests/ADT/APIntTest.cpp +++ b/llvm/unittests/ADT/APIntTest.cpp @@ -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()); -- 2.7.4