clang should optimize common patterns to portably read big/little-endian data
| Bugzilla Link | 20605 |
| Resolution | FIXED |
| Resolved on | Feb 01, 2017 10:01 |
| Version | trunk |
| OS | Linux |
| Attachments | Example code for the pattern that could be optimized |
| CC | @arpilipe,@majnemer,@filcab,@zmodem,@RKSimon,@nlewycky,@rnk |
Extended Description
A common idiom to portably read integers with well-defined endianess from a buffer is code like this:
uint32_t le32read(uint8_t buf[static 4]) {
return ((uint32_t)buf[0]
| (uint32_t)buf[1] << 8
| (uint32_t)buf[2] << 16
| (uint32_t)buf[3] << 24);
}
uint32_t be32read(uint8_t buf[static 4]) {
return ((uint32_t)buf[0]
| (uint32_t)buf[1] << 24
| (uint32_t)buf[2] << 16
| (uint32_t)buf[3] << 8);
}
On architectures where unaligned reads are legal (e.g. amd64), the above code could be compiled into something like this:
le32read:
mov (%rdi), %eax
ret
be32read:
mov (%rdi), %eax
bswap %eax
ret
Yet clang seems to not optimize this kind of code well. Here is the assembly clang generates (cleaned up):
le32read:
movzbl (%rdi), %eax
movzbl 1(%rdi), %ecx
shll $8, %ecx
orl %eax, %ecx
movzbl 2(%rdi), %edx
shll $16, %edx
orl %ecx, %edx
movzbl 3(%rdi), %eax
shll $24, %eax
orl %edx, %eax
ret
be32read:
movzbl (%rdi), %eax
shll $24, %eax
movzbl 1(%rdi), %ecx
shll $16, %ecx
orl %eax, %ecx
movzbl 2(%rdi), %edx
shll $8, %edx
orl %ecx, %edx
movzbl 3(%rdi), %eax
orl %edx, %eax
ret
It would be great if clang was capable of optimizing this kind of pattern as it pops up continuously and is one of the few (the only?) way to (de)serialise data with known endianess in a portable fashion.
Fixed by rL293036 as discussed above.
Thank you for implementing this. Feel free to mark this as closed.
The big endian code in the bug description is not correct. It must be:
uint32_t be32read(uint8_t buf[static 4]) { return ((uint32_t)buf[0] << 24 | (uint32_t)buf[1] << 16 | (uint32_t)buf[2] << 8 | (uint32_t)buf[3]); }
(Which is the code in the attachment)
We do fold the valid pattern to a single load and a bswap: movl (%rdi), %eax bswapl %eax
rL293036 fixes le32read on x86, but not be32read:
le32read: movl (%rdi), %eax retq
be32read: movzbl 1(%rdi), %ecx movzbl (%rdi), %eax movzbl 2(%rdi), %edx shll $24, %ecx shll $16, %edx orl %eax, %ecx movzbl 3(%rdi), %eax orl %ecx, %edx shll $8, %eax orl %edx, %eax retq
define i32 @be32read(i8* nocapture readonly dereferenceable(4)) { %2 = load i8, i8* %0, align 1 %3 = zext i8 %2 to i32 %4 = getelementptr inbounds i8, i8* %0, i64 1 %5 = load i8, i8* %4, align 1 %6 = zext i8 %5 to i32 %7 = shl nuw i32 %6, 24 %8 = or i32 %7, %3 %9 = getelementptr inbounds i8, i8* %0, i64 2 %10 = load i8, i8* %9, align 1 %11 = zext i8 %10 to i32 %12 = shl nuw nsw i32 %11, 16 %13 = or i32 %8, %12 %14 = getelementptr inbounds i8, i8* %0, i64 3 %15 = load i8, i8* %14, align 1 %16 = zext i8 %15 to i32 %17 = shl nuw nsw i32 %16, 8 %18 = or i32 %13, %17 ret i32 %18 }
+1 for getting this optimization.