Issue 241276
Summary [clang][X86-64] va_arg loads from the register save area with the type alignment (miscompile at -O3)
Labels clang
Assignees
Reporter jeffchen006
    For `va_arg(ap, S)` with S of alignment 16 in one GPR eightbyte, clang loads from `reg_save_area + gp_offset` with `align 16`. GPR slots are only 8-aligned. At -O3 X86 ISel uses an aligned SSE move and the program faults.

**Reproducer** (`repro.c`)
```c
/* f reads one struct S (16-byte aligned, 4 bytes of data) with va_arg.
   Correct output: 43 (3 + 4 * 10). clang -O3: SIGSEGV, an aligned SSE load
   (movdqa) from the va_arg register save area, which is only 8-byte aligned. */
#include <stdarg.h>
int printf(const char *, ...);
typedef unsigned short V2 __attribute__((vector_size(4)));
struct S { _Alignas(16) V2 v; };
int f(int n, ...) {
  va_list ap;
  va_start(ap, n);
  struct S s = va_arg(ap, struct S);
  va_end(ap);
  return s.v[0] + s.v[1] * 10;
}
int main(void) {
  struct S s = {{3, 4}};
  printf("%d\n", f(1, s));
  return 0;
}
```

**Commands and output** (clang version 24.0.0git (https://github.com/llvm/llvm-project.git 8207e9143575), Target: x86_64-unknown-linux-gnu):
```console
$ clang -O0 repro.c -o ./o0
$ ./o0
43
O0 rc=0
$ clang -O3 repro.c -o ./o3
$ ./o3
Segmentation fault
O3 rc=139
```
Expected (as `-O0`): `43`. `-O3` crashes with SIGSEGV.

**Why the expected output is right**
One variadic call with an `S` argument, read with `va_arg(ap, S)`. `packed` + `aligned(16)` is a documented GNU combination. The union return is read through the member that was written. UBSan/ASan/MSan at -O0 are clean.

**Potential Root cause**
`clang/lib/CodeGen/Targets/X86.cpp`, `X86_64ABIInfo::EmitVAArg`, register path, branch for a type with one INTEGER eightbyte and `RegSize < TySize`: `CGF.Builder.CreateAlignedLoad(CoTy, Addr, TyAlign)` with `TyAlign = 16`. `Addr` is `reg_save_area + gp_offset` (8-aligned). -O0 IR: `load i64, ptr %19, align 16` from `reg_save_area+8`. The other branch uses the slot alignment. (Branch from a27f40e5d963, #101639.)

**Possible Proposed fix**
```diff
-      llvm::Value *Src = "" Addr, TyAlign);
+      llvm::Value *Src = ""
+ CoTy, Addr, std::min(TyAlign, CharUnits::fromQuantity(Alignment)));
```

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to