Skip to content

Commit 0522ee3

Browse files
committed
[libc++] Add constant folding for optimized std::find variants
1 parent 4145ad2 commit 0522ee3

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

libcxx/include/__string/constexpr_c_functions.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,19 @@ _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp* __constexpr_memchr(_Tp*
132132
static_assert(sizeof(_Tp) == 1 && __libcpp_is_trivially_equality_comparable<_Tp, _Up>::value,
133133
"Calling memchr on non-trivially equality comparable types is unsafe.");
134134

135+
if (__builtin_constant_p(__count) && __builtin_constant_p(__value)) {
136+
for (; __count; --__count) {
137+
if (!__builtin_constant_p(*__str))
138+
break;
139+
if (*__str == __value)
140+
return __str;
141+
++__str;
142+
}
143+
}
144+
145+
if (__builtin_constant_p(__count) && __count == 0)
146+
return nullptr;
147+
135148
if (__libcpp_is_constant_evaluated()) {
136149
// use __builtin_char_memchr to optimize constexpr evaluation if we can
137150
#if _LIBCPP_STD_VER >= 17 && __has_builtin(__builtin_char_memchr)

libcxx/include/cwchar

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,19 @@ _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 _Tp* __constexpr_wmemchr(_Tp
231231
__libcpp_is_trivially_equality_comparable<_Tp, _Tp>::value,
232232
"Calling wmemchr on non-trivially equality comparable types is unsafe.");
233233

234+
if (__builtin_constant_p(__count) && __builtin_constant_p(__value)) {
235+
for (; __count; --__count) {
236+
if (!__builtin_constant_p(*__str))
237+
break;
238+
if (*__str == __value)
239+
return __str;
240+
++__str;
241+
}
242+
}
243+
244+
if (__builtin_constant_p(__count) && __count == 0)
245+
return nullptr;
246+
234247
#if __has_builtin(__builtin_wmemchr)
235248
if (!__libcpp_is_constant_evaluated()) {
236249
wchar_t __value_buffer = 0;

0 commit comments

Comments
 (0)