second draft: add Bitfields to D

Timon Gehr timon.gehr at gmx.ch
Mon May 6 20:37:47 UTC 2024


On 5/6/24 09:14, Walter Bright wrote:
> On 5/5/2024 2:08 AM, Timon Gehr wrote:
>> GCC 11.4.0, clang 14.0.0:
>>
>> ```c
>> #include <stdio.h>
>> struct __attribute__((packed)) S{
>>      long long x:8;
>> };
>> int main(){
>>      printf("%ld\n",sizeof(long long)); // 8
>>      printf("%ld\n",sizeof(struct S)); // 1
>> }
>> ```
> 
> The sizeof there, in both cases, is giving the size in bytes of the 
> memory object the field is a subset of.
> ...

This is C and neither sizeof is on a memory object, they are both on 
types. sizeof on x gives a compile error. However, with the DIP, given 
that you implement packed bitfields in DMD, when importing an example 
like this one, `x.sizeof` would be eight times as big as the size of the 
`struct` it is a part of.

> 
>> Maybe at least redefine `.sizeof` to give the size of the underlying 
>> storage unit for a bitfield.
> 
> That's what it's doing in the example.
> ...

Well, the DIP now says `bitfield.sizeof` is `typeof(bitfield).sizeof`. 
Unless I misunderstand and `typeof(x)` is not `long long`, this should 
not be the case in this example, because a `long long` is longer than 
the memory location it is packed into in this case. (I think this is 
another broken invariant.)

> BTW, I didn't implement packed bitfields in ImportC. It never occurred 
> to me :-/ I suppose it should get a bugzilla issue.
> 
> https://issues.dlang.org/show_bug.cgi?id=24538

Well, that will help, but the point was the C standard does not give the 
guarantees you assumed to hold earlier, and in practice it in fact does 
not hold, as in this example.


More information about the dip.development mailing list