Skip to content

[clang] Make __builtin_exp and __builtin_expf constexpr. - #199808

Open
lntue wants to merge 20 commits into
llvm:mainfrom
lntue:clang
Open

lntue wants to merge 20 commits into
llvm:mainfrom
lntue:clang

Conversation

@lntue

@lntue lntue commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

@lntue
lntue force-pushed the clang branch 4 times, most recently from 20537ea to 3fb91ac Compare May 27, 2026 04:07
@github-actions

github-actions Bot commented May 27, 2026 •

Copy link
Copy Markdown

🪟 Windows x64 Test Results

  • 146041 tests passed
  • 5001 tests skipped

✅ The build succeeded and all tests passed.

@github-actions

github-actions Bot commented May 27, 2026 •

Copy link
Copy Markdown

🐧 Linux x64 Test Results

  • 186785 tests passed
  • 7147 tests skipped

✅ The build succeeded and all tests passed.

@lntue
lntue marked this pull request as ready for review May 27, 2026 05:46
@lntue
lntue requested a review from AaronBallman May 27, 2026 05:46
@llvmorg-github-actions llvmorg-github-actions Bot added clang Clang issues not falling into any other category clang:frontend Language frontend issues, e.g. anything involving "Sema" clang:bytecode Issues for the clang bytecode constexpr interpreter labels May 27, 2026
@llvmorg-github-actions

llvmorg-github-actions Bot commented May 27, 2026 •

Copy link
Copy Markdown

@llvm/pr-subscribers-llvm-adt
@llvm/pr-subscribers-libc

@llvm/pr-subscribers-clang

Author: lntue

Changes

This is step 3 in https://discourse.llvm.org/t/rfc-make-clang-builtin-math-functions-constexpr-with-llvm-libc-to-support-c-23-constexpr-math-functions/86450


Full diff: https://github.com/llvm/llvm-project/pull/199808.diff

5 Files Affected:

  • (modified) clang/include/clang/Basic/Builtins.td (+8-1)
  • (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+16)
  • (modified) clang/lib/AST/ExprConstant.cpp (+13)
  • (modified) clang/test/Preprocessor/feature_tests.cpp (+3-1)
  • (added) clang/test/Sema/constant-builtins-exp.cpp (+19)
diff --git a/clang/include/clang/Basic/Builtins.td b/clang/include/clang/Basic/Builtins.td
index 84799929cee87..9e141fa802715 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4127,7 +4127,14 @@ def Erfc : FPMathTemplate, LibBuiltin<"math.h"> {
   let AddBuiltinPrefixedAlias = 1;
 }
 
-def Exp : FPMathTemplate, LibBuiltin<"math.h"> {
+def Exp : Template<["float", "double"], ["f", ""]>, LibBuiltin<"math.h"> {
+  let Spellings = ["exp"];
+  let Attributes = [NoThrow, ConstIgnoringErrnoAndExceptions, Constexpr];
+  let Prototype = "T(T)";
+  let AddBuiltinPrefixedAlias = 1;
+}
+
+def Expl : Template<["long double"], ["l"]>, LibBuiltin<"math.h"> {
   let Spellings = ["exp"];
   let Attributes = [NoThrow, ConstIgnoringErrnoAndExceptions];
   let Prototype = "T(T)";
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 8a53ae0937782..3aa172d350e11 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -706,6 +706,14 @@ static bool interp__builtin_fpclassify(InterpState &S, CodePtr OpPC,
   return true;
 }
 
+static bool interp__builtin_exp(InterpState &S, CodePtr OpPC,
+                                const InterpFrame *Frame) {
+  const Floating &Arg = S.Stk.pop<Floating>();
+  APFloat Result = exp(Arg.getAPFloat());
+  S.Stk.push<Floating>(Floating(Result));
+  return true;
+}
+
 static inline Floating abs(InterpState &S, const Floating &In) {
   if (!In.isNegative())
     return In;
@@ -4488,6 +4496,14 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const CallExpr *Call,
   case Builtin::BI__builtin_copysignf128:
     return interp__builtin_copysign(S, OpPC, Frame);
 
+  case Builtin::BI__builtin_exp:
+  case Builtin::BI__builtin_expf:
+    return interp__builtin_exp(S, OpPC, Frame);
+  case Builtin::BI__builtin_expl:
+  case Builtin::BI__builtin_expf16:
+  case Builtin::BI__builtin_expf128:
+    return false;
+
   case Builtin::BI__builtin_fmin:
   case Builtin::BI__builtin_fminf:
   case Builtin::BI__builtin_fminl:
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 0522d6f1dc944..54cd1dbc937c0 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -19948,6 +19948,19 @@ bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
     return true;
   }
 
+  case Builtin::BI__builtin_exp:
+  case Builtin::BI__builtin_expf: {
+    APFloat Input(0.);
+    if (!EvaluateFloat(E->getArg(0), Input, Info))
+      return false;
+    Result = exp(Input);
+    return true;
+  }
+  case Builtin::BI__builtin_expl:
+  case Builtin::BI__builtin_expf16:
+  case Builtin::BI__builtin_expf128:
+    return false;
+
   case Builtin::BI__builtin_fmax:
   case Builtin::BI__builtin_fmaxf:
   case Builtin::BI__builtin_fmaxl:
diff --git a/clang/test/Preprocessor/feature_tests.cpp b/clang/test/Preprocessor/feature_tests.cpp
index 029f446113af4..b49376a14644f 100644
--- a/clang/test/Preprocessor/feature_tests.cpp
+++ b/clang/test/Preprocessor/feature_tests.cpp
@@ -60,7 +60,9 @@
 #if  !__has_constexpr_builtin(__builtin_fmax) || \
      !__has_constexpr_builtin(__builtin_fmin) || \
      !__has_constexpr_builtin(__builtin_fmaximum_num) || \
-     !__has_constexpr_builtin(__builtin_fminimum_num)
+     !__has_constexpr_builtin(__builtin_fminimum_num) || \
+     !__has_constexpr_builtin(__builtin_exp) || \
+     !__has_constexpr_builtin(__builtin_expf)
 #error Clang should have these constexpr builtins
 #endif
 
diff --git a/clang/test/Sema/constant-builtins-exp.cpp b/clang/test/Sema/constant-builtins-exp.cpp
new file mode 100644
index 0000000000000..215d2c2765961
--- /dev/null
+++ b/clang/test/Sema/constant-builtins-exp.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -verify -fexperimental-new-constant-interpreter %s
+// expected-no-diagnostics
+
+constexpr float InfFloat = __builtin_inff();
+constexpr float NegInfFloat = -__builtin_inff();
+
+static_assert(InfFloat == __builtin_expf(InfFloat));
+static_assert(0.0f == __builtin_expf(NegInfFloat));
+static_assert(1.0f == __builtin_expf(0.0f));
+static_assert(0x1.5bf0a8p1f == __builtin_expf(1.0f));
+
+constexpr double InfDouble = __builtin_inf();
+constexpr double NegInfDouble = -__builtin_inf();
+
+static_assert(InfDouble == __builtin_exp(InfDouble));
+static_assert(0.0 == __builtin_exp(NegInfDouble));
+static_assert(1.0 == __builtin_exp(0.0));
+static_assert(0x1.5bf0a8b145769p1 == __builtin_exp(1.0));

@jcranmer-intel jcranmer-intel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation isn't meeting the [library.c]p3 restriction that exceptions (other than FE_INEXACT) cause library calls to not be constant expressions.

@lntue

lntue commented Jun 11, 2026

Copy link
Copy Markdown
Contributor Author

The implementation isn't meeting the [library.c]p3 restriction that exceptions (other than FE_INEXACT) cause library calls to not be constant expressions.

@jcranmer-intel I'm adding exception check for exp in APFloat at #203066. PTAL. Thanks,


constexpr float InfFloat = __builtin_inff();
constexpr float NegInfFloat = -__builtin_inff();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No testing with NaN input values?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hubert-reinterpretcast : I'm waiting for #203066 and I'll update this PR to include all edge cases.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hubert-reinterpretcast : I've updated the PR to use updated APFloat::exp and to include NaN and overflow cases. Any other tests that you would like to be added here?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any other tests that you would like to be added here?

The consensus for the overall constexpr cmath design in Clang from #158048 (comment) was that the constant evaluation would fail if FENV_ACCESS is ON and the context is not one where the language requires constant evaluation. That way, dynamic rounding modes and the setting of FE_INEXACT at run time are observed.

Once the logic is added, there should be a codegen test that expects the call to not be folded when FENV_ACCESS is ON.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once the logic is added, there should be a codegen test that expects the call to not be folded when FENV_ACCESS is ON.

@lntue, I think that logic needs to be added into the implementation for each of the functions (i.e., it should be present in this PR). An example of the expected behaviour (using the arithmetic operators) is https://godbolt.org/z/s6M63813s.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated the logic and the tests.

@lntue
lntue force-pushed the clang branch 2 times, most recently from 1159751 to 4a2f3d6 Compare June 18, 2026 20:28
@lntue
lntue requested a review from a team as a code owner June 19, 2026 04:49
@lntue

lntue commented Jun 19, 2026

Copy link
Copy Markdown
Contributor Author

Hmm, I'm so confused. For some reason, the CI's keep failing the non-constexpr on overflow tests:

FAIL: Clang :: Sema/constant-builtins-exp.cpp (25215 of 25215)
******************** TEST 'Clang :: Sema/constant-builtins-exp.cpp' FAILED ********************
Exit Code: 1
Command Output (stdout):
--
# RUN: at line 1
/home/gha/actions-runner/_work/llvm-project/llvm-project/build/bin/clang -cc1 -internal-isystem /home/gha/actions-runner/_work/llvm-project/llvm-project/build/lib/clang/23/include -nostdsysteminc -std=c++17 -fsyntax-only -verify /home/gha/actions-runner/_work/llvm-project/llvm-project/clang/test/Sema/constant-builtins-exp.cpp
# executed command: /home/gha/actions-runner/_work/llvm-project/llvm-project/build/bin/clang -cc1 -internal-isystem /home/gha/actions-runner/_work/llvm-project/llvm-project/build/lib/clang/23/include -nostdsysteminc -std=c++17 -fsyntax-only -verify /home/gha/actions-runner/_work/llvm-project/llvm-project/clang/test/Sema/constant-builtins-exp.cpp
# .---command stderr------------
# | error: 'expected-error' diagnostics expected but not seen: 
# |   File /home/gha/actions-runner/_work/llvm-project/llvm-project/clang/test/Sema/constant-builtins-exp.cpp Line 15: static assertion expression is not an integral constant expression
# |   File /home/gha/actions-runner/_work/llvm-project/llvm-project/clang/test/Sema/constant-builtins-exp.cpp Line 28: static assertion expression is not an integral constant expression
# | 2 errors generated.
# `-----------------------------
# error: command failed with exit status: 1
--

but it passed when I build and run it locally, using the same cmake commands in the Linux CI. And the similar APFloat tests passed. @hubert-reinterpretcast @jcranmer-intel

Comment thread clang/lib/AST/ExprConstant.cpp Outdated
// Inexact result means that it depends on rounding mode. If the requested
// mode is dynamic, the evaluation cannot be made in compile time.

if (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic breaks once <math.h> functions are considered.

For <math.h> functions, a constant rounding mode (which we ignore for folding of run-time evaluations) should not allow folding that ignores the dynamic rounding mode without regard to -frounding-math. Such folding occurs with this PR in its current state:

$ clang++ -w -frounding-math -S -o - -emit-llvm -Xclang -disable-llvm-passes -xc -<<<'double exp1() { _Pragma("STDC FENV_ROUND FE_DOWNWARD") return __builtin_exp(1.); }' | grep ret
  ret double f0x4005BF0A8B145769

Note 1: https://clang.llvm.org/docs/UsersManual.html#accessing-the-floating-point-environment makes a statement about the C standard in direct contradiction to C23 subclause 7.6.2 paragraph 3. According to the C standard, #pragma STDC FENV_ROUND FE_DYNAMIC affords no permission for the program to change the dynamic rounding mode when FENV_ACCESS is "off".

Note 2: From the same section of the Clang documentation and with reference to the same paragraph of the C standard,

The command line option -frounding-math behaves as if the translation unit began with #pragma STDC FENV_ROUND FE_DYNAMIC.

is vacuous at best and incorrect at worst. Having the translation unit begin that way has no effect according to the C standard, and that is true of the Clang implementation; however, the option does have an effect: https://godbolt.org/z/d8bcfe4jx.

lntue and others added 2 commits September 12, 2026 11:21
- Dynamic rounding mode and exception handling:
  - Only suppress constant folding in dynamic rounding mode when the result
    is inexact (`Status & opInexact`), allowing exact values (e.g. division
    by zero to infinity) to fold.
  - Address the FIXME in `checkFloatingPointResultForConstantFolding` and
    `CheckFloatStatus`: permit static and global variable initializers to fold
    at translation time under default FP settings (ISO C17 §7.6.1p2).

- `-fmath-errno` handling:
  - Move `-fmath-errno` checking out of general floating-point result checking
    and into math builtin evaluators, ensuring core arithmetic operators
    are unaffected.
  - Suppress runtime constant folding for math builtins only when domain,
    pole, or range errors would set `errno` at runtime.
  - Add `note_constexpr_math_errno` diagnostic note.

- Diagnostics & Rounding:
  - Refactor math builtin evaluation to use `getActiveRoundingMode`,
    removing hardcoded `NearestTiesToEven`.
  - Update diagnostic notes to standard-aligned phrasing:
    `note_constexpr_float_{overflow,underflow,divide_by_zero,invalid_op}`.

- Tests:
  - Add `clang/test/CodeGen/builtin-exp-folding.c` to test runtime folding
    and suppression under `-fmath-errno`, `-fno-math-errno`, `-frounding-math`,
    and `-ffp-exception-behavior=strict`.
  - In `clang/test/Sema/constant-builtins-exp.cpp`:
    - Add underflow tests for normal inputs yielding subnormals (`-88.0f`, `-709.0`).
    - Test quiet NaN with `__builtin_isnan`.
    - Add tests and FIXMEs for directed rounding modes (`FE_DOWNWARD`,
      `FE_UPWARD`, `FE_TOWARDZERO`).
@lntue

lntue commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

@hubert-reinterpretcast @jcranmer-intel : I got the following table summarizing Fold/No-Fold behaviors in various situations as follow:

Precedence & Controlling Rule opOK
(Exact, e.g. exp(0) = 1)
opInexact
(Inexact, e.g. exp(1))
opUnderflow
(Range error, e.g. exp(-88f))
opOverflow
(Range error, e.g. exp(100f))
opDivByZero
(e.g. 1.0 / 0.0, log(0))
opInvalidOp
(e.g. 0.0 / 0.0, sqrt(-1))
1. Constant Context (constexpr, static_assert)
(All rounding modes: default or #pragma STDC FENV_ROUND)
Fold Fold
(allowed by [library.c]p3)*
No Fold
(prohibited by [library.c]p3)
No Fold
(prohibited by [library.c]p3)
No Fold
(prohibited by [library.c]p3)
No Fold
(prohibited by [library.c]p3)
2. Global / Static Initializers (C17 §7.6.1p2)
(Evaluated at translation time under default FP settings)
Fold Fold
(bypasses strict FENV)
Depends on -fmath-errno
(No Fold if errno)
Depends on -fmath-errno
(No Fold if errno)
Fold (arithmetic)
Depends on -fmath-errno (builtins)
Fold (arithmetic)
Depends on -fmath-errno (builtins)
3. Runtime: #pragma STDC FENV_ACCESS ON
(or -ffp-model=strict, -ffp-exception-behavior=strict)
Fold
(no exceptions raised; exact)
No Fold
(must raise FE_INEXACT)
No Fold
(must raise FE_UNDERFLOW)
No Fold
(must raise FE_OVERFLOW)
No Fold
(must raise FE_DIVBYZERO)
No Fold
(must raise FE_INVALID)
4. Runtime: #pragma STDC FENV_ROUND FE_DYNAMIC
(Local block pragma overriding TU defaults)
Fold
(independent of RM)
No Fold
(result depends on dynamic RM)
No Fold
(depends on dynamic RM + errno)
No Fold
(depends on dynamic RM + errno)
Fold (arithmetic)
Depends on -fmath-errno (builtins)
Fold (arithmetic)
Depends on -fmath-errno (builtins)
5. Runtime: #pragma STDC FENV_ROUND FE_TONEAREST
(Local pragma overriding -frounding-math)
Fold Fold
(guaranteed tonearest)
Depends on -fmath-errno
(No Fold if errno)
Depends on -fmath-errno
(No Fold if errno)
Fold (arithmetic)
Depends on -fmath-errno (builtins)
Fold (arithmetic)
Depends on -fmath-errno (builtins)
6. Runtime: -frounding-math
(TU-level dynamic rounding default)
Fold
(independent of RM)
No Fold
(result depends on dynamic RM)
No Fold
(depends on dynamic RM)
No Fold
(depends on dynamic RM)
Fold (arithmetic)
Depends on -fmath-errno (builtins)
Fold (arithmetic)
Depends on -fmath-errno (builtins)
7. Runtime: -fmath-errno
(TU default on Linux/glibc with default RM)
Fold
(exact; errno not set)
Fold
(non-range; errno not set)
No Fold
(must write errno = ERANGE)
No Fold
(must write errno = ERANGE)
Fold (arithmetic)
No Fold (math builtins: ERANGE)
Fold (arithmetic)
No Fold (math builtins: EDOM)
8. Runtime: -fno-math-errno
(Default RM, ignore exceptions, ignore errno)
Fold Fold Fold
(folds to denormal or 0.0)
Fold
(folds to +inf)
Fold
(folds to inf)
Fold
(folds to NaN)
9. Runtime: -ffast-math
(Unconstrained math optimizations)
Fold Fold Fold Fold Fold Fold

*Note: Directed rounding modes in constexpr currently fail evaluation with note_constexpr_unsupported_rounding until implemented in llvm::APFloat::exp.

And I tried to add the tests to cover them as much as possible.
Can you take a look to see if I understand them correctly? Thanks,

bassiounix added a commit that referenced this pull request Sep 18, 2026
std::exp(double) and std::expf resolved to the C library's exp(double) and
expf(float) through `using ::exp;` and `using ::expf;` in <cmath>. Clang does
not constant-evaluate those spellings, so the constexpr checks for them failed
even with #199808. Import libc++'s own __math overloads instead, and add a
`template <class = int>` __math::expf so that std::expf doesn't clash with the
C library's non-template expf(float) when both are visible in the same scope,
e.g. after `using namespace std;` or `using std::expf;` at global scope.

std::exp is made constexpr by P1383R2, which is a C++26 paper, not by P0533R9
(C++23), so use _LIBCPP_CONSTEXPR_SINCE_CXX26 and move the checks out of the
P0533R9 test into new compile-time-only P1383R2 tests for Clang and GCC. GCC
already folds the C library's expl, hence the differing expectation there.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
bassiounix added a commit that referenced this pull request Sep 18, 2026
Now that __builtin_exp and __builtin_expf are constant-evaluable in
clang (#199808), mark libc++'s float, double, and integral-promoting
overloads of __math::exp as _LIBCPP_CONSTEXPR_SINCE_CXX23. The long
double overload stays non-constexpr because __builtin_expl is not
constant-evaluable yet.

Add constexpr coverage for std::exp and std::expf to the clang-specific
constexpr <cmath> test.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@AaronBallman

Copy link
Copy Markdown
Contributor

@hubert-reinterpretcast @jcranmer-intel I'd like to understand the next steps for this PR; getting this initial work unblocked will help us start making bigger inroads into the constexpr cmath efforts, so I'd like to keep momentum rolling here if we can.

@hubert-reinterpretcast

Copy link
Copy Markdown
Member

getting this initial work unblocked will help us start making bigger inroads into the constexpr cmath efforts, so I'd like to keep momentum rolling here if we can.

I fully understand; however, I have some internal commitments to address with higher priority due to release schedules and user requests.

@jcranmer-intel

Copy link
Copy Markdown
Contributor

@hubert-reinterpretcast @jcranmer-intel : I got the following table summarizing Fold/No-Fold behaviors in various situations as follow:

Looking only at this table for the moment (a little annoying, since it's wider than github's comment section allows, which makes it hard to read):

1. Constant Context (constexpr, static_assert)
(All rounding modes: default or #pragma STDC FENV_ROUND)

With the caveat that we follow the directed rounding mode, this row is correct.

2. Global / Static Initializers (C17 §7.6.1p2)
(Evaluated at translation time under default FP settings)

The behavior of this row is definitely wrong.

Pre-C23, there's no real discussion in the main body of the standard about requirements for floating-point constant expressions. Everything that exists is really relegated to Annex F, of which F.8 lays out some pretty clear rules (these quotes are from a late C23 draft, but with the exception of things added for FENV_ROUND, the wording doesn't change):

During translation, constant rounding direction modes (7.6.2) are in effect where specified. Elsewhere,
during translation the IEC 60559 default modes are in effect

An arithmetic constant expression of floating type, other than one in an initializer for an object that
has static or thread storage duration, is evaluated (as if) during execution

All computation for automatic initialization is done (as if) at execution time; thus, it is affected by
any operative modes and raises floating-point exceptions as required by IEC 60559 (provided the
state for the FENV_ACCESS pragma is "on"). All computation for initialization of objects that have
static or thread storage duration is done (as if) at translation time.

The conclusion is pretty clear here: static-storage initializers (which have to be done at translation time in C, there's no dynamic global initialization concept like in C++) gets done at translation time no matter what, everything else has to at least act like it's done at runtime.

C23 adds constexpr. The new rules in 6.7.1... I can't confidently make sense of them. From talking with Aaron, it seems that the best course of action is to ignore what C23 says and treat C23 constexpr like C++ constexpr.

With that in mind, this row should be entirely Fold. I'm also not sure this is lower priority than the constexpr rule (at least for C's static initializers), but I've exceeded my budget for thinking about this.

@hubert-reinterpretcast

hubert-reinterpretcast commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

With that in mind, this row should be entirely Fold.

For the builtin spelling, there is no conformance issue with this; however, for the non-builtin spelling, this needs a diagnostic under -pedantic? @AaronBallman, any input into this from a C conformance perspective? The friction seems to be that we need the non-builtin spelling to be constexpr for C++ (or at least newer levels thereof) but potentially not for C; therefore, OnlyBuiltinPrefixedAliasIsConstexpr is not helpful as it is.

@lntue

lntue commented Oct 16, 2026

Copy link
Copy Markdown
Contributor Author

C23 adds constexpr. The new rules in 6.7.1... I can't confidently make sense of them. From talking with Aaron, it seems that the best course of action is to ignore what C23 says and treat C23 constexpr like C++ constexpr.

With that in mind, this row should be entirely Fold. I'm also not sure this is lower priority than the constexpr rule (at least for C's static initializers), but I've exceeded my budget for thinking about this.

Thanks @jcranmer-intel!

I have updated the patch (both ExprConstant and Interp) and added tests in clang/test/CodeGen/builtin-exp-folding.c accordingly:

  1. constexpr: Evaluated under default (or constant FENV_ROUND) rounding mode; folds
    when opOK or opInexact, and rejects opOverflow, opUnderflow, opDivByZero, and opInvalidOp (CCEDiag + noteUndefinedBehavior).
  2. C non-constexpr static / thread-storage initializers (C23 Annex F.8): Since these are always evaluated at translation time in Clang (InConstantContext == true with EvaluationMode::ConstantFold / SE_AllowUndefinedBehavior) and C has no dynamic runtime initialization for globals, they now fold across all APFloat::opStatus and ignore runtime -fmath-errno, FENV_ACCESS, and dynamic -frounding-math (while still respecting constant FENV_ROUND). We also match Expr::EvaluateAsInitializer with VarDecl::evaluateValueImpl so only VD->isConstexpr() uses EvaluationMode::ConstantExpression in C23.
  3. Runtime expr (and C++ non-constant dynamic global initializers): follow the active FPOptions and -fmath-errno as before.

Here is the updated summary table:

Rule / Context opOK opInexact opUnderflow / opOverflow opDivByZero / opInvalidOp
1. Strict Constant Context
(C++ constexpr / constinit / static_assert, C23 constexpr)
Fold Fold
(per [library.c]p3)*
No Fold
(error per [library.c]p3)
No Fold
(error per [library.c]p3)
2. C Static / Thread Initializers
(non-constexpr, C23 F.8.3, F.8.5, F.8.6)
Fold Fold Fold Fold
3. Runtime: #pragma STDC FENV_ACCESS ON
(or -ffp-exception-behavior=strict / maytrap)
Fold No Fold No Fold No Fold
4. Runtime: #pragma STDC FENV_ROUND FE_DYNAMIC
(when FENV_ACCESS ON or -frounding-math)
Fold No Fold
(dynamic RM)
No Fold
(dynamic RM)
Fold (arith)
No Fold (if errno)
5. Runtime: #pragma STDC FENV_ROUND FE_TONEAREST
(overrides -frounding-math)
Fold Fold Fold (no errno)
No Fold (if errno)
Fold (arith / no errno)
No Fold (if errno)
6. Runtime: -frounding-math
(TU-level dynamic rounding)
Fold No Fold
(dynamic RM)
No Fold
(dynamic RM)
Fold (arith)
No Fold (if errno)
7. Runtime: -fmath-errno
(default RM, exceptions ignored)
Fold Fold Fold (arith)
No Fold (builtins: ERANGE)
Fold (arith)
No Fold (builtins: ERANGE/EDOM)
8. Runtime: -fno-math-errno
(default RM, exceptions ignored)
Fold Fold Fold Fold
9. Runtime: -ffast-math Fold Fold Fold Fold

@hubert-reinterpretcast

Copy link
Copy Markdown
Member

The conclusion is pretty clear here: static-storage initializers (which have to be done at translation time in C, there's no dynamic global initialization concept like in C++) gets done at translation time no matter what, everything else has to at least act like it's done at runtime.

@jcranmer-intel, I see that you quoted the C wording that supports evaluation (as if) at translation time, but we know that (standard) C does not evaluate function calls in constant expressions, so we are free here to reject evaluation.

It sounds like you believe that evaluation should succeed even in the cases where C++ constant evaluation would fail because, unlike in C++, there is no fallback to dynamic initialization; however, I am not quite following what aspect of "no fallback to dynamic initialization" is the impetus for expecting the evaluation to succeed. For example, an observation that usage in such an initializer is indicative of folding intent in C but not C++ is not particularly helpful because C++ would reject "error" cases even when the folding intent is made clear with, e.g., constexpr.

In any case, C2y draft N3886 has, in subclause 6.7.2 , "Storage-class specifiers", paragraph 5:

An object declared with storage-class specifier constexpr or any of its members, even recursively, shall not have an atomic type, or a variably modified type, or a type that is volatile or restrict qualified. An initializer of floating type shall be evaluated with the translation-time floating-point environment.

Therefore, it appears to me that C's constexpr initialization is not much different from C's static/thread storage duration and the choice of rejecting "errors" should be consistent between the two. In other words, the decision to be made is whether we believe that C has an underlying design that leads to successful translation-time evaluation even for "error" cases (at least for IEEE formats). I do not believe that expecting successful translation-time evaluation in "error" cases is reasonable in the general case, e.g., for invalid operations in a floating-point format with no NaN values.

@github-actions

github-actions Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

✅ With the latest revision this PR passed the C/C++ code formatter.

@jcranmer-intel

Copy link
Copy Markdown
Contributor

Therefore, it appears to me that C's constexpr initialization is not much different from C's static/thread storage duration and the choice of rejecting "errors" should be consistent between the two.

C constexpr is the root of the whole mess for me. The intent, as I understand it, is to import C++'s constexpr behavior into C, including the whole "undefined behavior is a failure" milieu, but that collides with C not having sufficient language to really enable that, C++ being (especially at the time the proposal was made for C) completely mum on floating-point behavior, and colliding with C already have existing strict floating-point semantic behavior that is somewhat optional (being a part of Annex F). My understanding from @AaronBallman is that we're planning to handle this by just using the same C++ constexpr machinery for C constexpr.

In other words, the decision to be made is whether we believe that C has an underlying design that leads to successful translation-time evaluation even for "error" cases (at least for IEEE formats).

WG21 has made it abundantly clear that they think that, e.g., 1.0/0.0 is "wrong;" there's a whole paper on that idea with very strong consensus for it. CFP, in my conversations with them, is pretty equally adamant that under IEEE 754 rules, 1.0/0.0 yielding infinity at translation time is totally the right thing. (I'd have to defer to Rajan for a ruling on behavior on systems like HexFloat without infinity/NaN). I'm not entirely certain how WG14 as a group would vote, but I suspect they would likely follow the recommendation of CFP here over WG21.

@hubert-reinterpretcast

hubert-reinterpretcast commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

My understanding from @AaronBallman is that we're planning to handle this by just using the same C++ constexpr machinery for C constexpr.

As purely a pragmatic implementation decision where we are just using what we have for C++ anyway, I can understand this decision. At the end of the day though, the C wording treats both cases as parallel. In C2y draft N3886, subclause F.8.5, "Constant Expressions" (an earlier version of which you quote above) has:

An arithmetic constant expression of floating type, other than one in an initializer for an object that has static or thread storage duration or that is declared with storage-class specifier constexpr, is evaluated (as if) during execution; [...]

So I still think we should ideally be doing the same thing for the C constexpr case as for the static/thread-storage initialization one; which, based on the rest of your comment means folding cases with "errors" at least for IEEE-like types.

Anyhow, I think we can switch the C constexpr behaviour later. It seems we will have both choices of behaviour implemented anyway.

CFP, in my conversations with them, is pretty equally adamant that under IEEE 754 rules, 1.0/0.0 yielding infinity at translation time is totally the right thing. (I'd have to defer to Rajan for a ruling on behavior on systems like HexFloat without infinity/NaN).

Okay. I'll reach out to Rajan to confirm whether we want the translation to fail in the HexFloat case. As noted in the HexFloat RFC thread, there is no obvious, consistent result value for error cases. Perhaps more importantly, unlike infinity/NaN, such values don't have a good propagation mechanism. The PR already uses std::optional in a way that evaluation of the math function call could return no "value", so we can have translation fail by returning no value.

@hubert-reinterpretcast

Copy link
Copy Markdown
Member

I'll reach out to Rajan to confirm whether we want the translation to fail in the HexFloat case.

This is the reply I got:

Yes, I believe this should be considered an error case in general as that is normally the intent of the result of operations in that format (abend at runtime).

Which means that another reason to reject such operations at compile time (for HexFloat) is by analogy to integer division-by-zero.

C2y draft N3886 subclause 6.6.1 paragraph 2 has wording that appears consistent with the view that operations that would fail in a run-time environment set up to emulate the compile-time environment should not succeed at compile time:

Values of address constants or arithmetic constant expressions with floating type and values that are derived from these are possibly only determined during linking (translation phase 8) or just before program startup.

@mgcarrasco

Copy link
Copy Markdown
Contributor

Hi! This comment was generated using fuzz-fill, a new tool we're building to help improve LLVM test coverage by spotting lines introduced in a PR that don't yet appear to be exercised by the full test suite, including any tests added in this PR.

Looking at PR head 5993891, we found 2 lines added or modified here that we couldn't find a test for:

  1. S.CCEDiag(E, diag::note_constexpr_float_divide_by_zero) << FD;
  2. Info.CCEDiag(E, diag::note_constexpr_float_divide_by_zero) << FD;

If it makes sense, adding a test that validates these lines would be great. And if any of them are already tested and we missed it, we'd love to hear so we can improve the tool. Feel free to give us some feedback on whether this review was useful from your perspective. Thanks!

@AaronBallman

Copy link
Copy Markdown
Contributor

Hi! This comment was generated using fuzz-fill, a new tool we're building to help improve LLVM test coverage by spotting lines introduced in a PR that don't yet appear to be exercised by the full test suite, including any tests added in this PR.

@mgcarrasco thank you for the comment! I'm not certain if this is using an LLM or not, but the "this comment was generated" tickled my dangersense so I'd like to verify this tool conforms to our AI policy (https://llvm.org/docs/AIToolPolicy.html), in particular:

An important implication of this policy is that it bans agents that take action in our digital spaces without human approval, such as the GitHub @claude agent. Similarly, automated review tools that publish comments without human review are not allowed.

Is this tool fully automated, or is there a human in the loop verifying everything the tool wants to say before it is posted?

Also, was there an RFC somewhere about the tool or its strategy? Personally, I like the tool so far and I think it's a good idea in general so long as there's a human in the loop with it. This kind of feedback on PRs has the potential to be incredibly useful! I just want to make sure there is community buy-in before the tool goes hog-wild on every PR in the project.

@mgcarrasco

Copy link
Copy Markdown
Contributor

Hi! This comment was generated using fuzz-fill, a new tool we're building to help improve LLVM test coverage by spotting lines introduced in a PR that don't yet appear to be exercised by the full test suite, including any tests added in this PR.

@mgcarrasco thank you for the comment! I'm not certain if this is using an LLM or not, but the "this comment was generated" tickled my dangersense so I'd like to verify this tool conforms to our AI policy (https://llvm.org/docs/AIToolPolicy.html), in particular:

An important implication of this policy is that it bans agents that take action in our digital spaces without human approval, such as the GitHub @claude agent. Similarly, automated review tools that publish comments without human review are not allowed.

Is this tool fully automated, or is there a human in the loop verifying everything the tool wants to say before it is posted?

Also, was there an RFC somewhere about the tool or its strategy? Personally, I like the tool so far and I think it's a good idea in general so long as there's a human in the loop with it. This kind of feedback on PRs has the potential to be incredibly useful! I just want to make sure there is community buy-in before the tool goes hog-wild on every PR in the project.

Thanks @AaronBallman, this is very encouraging! Sorry for the confusion. I have posted and checked every comment myself. The analysis is not done by an LLM: the coverage comes from instrumenting the build and running the test suite. These reports were never meant to be posted by an LLM without anyone in the loop, and I will make that clearer in future comments.

The project started by filling coverage gaps already in the codebase. We motivated those tests by placing an abort on the uncovered lines, which showed that no test exercised them in LLVM CI. From there it moved to finding coverage gaps in AMDGPU and SPIR-V backend PRs. I have recently extended it to a wider set of LLVM components, and I was sharing the results of analysing some of those PRs.

Before I post, I look at the reported lines in the context of the PR. Seeing how that feedback is addressed has been useful: sometimes the right fix is a new test, and sometimes it is a chance to remove code that is not needed. Some reported gaps are assertions or other paths that are naturally unreachable, and I filter those out. In this case the gap is error handling. When I checked, the other diagnostic errors here are already tested, and this one is not.

An RFC is a good idea, and more feedback on the tool would be super welcome. These comments are also meant to gather concrete cases of when the tool is helpful (and perhaps how often). At the moment, there are probably no other tool users other than myself while developing it. We want to help reviewers and developers. Posting these automatically on LLVM threads would be a much bigger step, and that is not the plan without a community discussion.

@AaronBallman

Copy link
Copy Markdown
Contributor

Thanks @AaronBallman, this is very encouraging! Sorry for the confusion. I have posted and checked every comment myself. The analysis is not done by an LLM: the coverage comes from instrumenting the build and running the test suite. These reports were never meant to be posted by an LLM without anyone in the loop, and I will make that clearer in future comments.

The project started by filling coverage gaps already in the codebase. We motivated those tests by placing an abort on the uncovered lines, which showed that no test exercised them in LLVM CI. From there it moved to finding coverage gaps in AMDGPU and SPIR-V backend PRs. I have recently extended it to a wider set of LLVM components, and I was sharing the results of analysing some of those PRs.

Before I post, I look at the reported lines in the context of the PR. Seeing how that feedback is addressed has been useful: sometimes the right fix is a new test, and sometimes it is a chance to remove code that is not needed. Some reported gaps are assertions or other paths that are naturally unreachable, and I filter those out. In this case the gap is error handling. When I checked, the other diagnostic errors here are already tested, and this one is not.

Fantastic, this sounds like a good process to follow. Thank you for alleviating my concerns! I can think of two ways to avoid the same confusion in the future (other ideas likely exist too): (1) if posting from your own account, remove the "was generated" wording and try to avoid any boilerplate text so it looks like more of a human communication or (2) instead of posting from your own account, make a bot account and have the tool post from that so it's more clearly labeled as coming from a bot.

An RFC is a good idea, and more feedback on the tool would be super welcome. These comments are also meant to gather concrete cases of when the tool is helpful (and perhaps how often). At the moment, there are probably no other tool users other than myself while developing it. We want to help reviewers and developers. Posting these automatically on LLVM threads would be a much bigger step, and that is not the plan without a community discussion.

It sounds like the early experiments are on an ad hoc basis rather than anything widespread, so I don't insist on an RFC at this point. But if you get encouraging signals with these early experiments and want to start producing these comments more frequently, I would recommend posting an RFC at some point to get community buy-in on the idea. We have https://llvm.org/docs/FuzzingLLVM.html which lists a fair amount of information about fuzzing the project, so the RFC is mostly about community awareness of the effort, ensuring this tool's behaviors meet community needs and expectations, we're not duplicating efforts such that multiple tools point out the same issues, etc.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clang:bytecode Issues for the clang bytecode constexpr interpreter clang:frontend Language frontend issues, e.g. anything involving "Sema" clang Clang issues not falling into any other category libc llvm:adt

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants