Issue 234269
Summary [clang] [InstSimplify] an odd byte distance is no longer rounded down (miscompile from C, -O1+)
Labels backend:X86, miscompilation, generated by fuzzer
Assignees
Reporter YuanchengJiang
    ## C reproducer — `repro.c`
```c
#include <stdio.h>

/* the short at or before byte offset k of the buffer p */
__attribute__((noinline)) short *align_down(short *p, long k) {
  char *q = (char *)p + k;
  long d = q - (char *)p;           /* byte distance (== k) */
  return p + (d >> 1);              /* d / 2 shorts, rounded down */
}

int main(void) {
  short buf[8];
  volatile long k = 5;              /* odd byte offset */
  short *r = align_down(buf, k);
  printf("%ld\n", (long)((char *)r - (char *)buf));   /* want 4 */
  return (char *)r - (char *)buf != 4;
}
```

| compiler (x86-64, native) | output |
|---|---|
| `clang -O0` | `4` (correct) |
| `clang -O1` / `-O2` / `-O3` | **`5` (WRONG)** |
| `-O2` with the fix below | `4` |

Trunk: https://godbolt.org/z/hP5WbEbMM

All arithmetic stays inside `buf`, so there is no UB. At `-O2`, `align_down` becomes
`getelementptr inbounds i8, ptr %p, i64 %k`: it returns `q` itself.

## Root cause
`simplifyGEPInst` (InstructionSimplify.cpp):
```cpp
  // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of size 1 << C.
  if (match(Indices[0], m_AShr(m_Sub(m_PtrToIntOrAddr(m_Value(P)), m_PtrToIntOrAddr(m_Specific(Ptr))),
                               m_ConstantInt(C))) && TyAllocSize == 1ULL << C && CanSimplify())
    return P;
  // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of size C.
  if (match(Indices[0], m_SDiv(..., m_SpecificInt(TyAllocSize))) && CanSimplify())
    return P;
```
- **Why exactness matters:** `V + sizeof(T) × ((P − V) >> C)` equals `P` only if `P − V` is a multiple of `sizeof(T)`.
  For an odd byte distance the shift rounds down (and `sdiv` rounds toward zero), so the GEP lands before `P`.
- **What the fold misses:** it never checks the `exact` flag. Clang's own pointer subtraction emits `sdiv exact`,
  which is fine. A user-written shift of a byte distance, as in `repro.c`, is not exact.

## Fix (validated)
Only fold when the `ashr` / `sdiv` is `exact`:
```cpp
      ... && cast<PossiblyExactOperator>(Indices[0])->isExact() && ...
```
Results:
- `repro.c` prints `4` at `-O2`.
- TV is silent on `ptrtoaddr.ll`.
- Only `gep_of_sub_ptrtoaddr_ashr` and the non-exact `sdiv` by 3 case in that file change; `gep.ll`, `ptr_diff.ll` and
  `compare.ll` are unchanged.

The CHECK lines of those two `ptrtoaddr.ll` functions must be updated, or `exact` added to their inputs if the intent
was the exact case.

In the AGT tree this is v251 (`AGT_NOFIX=1` disables it). The positive suite entry is S30.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to