Issue 241289
Summary [clang][Sema] C23 enum with underlying type bool converts like an integer (miscompile at -O3)
Labels clang
Assignees
Reporter jeffchen006
    In C23, conversion to `enum B : bool` must have the semantics of conversion to `bool` (2.5 -> true). Clang treats the enum as an integer type and emits `fptoui double to i1`, which is poison for 2.5. The value differs between -O0 and -O3, and both are wrong.

**Reproducer** (`repro.c`)
```c
// C23 6.7.3.3p16: "Conversion to the enumerated type has the same semantics as
// conversion to the underlying type."  The underlying type here is bool, so
// 2.5 -> enum B is a conversion to bool (6.3.1.2): any nonzero value -> true.
// (6.3.1.4p1 excludes bool, so there is no out-of-range UB.)
// Correct output: 1
int printf(const char *, ...);
enum B : bool { F, T };
volatile double d = 2.5;
int main(void) {
  enum B b = d;
 printf("%d\n", b);
  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 -std=c23 -O0 repro.c -o o0
$ ./o0
0
$ clang -std=c23 -O3 repro.c -o o3
$ ./o3
2
```
Correct: `1`. Clang `-O0` prints `0`, `-O3` prints `2`.

**Why the expected output is right**
N3220 6.7.3.3p16: conversion to the enum has the semantics of conversion to the underlying type (bool), so 2.5 -> true (6.3.1.2). No UB in the source.

**How the -O0/-O3 difference arises**
UBSan at -O0 reports "2.5 is outside the range of representable values of type enum B" because it uses the same wrong integer view; with bool semantics there is no range check (6.3.1.4p1 excludes bool). The poison from `fptoui ... to i1` gives different values at -O0 and -O3.

**Potential Root cause**
`clang/lib/AST/Type.cpp`, `Type::getScalarTypeKind` returns `STK_Integral` for every `EnumType`, also for a fixed underlying type `bool`. `clang/lib/Sema/SemaExpr.cpp`, `Sema::PrepareScalarCast`, then picks `CK_FloatingToIntegral` / `CK_IntegralCast` instead of `CK_FloatingToBoolean` / `CK_IntegralToBoolean`. IR: `fptoui double %3 to i1` and `trunc i32 to i1`.

**Possible Proposed fix**
```diff
+  auto DestKind = DestTy->getScalarTypeKind();
+  if (const auto *ED = DestTy->getAsEnumDecl();
+      ED && ED->isFixed() && ED->getIntegerType()->isBooleanType())
+    DestKind = Type::STK_Bool;
 ... switch (DestKind) ...
```
(Postfix `++` of such an enum in CodeGen `EmitScalarPrePostIncDec` needs the same check.)

Related: PR #211172 (44629e6, CWG1094: float to bool-backed enum in C++ `static_cast`). That fix covers only the C++ cast path; the C implicit/explicit conversion and the integer case here are not covered.

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

Reply via email to