Repository navigation
Conversation
20537ea to
3fb91ac
Compare
🪟 Windows x64 Test Results
✅ The build succeeded and all tests passed. |
🐧 Linux x64 Test Results
✅ The build succeeded and all tests passed. |
|
@llvm/pr-subscribers-llvm-adt @llvm/pr-subscribers-clang Author: lntue Changes5 Files Affected:
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
left a comment
There was a problem hiding this comment.
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(); | ||
|
|
There was a problem hiding this comment.
No testing with NaN input values?
There was a problem hiding this comment.
@hubert-reinterpretcast : I'm waiting for #203066 and I'll update this PR to include all edge cases.
There was a problem hiding this comment.
@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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Once the logic is added, there should be a codegen test that expects the call to not be folded when
FENV_ACCESSisON.
@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.
There was a problem hiding this comment.
I updated the logic and the tests.
1159751 to
4a2f3d6
Compare
|
Hmm, I'm so confused. For some reason, the CI's keep failing the non-constexpr on overflow tests: but it passed when I build and run it locally, using the same |
| // 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) { |
There was a problem hiding this comment.
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 f0x4005BF0A8B145769Note 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-mathbehaves 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.
- 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`).
|
@hubert-reinterpretcast @jcranmer-intel : I got the following table summarizing Fold/No-Fold behaviors in various situations as follow:
*Note: Directed rounding modes in And I tried to add the tests to cover them as much as possible. |
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]>
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]>
|
@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. |
I fully understand; however, I have some internal commitments to address with higher priority due to release schedules and user requests. |
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):
With the caveat that we follow the directed rounding mode, this row is correct.
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
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 With that in mind, this row should be entirely Fold. I'm also not sure this is lower priority than the |
For the builtin spelling, there is no conformance issue with this; however, for the non-builtin spelling, this needs a diagnostic under |
Thanks @jcranmer-intel! I have updated the patch (both
Here is the updated summary table:
|
@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., In any case, C2y draft N3886 has, in subclause 6.7.2 , "Storage-class specifiers", paragraph 5:
Therefore, it appears to me that C's |
|
✅ With the latest revision this PR passed the C/C++ code formatter. |
C
WG21 has made it abundantly clear that they think that, e.g., |
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:
So I still think we should ideally be doing the same thing for the C Anyhow, I think we can switch the C
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 |
This is the reply I got:
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:
|
|
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:
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! |
@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:
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. |
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.
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 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
#139885