#unaligned reads/writes
1 messages · Page 1 of 1 (latest)
they will probably be slower, not guaranteed though. depends on the target. but yes they are well defined
i think on most CPUs unaligned access is either forbidden (so it needs to read a byte at a time and use shifts and ORs instead of a simple load) or slower than aligned ones
but some very simple CPUs like microcontrollers might have no alignment requirement/preference at all
I believe on x64, unaligned reads and writes are the same speed as normal ones generally, but they will be slower if the read/write straddles a cache-line.
But indeed it depends on the CPU in question and how it's set up.
I think ARM CPUs can crash you for instance - though I seem to recall that is actually something that can be chosen by the OS as to whether it ultimately does or not.
the short answer is that zig makes it work and the only difference you may observe is performance
Right
If you see align in a pointy type somewhere, then it means that Zig will emit machine instructions that are defined to not care about alignment.
https://godbolt.org/z/voPcxq1jd here's the worst case, it would seem risc-v requires alignment
Indeed - many fewer instructions if aligned -- though, since it's RISC, I wonder how much difference that actually makes
RISC CPUs have fewer simpler instructions than CISC, AFAIK.
I seem to remember hearing something about them being able to execute those instructions faster than CISC could (at least as a baseline) simply due to less complexity and circuitry or whatever being necessary to do it.
the aligned version is 4 instrs: shift index left by 3, add to base address, load, return
Indeed
I'd be interested in seeing what the timings would be in real code for that case
a high performance cpu is going to use microcode no matter the target ISA... so (speaking extremely broadly) you're looking at the performance of either decoding a few instructions and splitting to more uops (CISC), or decoding a lot of instructions and fusing to fewer uops (RISC)
there are some cases in the RISC-V spec where they actually specify the instruction sequence you should use for various complex operations, so compiler devs can emit code that the cpu designers know to optimize for
i wonder if there is such a recommendation for unaligned accesses