[clang] a0f8890 - [clang][C23] Support N3029 Improved Normal Enumerations (#103917)

via cfe-commits cfe-commits at lists.llvm.org
Fri Sep 13 02:11:38 PDT 2024


Author: Mariya Podchishchaeva
Date: 2024-09-13T11:11:34+02:00
New Revision: a0f88901a4e6a6618c3ec02108103d0415e28834

URL: https://github.com/llvm/llvm-project/commit/a0f88901a4e6a6618c3ec02108103d0415e28834
DIFF: https://github.com/llvm/llvm-project/commit/a0f88901a4e6a6618c3ec02108103d0415e28834.diff

LOG: [clang][C23] Support N3029 Improved Normal Enumerations (#103917)

Basically clang already implemented 90% of the feature as an extension.
This commit disables warnings for C23 and aligns types of enumerators
according to the recent wording.

Added: 
    clang/test/C/C23/n3029.c

Modified: 
    clang/docs/ReleaseNotes.rst
    clang/include/clang/Basic/DiagnosticSemaKinds.td
    clang/lib/Sema/SemaDecl.cpp
    clang/test/Misc/warning-flags.c
    clang/test/Sema/enum.c
    clang/www/c_status.html

Removed: 
    


################################################################################
diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c4fa017b982bbd..3929a9fb599259 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -179,6 +179,8 @@ C2y Feature Support
 C23 Feature Support
 ^^^^^^^^^^^^^^^^^^^
 
+- Clang now supports `N3029 <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3029.htm>`_ Improved Normal Enumerations.
+
 Non-comprehensive list of changes in this release
 -------------------------------------------------
 

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index efdc058edca56d..3a465464bc5b47 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1039,7 +1039,6 @@ def err_opencl_invalid_param : Error<
   "declaring function parameter of type %0 is not allowed%select{; did you forget * ?|}1">;
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you forget * ?|}1">;
-def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup<IgnoredPragmas>;
@@ -6194,9 +6193,13 @@ def err_misplaced_ivar : Error<
 def warn_ivars_in_interface : Warning<
   "declaration of instance variables in the interface is deprecated">,
   InGroup<DiagGroup<"objc-interface-ivars">>, DefaultIgnore;
-def ext_enum_value_not_int : Extension<
-  "ISO C restricts enumerator values to range of 'int' (%0 is too "
-  "%select{small|large}1)">;
+def ext_c23_enum_value_not_int : Extension<
+  "%select{|incremented }0enumerator value which exceeds the range of 'int' is "
+  "a C23 extension (%1 is too %select{small|large}2)">, InGroup<C23>;
+def warn_c17_compat_enum_value_not_int : Warning<
+  "%select{|incremented }0enumerator value which exceeds the range of 'int' is "
+  "incompatible with C standards before C23 (%1 is too %select{small|large}2)">,
+  DefaultIgnore, InGroup<CPre23Compat>;
 def ext_enum_too_large : ExtWarn<
   "enumeration values exceed range of largest integer">, InGroup<EnumTooLarge>;
 def ext_enumerator_increment_too_large : ExtWarn<

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 3c6a0dff798ff6..8557c25b93a8da 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -19479,11 +19479,13 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
           //   representable as an int.
 
           // Complain if the value is not representable in an int.
-          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
-            Diag(IdLoc, diag::ext_enum_value_not_int)
-              << toString(EnumVal, 10) << Val->getSourceRange()
-              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
-          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
+          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) {
+            Diag(IdLoc, getLangOpts().C23
+                            ? diag::warn_c17_compat_enum_value_not_int
+                            : diag::ext_c23_enum_value_not_int)
+                << 0 << toString(EnumVal, 10) << Val->getSourceRange()
+                << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
+          } else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
             // Force the type of the expression to 'int'.
             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
           }
@@ -19558,17 +19560,22 @@ EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
 
         // If we're not in C++, diagnose the overflow of enumerator values,
         // which in C99 means that the enumerator value is not representable in
-        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
-        // permits enumerator values that are representable in some larger
-        // integral type.
-        if (!getLangOpts().CPlusPlus && !T.isNull())
-          Diag(IdLoc, diag::warn_enum_value_overflow);
-      } else if (!getLangOpts().CPlusPlus &&
-                 !EltTy->isDependentType() &&
+        // an int (C99 6.7.2.2p2). However C23 permits enumerator values that
+        // are representable in some larger integral type and we allow it in
+        // older language modes as an extension.
+        // Exclude fixed enumerators since they are diagnosed with an error for
+        // this case.
+        if (!getLangOpts().CPlusPlus && !T.isNull() && !Enum->isFixed())
+          Diag(IdLoc, getLangOpts().C23
+                          ? diag::warn_c17_compat_enum_value_not_int
+                          : diag::ext_c23_enum_value_not_int)
+              << 1 << toString(EnumVal, 10) << 1;
+      } else if (!getLangOpts().CPlusPlus && !EltTy->isDependentType() &&
                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
         // Enforce C99 6.7.2.2p2 even when we compute the next value.
-        Diag(IdLoc, diag::ext_enum_value_not_int)
-          << toString(EnumVal, 10) << 1;
+        Diag(IdLoc, getLangOpts().C23 ? diag::warn_c17_compat_enum_value_not_int
+                                      : diag::ext_c23_enum_value_not_int)
+            << 1 << toString(EnumVal, 10) << 1;
       }
     }
   }
@@ -19887,9 +19894,6 @@ void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
     return;
   }
 
-  // TODO: If the result value doesn't fit in an int, it must be a long or long
-  // long value.  ISO C does not support this, but GCC does as an extension,
-  // emit a warning.
   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
@@ -19898,13 +19902,14 @@ void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
   // reverse the list.
   unsigned NumNegativeBits = 0;
   unsigned NumPositiveBits = 0;
+  bool MembersRepresentableByInt = true;
 
   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
     EnumConstantDecl *ECD =
       cast_or_null<EnumConstantDecl>(Elements[i]);
     if (!ECD) continue;  // Already issued a diagnostic.
 
-    const llvm::APSInt &InitVal = ECD->getInitVal();
+    llvm::APSInt InitVal = ECD->getInitVal();
 
     // Keep track of the size of positive and negative values.
     if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
@@ -19916,6 +19921,8 @@ void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
       NumNegativeBits =
           std::max(NumNegativeBits, (unsigned)InitVal.getSignificantBits());
     }
+    MembersRepresentableByInt &=
+        isRepresentableIntegerValue(Context, InitVal, Context.IntTy);
   }
 
   // If we have an empty set of enumerators we still need one bit.
@@ -19937,7 +19944,7 @@ void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
   //   int, long long int, or unsigned long long int.
   // C99 6.4.4.3p2:
   //   An identifier declared as an enumeration constant has type int.
-  // The C99 rule is modified by a gcc extension
+  // The C99 rule is modified by C23.
   QualType BestPromotionType;
 
   bool Packed = Enum->hasAttr<PackedAttr>();
@@ -20031,7 +20038,7 @@ void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
     auto *ECD = cast_or_null<EnumConstantDecl>(D);
     if (!ECD) continue;  // Already issued a diagnostic.
 
-    // Standard C says the enumerators have int type, but we allow, as an
+    // C99 says the enumerators have int type, but we allow, as an
     // extension, the enumerators to be larger than int size.  If each
     // enumerator value fits in an int, type it as an int, otherwise type it the
     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
@@ -20045,9 +20052,14 @@ void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
     QualType NewTy;
     unsigned NewWidth;
     bool NewSign;
-    if (!getLangOpts().CPlusPlus &&
-        !Enum->isFixed() &&
-        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
+    if (!getLangOpts().CPlusPlus && !Enum->isFixed() &&
+        MembersRepresentableByInt) {
+      // C23 6.7.3.3.3p15:
+      // The enumeration member type for an enumerated type without fixed
+      // underlying type upon completion is:
+      //  - int if all the values of the enumeration are representable as an
+      //  int; or,
+      //  - the enumerated type
       NewTy = Context.IntTy;
       NewWidth = IntWidth;
       NewSign = true;

diff  --git a/clang/test/C/C23/n3029.c b/clang/test/C/C23/n3029.c
new file mode 100644
index 00000000000000..26d6dfdcc60462
--- /dev/null
+++ b/clang/test/C/C23/n3029.c
@@ -0,0 +1,65 @@
+// RUN: %clang_cc1 -verify=expected,all -triple x86_64-unknown-linux-gnu -fsyntax-only -std=c23 %s -Wpre-c23-compat
+// RUN: %clang_cc1 -verify=pedantic,all -triple x86_64-unknown-linux-gnu -fsyntax-only -std=c17 %s -pedantic
+
+#include <limits.h>
+
+#define GET_TYPE_INT(x) _Generic(x, \
+  char: 1,\
+  unsigned char: 2,\
+  signed char: 3,\
+  short: 4,\
+  unsigned short: 5,\
+  int: 6,\
+  unsigned int: 7,\
+  long: 8,\
+  unsigned long: 9,\
+  long long: 10,\
+  unsigned long long: 11,\
+  default: 0xFF\
+  )\
+
+enum x {
+a = INT_MAX,
+b = ULLONG_MAX, // expected-warning {{enumerator value which exceeds the range of 'int' is incompatible with C standards before C23}}
+                // pedantic-warning at -1 {{enumerator value which exceeds the range of 'int' is a C23 extension}}
+a_type = GET_TYPE_INT(a),
+b_type = GET_TYPE_INT(b)
+};
+
+_Static_assert(GET_TYPE_INT(a) == GET_TYPE_INT(b), "ok"); 
+
+extern enum x e_a;
+extern __typeof(b) e_a;
+extern __typeof(a) e_a;
+
+enum a {
+  a0 = 0xFFFFFFFFFFFFFFFFULL // expected-warning {{enumerator value which exceeds the range of 'int' is incompatible with C standards before C23}}
+                             // pedantic-warning at -1 {{enumerator value which exceeds the range of 'int' is a C23 extension}}
+};
+
+_Bool e (void) {
+  return a0;
+}
+
+int f (void) {
+  return a0; // all-warning {{implicit conversion from 'unsigned long' to 'int' changes value from 18446744073709551615 to -1}}
+}
+
+unsigned long g (void) {
+  return a0;
+}
+
+unsigned long long h (void) {
+  return a0;
+}
+
+enum big_enum {
+  big_enum_a = LONG_MAX, // expected-warning {{enumerator value which exceeds the range of 'int' is incompatible with C standards before C23}}
+                         // pedantic-warning at -1 {{enumerator value which exceeds the range of 'int' is a C23 extension}}
+  big_enum_b = a + 1, // expected-warning {{enumerator value which exceeds the range of 'int' is incompatible with C standards before C23}}
+                      // pedantic-warning at -1 {{enumerator value which exceeds the range of 'int' is a C23 extension}}
+  big_enum_c = ULLONG_MAX // expected-warning {{enumerator value which exceeds the range of 'int' is incompatible with C standards before C23}}
+                          // pedantic-warning at -1 {{enumerator value which exceeds the range of 'int' is a C23 extension}}
+};
+
+_Static_assert(GET_TYPE_INT(big_enum_a) == GET_TYPE_INT(big_enum_b), "ok");

diff  --git a/clang/test/Misc/warning-flags.c b/clang/test/Misc/warning-flags.c
index e4e16f074cef33..80c01099140f79 100644
--- a/clang/test/Misc/warning-flags.c
+++ b/clang/test/Misc/warning-flags.c
@@ -18,7 +18,7 @@ This test serves two purposes:
 
 The list of warnings below should NEVER grow.  It should gradually shrink to 0.
 
-CHECK: Warnings without flags (63):
+CHECK: Warnings without flags (62):
 
 CHECK-NEXT:   ext_expected_semi_decl_list
 CHECK-NEXT:   ext_missing_whitespace_after_macro_name
@@ -46,7 +46,6 @@ CHECK-NEXT:   warn_drv_amdgpu_cov6
 CHECK-NEXT:   warn_drv_assuming_mfloat_abi_is
 CHECK-NEXT:   warn_drv_clang_unsupported
 CHECK-NEXT:   warn_drv_pch_not_first_include
-CHECK-NEXT:   warn_enum_value_overflow
 CHECK-NEXT:   warn_expected_qualified_after_typename
 CHECK-NEXT:   warn_fe_backend_unsupported
 CHECK-NEXT:   warn_fe_cc_log_diagnostics_failure
@@ -86,4 +85,4 @@ CHECK-NEXT:   warn_weak_import
 
 The list of warnings in -Wpedantic should NEVER grow.
 
-CHECK: Number in -Wpedantic (not covered by other -W flags): 25
+CHECK: Number in -Wpedantic (not covered by other -W flags): 24

diff  --git a/clang/test/Sema/enum.c b/clang/test/Sema/enum.c
index b0707914c0d852..4f6d04ba7f9182 100644
--- a/clang/test/Sema/enum.c
+++ b/clang/test/Sema/enum.c
@@ -1,23 +1,23 @@
-// RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify -pedantic
-// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu %s -fsyntax-only -std=c23 -verify -pedantic
+// RUN: %clang_cc1 -triple %itanium_abi_triple %s -fsyntax-only -verify=expected,pre-c23 -pedantic
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu %s -fsyntax-only -std=c23 -verify=expected -pedantic
 enum e {A,
-        B = 42LL << 32,        // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+        B = 42LL << 32,        // pre-c23-warning {{enumerator value which exceeds the range of 'int' is a C23 extension}}
       C = -4, D = 12456 };
 
 enum f { a = -2147483648, b = 2147483647 }; // ok.
 
 enum g {  // too negative
-   c = -2147483649,         // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+   c = -2147483649,         // pre-c23-warning {{enumerator value which exceeds the range of 'int' is a C23 extension}}
    d = 2147483647 };
 enum h { e = -2147483648, // too pos
-   f = 2147483648,           // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
-  i = 0xFFFF0000 // expected-warning {{too large}}
+   f = 2147483648,           // pre-c23-warning {{enumerator value which exceeds the range of 'int' is a C23 extension}}
+  i = 0xFFFF0000 // pre-c23-warning {{too large}}
 };
 
 // minll maxull
 enum x                      // expected-warning {{enumeration values exceed range of largest integer}}
-{ y = -9223372036854775807LL-1,  // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
-z = 9223372036854775808ULL };    // expected-warning {{ISO C restricts enumerator values to range of 'int'}}
+{ y = -9223372036854775807LL-1,  // pre-c23-warning {{enumerator value which exceeds the range of 'int' is a C23 extension}}
+z = 9223372036854775808ULL };    // pre-c23-warning {{enumerator value which exceeds the range of 'int' is a C23 extension}}
 
 int test(void) {
   return sizeof(enum e) ;
@@ -169,13 +169,16 @@ enum class GH42372_2 {
   One
 };
 
+enum IncOverflow {
+  V2 = __INT_MAX__,
+  V3 // pre-c23-warning {{incremented enumerator value which exceeds the range of 'int' is a C23 extension}}
+};
+
 #if __STDC_VERSION__ >= 202311L
 // FIXME: GCC picks __uint128_t as the underlying type for the enumeration
 // value and Clang picks unsigned long long.
-// FIXME: Clang does not yet implement WG14 N3029, so the warning about
-// restricting enumerator values to 'int' is not correct.
 enum GH59352 { // expected-warning {{enumeration values exceed range of largest integer}}
- BigVal = 66666666666666666666wb // expected-warning {{ISO C restricts enumerator values to range of 'int' (66666666666666666666 is too large)}}
+ BigVal = 66666666666666666666wb
 };
 _Static_assert(BigVal == 66666666666666666666wb); /* expected-error {{static assertion failed due to requirement 'BigVal == 66666666666666666666wb'}}
                                                      expected-note {{expression evaluates to '11326434445538011818 == 66666666666666666666'}}
@@ -191,4 +194,38 @@ _Static_assert(
     __uint128_t : 1
     )
 );
+
+#include <limits.h>
+
+void fooinc23() {
+  enum E1 {
+    V1 = INT_MAX
+  } e1;
+
+  enum E2 {
+    V2 = INT_MAX,
+    V3
+  } e2;
+
+  enum E3 {
+    V4 = INT_MAX,
+    V5 = LONG_MIN
+  } e3;
+
+  enum E4 {
+    V6 = 1u,
+    V7 = 2wb
+  } e4;
+
+  _Static_assert(_Generic(V1, int : 1));
+  _Static_assert(_Generic(V2, int : 0, unsigned int : 1));
+  _Static_assert(_Generic(V3, int : 0, unsigned int : 1));
+  _Static_assert(_Generic(V4, int : 0, signed long : 1));
+  _Static_assert(_Generic(V5, int : 0, signed long : 1));
+  _Static_assert(_Generic(V6, int : 1));
+  _Static_assert(_Generic(V7, int : 1));
+  _Static_assert(_Generic((enum E4){}, unsigned int : 1));
+
+}
+
 #endif // __STDC_VERSION__ >= 202311L

diff  --git a/clang/www/c_status.html b/clang/www/c_status.html
index 255690cd6d34e2..6e37dd65ccbdee 100644
--- a/clang/www/c_status.html
+++ b/clang/www/c_status.html
@@ -687,7 +687,7 @@ <h2 id="c2x">C23 implementation status</h2>
     <tr>
       <td>Improved normal enumerations</td>
       <td><a href="https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3029.htm">N3029</a></td>
-      <td class="unknown" align="center">Unknown</td>
+      <td class="unreleased" align="center">Clang 20</td>
     </tr>
     <tr>
       <td>Relax requirements for va_start</td>


        


More information about the cfe-commits mailing list