PatternLanguage icon indicating copy to clipboard operation
PatternLanguage copied to clipboard

Bitfield order defaults to MostToLeastSignificant in big endian

Open brliron opened this issue 2 years ago • 2 comments

The default bits order for a bitfield (without a bitfield_order attribute) is LeastToMostSignificant, but when switching to big endian with #pragma endian big, that default seems to change to MostToLeastSignificant.

Using this bitfield as an example:

bitfield MyBitfield {
  x : 1;
};

For a file containing a single byte set to 0x01, without any #pragma directive, x has a value of 1. With #pragma endian big, x has a value of 0 (and when I change the content of the file to 0x80, then x becomes 1).

Because endianness is about the order of bytes and not about the order of bits, I think keeping the same default for big endian and for little endian would make more sense. LeastToMostSignificant already handles endianness properly (or at least, like I would expect it to). For example, with a file containing 00 00 00 01, and with the following pattern:

#pragma endian big
#include <std/core.pat>

bitfield MyBitfield {
  x : 1;
} [[bitfield_order(std::core::BitfieldOrder::LeastToMostSignificant, 32)]];

, x properly shows the value 1.

brliron avatar Sep 25 '23 15:09 brliron

I found this quote searching for information on the subject

You can depend on the ordering of bit-fields to be deterministic as long as your program is intentionally not cross-platform.

While the C specification does not dictate the ordering of bit-fields, the platform's ABI does. In the case of System V AMD 64, the allocation order of bit-fields is defined as "right to left" (section 3.1.2). For ARM 64, it depends on the endianness of the data type (section 8.1.8.2). Because your C compiler adheres to platform ABI of the target architecture you're compiling against, you can depend on a fixed allocation order of bit-fields within a given platform.

That seems to imply that the ABI for big endian platforms specify left to right bit-field ordering and left to right ordering for little endian platforms. I think the defaults should reflect this.

paxcut avatar Sep 25 '23 18:09 paxcut

Indeed, this seems to be the case. I didn't know that, and with that in mind, the current default makes sense.

But then, I have an issue with the documentation. The bitfield_order description in https://docs.werwolv.net/pattern-language/core-language/attributes#type-attributes says:

Ordering the fields from least to most significant bit is the default

which is wrong.

brliron avatar Sep 26 '23 10:09 brliron

Should be resolved in https://github.com/WerWolv/Documentation/pull/16.

C3pa avatar Jul 11 '24 05:07 C3pa

Yep, looks good. Thanks

brliron avatar Jul 13 '24 08:07 brliron