Skip to content

Commit 4a96893

Browse files
committed
[libc] Fix exp2f and prevent misuse of likely/unlikely
Let's make sure that we only accept boolean expressions when using likely/unlikely. Differential Revision: https://reviews.llvm.org/D143732
1 parent 065a8cf commit 4a96893

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

libc/src/__support/macros/attributes.h

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,18 @@
1919

2020
#define LIBC_INLINE inline
2121
#define LIBC_INLINE_ASM __asm__ __volatile__
22-
#define LIBC_LIKELY(x) __builtin_expect(!!(x), 1)
23-
#define LIBC_UNLIKELY(x) __builtin_expect(x, 0)
22+
23+
// We use a template to implement likely/unlikely to make sure that we don't
24+
// accidentally pass an integer.
25+
namespace __llvm_libc::details {
26+
template <typename T>
27+
constexpr LIBC_INLINE bool expects_bool_condition(T value, T expected) {
28+
return __builtin_expect(value, expected);
29+
}
30+
} // namespace __llvm_libc::details
31+
#define LIBC_LIKELY(x) __llvm_libc::details::expects_bool_condition(x, true)
32+
#define LIBC_UNLIKELY(x) __llvm_libc::details::expects_bool_condition(x, false)
33+
2434
#define LIBC_UNUSED __attribute__((unused))
2535

2636
#endif // LLVM_LIBC_SUPPORT_MACROS_ATTRIBUTES_H

libc/src/math/generic/exp2f.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ LLVM_LIBC_FUNCTION(float, exp2f, (float x)) {
6969
}
7070

7171
// Check exceptional values.
72-
if (LIBC_UNLIKELY(x_u & exval_mask) == exval_mask) {
72+
if (LIBC_UNLIKELY((x_u & exval_mask) == exval_mask)) {
7373
if (LIBC_UNLIKELY(x_u == exval1)) { // x = 0x1.853a6ep-9f
7474
if (fputil::get_round() == FE_TONEAREST)
7575
return 0x1.00870ap+0f;

0 commit comments

Comments
 (0)