4 ms·
There's a distinction to be made between packing bits in a structure and using bitfields to access packed bits (as opposed to doing the shifts and masks manuall
by jcranmer 9y ago
There's a distinction to be made between packing bits in a structure and using bitfields to access packed bits (as opposed to doing the shifts and masks manually).
From a compiler writer's perspective, bitfields are one of the worst things ever proposed for a standard. The nonportability of which way bits are laid out is the least of their problems. The logic of how you actually pack bits in the struct is surprisingly nontrivial. The underlying semantics of bitfields are so weird pretty much every time they could be used, they need to be special-cased--both in the standard sense and in the implementation sense. This means that using bitfields requires navigating a field of landmines of potential compiler (or, worse, spec) bugs.
- eecsninja 9y agoThe solution is just to make sure you have padding fields that result in an overall size that's a multiple of however many bits e.g. 32 or 64 bits. Use static_assert() to enforce the size. See my earlier comment about unit testing too.
- jcranmer 9y agoWell, to have a good chance of avoiding the landmines, you need to: * Pack the bitfields in a struct all by themselves. Don't mix bitfields and non-bitfields in the same struct. (This means that you limit the scope of insanity to other bitfields, not potentially expanding it to other regular fields). * Make sure that the underlying type of all the bitfields within the struct have the same type. And make it be unsigned. * Pad the bitfields to the appropriate size of the type. * Only access the bitfields by copying them to/from the appropriate local variable (you don't want to trip code up on the bitfields-aren't-quite-the-type-they-say-they-are logic).
- eecsninja 9y agoI've only used bitfields for register access. I get the first 3 points you make. (I use uint32_t for all fields) What is the danger in #4 if you've followed #1-3? You seem overly paranoid. Is there something from your experience that makes you nervous about bitfields?
- jcranmer 9y agoI work on compilers for a living, which means I have a first-hand impression of the fallout of "the semantics seem clear until you actually think about all of the corner cases." I also have an appreciation for compilers blindly doing the wrong thing when you start mixing weird constructs together, and bitfields are very much a weird construct. The last rule is a recognition that bitfields are weird constructs, and their interactions with other weird constructs are likely to cause problems. One example: try using a bitfield in a ternary lvalue operation, especially with clang.