Skip to content

Commit 45c84d5

Browse files
authoredOct 27, 2024
[libc] Add __builtin_expect tag on assert conditions; NFC (#99498)
1 parent d2e9532 commit 45c84d5

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed
 

‎libc/src/__support/CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,7 @@ add_header_library(
277277
DEPENDS
278278
.integer_to_string
279279
libc.src.__support.OSUtil.osutil
280+
libc.src.__support.macros.optimization
280281
)
281282

282283
add_header_library(

‎libc/src/__support/libc_assert.h

+3-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
#include "src/__support/OSUtil/exit.h"
2525
#include "src/__support/OSUtil/io.h"
2626
#include "src/__support/integer_to_string.h"
27-
#include "src/__support/macros/attributes.h" // For LIBC_INLINE
27+
#include "src/__support/macros/attributes.h" // For LIBC_INLINE
28+
#include "src/__support/macros/optimization.h" // For LIBC_UNLIKELY
2829

2930
namespace LIBC_NAMESPACE_DECL {
3031

@@ -71,7 +72,7 @@ LIBC_INLINE void report_assertion_failure(const char *assertion,
7172

7273
#define LIBC_ASSERT(COND) \
7374
do { \
74-
if (!(COND)) { \
75+
if (LIBC_UNLIKELY(!(COND))) { \
7576
LIBC_NAMESPACE::write_to_stderr(__FILE__ ":" __LIBC_LINE_STR__ \
7677
": Assertion failed: '" #COND \
7778
"' in function: '"); \

‎libc/src/assert/assert.h

+13-3
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,18 @@
1818
#ifdef NDEBUG
1919
#define assert(e) (void)0
2020
#else
21+
22+
#ifdef __has_builtin
23+
#if __has_builtin(__builtin_expect)
24+
#define __LIBC_ASSERT_LIKELY(e) __builtin_expect(e, 1)
25+
#endif
26+
#endif
27+
#ifndef __LIBC_ASSERT_LIKELY
28+
#define __LIBC_ASSERT_LIKELY(e) e
29+
#endif
30+
2131
#define assert(e) \
22-
((e) ? (void)0 \
23-
: LIBC_NAMESPACE::__assert_fail(#e, __FILE__, __LINE__, \
24-
__PRETTY_FUNCTION__))
32+
(__LIBC_ASSERT_LIKELY(e) ? (void)0 \
33+
: LIBC_NAMESPACE::__assert_fail( \
34+
#e, __FILE__, __LINE__, __PRETTY_FUNCTION__))
2535
#endif // NDEBUG

0 commit comments

Comments
 (0)