| Issue |
244615
|
| Summary |
Wrong code at -Os: `cttz(x, true)` lowered to BSF, then MOVD copies the undefined upper bits of its destination into a constant-0 vector lane
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
haoxintu
|
## Description
```c
typedef short v2s __attribute__((ext_vector_type(2)));
typedef unsigned short v2u __attribute__((ext_vector_type(2)));
__attribute__((noinline)) void
k (const short *pa, const short *pb, short *po, unsigned junk) /* junk arrives in %ecx */
{
(void) junk;
v2s a = { pa[0], pa[1] }, b = { pb[0], pb[1] };
v2s r = (v2s) __builtin_elementwise_ctzg ((v2u) __builtin_shufflevector (a, ((v2s) {32767, 32767}), 1, 3),
(v2u) __builtin_shufflevector (a, b, 1, 2));
po[0] = r[0];
po[1] = r[1];
}
int main (void)
{
/* a[1] == 0: lane 0 takes the fallback a[1] = 0, lane 1 is ctz (32767) = 0 */
short a[2] = { 0, 0 }, b[2] = { 5, 0 }, o[2];
k (a, b, o, 0x12340000u);
if (o[0] != 0 || o[1] != 0)
__builtin_abort ();
return 0;
}
```
```
$ clang -Os repro.c && ./a.out # Aborted; -O0/-O1/-O2/-O3 are fine
```
The IR is fine: lane 1 is the constant 0, and the `cttz(x, true)` result (poison for x == 0) only feeds lane 0, which the select replaces by the fallback when x == 0. The -Os code is:
```
bsfl %eax, %ecx # x == 0: %ecx keeps its old value (here the argument junk = 0x12340000)
movd %ecx, %xmm1 # all 32 bits -> lanes 0 and 1
...
movd %xmm2, (%rdx)
```
Building the `<2 x i16>` from the 32-bit BSF result assumes the upper 16 bits are zero, because `cttz` of an i16 is at most 16. That holds only for a nonzero input. For x == 0, lane 1 receives the upper half of `%ecx`: `o[1]` is 4660 = 0x1234.
`llc -O2` (trunk and LLVM 21) on this IR shows the same thing. The driver passes 0x12340000 in `%ecx` and prints `0 4660`:
```llvm
define void @k(ptr %pa, ptr %pb, ptr %po, i32 %junk) optsize {
%p1 = getelementptr inbounds i8, ptr %pa, i64 2
%x = load i16, ptr %p1, align 2
%y = load i16, ptr %pb, align 2
%c = call i16 @llvm.cttz.i16(i16 %x, i1 true)
%v = insertelement <2 x i16> <i16 poison, i16 0>, i16 %c, i64 0
%t = insertelement <2 x i16> <i16 poison, i16 32767>, i16 %x, i64 0
%iszero = icmp eq <2 x i16> %t, zeroinitializer
%f0 = insertelement <2 x i16> poison, i16 %x, i64 0
%f = insertelement <2 x i16> %f0, i16 %y, i64 1
%r = select <2 x i1> %iszero, <2 x i16> %f, <2 x i16> %v
store <2 x i16> %r, ptr %po, align 2
ret void
}
```
Without `optsize` the same IR is compiled correctly.
Reproduced in Godbolt (x86-64 clang trunk, -Os and -O1): https://godbolt.org/z/e8Efq8M3e
## Checked Versions
- Wrong at -Os with clang trunk 2012344e5da8 (2026-11-19). -O0/-O1/-O2/-O3 are fine.
- llc from LLVM 21.1.8 miscompiles the IR the same way, so this is not a recent regression.
- Sanitizers (ASan, UBSan) are clean.
Thanks.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs