Re: Unaligned access trade-offs for SFrame FRE layout
Segher Boessenkool <[email protected]> Tue, 16 Sep 2025 12:54:24 -0500
| Newsgroups | org.kernel.vger.linux-toolchains |
|---|---|
| Message-ID | <aMmkUNXT2Fi-0D1h@gate> |
On Tue, Sep 16, 2025 at 11:44:26AM -0500, Segher Boessenkool wrote:
> On Tue, Sep 16, 2025 at 09:32:30AM -0700, Fangrui Song wrote:
> > The read32le(p) function is either a standard read or a byte-swapped
> > read.
>
> You should never overcomplicate things by doing byte-swaps. Instead,
> just say what you mean:
>
> u32 read32le(u8 *p)
> {
> return p[0] + 0x100*p[1] + 0x10000*p[2] + 0x1000000*p[3];
> }
>
> or something like that. The compiler can optimise such things just
> fine! There is no need to go via extra indirections.
The following actually compiles to optimal code, both with -mbig and
with -mlittle:
===
typedef unsigned int u32;
typedef unsigned char u8;
u32 read32le(u8 *p)
{
return (u32)p[0] | (u32)p[1]<<8 | (u32)p[2]<<16 | (u32)p[3]<<24;
}
===
With -O2 -mbig:
lwbrx 3,0,3 # 10 [c=8 l=4] bswapsi2_load
blr # 18 [c=4 l=4] simple_return
(on a BE system), and with -O2 -mlittle:
lwz 3,0(3) # 11 [c=8 l=4] *movsi_internal1/3
blr # 19 [c=4 l=4] simple_return
(I used -mcpu=power10, because a) why not, and b) with an ancient CPU
GCC will make more sure not to do misaligned accesses. Power8 is fine
already, 970 (aka Apple G5) isn't (for the LE accesses on a BE host):
and that is good, because such accesses will frequently trap, so on
average they are quite expensive if done as a single read.
Segher