4 ms·
Among other things, I seen lots of inefficiencies with bitfields. I tend to use them a lot in hardware register access and packing of data in embedded developme
by pkaye 9y ago
Among other things, I seen lots of inefficiencies with bitfields. I tend to use them a lot in hardware register access and packing of data in embedded development. Imagine a bitfield that fits into one word and setting each of the bitfields to a constant. A good compiler should be able to set all the values with one load operations. Some compilers would break this into many separate loads. I think the ARM compilers were worse at this while Clang would optimize it much better. Many times had to forgo bitfields and use macro definitions and masking to get the best code generation at the cost of readability.
- lomnakkus 9y ago> A good compiler should be able to set all the values with one load operations. Hm? I believe that might actually be entirely wrong for many pieces of actual hardware that I've worked with. Setting a single bit may change the interpretation of a subsequently set bit, so you can't really "batch" the updates. (I'm happy for you if this isn't an issue you've faced. We did. Feel sorry for us.)
- morio 9y agoThat's what the keyword volatile is for. If something is not marked volatile the compiler is allowed to change the order and collapse any memory accesses it deems unnecessary.
- lomnakkus 9y agoIndeed, but I don't think that was the poster I was responding to was talking about? I mean, he/she was talking about bitfields and similar things and how writes to those could be coalesced? In genreal, they cannot. (I dunno, it seemed appropriate to mention the caveats.)
- carlmr 9y agoNot coalescing writes on non-volatile bitfields probably isn't guaranteed by the standard. If you depend on it I hope you have a test catching that.
- AstralStorm 9y agoWhy use bit fields at all instead of straightforward bit math then? They're not really convenient and have weird alignment rules already.
- nitrogen 9y agoThis is totally right and shouldn't be downvoted, but the reply is also right that volatile should prevent optimization. On some hardware, "writing" to "memory" is really sending a message to a device, and writing 0x80 followed by 0x08 is not the same thing as writing 0x88.
- pkaye 9y agoWhat we did was load the hardware register word to a local variable, set the appropriate bits then store it back.
- asb 9y agoThere's been some discussion about bitfield access optimisation in the LLVM community. This RFC thread may be interesting to you http://lists.llvm.org/pipermail/llvm-dev/2017-March/110895.html http://lists.llvm.org/pipermail/llvm-dev/2017-March/110895.h.... If you enjoy these sorts of discussions, you might like http://llvmweekly.org/ http://llvmweekly.org/ (disclaimer: I'm the author).