diff --git a/llvm/include/llvm/Support/KnownBits.h b/llvm/include/llvm/Support/KnownBits.h --- a/llvm/include/llvm/Support/KnownBits.h +++ b/llvm/include/llvm/Support/KnownBits.h @@ -249,7 +249,8 @@ return countMinLeadingZeros(); if (isNegative()) return countMinLeadingOnes(); - return 0; + // Every value has at least 1 sign bit. + return 1; } /// Returns the maximum number of trailing zero bits possible. diff --git a/llvm/unittests/Support/KnownBitsTest.cpp b/llvm/unittests/Support/KnownBitsTest.cpp --- a/llvm/unittests/Support/KnownBitsTest.cpp +++ b/llvm/unittests/Support/KnownBitsTest.cpp @@ -442,6 +442,17 @@ }); } +TEST(KnownBitsTest, CountMinSignedBits) { + const unsigned Bits = 4; + ForeachKnownBits(Bits, [&](const KnownBits &Known) { + unsigned Expected = Bits; + ForeachNumInKnownBits(Known, [&](const APInt &N) { + Expected = std::min(Expected, N.getNumSignBits()); + }); + EXPECT_EQ(Expected, Known.countMinSignBits()); + }); +} + TEST(KnownBitsTest, SExtOrTrunc) { const unsigned NarrowerSize = 4; const unsigned BaseSize = 6;