[clang] [clang] Add clang::preferred_type attribute for bitfields (PR #69104)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Thu Oct 19 09:34:21 PDT 2023


AaronBallman wrote:

> Taking the example above, I think it would have to look the following way to fully complement a check for bit-field width in `preferred_type`:
> 
> ```c++
>  enum StoredNameKind : unsigned _BitInt(3) { 
> ... snip ...
>```
> I think we can robustly diagnose new enumerators if the code is written this way. 

There's some danger here. `_BitInt` is a C23 feature as are enumerations with a fixed underlying type. Enumerations with a fixed underlying type *explicitly* disallow using a bit-precise integer type as the underlying type. See C23 6.7.2.2p4, which says in part, "For all the integer constant expressions which make up the values of the enumeration constants, there shall be a type capable of representing all the values that is a standard or extended signed or unsigned integer type, or char.".

So relying on `_BitInt` as the underlying type isn't going to work in C unless we wish to ignore that constraint. Further, we might wish to extend that constraint to C++ use of `_BitInt` (to ease accidental header compatibility issues) for similar reasons to why it was restricted in C.

I'm still thinking my way through a `non_storable` attribute, but on its face, it seems like it could be overkill. I suspect (but haven't measured!) that there is *way* more code out there that maps enumerations to bit-fields that expect all members of the enumeration to be possible to store than there is code that has a sentinel value not expected to be used. I kind of wonder if the correct answer to those more exceptional situations is "don't use this attribute, you're not doing a straight mapping in this case." Would it perhaps make sense to handle the common path first, see what usage experience finds in the wild, and then consider `non_storable` in the future?

https://github.com/llvm/llvm-project/pull/69104


More information about the cfe-commits mailing list