diff --git a/llvm/include/llvm/Support/KnownBits.h b/llvm/include/llvm/Support/KnownBits.h index 1f32760a6fd1..1674bad21e95 100644 --- a/llvm/include/llvm/Support/KnownBits.h +++ b/llvm/include/llvm/Support/KnownBits.h @@ -249,7 +249,14 @@ public: return countMinLeadingZeros(); if (isNegative()) return countMinLeadingOnes(); - return 0; + // Every value has at least 1 sign bit. + return 1; + } + + /// Returns the maximum number of bits needed to represent all possible + /// signed values with these known bits. + unsigned countMaxSignedBits() const { + return getBitWidth() - countMinSignBits() + 1; } /// Returns the maximum number of trailing zero bits possible. diff --git a/llvm/unittests/Support/KnownBitsTest.cpp b/llvm/unittests/Support/KnownBitsTest.cpp index f9631f29902f..d41402b69fc0 100644 --- a/llvm/unittests/Support/KnownBitsTest.cpp +++ b/llvm/unittests/Support/KnownBitsTest.cpp @@ -442,6 +442,17 @@ TEST(KnownBitsTest, CountMaxActiveBits) { }); } +TEST(KnownBitsTest, CountMaxSignedBits) { + unsigned Bits = 4; + ForeachKnownBits(Bits, [&](const KnownBits &Known) { + unsigned Expected = 0; + ForeachNumInKnownBits(Known, [&](const APInt &N) { + Expected = std::max(Expected, N.getMinSignedBits()); + }); + EXPECT_EQ(Expected, Known.countMaxSignedBits()); + }); +} + TEST(KnownBitsTest, SExtOrTrunc) { const unsigned NarrowerSize = 4; const unsigned BaseSize = 6;