[AMDGPU] HIP miscompilation bug (returning aggregate union types across functions)
The following HIP program triggers a miscompilation bug. The output should be a deterministic value as it's UB free. The bug manifests by enabling optimisations which cause a divergence in the printed value.
Test File: HIPProg.hip
How to reproduce:
clang++ -O0 -x hip HIPProg.hip -Wno-c++11-narrowing --offload-arch=native -o O0.outclang++ -O1 -x hip HIPProg.hip -Wno-c++11-narrowing --offload-arch=native -o O1.out./O0.out./O1.out
Compare output values: Bug (-O1): 50331648 Ref (-O0): 0
tagging @mgcarrasco who is working on it confirmed in commit a4cd17e
@llvm/issue-subscribers-backend-amdgpu
Author: ElliotBLabs
Test File: HIPProg.hip
How to reproduce:
clang++ -O0 -x hip HIPProg.hip -Wno-c++11-narrowing --offload-arch=native -o O0.outclang++ -O1 -x hip HIPProg.hip -Wno-c++11-narrowing --offload-arch=native -o O1.out./O0.out./O1.out
Compare output values: Bug (-O1): 50331648 Ref (-O0): 0
I think this is a clang ABI lowering problem rather than a backend one.
AMDGPUABIInfo::classifyReturnType and classifyArgumentType pass
aggregates larger than 8 bytes (up to 16 registers) with getDirect(), i.e.
as clang's LLVM type for the record. For a union that is the type of one
member, so bytes that are padding in that member are dropped. In the
reproducer, U2 is returned as S0's type, and byte 3 of f0 is padding in
S0, which matches the wrong value 0x03000000.
Smaller reproducer (-x hip --offload-arch=gfx90a, clang 23.1.4; the
lowering in AMDGPU.cpp is unchanged on trunk):
union U { unsigned long a; struct { unsigned short x; unsigned long y; } s; };
__device__ __attribute__((noinline)) U ret_u(const unsigned long *p) { U u; u.a = *p; return u; }
__device__ __attribute__((noinline)) unsigned long take_u(U u) { return u.a; }
At -O2, take_u compiles to v_and_b32 v0, 0xffff, v0; v_mov_b32 v1, 0, so
only the low 16 bits of a reach the callee, and ret_u returns
{ i16, i64 undef }. The same problem for NVPTX returns is #237641; #237655
fixes it by returning records as integer arrays, as most targets do.