Skip to content

Commit c56211b

Browse files
authored
[libc] Make math-macros.h C++-friendly (#86206)
The isfinite, isnan, and isinf "functions" are specified by C99..C23 to be macros that act as type-generic functions. Defining them as their __builtin_* counterparts works fine for this. However, in C++ the identifiers need to be usable in different contexts, such as being declared inside a C++ namespace. So define inline constexpr template functions for them under `#ifdef __cplusplus`.
1 parent b8e5363 commit c56211b

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

libc/include/llvm-libc-macros/math-macros.h

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,6 @@
3030
#define FP_LLOGB0 (-LONG_MAX - 1)
3131
#define FP_LLOGBNAN LONG_MAX
3232

33-
#define isfinite(x) __builtin_isfinite(x)
34-
#define isinf(x) __builtin_isinf(x)
35-
#define isnan(x) __builtin_isnan(x)
36-
3733
#ifdef __FAST_MATH__
3834
#define math_errhandling 0
3935
#elif defined(__NO_MATH_ERRNO__)
@@ -44,4 +40,32 @@
4440
#define math_errhandling (MATH_ERRNO | MATH_ERREXCEPT)
4541
#endif
4642

43+
// These must be type-generic functions. The C standard specifies them as
44+
// being macros rather than functions, in fact. However, in C++ it's important
45+
// that there be function declarations that don't interfere with other uses of
46+
// the identifier, even in places with parentheses where a function-like macro
47+
// will be expanded (such as a function declaration in a C++ namespace).
48+
49+
#ifdef __cplusplus
50+
51+
template <typename T> inline constexpr bool isfinite(T x) {
52+
return __builtin_isfinite(x);
53+
}
54+
55+
template <typename T> inline constexpr bool isinf(T x) {
56+
return __builtin_isinf(x);
57+
}
58+
59+
template <typename T> inline constexpr bool isnan(T x) {
60+
return __builtin_isnan(x);
61+
}
62+
63+
#else
64+
65+
#define isfinite(x) __builtin_isfinite(x)
66+
#define isinf(x) __builtin_isinf(x)
67+
#define isnan(x) __builtin_isnan(x)
68+
69+
#endif
70+
4771
#endif // LLVM_LIBC_MACROS_MATH_MACROS_H

0 commit comments

Comments
 (0)