[AggressiveInstCombine] Fold reversed consecutive byte loads using bswap
foldConsecutiveLoads() can combine consecutive byte loads when their shift order matches the target endianness.
However, the reversed form is currently missed. For example, on a little-endian target:
%a = load i8, ptr %p
%b = load i8, ptr %p1
%c = load i8, ptr %p2
%d = load i8, ptr %p3
; zext omitted
%a0 = shl i32 %a, 24
%a1 = shl i32 %b, 16
%a2 = shl i32 %c, 8
%r0 = or i32 %a0, %a1
%r1 = or i32 %r0, %a2
%r2 = or i32 %r1, %d
could be represented as:
%wide = load i32, ptr %p
%result = call i32 @llvm.bswap.i32(i32 %wide)
When the load order is consecutive but the bit placement is reversed relative to the target endianness, foldConsecutiveLoads() could generate a wide load followed by llvm.bswap.
This is independently useful and also forms part of the optimization requested in #201107.
I'd be happy to take a look at this :) seems like a good learning opportunity for a first contribution
Note that wider load needs to take the alignment from the original narrow loads. So it may not be natively aligned.
On targets that don't natively support unaligned loads or bswap, for example base RISC-V, the backend will need to re-expand the sequence and will probably generate worse code than the pre-transformed sequence.
@martonmoro This transformation groups the same operations into a bswap, so I have not observed any performance benefit beyond simplifying the LLVM IR. I opened the issue because this point needs further verification.
@martonmoro This transformation groups the same operations into a bswap, so I have not observed any performance benefit beyond simplifying the LLVM IR. I opened the issue because this point needs further verification.
I think then I'll wait for some feedback on your idea before starting the implementation
On RISC-V rv64gcv with unaligned memory support, I've recently found a case in 557.xz_r from spec2017 where the sha_compress function calls load64 which is big endian load packed one byte at a time. This load64 function called in a loop with 16 iterations. The load64 gets unrolled into i8 loads+zext+shl+or and inlined. The loop vectorizer vectorizes the 16 iteration loop using segment loads. It looks quite complex.
If we were able to create the i64 load and bswap before the vectorizer, we are able to avoid the complex vectorization.
I asked AI to code up a patch that can recognize the pattern. I can make a PR for it.
@topperc That sounds great. And thank you for bringing this case to my attention. Given what you've found, it seems only natural that you should be the one to submit the patch. Please go ahead!