Issue 241291
Summary [SimplifyLibCalls] pow(2^n, x) -> exp2(n*x) loses ERANGE under -fmath-errno (miscompile at -O3)
Labels new issue
Assignees
Reporter jeffchen006
    `pow(4.0, 1e308)` overflows and glibc sets `errno = ERANGE`. InstCombine rewrites it to `exp2(2.0 * x)`. The `fmul` overflows to +inf silently and `exp2(inf)` is exact, so errno stays 0.

**Reproducer** (`repro.c`)
```c
/* pow(4, 1e308) overflows, so glibc sets errno = ERANGE.
   Correct output: 34 (ERANGE on Linux) */
#include <errno.h>
#include <math.h>
#include <stdio.h>
volatile double x = 1e308;
int main(void) {
  errno = 0;
  pow(4.0, x);
  printf("%d\n", errno);
  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 -lm
$ ./o0
34
$ clang -O3 repro.c -o o3 -lm
$ ./o3
0
```
Expected (as `-O0`): `34` (ERANGE). `-O3` prints `0`.

**Why the expected output is right**
One volatile read of `1e308`; `pow(4, 1e308)` overflows (a range error, C11 7.12.1p4); glibc sets ERANGE. Same library at -O0 and -O3; `-fmath-errno` is the default. UBSan/ASan/MSan at -O0 are clean.

**Potential Root cause**
`llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp`, `LibCallSimplifier::replacePowWithExp`, branch `pow(2.0 ** n, x) -> exp2(n * x)`: for an errno-writing `pow` it still rewrites and emits the `exp2` libcall, so it intends to keep errno. But the new `fmul x, n` overflows to +-inf silently when |n*x| > DBL_MAX, and `exp2(+-inf)` has no range error.

**Possible Proposed fix**
Do the rewrite only when `pow` does not write errno:
```diff
   // pow(2.0 ** n, x) -> exp2(n * x)
-  if (hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
+  if (Pow->doesNotAccessMemory() &&
+      hasFloatFn(M, TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
```
(Alternative: also allow it with `ninf` on the call.)

Related: PR #183099 (fixed the same flaw for `pow(x, 2.0) -> x*x`; its review also named `pow(x, -1.0)`). The `pow(2^n, x) -> exp2(n*x)` path here is not reported.

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

Reply via email to