summaryrefslogtreecommitdiff
path: root/libstdc++-v3/include/std
AgeCommit message (Collapse)Author
2025-11-21libstdc++: Implement LWG 4406 and LWG 3424 for std::optional and std::expectedJonathan Wakely
This adjusts the return statements of optional::value_or and expected::value_or to not perform explicit conversions, so that the actual conversion performed matches the requirements expressed in the Mandates: elements (LWG 4406). Also adjust the return types to remove cv-qualifiers (LWG 3424). libstdc++-v3/ChangeLog: * include/std/expected (expected::value_or): Use remove_cv_t for the return type. Do not use static_cast for return statement. Adjust static_assert conditions to match return statements. * include/std/optional (optional::value_or): Likewise. (optional<T&>::value_or): Likewise. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-11-21libstdc++: Implement P3223R2 Making std::istream::ignore less surprisingYuao Ma
libstdc++-v3/ChangeLog: * include/std/istream (ignore): Add an overload for char. * testsuite/27_io/basic_istream/ignore/char/93672.cc: Adjust expected behaviour for C++26 mode. * testsuite/27_io/basic_istream/ignore/char/4.cc: New test. Co-authored-by: Jonathan Wakely <jwakely@redhat.com>
2025-11-20libstdc++: [_GLIBCXX_DEBUG] Fix std::erase_if behavior for __gnu_debug::vectorFrançois Dumont
When using directly __gnu_debug::vector the std::erase_if is called with a reference to the std::vector base class and so is missing the invalidation of the iterators implied by this operation. To fix this provide a std::erase_if overload dedicated to __gnu_debug::vector. Doing so we can cleanup the implementation dedicated to std::vector from any _GLIBCXX_DEBUG consideration. libstdc++-v3/ChangeLog: * include/debug/vector (std::erase_if, std::erase): New overloads for std::__debug::vector instances. * include/std/vector (std::erase_if, std::erase): Make overloads specific to normal std::vector implementation. * testsuite/23_containers/vector/debug/erase.cc: New test case. * testsuite/23_containers/vector/debug/invalidation/erase.cc: New test case.
2025-11-20libstdc++: Prepare mdspan-related code for submdspan.Luc Grosheintz
The changes needed for submdspan are: * In submdspan related code the user-defined integer-like types need to be copy- and move-constructable. * The traits for writing tests that work with both left- and right, possibly padded, layouts will also be useful for submdspan. Therefore, this code is moved up and generalized. * Move __offset further up in <mdspan> and fix some formatting mistakes. libstdc++-v3/ChangeLog: * include/std/mdspan: Improve formatting and placement. * testsuite/23_containers/mdspan/int_like.h: Optionally, add move- and copy-ctors. * testsuite/23_containers/mdspan/layouts/padded_traits.h: Move to... * testsuite/23_containers/mdspan/layout_traits.h: ...here. * testsuite/23_containers/mdspan/layouts/ctors.cc: Fix include. * testsuite/23_containers/mdspan/layouts/mapping.cc: Ditto. * testsuite/23_containers/mdspan/layouts/padded.cc: Ditto. * testsuite/23_containers/mdspan/layouts/padded_neg.cc: Ditto. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-11-19libstdc++: Make <mdspan> compatible with clang.Luc Grosheintz
These three changes are needed to make <mdspan> compatible with Clang: - the type alias _Storage must occur before its first use. - the friend declarations of function must match exactly, including noexcept and constexpr. - the 'template' in typename T::template type<double>. libstdc++-v3/ChangeLog: * include/std/mdspan (extents::_Storage): Move type alias before its first use. (__mdspan::__static_extents): Add missing noexcept and constexpr to friend declaration in extents. (__mdspan::__dynamic_extents): Ditto. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-11-19c++, libstdc++: Implement CWG1670 and LWG4468Jakub Jelinek
The following patch attempts to implement CWG1670 and related LWG4468. 2025-11-19 Jakub Jelinek <jakub@redhat.com> gcc/cp/ * parser.cc (cp_parser_conversion_type_id): Implement C++ DR1670 - auto as conversion-type-id. Pedwarn on conversion operators with placeholder return type. gcc/testsuite/ * g++.dg/DRs/dr1670-1.C: New test. * g++.dg/DRs/dr1670-2.C: New test. * g++.dg/DRs/dr1670-3.C: New test. * g++.dg/modules/auto-1_a.H: Use dg-options instead of dg-additional-options. * g++.dg/modules/auto-1_b.C: Likewise. * g++.dg/cpp1y/auto-fn12.C: Likewise. * g++.dg/cpp1y/auto-fn13.C: Add empty dg-options. * g++.dg/cpp1y/auto-fn22.C: Likewise. * g++.dg/cpp1y/constexpr-assert2.C: Likewise. * g++.dg/cpp1y/auto-fn44.C: Add dg-options -Wpedantic and expect further warnings. * g++.dg/cpp1y/auto-fn50.C: Likewise. * g++.dg/cpp0x/auto9.C: Expect two errors always rather than just for C++11. libstdc++-v3/ * include/std/type_traits (constant_wrapper conversion operator): Use decltype(value) instead of decltype(auto). Resolves LWG4468.
2025-11-18libstdc++: shared_mutex: Respond consistently to errors and deadlockMike Crowe
Make the shared_mutex::try_lock(), shared_timed_mutex::try_lock_until() and shared_timed_mutex::try_lock_shared_until() all handle errors from pthread functions consistently by returning false to indicate that the lock could not be taken. If _GLIBCXX_ASSERTIONS is defined then unexpected errors, such as EDEADLK and EINVAL will cause an assertion failure. If _GLIBCXX_ASSERTIONS is not defined then these functions no longer ever return true incorrectly indicating that they have taken the lock. This removes the previous behaviour of looping on EDEADLK in try_lock_shared_until() and no longer returns true on EINVAL in all of these functions. (In theory at least it should not be possible to trigger EINVAL since 5dba17a3e709859968f939354e6e5e8d796012d3.) Unfortunately my reading of POSIX is that pthread_rwlock_clockrdlock[1], pthread_rwlock_timedrdlock pthread_rwlock_clockwrlock[2] and pthread_rwlock_timedwrlock are allowed to deadlock rather than return EDEADLK when trying to take a lock a second time from the same thread. This means that the deadlock tests cannot be enabled by default. I believe that the tests do work with glibc (2.31 & 2.36) and with the __shared_mutex_cv implementation though. [1] https://pubs.opengroup.org/onlinepubs/9799919799/functions/pthread_rwlock_clockrdlock.html [2] https://pubs.opengroup.org/onlinepubs/9799919799/functions/pthread_rwlock_clockwrlock.html libstdc++-v3/ChangeLog: * include/std/shared_mutex (try_lock, try_lock_until) (try_lock_shared_until): Respond consistently to errors and deadlocks. * testsuite/30_threads/shared_timed_mutex/try_lock_until/116586.cc: Test deadlock behaviour if possible. Signed-off-by: Mike Crowe <mac@mcrowe.com>
2025-11-14libstdc++: Ensure that _Utf_view is always a view.Tomasz Kamiński
Previously, _Utf_view accepted any input_range, including reference-to-array types like char(&)[2], and stored it as the _M_base member. In such cases, _Utf_view was not assignable, failing the requirements of view concept. This patch addresses the issue by adding the ranges::view constraint to the second template parameter of _Utf_view, and for clarity renaming it from _Range to _View. The constructor is also adjusted to accept its argument by value (views must be O(1) move-constructible). This prevents implicitly generated CTAD from deducing a reference type. This makes _Utf_view consistent with both other standard views and the wording from P2728R8: Unicode in the Library, Part 1: UTF Transcoding [1]. The explicit CTAD from viewable_range is not defined for _Utf_view because it depends on views::all_t, views::ref_view, and views::owning_view, which are declared in <ranges>. Consequently, users must explicitly cast the argument to a view or specify it as a template parameter. [1] https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2728r8.html libstdc++-v3/ChangeLog: * include/bits/unicode.h (_Utf_view): Rename the template parameter from _Range to _View and constrain it with ranges::view. (_Utf_view::_Utf_view): Accept by value instead of rvalue reference. * include/std/format (__format::__write_padded): Replace _Utf_view over const char32_t(&)[1] with span<const char32_t, 1>. * testsuite/ext/unicode/view.cc: Add checks if specialization of _Utf_view satisfy view. Wrap arrays into std::span before constructing _Utf_view. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-11-14libstdc++: Add comment to __cpp_lib_bitset preprocessor conditionJonathan Wakely
libstdc++-v3/ChangeLog: * include/std/bitset: Add comment to feature test macro test.
2025-11-14libstdc++: std::bitset<0>("zero") should throw std::invalid_argument [PR121054]Karpalo Toivonen
According to the standard the first n characters of a bitset constructor string need to be checked instead of only N. libstdc++-v3/ChangeLog: PR libstdc++/121054 * include/std/bitset: Add string check to constructor. * testsuite/20_util/bitset/121054.cc: New test. * testsuite/20_util/bitset/cons/constexpr_c++23.cc: Fix. Co-authored-by: Jonathan Wakely <jwakely@redhat.com>
2025-11-14libstdc++: Use _Bind_front_t/_Bind_back_t in bind_front<f>/bind_back<f> ↵Tomasz Kamiński
[PR122032] This patch changes the implementation of bind_front<f> and bind_back<f> to return a _Bind_front_t<_Bind_fn_t<f>, ...> and _Bind_back_t<_Bind_fn_t<f>, ...> respectively, replacing the previous lambda-based implementation. The prior use of a lambda caused non-conforming behavior with respect to C++23 [func.require] p8, which requires that bind_front<f>(s), bind_front<f>(move(s)), and bind_front<f>(as_const(s)) produce the same type. Additionally, using specialized structs reduces the size of the resulting functor in certain scenarios (see PR). For the zero-argument case, the function still returns a _Bind_fn_t<f>. Since this type is already a perfect forwarding call wrapper, it yields the same result as _Bind_front_t<_Bind_fn_t<f>>. A consequence of this change is that the types returned by bind_front<f>(args...) and bind_back<f>(args...) are no longer structural - they are not required to be structural by the standard. PR libstdc++/122032 libstdc++-v3/ChangeLog: * include/std/functional (std::bind_front<f>, std::bind_back<f>): Define in terms of _Bind_front_t/_Bind_back_t. * testsuite/20_util/function_objects/bind_back/nttp.cc: New tests. * testsuite/20_util/function_objects/bind_front/nttp.cc: New tests. Reviewed-by: Patrick Palka <ppalka@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-11-13libstdc++: Optimize handling of optional for views: take, drop, reverse and ↵Tomasz Kamiński
as_const. This implements P3913R1: Optimize for std::optional in range adaptors. Specifically, for an opt of type optional<T> that is a view: * views::reverse(opt), views::take(opt, n), and views::drop(opt, n) returns optional<T>. * views::as_const(opt), optional<T&> is converted into optional<const T&>. optional<T const> is not used in the non-reference case because, such type is not move assignable, and thus not a view. libstdc++-v3/ChangeLog: * include/std/optional (__is_optional_ref): Define. * include/std/ranges (_Take::operator(), _Drop::operator()) (_Reverse::operator()): Handle optional<T> that are view. (_AsConst::operator()): Handle optional<T&>. * testsuite/20_util/optional/range.cc: New tests. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-11-12libstdc++: Add ranges::borrowed_range specialization for optional<T&> [PR122425]Tomasz Kamiński
PR libstdc++/122425 libstdc++-v3/ChangeLog: * include/std/optional (ranges::enable_borrowed_range<optional<_Tp&>>): Define. * testsuite/20_util/optional/range.cc: Update tests. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-11-12libstdc++: optional<T&> for function and unbounded array should not be range ↵Tomasz Kamiński
[PR122396] This implements proposed resolution for LWG4308 [1]. For T denoting either function type or unbounded array, the optional<T&> no longer exposes iterator, and viable begin/end members. The conditionally provided iterator type, it is now defined in __optional_ref_base base class. Furthermore, range support for optional<T&> is now also guarded by __cpp_lib_optional_range_support. [1] https://cplusplus.github.io/LWG/issue4308 PR libstdc++/122396 libstdc++-v3/ChangeLog: * include/std/optional (__optional_ref_base): Define. (std::optional<_Tp&>): Inherit from __optional_ref_base<_Tp>. (optional<_Tp&>::iterator): Move to base class. (optional<_Tp&>::begin, optional<_Tp&>::end): Use deduced return type and constrain accordingly. * testsuite/20_util/optional/range.cc: Add test for optional<T&>. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-30libstd++: Implement C++23 P2674R1 - A trait for implicit lifetime typesJakub Jelinek
The following patch attempts to implement the library side of the C++23 P2674R1 paper. As mentioned in the paper, since CWG2605 the trait isn't really implementable purely on the library side. The compiler side has been committed earlier, so this just uses the new builtin trait on the library side. 2025-10-30 Jakub Jelinek <jakub@redhat.com> * include/bits/version.def (is_implicit_lifetime): New. * include/bits/version.h: Regenerate. * include/std/type_traits (std::is_implicit_lifetime, std::is_implicit_lifetime_v): New trait. * src/c++23/std.cc.in (std::is_implicit_lifetime, std::is_implicit_lifetime_v): Export. * testsuite/20_util/is_implicit_lifetime/version.cc: New test. * testsuite/20_util/is_implicit_lifetime/value.cc: New test.
2025-10-29libstdc++: Implement const copy-assignment for tuple<> [PR119721]Tomasz Kamiński
This patch completes the implementation of P2321R2, giving tuple proper proxy reference semantics. The assignment operator is implemented as a template constrained to accept only tuple<>. Consequently, the language does not consider it a copy assignment operator, which prevents tuple<> from losing its trivially copyable status. The _Tuple template parameter is defaulted, ensuring the operator remains a viable candidate for assignment with an empty brace-init list. PR libstdc++/119721 libstdc++-v3/ChangeLog: * include/std/tuple (tuple<>::operator=(const _Tuple&) const) [__cpp_lib_ranges_zip]: Define. * testsuite/23_containers/tuple/cons/119721.cc: Test const assignment. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-29libstdc++: Add constructors and assignments for tuple<> with tuple-like ↵Osama Abdelkader
types [PR119721] This patch adds support for constructing and assigning tuple<> from other empty tuple-like types (e.g., array<T, 0>), completing the C++23 tuple-like interface for the zero-element tuple specialization. The implementation includes: - Constructor from forwarding reference to tuple-like types - Allocator-aware constructor from tuple-like types - Assignment operator from tuple-like types - Const assignment operator from tuple-like types PR libstdc++/119721 libstdc++-v3/ChangeLog: * include/std/tuple (tuple<>::tuple(const tuple&)) (tuple<>::operator=(const tuple&)): Define as defaulted. (tuple<>::swap): Moved the defintion after assignments. (tuple<>::tuple(_UTuple&&)) (tuple<>::tuple(allocator_arg_t, const _Alloc&, _UTuple&&)) (tuple<>::operator=(_UTuple&&)) [__cpp_lib_tuple_like]: Define. (tuple<>::operator==, tuple<>::opeator<=>): Parenthesize constrains individually. * testsuite/23_containers/tuple/cons/119721.cc: New test for constructors and assignments with empty tuple-like types. * testsuite/20_util/tuple/requirements/empty_trivial.cc: New test verifying tuple<> remains trivially copyable. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Co-authored-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-29libstdc++: Simplify std::regex_traits::valueJonathan Wakely
We don't need to use an istringstream to convert a hex digit to its numerical value. And if we don't use istringstream there, we don't need to include <sstream> in <regex>. libstdc++-v3/ChangeLog: * include/bits/regex.tcc (regex_traits::value): Implement without using istringstream. * include/std/regex: Do not include <sstream>. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-27libstdc++: Make std::valarray support overaligned types [PR108951]Jonathan Wakely
Switch std::valarray<T> memory allocation to use std::__new_allocator<T> to allocate and deallocate memory. This adds support for extended alignment types without needing to duplicate all the logic from __new_allocator::allocate and __new_allocator::dellocate. std::__new_allocator is used instead of std::allocator because we want to ensure that the memory is still allocated with operator new, so we don't want to use any possible program-defined specialization of std::allocator<T> which the user might have provided. To make using an allocator possible, __valarray_release_memory needs to become a function template so that it knows the type T. It also needs an additional parameter specifying the size of the allocation. This change doesn't cause an ABI change for types with fundamental alignment, because __new_allocator still uses the same operator delete function (or the sized version, which is ABI compatible) to free the memory. So if memory for a valarray is allocated in one translation unit and deallocated in another, and those TUs are compiled with different versions of GCC, we still get memory from the same operator new and release it with the same operator delete (or the compatibled sized version). For types with extended alignment this does potentially cause an ABI change on targets where the aligned version of operator delete doesn't just call free(p), but support for extended alignment types was previously just broken and had undefined behaviour. libstdc++-v3/ChangeLog: PR libstdc++/108951 * include/bits/valarray_array.h( __valarray_get_storage): Use std::__new_allocator. (__valarray_release_memory): Likewise. * include/std/valarray: Pass _M_size to __valarray_release_memory. * testsuite/26_numerics/valarray/108951.cc: New test. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-24libstdc++: Forward arguments for bind_front<f>,bind_back<f>,nttp<f> [PR122022]Tomasz Kamiński
This patch fixes a missing forwarding-reference (&&) in _Bind_fn_t::operator() and lambda returned from not_fn<f>. The bind_front<f>/bind_back<f> tests were updated to use a structure similar to r16-3398-g250dd5b5604fbc to cover cases involving zero, one, and many bound arguments. PR libstdc++/122022 libstdc++-v3/ChangeLog: * include/std/functional (_Bind_fn_t): Use forwarding reference as paremeter. (std::not_fn<f>): Use forwarding reference as lambda parameter. * testsuite/20_util/function_objects/bind_back/nttp.cc: Rework tests. * testsuite/20_util/function_objects/bind_front/nttp.cc: Likewise. * testsuite/20_util/function_objects/not_fn/nttp.cc: Add test for argument forwarding.
2025-10-22libstdc++: Add missing constraints to views::indicesJonathan Wakely
Calling views::indices(n) should be expression equivalent to views::iota(decltype(n)(0), n), which means it should have the same constraints as views::iota and be SFINAE-friendly. libstdc++-v3/ChangeLog: * include/std/ranges (indices::operator()): Constrain using __can_iota_view concept. * testsuite/std/ranges/indices/1.cc: Check SFINAE-friendliness required by expression equivalence. Replace unused <vector> header with <stddef.h> needed for size_t.
2025-10-22libstdc++: Implement optional<T&> from P2988R12 [PR121748]Giuseppe D'Angelo
This patch implements optional<T&> based on the P2988R12 paper, incorporating corrections from LWG4300, LWG4304, and LWG3467. The resolution for LWG4015 is also extended to cover optional<T&>. We introduce _M_fwd() helper, that is equivalent to operator*(), except that it does not check non-empty precondition. It is used in to correctly propagate the value during move construction from optional<T&>. This is necessary because moving an optional<T&> must not move the contained object, which is the key distinction between *std::move(opt) and std::move(*opt). The implementation deviates from the standard by providing a separate std::swap overload for std::optional<T&>, which simplifies preserving the resolution of LWG2766. This introduces a few changes to make_optional behavior (see included test): * some previously valid uses of make_optional<T>({...}) (where T is not a reference type) now become ill-formed (see optional/make_optional_neg.cc). * make_optional<T&>(t) and make_optional<const T&>(ct), where decltype(t) is T&, and decltype(ct) is const T& now produce optional<T&> and optional<const T&> respectively, instead of optional<T>. * a few other uses of make_optional<R> with reference type R are now ill-formed. PR libstdc++/121748 libstdc++-v3/ChangeLog: * include/bits/version.def: Bump value for optional, * include/bits/version.h: Regenerate. * include/std/optional (std::__is_valid_contained_type_for_optional): Define. (std::optional<T>): Use __is_valid_contained_type_for_optional. (optional<T>(const optional<_Up>&), optional<T>(optional<_Up>&&)) (optional<T>::operator=(const optional<_Up>&)) (optional<T>::operator=(optional<_Up>&&)): Replacex._M_get() with x._M_fwd(), and std::move(x._M_get()) with std::move(x)._M_fwd(). (optional<T>::and_then): Remove uncessary remove_cvref_t. (optional<T>::_M_fwd): Define. (std::optional<T&>): Define new partial specialization. (std::swap(std::optional<T&>, std::optional<T&>)): Define. (std::make_optional(_Tp&&)): Add non-type template parameter. (std::make_optional): Use parenthesis to constructor optional. (std::hash<optional<T>>): Add comment. * testsuite/20_util/optional/make_optional-2.cc: Guarded not longer working example. * testsuite/20_util/optional/relops/constrained.cc: Expand test to cover optionals of reference. * testsuite/20_util/optional/requirements.cc: Ammend for optional<T&>. * testsuite/20_util/optional/requirements_neg.cc: Likewise. * testsuite/20_util/optional/version.cc: Test new value of __cpp_lib_optional. * testsuite/20_util/optional/make_optional_neg.cc: New test. * testsuite/20_util/optional/monadic/ref_neg.cc: New test. * testsuite/20_util/optional/ref/access.cc: New test. * testsuite/20_util/optional/ref/assign.cc: New test. * testsuite/20_util/optional/ref/cons.cc: New test. * testsuite/20_util/optional/ref/internal_traits.cc: New test. * testsuite/20_util/optional/ref/make_optional/1.cc: New test. * testsuite/20_util/optional/ref/make_optional/from_args_neg.cc: New test. * testsuite/20_util/optional/ref/make_optional/from_lvalue_neg.cc: New test. * testsuite/20_util/optional/ref/make_optional/from_rvalue_neg.cc: New test. * testsuite/20_util/optional/ref/monadic.cc: New test. * testsuite/20_util/optional/ref/relops.cc: New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Co-authored-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-22libstdc++: Add comparison operators between tuple<> and array<T, 0> [PR119721]Osama Abdelkader
This fixes the C++23 compliance issue where std::tuple<> cannot be compared with other empty tuple-like types such as std::array<T, 0>. The operators correctly allow comparison with array<T, 0> even when T is not comparable, because empty tuple-like types don't compare element values. PR libstdc++/119721 libstdc++-v3/ChangeLog: * include/std/tuple (tuple<>::operator==, tuple<>::operator<=>): Define. * testsuite/23_containers/tuple/comparison_operators/119721.cc: New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
2025-10-21libstdc++: Implement P3060R3: Add std::views::indices(n)Yuao Ma
This patch adds the views::indices function using iota. libstdc++-v3/ChangeLog: * include/bits/version.def: Add ranges_indices FTM. * include/bits/version.h: Regenerate. * include/std/ranges: Implement views::indices. * testsuite/std/ranges/indices/1.cc: New test.
2025-10-18libstdc++: Implement P1494 and P3641 Partial program correctness [PR119060]Iain Sandoe
This implements the library parts of P1494 as amended by P3641. For GCC the compiler itself treats stdio operations as equivalent to the observable checkpoint and thus it does not appear to be necessary to add calls to those functions (it will not alter the outcome). This adds the facility for C++26, although there is no reason, in principle, that it would not work back to C++11 at least. PR c++/119060 libstdc++-v3/ChangeLog: * include/bits/version.def: Add observable_checkpoint at present allowed from C++26. * include/bits/version.h: Regenerate. * include/std/utility: Add std::observable_checkpoint(). * src/c++23/std.cc.in: Add obervable_checkpoint () to utility. Signed-off-by: Iain Sandoe <iain@sandoe.co.uk>
2025-10-16libstdc++: Improve ostream output for std::stacktraceJonathan Wakely
With this change stacktrace entries always output the frame address, and source file information no longer results in " at :0", e.g. 16# myfunc(int) at /tmp/bt.cc:48 [0x4008b7] 17# main at /tmp/bt.cc:61 [0x40091a] 18# __libc_start_call_main [0x7efc3d6d3574] 19# __libc_start_main@GLIBC_2.2.5 [0x7efc3d6d3627] 20# _start [0x400684] This replaces the previous output: 16# myfunc(int) at /tmp/bt.cc:48 17# main at /tmp/bt.cc:61 18# __libc_start_call_main at :0 19# __libc_start_main@GLIBC_2.2.5 at :0 20# _start at :0 A change that is not visible in the examples above is that for a non-empty stacktrace_entry, we now print "<unknown>" for the function name if description() returns an empty string. For an empty (e.g. default constructed) stacktrace_entry the entire string representation is now "<unknown>" instead of an empty string. Instead of printing "<unknown>" for the function name, we could set that string in the stacktrace_entry::_Info object, so that description() returns "<unknown>" and then operator<< wouldn't need to handle an empty description() string. However, returning an empty string from that function seems simpler for users to detect, rather than having to parse "<unknown>". We could also choose a different string for an empty stacktrace_entry, maybe "<none>" or "<invalid>", but "<unknown>" seems good. libstdc++-v3/ChangeLog: * include/std/stacktrace (operator<<(ostream&, const stacktrace_entry&)): Improve output when description() or source_file() returns an empty string, or the stacktrace_entry is invalid. Append frame address to output. (operator<<(ostream&, const basic_stacktrace<A>&)): Use the size_type of the correct specialization. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Reviewed-by: Nathan Myers <nmyers@redhat.com>
2025-10-15libstdc++: Remove invalid entry from the end of std::stacktraceJonathan Wakely
The backtrace_simple function seems to consistently invoke the callback with an invalid -1UL value as the last entry, which seems to come from _Unwind_Backtrace. The glibc backtrace(3) function has a special case to not include that final invalid address, but libbacktrace doesn't seem to handle it. Do so in std::stacktrace::current() instead. libstdc++-v3/ChangeLog: * include/std/stacktrace (basic_stacktrace::current): Call _M_trim before returning. (basic_stacktrace::_M_trim): New member function.
2025-10-14libstdc++: Avoid overflow in timeout conversions [PR113327]Jonathan Wakely
When converting from a coarse duration with a very large value, the existing code scales that up to chrono::seconds which overflows the chrono::seconds::rep type. For example, sleep_for(chrono::hours::max()) tries to calculate LLONG_MAX * 3600, which overflows to -3600 and so the sleep returns immediately. The solution in this commit is inspired by this_thread::sleep_for in libc++ which compares the duration argument to chrono::duration<long double>(nanoseconds::max()) and limits the duration to nanoseconds::max(). Because we split the duration into seconds and nanoseconds, we can use seconds::max() as our upper limit. We might need to limit further if seconds::max() doesn't fit in the type used for sleeping, which is one of std::time_t, unsigned int, or chrono::milliseconds. To fix this everywhere that uses timeouts, new functions are introduced for converting from a chrono::duration or chrono::time_point to a timespec (or __gthread_time_t which is just a timespec on Linux). These functions provide one central place where we can avoid overflow and also handle negative timeouts (as these produce errors when passed to OS functions that do not accept absolute times before the epoch). All negative durations are converted to zero, and negative time_points are converted to the epoch. The new __to_timeout_gthread_time_t function in <bits/std_mutex.h> requires adding <bits/chrono.h> to that header, but that only affects <syncstream>. All other consumers of <bits/std_mutex.h> were already including <bits/chrono.h> for timeouts (e.g. <shared_mutex> and <condition_variable>). libstdc++-v3/ChangeLog: PR libstdc++/113327 PR libstdc++/116586 PR libstdc++/119258 PR libstdc++/58931 * include/bits/chrono.h (__to_timeout_timespec): New overloaded function templates for converting chrono types to timespec. * include/bits/std_mutex.h (__to_timeout_gthread_time_t): New function template for converting time_point to __gthread_time_t. * include/bits/this_thread_sleep.h (sleep_for): Use __to_timeout_timespec. (__sleep_for): Remove namespace-scope declaration. * include/std/condition_variable: Likewise. * include/std/mutex: Likewise. * include/std/shared_mutex: Likewise. * src/c++11/thread.cc (limit): New helper function. (__sleep_for): Use limit to prevent overflow when converting chrono::seconds to time_t, unsigned, or chrono::milliseconds. * src/c++20/atomic.cc: Use __to_timeout_timespec and __to_timeout_gthread_time_t for timeouts. * testsuite/30_threads/this_thread/113327.cc: New test. Reviewed-by: Mike Crowe <mac@mcrowe.com> Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-14libstdc++: Remove unused local type alias <format>.Luc Grosheintz
After r16-4421-g59cabe08b57a26 the local type alias _String isn't used anymore and therefore causes warnings when building the tests with `-Wall -Wextra`. libstdc++-v3/ChangeLog: * include/std/format (_M_format_range): Remove unused local type alias _String. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>0 Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-10-14libstdc++: Implement _Escaping_sink to avoid construction of stringTomasz Kamiński
This patch implements _Escaping_sink that stores characters in a local (stack) buffer. When the buffer is full, the range of characters is escaped and written to the underlying sink. To support above, the __write_escaped_unicode_part function are defined. It takes __str and __prev_esc by reference. The __prev_esc value is updated based on the last character written. If the buffer ends with an incomplete code point sequence, __str is left non-empty and last code points are not written. _Escaping_sink then copies these characters to the front of the buffer to reconstruct the full code point. __formatter__str::_M_format_range now uses _Escaping_sink to escape any non-continuous character sequences. libstdc++-v3/ChangeLog: * include/std/format (__format::__write_escape_seqs) (__format::_Escaping_sink): Define. (__format::__write_escaped_unicode_part): Extract from __format::__write_escaped_unicode. (__format::__write_escaped_unicode): Forward to __write_escaped_unicode_part. (__formatter_str::_M_format_range): Use _Escaping sink. * testsuite/std/format/ranges/string.cc: New tests for character which codepoints will be split in buffer and escaping. Invoked test_padding. Reviewed-by: Patrick Palka <ppalka@redhat.com> Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-10libstdc++: Adjust enable_nonlocking_formatter_optimization specializations ↵Tomasz Kamiński
[PR121790] This patch addresses several issues related to the additional specializations for enable_nonlocking_formatter_optimization fomr P3235R3 proposal: * LWG4399 [1]: Apply remove_cvref_t to tuple and pair elements when checking if the direct printing optimization is enabled. * LWG4398 [2]: Disable the direct printing optimization for the standard library container adaptors: queue, priority_queue, and stack. * LWG4400 [3]: Enable the direct printing optimization only for durations that use standard arithmetic types. Conditionally enable it for hh_mm_ss and time_points based on their underlying Duration template argument. [1] https://cplusplus.github.io/LWG/issue4399 [2] https://cplusplus.github.io/LWG/issue4398 [3] https://cplusplus.github.io/LWG/issue4400 PR libstdc++/121790 libstdc++-v3/ChangeLog: * include/bits/chrono_io.h (enable_nonlocking_formatter_optimization): Adjust specializations for duration, hh_mm_ss and time_points. * include/std/format (enable_nonlocking_formatter_optimization): Apply remove_cvref_t on pair and tuple elements. * include/std/queue (enable_nonlocking_formatter_optimization): Change specialization value to false. * include/std/stack (enable_nonlocking_formatter_optimization): Change specialization value to false. * testsuite/std/format/ranges/adaptors.cc: Adjusted tests. * testsuite/std/format/tuple.cc: Adjusted tests. * testsuite/std/time/format/nonlocking.cc: Adjusted tests. Reviewed-by: Jonathan Wakely <jwakely@redhat.com>
2025-10-10libstdc++: Implement P3235R3 optimizations for std::print [PR121790]Tomasz Kamiński
This patch implements additional enable_nonlocking_formatter_optimization specializations listed in P3235R3. PR libstdc++/121790 libstdc++-v3/ChangeLog: * include/bits/chrono_io.h (enable_nonlocking_formatter_optimization): Define specializations for chrono types. * include/bits/version.def (print): Bump. * include/bits/version.h: Regenerate. * include/std/format (enable_nonlocking_formatter_optimization): Define specializations for pair, tuple and ranges. * include/std/queue (enable_nonlocking_formatter_optimization): Define specializations for queue and priority_queue. * include/std/stack (enable_nonlocking_formatter_optimization): Define specialization for stack. * include/std/stacktrace (enable_nonlocking_formatter_optimization): Define specialization for basic_stacktrace and stacktrace_entry. * include/std/thread (enable_nonlocking_formatter_optimization): Define specialization for thread::id. * include/std/vector (enable_nonlocking_formatter_optimization): Define specialization for vector<bool>::reference. * testsuite/23_containers/vector/bool/format.cc: Test value of enable_nonlocking_formatter_optimization. * testsuite/30_threads/thread/id/output.cc: Likewise. * testsuite/std/format/ranges/adaptors.cc: Likewise. * testsuite/std/format/ranges/formatter.cc: Likewise. * testsuite/std/format/tuple.cc: Likewise. * testsuite/std/time/format/empty_spec.cc: Extract Rep class to custom_rep.h. * testsuite/std/time/format/custom_rep.h: Extracted from empty_spec.cc. * testsuite/std/time/format/nonlocking.cc: New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com>
2025-10-10libstdc++: Implement P3107R5 optimizations for std::print [PR121790]Jonathan Wakely
The names of the vprint functions follow the convention from P3235R3. This takes advantage of the additional permission proposed by P3107R5 so that std::print can write directly to a FILE stream, rather than formatting to an intermediate std::string temporary and then writing that to the stream. The change is to write to a new _File_sink type instead of a _Str_sink that populates a std::string. There are three implementations of _File_sink. For non-Glibc targets that support POSIX flockfile and putc_unlocked, the stream will be locked and then formatted characters will be buffered on the stack (instead of allocating a std::string) and copied to the stream when the buffer fills up. For Glibc, _File_sink will lock the stream but then if the file is line-buffered or fully buffered, characters will be written directly into the file's output buffer. This avoids two levels of buffering and copying the characters from one to the other. For an unbuffered stream (like stderr) the _File_sink buffer will still be used, to avoid the overhead of lots of small writes to the stream. Because this version of _File_sink accesses the stream's buffer directly it relies on glibc-specific implementation details that are exposed in public headers. A fallback definition of _File_sink just wraps a _Str_sink so is equivalent to the original code, and is used when flockfile isn't available. Both forms of std::println (taking a FILE* and a std::ostream) can be implemented more efficiently by appending a newline to the format string, to avoid formatting twice. PR libstdc++/121790 libstdc++-v3/ChangeLog: * acinclude.m4 (GLIBCXX_CHECK_STDIO_LOCKING): New macro to check for std::print dependencies. * config.h.in: Regenerate. * configure: Regenerate. * configure.ac: Use GLIBCXX_CHECK_STDIO_LOCKING. * include/bits/formatfwd.h (enable_nonlocking_formatter_optimization): Define new variable template. * include/bits/version.def (print): Bump value. * include/bits/version.h: Regenerate. * include/std/format (enable_nonlocking_formatter_optimization): Define specializations for variable template. * include/std/ostream (print) [!_WIN32]: Do not use vprint_unicode at all. (println): Append newline to format string instead of formatting twice. * include/std/print (_File_sink): New class. (vprint_nonunicode_locking): New function. (vprint_unicode_locking): New function reusing previous code from vprint_unicode. (vprintf_unicode): Defer to vprint_nonunicode for Windows or to vprint_unicode_locking otherwise. (print): [!_WIN32]: Do no use vprint_unicode at all. Check enable_nonlocking_formatter_optimization and defer to either vprint_nonunicode_locking or vprint_nonunicode. (println): Use vprint_unicode or format directly to a _File_sink instead of formatting twice. * testsuite/27_io/print/1.cc: Updated and added new tests. * testsuite/std/format/formatter/nonlocking.cc: New tests. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Co-authored-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-10libstdc++: Handle cv-qualified types in atomic and atomic_ref [PR115402]Giuseppe D'Angelo
Implements P3233R1 (DR for C++20/C++11, fixes LWG 4069 and 3508). This commit implements std::atomic_ref<cv T> support (LWG3508) as DR for C++20, by extractingparts of the __atomic_ref class (that atomic_ref inherits from) into a further base class (__atomic_ref_base): * __atomic_ref_base<const T> implements non-mutating (const) atomic API. Single base class is used, and the difference in is_always_lock_free and required_aligment values between types are handled by _S_is_always_lock_free, _S_required_aligment helper functions. * __atomic_ref_base<T> implements the common atomic APIs. The non-mutating operations are handled by inherting from __atomic_ref_base<const T> partial partial specialization. Tu support that __atomic_ref_base<const T> stores mutable pointer to T, and performs const_cast in constructor. * __atomic_ref<T, ....> inherits from __atomic_ref_base<T>, and implement type-specific mutable APIs (fetch_add, -=, ...) and difference_type member type. * __atomic_ref<const T, ...> inherits from __atomic_ref_base<const T> and adds different_type member, whose presence and denoted type depends on T. The __atomic_ref specialization selection is adjusted to handle cv-qualified bool (add remove_cv_t) and pointer types. To handle the later, additional constant template parameter is introduced. The atomic wait and notify operations are currently not supported for volatile types, to signal that static assert is added to corresponding methods of atomic_ref. At the same time, disable support for cv-qualified types in std::atomic (for instance, std::atomic<volatile T> isn't meaningful; one should use volatile std::atomic<T>), again as per the paper, resolving LWG4069 as DR for C++11. This only affects atomic<volatile T>, as specialization atomic with const-qualifed types was already producing an compile-time error. PR libstdc++/115402 libstdc++-v3/ChangeLog: * include/bits/atomic_base.h (__atomic_ref_base<const _Tp>) (__atomic_ref_base<_Tp>): Define by extracting common methods from atomic_ref specializations. (__atomic_ref<_Tp, In, Fp, Pt>): Inherit from __atomic_ref_base and remove extracted method. (__atomic_ref<const _Tp, In, Fp, Pt>): Define. * include/std/atomic (std::atomic): Added an * testsuite/29_atomics/atomic/requirements/types_neg.cc: Add test for volatile qualified types. * testsuite/29_atomics/atomic_ref/bool.cc: Move the content to op_support.cc, add test for bool. * testsuite/29_atomics/atomic_ref/op_support.cc: New test expanded from atomic_ref/bool.cc. * testsuite/29_atomics/atomic_ref/cv_qual.cc: New test. * testsuite/29_atomics/atomic_ref/requirements_neg.cc: New test. * testsuite/29_atomics/atomic_ref/deduction.cc: Add tests for cv-qualified types. * testsuite/29_atomics/atomic_ref/float.cc: Likewise. * testsuite/29_atomics/atomic_ref/generic.cc: Likewise. * testsuite/29_atomics/atomic_ref/integral.cc: Likewise. * testsuite/29_atomics/atomic_ref/pointer.cc: Likewise. * testsuite/29_atomics/atomic_ref/requirements.cc: Likewise. * testsuite/29_atomics/atomic_ref/wait_notify.cc: Add tests for const qualified types. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Co-authored-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Giuseppe D'Angelo <giuseppe.dangelo@kdab.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-10-08libstdc++: Implement submdspan_mapping_result. [PR110352]Luc Grosheintz
Implement the class submdspan_mapping_result and add it to the std module. PR libstdc++/110352 libstdc++-v3/ChangeLog: * include/std/mdspan (submdspan_mapping_result): New class. * src/c++23/std.cc.in (submdspan_mapping_result): Add. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-10-08libstdc++: Implement full_extent_t. [PR110352]Luc Grosheintz
Add the class and updates the std module. PR libstdc++/110352 libstdc++-v3/ChangeLog: * include/std/mdspan (full_extent_t): New class. * src/c++23/std.cc.in (full_extent_t): Add. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-10-08libstdc++: Implement strided_slice from <mdspan>. [PR110352]Luc Grosheintz
Adds strided_slice as standardized in N5014. Also creates the internal feature testing macro for submdspan. PR libstdc++/110352 libstdc++-v3/ChangeLog: * include/bits/version.def (submdspan): New internal macro. * include/bits/version.h: Regenerate. * include/std/mdspan (strided_slice): New class. * src/c++23/std.cc.in (strided_slice): Add. * testsuite/23_containers/mdspan/submdspan/strided_slice.cc: New test. * testsuite/23_containers/mdspan/submdspan/strided_slice_neg.cc: New test. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-10-08libstdc++: Improve and cleanup mdspan related code.Luc Grosheintz
The improvement is that in __index_type_cast, we don't need to check at runtime if we know that _IndexType is smaller than _OIndexType. The cleanup is whitespace (overlength lines) in <mdspan>, grouping is_always_foo and is_foo together, and de-uglifying a variable in test code. libstdc++-v3/ChangeLog: * include/std/mdspan (__mdspan::__index_type_cast): Optimize by skipping a __glibcxx_assert if it's know at compile-time. (std::layout_left_padded, std::layout_righ_padded): Reorder is_always_strided and is_unique member functions. * testsuite/23_containers/mdspan/int_like.h: Rename _M_i to value. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-10-08libstdc++: Implement std::layout_right_padded [PR110352].Luc Grosheintz
This commit adds the right padded layout as described in N5014, with LWG4372 (dynamic padding value) and LWG4314 (move in operator()). PR libstdc++/110352 libstdc++-v3/ChangeLog: * include/std/mdspan (_RightPaddedIndices): Traits for right padded layouts. (layout_right::mapping::mapping) New overload for right padded layouts. (layout_right_padded): Add implementation. * src/c++23/std.cc.in (layout_right_padded): Add. * testsuite/23_containers/mdspan/layouts/ctors.cc: Update test for right padded layouts. * testsuite/23_containers/mdspan/layouts/empty.cc: Ditto. * testsuite/23_containers/mdspan/layouts/mapping.cc: Ditto. * testsuite/23_containers/mdspan/layouts/padded.cc: Ditto. * testsuite/23_containers/mdspan/layouts/padded_neg.cc: Ditto. * testsuite/23_containers/mdspan/layouts/padded_traits.h: Ditto. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-10-08libstdc++: Implement std::layout_left_padded [PR110352].Luc Grosheintz
This commit adds a new layout layout_left_padded as standardized in N5014. It adds a purely internal feature testing macro padded_layouts and registers layout_left_padded in the std module. This commit implements LWG4372, because without it's not possible to properly test padded layouts with a dynamic padding value. It also implements LWG4314, for consistency with prior layouts. The implementation uses a _PaddedStorage to deduplicate most of the code shared between left- and right-padded layouts. It's implemented through aggregation rather than inheritence, because of a bug related to inheriting conditionally explicit ctors. The tests are written such that the canonical version works for layout_left_padded. A version for layout_right_padded is derived essentially by reversing the order of the extents. PR libstdc++/110352 libstdc++-v3/ChangeLog: * include/bits/version.def (padded_layouts): Add new internal feature testing macro. * include/bits/version.h: Regenerate. * include/std/mdspan (__fwd_prod): New overload. (layout_left_padded): Add declaration and implementation. (layout_right_padded): Add declaration only. (layout_left::mapping::mapping): New overload for left padded mappings. (__index_type_cast): New function that performs a checked cast to index_type. (__is_left_padded_mapping): New concept. (__is_right_padded_mapping): Ditto. (__standardized_mapping): Recognize left and right padded mappings. (_LeftPaddedIndices): Traits for left padded details. (_PaddedStorage): New class for implementing padded layouts. * src/c++23/std.cc.in (layout_left_padded): Add. * testsuite/23_containers/mdspan/layouts/class_mandate_neg.cc: Refactor and add tests for layout_left_padded. * testsuite/23_containers/mdspan/layouts/ctors.cc: Ditto. * testsuite/23_containers/mdspan/layouts/empty.cc: Ditto. * testsuite/23_containers/mdspan/layouts/mapping.cc: Ditto. * testsuite/23_containers/mdspan/layouts/padded.cc: Ditto. * testsuite/23_containers/mdspan/layouts/padded_neg.cc: Ditto. * testsuite/23_containers/mdspan/layouts/padded_traits.h: New traits. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-10-01libstdc++: Avoid _GLIBCXX20_CONSTEXPR in C++ >= 20 code sectionsFrançois Dumont
libstdc++-v3/ChangeLog: * include/std/vector (std::erase_if, std::erase): Replace _GLIBCXX20_CONSTEXPR with 'constexpr' and remove implied 'inline' keyword. * include/std/string (std::erase_if, std::erase): Likewise.
2025-09-30libstdc++: std::inplace_vector implementation cleaupFrançois Dumont
Remove duplicated std::swap implementation. libstdc++-v3/ChangeLog * include/std/inplace_vector: (std::swap(inplace_vector<>&, inplace_vector<>&)): Remove the duplicated implementation at std namespace level. Keep the friend inline one. (inplace_vector<Tp, 0>::assign(initializer_list<>)): Add missing return statement.
2025-09-27libstdc++: Fix some -Wsign-compare warnings in headersJonathan Wakely
In all these cases we know the value with signed type is not negative so the cast is safe. libstdc++-v3/ChangeLog: * include/bits/deque.tcc (deque::_M_shrink_to_fit): Cast difference_type to size_type to avoid -Wsign-compare warning. * include/std/spanstream (basic_spanbuf::seekoff): Cast streamoff to size_t to avoid -Wsign-compare warning.
2025-09-26libstdc++: Simplify std::erase functions for sequence containersJonathan Wakely
This removes the use of std::ref that meant that __remove_if used an indirection through the reference, which might be a pessimization. Users can always use std::ref to pass expensive predicates into erase_if, but we shouldn't do it unconditionally. We can std::move the predicate so that if it's not cheap to copy and the user didn't use std::ref, then we try to use a cheaper move instead of a copy. There's no reason that std::erase shouldn't just be implemented by forwarding to std::erase_if. I probably should have done that in r12-4083-gacf3a21cbc26b3 when std::erase started to call __remove_if directly. libstdc++-v3/ChangeLog: * include/std/deque (erase_if): Move predicate instead of wrapping with std::ref. (erase): Forward to erase_if. * include/std/inplace_vector (erase_if, erase): Likewise. * include/std/string (erase_if, erase): Likewise. * include/std/vector (erase_if, erase): Likewise. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-09-26libstdc++: Eliminate __gnu_cxx::__ops function objectsJonathan Wakely
This removes the indirect functors from <bits/predefined_ops.h> that are used by our STL algorithms. Currently we wrap all predicates and values into callables which accept iterator arguments, and automatically dereference the iterators. With this change we no longer do that dereferencing and so all predicates are passed values not iterators, and the algorithms that invoke those predicates must dereference the iterators. This avoids wrapping user-provided predicates into another predicate that does the dereferencing. User-provided predicates are now passed unchanged to our internal algos like __search_n. For the overloads that take a value instead of a predicate, we still need to create a predicate that does comparison to the value, but we can now use std::less<void> and std::equal_to<void> as the base predicate and bind the value to those base predicates. Because the "transparent operators" std::less<void> and std::equal_to<void> were not added until C++14, this change defines those explicit specializations unconditionally for C++98 and C++11 too (but the default template arguments that make std::less<> and std::equal_to<> refer to those specializations are still only present for C++14 and later, because we don't need to rely on those default template arguments for our internal uses). When binding a predicate and a value into a new call wrapper, we now decide whether to store the predicate by value when it's an empty type or a scalar (such as a function pointer). This avoids a double-indirection through function pointers, and avoids storing and invoking stateless empty functors through a reference. For C++11 and later we also use [[no_unique_address]] to avoid wasted storage for empty predicates (which includes all standard relational ops, such as std::less). The call wrappers in bits/predefined_ops.h all have non-const operator() because we can't be sure that the predicates they wrap are const-invocable. The requirements in [algorithms.requirements] for Predicate and BinaryPredicate template arguments require pred(*i) to be valid, but do not require that std::to_const(pred)(*i) has to be valid, and similarly for binary_pred. libstdc++-v3/ChangeLog: * include/bits/predefined_ops.h (equal_to, less): Define aliases for std::equal_to<void> and std::less<void>. (bind1st, bind2nd, not1, __equal_to): New object generator functions for adapting predicates. (__iter_less_iter, __iter_less_val, __iter_comp_val) (__val_less_iter, __val_comp_iter, __iter_equal_to_iter) (__iter_equal_to_val, __iter_comp_iter, __negate): Remove all object generator functions and the class templates they return. * include/bits/stl_algo.h (__move_median_to_first, __find_if_not) (__find_if_not_n, __search_n_aux, find_end, find_if_not) (__remove_copy_if, remove_copy, remove_copy_if, remove) (remove_if, __adjacent_find, __unique, unique, __unique_copy) (__unique_copy_1, __stable_partition_adaptive, stable_partition) (__heap_select, __partial_sort_copy, partial_sort_copy) (__unguarded_linear_insert, __insertion_sort) (__unguarded_insertion_sort, __unguarded_partition) (lower_bound, __upper_bound, upper_bound, __equal_range) (equal_range, binary_search, __move_merge_adaptive) (__move_merge_adaptive_backward, __merge_adaptive_resize) (__merge_without_buffer, inplace_merge, __move_merge) (__includes, includes, __next_permutation, next_permutation) (__prev_permutation, prev_permutation, __replace_copy_if) (replace_copy, replace_copy_if, __is_sorted_until) (is_sorted_until, __minmax_element, minmax_element, minmax) (is_permutation, __is_permutation, find, find_if, adjacent_find) (count, count_if, search, search_n, unique_copy, partial_sort) (nth_element, sort, __merge, merge, stable_sort, __set_union) (set_union, __set_intersection, set_intersection) (__set_difference, set_difference, __set_symmetric_difference) (set_symmetric_difference, __min_element, min_element) (__max_element, max_element, min, max): Use direct predicates instead of __iter_equal_to_iter, __iter_comp_iter, and __iter_less_iter, __negate etc. Dereference iterators when invoking predicates. * include/bits/stl_algobase.h (__lexicographical_compare_impl) (__lexicographical_compare::__lc, __lower_bound, lower_bound) (lexicographical_compare, __mismatch, mismatch, __find_if) (__count_if, __remove_if, __search, __is_permutation) (is_permutation, search): Likewise. * include/bits/stl_function.h (equal_to<void>, less<void>): Define transparent comparison functions for C++98 and C++11. * include/bits/stl_heap.h (__is_heap_until, __is_heap) (__push_heap, push_heap, __adjust_heap, pop_heap, make_heap) (sort_heap, is_heap_until, is_heap): Likewise. * include/std/deque (erase_if): Remove call to __pred_iter. (erase): Replace __iter_equals_val with __equal_to. * include/std/inplace_vector (erase_if, erase): Likewise. * include/std/string (erase_if, erase): Likewise. * include/std/vector (erase_if, erase): Likewise. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Reviewed-by: François Dumont <frs.dumont@gmail.com>
2025-09-25libstdc++: Refactor __mdspan::__static_quotient.Luc Grosheintz
For padded layouts we want to check that the product of the padded stride with the remaining extents is representable. Creating a second overload, allows passing in subspans of the static extents and retains the ergonomics for the common case of passing in all static extents. libstdc++-v3/ChangeLog: * include/std/mdspan (__static_quotient): New overload. Reviewed-by: Tomasz Kamiński <tkaminsk@redhat.com> Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Luc Grosheintz <luc.grosheintz@gmail.com>
2025-09-23libstdc++: Implement Philox Engine (PR119794)1nfocalypse
Conforms with errata LWG4143, LWG4153 for Philox Engine. PR libstdc++/119794 libstdc++-v3/ChangeLog: * include/bits/random.h (philox_engine): Define. * include/bits/random.tcc (philox_engine): Define member functions. * include/bits/version.def (philox_engine): New macro. * include/bits/version.h: Regenerated. * include/std/random: Define __glibcxx_want_philox_engine and include <bits/version.h>. * testsuite/26_numerics/random/pr60037-neg.cc: Adjust dg-error line number. * testsuite/26_numerics/random/philox4x32.cc: New test. * testsuite/26_numerics/random/philox4x64.cc: New test. * testsuite/26_numerics/random/philox_engine/cons/119794.cc: New test. * testsuite/26_numerics/random/philox_engine/cons/copy.cc: New test. * testsuite/26_numerics/random/philox_engine/cons/default.cc: New test. * testsuite/26_numerics/random/philox_engine/cons/seed.cc: New test. * testsuite/26_numerics/random/philox_engine/cons/seed_seq.cc: New test. * testsuite/26_numerics/random/philox_engine/operators/equal.cc: New test. * testsuite/26_numerics/random/philox_engine/operators/inequal.cc: New test. * testsuite/26_numerics/random/philox_engine/operators/serialize.cc: New test. * testsuite/26_numerics/random/philox_engine/requirements/constants.cc: New test. * testsuite/26_numerics/random/philox_engine/requirements/constexpr_data.cc: New test. * testsuite/26_numerics/random/philox_engine/requirements/constexpr_functions.cc: New test. * testsuite/26_numerics/random/philox_engine/requirements/typedefs.cc: New test.
2025-09-22libstdc++: Move start_lifetime_as functions to bits/stl_construct.h [PR106658]Tomasz Kamiński
This allows inplace_vector to use these functions without including the entire <memory> header. Preprocessor checks are changed to use __glibcxx macros, so new functions are available outside memory header, that exports __cpp_lib macros. PR libstdc++/106658 libstdc++-v3/ChangeLog: * include/bits/stl_construct.h (std::start_lifetime_as_array) (std::start_lifetime_as): Moved from std/memory, with update to guard macros. * include/std/memory (std::start_lifetime_as_array) (std::start_lifetime_as): Moved to bits/stl_construct.h. Reviewed-by: Jonathan Wakely <jwakely@redhat.com> Signed-off-by: Tomasz Kamiński <tkaminsk@redhat.com>
2025-09-19libstdc++: Add NTTP bind_front, -back, not_fn (P2714) [PR119744]Nathan Myers
Add non-type template parameter function-object/-pointer argument versions of bind_front, bind_back, and not_fn. This introduces a new internal type _Bind_fn_t to carry the template-argument function object when no arguments are bound, used in both bind_front and bind_back. Otherwise they return a lambda object that has captured the arguments. There is no need to change libstdc++-v3/src/c++23/std.cc.in because existing exports: "using std::bind_front;" etc. export the new overloads. libstdc++-v3/ChangeLog: PR libstdc++/119744 * include/bits/version.def: Redefine __cpp_lib_bind_front etc. * include/bits/version.h: Ditto. * include/std/functional: Add new bind_front etc. overloads * testsuite/20_util/function_objects/bind_back/1.cc: Check plumbing better * testsuite/20_util/function_objects/bind_back/nttp.cc: New test. * testsuite/20_util/function_objects/bind_back/nttp_neg.cc: New test. * testsuite/20_util/function_objects/bind_front/1.cc: Check plumbing better * testsuite/20_util/function_objects/bind_front/nttp.cc: New test. * testsuite/20_util/function_objects/bind_front/nttp_neg.cc: New test. * testsuite/20_util/function_objects/not_fn/nttp.cc: New test. * testsuite/20_util/function_objects/not_fn/nttp_neg.cc: New test. * testsuite/20_util/headers/functional/synopsis.cc: New decls.
2025-09-18libstdc++: Implement C++23 P2590R2 - Explicit lifetime management [PR106658]Jakub Jelinek
As I can't think of how the middle-end would treat __builtin_start_lifetime_as other than a blackbox and probably would need to be implemented as such inline asm in RTL, this patch just implements it using inline asm in the library. If not anything else, it can serve as fallback before we and/or clang get some builtin for it. Right now the inline asms pretend (potential) read from and write to the whole memory region and make optimizers forget where the return value points to. If the optimizers don't know where it points to, I think that should be good enough, but I'm a little bit afraid of possibly future optimizations trying to optimize q->c = 1; q->d = 2; auto p = std::start_lifetime_as<S>(q); if (p == reinterpret_cast<decltype (p)>(q)) return p->a + p->b; that because of the guarding condition or perhaps assertion we could simply use the q pointer in MEM_REFs with S type and be surprised by TBAA. Though if it is a must-alias case, then we should be fine as well. Though guess that would be the same case with a builtin. 2025-09-18 Jakub Jelinek <jakub@redhat.com> PR c++/106658 * include/bits/version.def: Implement C++23 P2590R2 - Explicit lifetime management. (start_lifetime_as): New. * include/bits/version.h: Regenerate. * include/std/memory (std::start_lifetime_as, std::start_lifetime_as_array): New function templates. * src/c++23/std.cc.in (std::start_lifetime_as, std::start_lifetime_as_array): Export. * testsuite/std/memory/start_lifetime_as/start_lifetime_as.cc: New test.