Fix _BitInt suffix width calculation
authorAaron Ballman <aaron@aaronballman.com>
Tue, 22 Mar 2022 14:00:05 +0000 (10:00 -0400)
committerAaron Ballman <aaron@aaronballman.com>
Tue, 22 Mar 2022 14:00:05 +0000 (10:00 -0400)
@mgehre-amd pointed out the following post-commit review feedback on
the changes in 8cba72177dcd8de5d37177dbaf2347e5c1f0f1e8:

As an example, the paper says 3wb /* Yields an _BitInt(3); two value
bits, one sign bit */.
So I would expect that 0xFwb gives _BitInt(5); four value bits, one
sign bit, but with this implementation I get _BitInt(2).
This is because ResultVal as 4 bits, and getMinSignedBits() inteprets
it as negative and thus says that 1 bit is enough to represent -1.

This corrects the behavior for calculating the bit-width and adds some
test coverage.

clang/lib/Sema/SemaExpr.cpp
clang/test/Lexer/bitint-constants.c

index be90c58e066d8285eb0c7431da898165fe038e68..7fdeb7a8e30be329ea455ce33722f0fb8f699ac3 100644 (file)
@@ -3979,8 +3979,8 @@ ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
       if (Literal.isBitInt) {
         // The signed version has one more bit for the sign value. There are no
         // zero-width bit-precise integers, even if the literal value is 0.
-        Width = Literal.isUnsigned ? std::max(ResultVal.getActiveBits(), 1u)
-                                   : std::max(ResultVal.getMinSignedBits(), 2u);
+        Width = std::max(ResultVal.getActiveBits(), 1u) +
+                (Literal.isUnsigned ? 0u : 1u);
 
         // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
         // and reset the type to the largest supported width.
index 243f8c0377c273be26e1dec359e3648cd8215b5f..2ff35e8207786e91ab6d9411bdbdda38d175de13 100644 (file)
@@ -142,3 +142,18 @@ void ValidSuffixInvalidValue(void) {
   0xFFFF'FFFF'FFFF'FFFF'FFFF'FFFF'FFFF'FFFF'1wb; // expected-error {{integer literal is too large to be represented in any signed integer type}}
   0xFFFF'FFFF'FFFF'FFFF'FFFF'FFFF'FFFF'FFFF'1uwb; // expected-error {{integer literal is too large to be represented in any integer type}}
 }
+
+void TestTypes(void) {
+  // 2 value bits, one sign bit
+  _Static_assert(__builtin_types_compatible_p(__typeof__(3wb), _BitInt(3)));
+  // 2 value bits, one sign bit
+  _Static_assert(__builtin_types_compatible_p(__typeof__(-3wb), _BitInt(3)));
+  // 2 value bits, no sign bit
+  _Static_assert(__builtin_types_compatible_p(__typeof__(3uwb), unsigned _BitInt(2)));
+  // 4 value bits, one sign bit
+  _Static_assert(__builtin_types_compatible_p(__typeof__(0xFwb), _BitInt(5)));
+  // 4 value bits, one sign bit
+  _Static_assert(__builtin_types_compatible_p(__typeof__(-0xFwb), _BitInt(5)));
+  // 4 value bits, no sign bit
+  _Static_assert(__builtin_types_compatible_p(__typeof__(0xFuwb), unsigned _BitInt(4)));
+}