llvm-project
llvm-project copied to clipboard
[InstCombine] missed X + ((-X) & (C - 1)) -> (X + C - 1) & -C
found from https://github.com/gcc-mirror/gcc/commit/c07fc7b5c69884adbfea21c3db08a9583f664377
X | -X has every bit from the lowest set bit of X upwards, so adding X to
it clears that bit, and masking with it isolates the padding needed to
round X up:
X + (X | -X) -> X & (X - 1)
X + ((-X) & (C - 1)) -> (X + C - 1) & -C for a power of two C
The second is the alignment round up written with the padding computed
first, which is how allocators tend to spell it.
Neither needs a wrapping type. X - 1 overflows only for the most
negative value, where the source already does, and rounding X up is
representable exactly when X + C - 1 is, because the largest multiple of
C below the maximum leaves room for C - 1. Restrict both rules to integral
types. The bitwise operations also accept fixed-point types, whose
saturating arithmetic does not have these integer semantics.
int f (int x) { return x + ((-x) & 15); }
aarch64 -O2:
before after
neg w1, w0 add w0, w0, 15
and w1, w1, 15 and w0, w0, -16
add w0, w1, w0
The vector spelling folds too, a uniform vector constant is matched with
uniform_integer_cst_p.
int
foo (int x)
{
return x + ((-x) & 15);
}
int
bar (int x)
{
return (x + 16 -1) & -16;
}
gcc:
"foo":
lea eax, [rdi+15]
and eax, -16
ret
"bar":
lea eax, [rdi+15]
and eax, -16
ret
clang:
foo:
mov eax, edi
neg eax
and eax, 15
add eax, edi
ret
bar:
lea eax, [rdi + 15]
and eax, -16
ret
https://godbolt.org/z/3W3dGGzYh https://alive2.llvm.org/ce/z/PDx7Lw
I'd like to work on this