Commit 92b69215e6

Andrew Kelley <andrew@ziglang.org>
2021-08-17 08:30:18
update libcxx, libcxxabi, libunwind, and tsan to llvm 13 rc1
1 parent 1b8f0d8
Changed files (581)
lib
libcxx
include
__algorithm
__format
__functional
__iterator
__memory
__random
__ranges
__support
__utility
__variant
experimental
ext
src
libcxxabi
libunwind
tsan
interception
sanitizer_common
ubsan
src
lib/libcxx/include/__algorithm/adjacent_find.h
@@ -0,0 +1,51 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_ADJACENT_FIND_H
+#define _LIBCPP___ALGORITHM_ADJACENT_FIND_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+adjacent_find(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __pred) {
+  if (__first != __last) {
+    _ForwardIterator __i = __first;
+    while (++__i != __last) {
+      if (__pred(*__first, *__i))
+        return __first;
+      __first = __i;
+    }
+  }
+  return __last;
+}
+
+template <class _ForwardIterator>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+adjacent_find(_ForwardIterator __first, _ForwardIterator __last) {
+  typedef typename iterator_traits<_ForwardIterator>::value_type __v;
+  return _VSTD::adjacent_find(__first, __last, __equal_to<__v>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_ADJACENT_FIND_H
lib/libcxx/include/__algorithm/all_of.h
@@ -0,0 +1,37 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_ALL_OF_H
+#define _LIBCPP___ALGORITHM_ALL_OF_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Predicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred) {
+  for (; __first != __last; ++__first)
+    if (!__pred(*__first))
+      return false;
+  return true;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_ALL_OF_H
lib/libcxx/include/__algorithm/any_of.h
@@ -0,0 +1,37 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_ANY_OF_H
+#define _LIBCPP___ALGORITHM_ANY_OF_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Predicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+any_of(_InputIterator __first, _InputIterator __last, _Predicate __pred) {
+  for (; __first != __last; ++__first)
+    if (__pred(*__first))
+      return true;
+  return false;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_ANY_OF_H
lib/libcxx/include/__algorithm/binary_search.h
@@ -0,0 +1,61 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_BINARY_SEARCH_H
+#define _LIBCPP___ALGORITHM_BINARY_SEARCH_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/lower_bound.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _ForwardIterator, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+__binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
+{
+    __first = _VSTD::__lower_bound<_Compare>(__first, __last, __value_, __comp);
+    return __first != __last && !__comp(__value_, *__first);
+}
+
+template <class _ForwardIterator, class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__binary_search<_Comp_ref>(__first, __last, __value_, __comp);
+}
+
+template <class _ForwardIterator, class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
+{
+    return _VSTD::binary_search(__first, __last, __value_,
+                             __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
+}
+
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_BINARY_SEARCH_H
lib/libcxx/include/__algorithm/clamp.h
@@ -0,0 +1,52 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_CLAMP_H
+#define _LIBCPP___ALGORITHM_CLAMP_H
+
+#include <__config>
+#include <__debug>
+#include <__algorithm/comp.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+// clamp
+template<class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+const _Tp&
+clamp(const _Tp& __v, const _Tp& __lo, const _Tp& __hi, _Compare __comp)
+{
+    _LIBCPP_ASSERT(!__comp(__hi, __lo), "Bad bounds passed to std::clamp");
+    return __comp(__v, __lo) ? __lo : __comp(__hi, __v) ? __hi : __v;
+
+}
+
+template<class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+const _Tp&
+clamp(const _Tp& __v, const _Tp& __lo, const _Tp& __hi)
+{
+    return _VSTD::clamp(__v, __lo, __hi, __less<_Tp>());
+}
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_CLAMP_H
lib/libcxx/include/__algorithm/comp.h
@@ -0,0 +1,97 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_COMP_H
+#define _LIBCPP___ALGORITHM_COMP_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// I'd like to replace these with _VSTD::equal_to<void>, but can't because:
+//   * That only works with C++14 and later, and
+//   * We haven't included <functional> here.
+template <class _T1, class _T2 = _T1>
+struct __equal_to
+{
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 bool operator()(const _T1& __x, const _T2& __y) const {return __x == __y;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 bool operator()(const _T2& __x, const _T1& __y) const {return __x == __y;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 bool operator()(const _T2& __x, const _T2& __y) const {return __x == __y;}
+};
+
+template <class _T1>
+struct __equal_to<_T1, _T1>
+{
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
+};
+
+template <class _T1>
+struct __equal_to<const _T1, _T1>
+{
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
+};
+
+template <class _T1>
+struct __equal_to<_T1, const _T1>
+{
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
+};
+
+template <class _T1, class _T2 = _T1>
+struct __less
+{
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T1& __x, const _T2& __y) const {return __x < __y;}
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T2& __x, const _T1& __y) const {return __x < __y;}
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T2& __x, const _T2& __y) const {return __x < __y;}
+};
+
+template <class _T1>
+struct __less<_T1, _T1>
+{
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
+};
+
+template <class _T1>
+struct __less<const _T1, _T1>
+{
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
+};
+
+template <class _T1>
+struct __less<_T1, const _T1>
+{
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
+};
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_COMP_H
lib/libcxx/include/__algorithm/comp_ref_type.h
@@ -0,0 +1,87 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_COMP_REF_TYPE_H
+#define _LIBCPP___ALGORITHM_COMP_REF_TYPE_H
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#ifdef _LIBCPP_DEBUG
+
+template <class _Compare>
+struct __debug_less
+{
+    _Compare &__comp_;
+    _LIBCPP_CONSTEXPR_AFTER_CXX17
+    __debug_less(_Compare& __c) : __comp_(__c) {}
+
+    template <class _Tp, class _Up>
+    _LIBCPP_CONSTEXPR_AFTER_CXX17
+    bool operator()(const _Tp& __x,  const _Up& __y)
+    {
+        bool __r = __comp_(__x, __y);
+        if (__r)
+            __do_compare_assert(0, __y, __x);
+        return __r;
+    }
+
+    template <class _Tp, class _Up>
+    _LIBCPP_CONSTEXPR_AFTER_CXX17
+    bool operator()(_Tp& __x,  _Up& __y)
+    {
+        bool __r = __comp_(__x, __y);
+        if (__r)
+            __do_compare_assert(0, __y, __x);
+        return __r;
+    }
+
+    template <class _LHS, class _RHS>
+    _LIBCPP_CONSTEXPR_AFTER_CXX17
+    inline _LIBCPP_INLINE_VISIBILITY
+    decltype((void)declval<_Compare&>()(
+        declval<_LHS &>(), declval<_RHS &>()))
+    __do_compare_assert(int, _LHS & __l, _RHS & __r) {
+        _LIBCPP_ASSERT(!__comp_(__l, __r),
+            "Comparator does not induce a strict weak ordering");
+    }
+
+    template <class _LHS, class _RHS>
+    _LIBCPP_CONSTEXPR_AFTER_CXX17
+    inline _LIBCPP_INLINE_VISIBILITY
+    void __do_compare_assert(long, _LHS &, _RHS &) {}
+};
+
+#endif // _LIBCPP_DEBUG
+
+template <class _Comp>
+struct __comp_ref_type {
+  // Pass the comparator by lvalue reference. Or in debug mode, using a
+  // debugging wrapper that stores a reference.
+#ifndef _LIBCPP_DEBUG
+  typedef typename add_lvalue_reference<_Comp>::type type;
+#else
+  typedef __debug_less<_Comp> type;
+#endif
+};
+
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_COMP_REF_TYPE_H
lib/libcxx/include/__algorithm/copy.h
@@ -0,0 +1,82 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_COPY_H
+#define _LIBCPP___ALGORITHM_COPY_H
+
+#include <__config>
+#include <__algorithm/unwrap_iter.h>
+#include <__iterator/iterator_traits.h>
+#include <cstring>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// copy
+
+template <class _InputIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+__copy_constexpr(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
+{
+    for (; __first != __last; ++__first, (void) ++__result)
+        *__result = *__first;
+    return __result;
+}
+
+template <class _InputIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+_OutputIterator
+__copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
+{
+    return _VSTD::__copy_constexpr(__first, __last, __result);
+}
+
+template <class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+typename enable_if
+<
+    is_same<typename remove_const<_Tp>::type, _Up>::value &&
+    is_trivially_copy_assignable<_Up>::value,
+    _Up*
+>::type
+__copy(_Tp* __first, _Tp* __last, _Up* __result)
+{
+    const size_t __n = static_cast<size_t>(__last - __first);
+    if (__n > 0)
+        _VSTD::memmove(__result, __first, __n * sizeof(_Up));
+    return __result + __n;
+}
+
+template <class _InputIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
+{
+    if (__libcpp_is_constant_evaluated()) {
+        return _VSTD::__copy_constexpr(__first, __last, __result);
+    } else {
+        return _VSTD::__rewrap_iter(__result,
+            _VSTD::__copy(_VSTD::__unwrap_iter(__first),
+                          _VSTD::__unwrap_iter(__last),
+                          _VSTD::__unwrap_iter(__result)));
+    }
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_COPY_H
lib/libcxx/include/__algorithm/copy_backward.h
@@ -0,0 +1,84 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_COPY_BACKWARD_H
+#define _LIBCPP___ALGORITHM_COPY_BACKWARD_H
+
+#include <__config>
+#include <__algorithm/unwrap_iter.h>
+#include <__iterator/iterator_traits.h>
+#include <cstring>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _BidirectionalIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+__copy_backward_constexpr(_BidirectionalIterator __first, _BidirectionalIterator __last, _OutputIterator __result)
+{
+    while (__first != __last)
+        *--__result = *--__last;
+    return __result;
+}
+
+template <class _BidirectionalIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+_OutputIterator
+__copy_backward(_BidirectionalIterator __first, _BidirectionalIterator __last, _OutputIterator __result)
+{
+    return _VSTD::__copy_backward_constexpr(__first, __last, __result);
+}
+
+template <class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+typename enable_if
+<
+    is_same<typename remove_const<_Tp>::type, _Up>::value &&
+    is_trivially_copy_assignable<_Up>::value,
+    _Up*
+>::type
+__copy_backward(_Tp* __first, _Tp* __last, _Up* __result)
+{
+    const size_t __n = static_cast<size_t>(__last - __first);
+    if (__n > 0)
+    {
+        __result -= __n;
+        _VSTD::memmove(__result, __first, __n * sizeof(_Up));
+    }
+    return __result;
+}
+
+template <class _BidirectionalIterator1, class _BidirectionalIterator2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_BidirectionalIterator2
+copy_backward(_BidirectionalIterator1 __first, _BidirectionalIterator1 __last,
+              _BidirectionalIterator2 __result)
+{
+    if (__libcpp_is_constant_evaluated()) {
+        return _VSTD::__copy_backward_constexpr(__first, __last, __result);
+    } else {
+        return _VSTD::__rewrap_iter(__result,
+            _VSTD::__copy_backward(_VSTD::__unwrap_iter(__first),
+                                   _VSTD::__unwrap_iter(__last),
+                                   _VSTD::__unwrap_iter(__result)));
+    }
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_COPY_BACKWARD_H
lib/libcxx/include/__algorithm/copy_if.h
@@ -0,0 +1,48 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_COPY_IF_H
+#define _LIBCPP___ALGORITHM_COPY_IF_H
+
+#include <__config>
+#include <__algorithm/unwrap_iter.h>
+#include <__iterator/iterator_traits.h>
+#include <cstring>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template<class _InputIterator, class _OutputIterator, class _Predicate>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+copy_if(_InputIterator __first, _InputIterator __last,
+        _OutputIterator __result, _Predicate __pred)
+{
+    for (; __first != __last; ++__first)
+    {
+        if (__pred(*__first))
+        {
+            *__result = *__first;
+            ++__result;
+        }
+    }
+    return __result;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_COPY_IF_H
lib/libcxx/include/__algorithm/copy_n.h
@@ -0,0 +1,72 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_COPY_N_H
+#define _LIBCPP___ALGORITHM_COPY_N_H
+
+#include <__config>
+#include <__algorithm/copy.h>
+#include <__algorithm/unwrap_iter.h>
+#include <__iterator/iterator_traits.h>
+#include <cstring>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template<class _InputIterator, class _Size, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+typename enable_if
+<
+    __is_cpp17_input_iterator<_InputIterator>::value &&
+   !__is_cpp17_random_access_iterator<_InputIterator>::value,
+    _OutputIterator
+>::type
+copy_n(_InputIterator __first, _Size __orig_n, _OutputIterator __result)
+{
+    typedef decltype(_VSTD::__convert_to_integral(__orig_n)) _IntegralSize;
+    _IntegralSize __n = __orig_n;
+    if (__n > 0)
+    {
+        *__result = *__first;
+        ++__result;
+        for (--__n; __n > 0; --__n)
+        {
+            ++__first;
+            *__result = *__first;
+            ++__result;
+        }
+    }
+    return __result;
+}
+
+template<class _InputIterator, class _Size, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+typename enable_if
+<
+    __is_cpp17_random_access_iterator<_InputIterator>::value,
+    _OutputIterator
+>::type
+copy_n(_InputIterator __first, _Size __orig_n, _OutputIterator __result)
+{
+    typedef decltype(_VSTD::__convert_to_integral(__orig_n)) _IntegralSize;
+    _IntegralSize __n = __orig_n;
+    return _VSTD::copy(__first, __first + __n, __result);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_COPY_N_H
lib/libcxx/include/__algorithm/count.h
@@ -0,0 +1,40 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_COUNT_H
+#define _LIBCPP___ALGORITHM_COUNT_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Tp>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    typename iterator_traits<_InputIterator>::difference_type
+    count(_InputIterator __first, _InputIterator __last, const _Tp& __value_) {
+  typename iterator_traits<_InputIterator>::difference_type __r(0);
+  for (; __first != __last; ++__first)
+    if (*__first == __value_)
+      ++__r;
+  return __r;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_COUNT_H
lib/libcxx/include/__algorithm/count_if.h
@@ -0,0 +1,40 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_COUNT_IF_H
+#define _LIBCPP___ALGORITHM_COUNT_IF_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Predicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    typename iterator_traits<_InputIterator>::difference_type
+    count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred) {
+  typename iterator_traits<_InputIterator>::difference_type __r(0);
+  for (; __first != __last; ++__first)
+    if (__pred(*__first))
+      ++__r;
+  return __r;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_COUNT_IF_H
lib/libcxx/include/__algorithm/equal.h
@@ -0,0 +1,90 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_EQUAL_H
+#define _LIBCPP___ALGORITHM_EQUAL_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+#include <iterator> // FIXME: replace with <__iterator/distance.h> when it lands
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _BinaryPredicate __pred) {
+  for (; __first1 != __last1; ++__first1, (void)++__first2)
+    if (!__pred(*__first1, *__first2))
+      return false;
+  return true;
+}
+
+template <class _InputIterator1, class _InputIterator2>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2) {
+  typedef typename iterator_traits<_InputIterator1>::value_type __v1;
+  typedef typename iterator_traits<_InputIterator2>::value_type __v2;
+  return _VSTD::equal(__first1, __last1, __first2, __equal_to<__v1, __v2>());
+}
+
+#if _LIBCPP_STD_VER > 11
+template <class _BinaryPredicate, class _InputIterator1, class _InputIterator2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+__equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2,
+        _BinaryPredicate __pred, input_iterator_tag, input_iterator_tag) {
+  for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void)++__first2)
+    if (!__pred(*__first1, *__first2))
+      return false;
+  return __first1 == __last1 && __first2 == __last2;
+}
+
+template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+__equal(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1, _RandomAccessIterator2 __first2,
+        _RandomAccessIterator2 __last2, _BinaryPredicate __pred, random_access_iterator_tag,
+        random_access_iterator_tag) {
+  if (_VSTD::distance(__first1, __last1) != _VSTD::distance(__first2, __last2))
+    return false;
+  return _VSTD::equal<_RandomAccessIterator1, _RandomAccessIterator2,
+                      typename add_lvalue_reference<_BinaryPredicate>::type>(__first1, __last1, __first2, __pred);
+}
+
+template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2,
+      _BinaryPredicate __pred) {
+  return _VSTD::__equal<typename add_lvalue_reference<_BinaryPredicate>::type>(
+      __first1, __last1, __first2, __last2, __pred, typename iterator_traits<_InputIterator1>::iterator_category(),
+      typename iterator_traits<_InputIterator2>::iterator_category());
+}
+
+template <class _InputIterator1, class _InputIterator2>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2) {
+  typedef typename iterator_traits<_InputIterator1>::value_type __v1;
+  typedef typename iterator_traits<_InputIterator2>::value_type __v2;
+  return _VSTD::__equal(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>(),
+                        typename iterator_traits<_InputIterator1>::iterator_category(),
+                        typename iterator_traits<_InputIterator2>::iterator_category());
+}
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_EQUAL_H
lib/libcxx/include/__algorithm/equal_range.h
@@ -0,0 +1,87 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_EQUAL_RANGE_H
+#define _LIBCPP___ALGORITHM_EQUAL_RANGE_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/half_positive.h>
+#include <__algorithm/lower_bound.h>
+#include <__algorithm/upper_bound.h>
+#include <iterator>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _ForwardIterator, class _Tp>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_ForwardIterator, _ForwardIterator>
+__equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
+{
+    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
+    difference_type __len = _VSTD::distance(__first, __last);
+    while (__len != 0)
+    {
+        difference_type __l2 = _VSTD::__half_positive(__len);
+        _ForwardIterator __m = __first;
+        _VSTD::advance(__m, __l2);
+        if (__comp(*__m, __value_))
+        {
+            __first = ++__m;
+            __len -= __l2 + 1;
+        }
+        else if (__comp(__value_, *__m))
+        {
+            __last = __m;
+            __len = __l2;
+        }
+        else
+        {
+            _ForwardIterator __mp1 = __m;
+            return pair<_ForwardIterator, _ForwardIterator>
+                   (
+                      _VSTD::__lower_bound<_Compare>(__first, __m, __value_, __comp),
+                      _VSTD::__upper_bound<_Compare>(++__mp1, __last, __value_, __comp)
+                   );
+        }
+    }
+    return pair<_ForwardIterator, _ForwardIterator>(__first, __first);
+}
+
+template <class _ForwardIterator, class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+pair<_ForwardIterator, _ForwardIterator>
+equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__equal_range<_Comp_ref>(__first, __last, __value_, __comp);
+}
+
+template <class _ForwardIterator, class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+pair<_ForwardIterator, _ForwardIterator>
+equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
+{
+    return _VSTD::equal_range(__first, __last, __value_,
+                             __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_EQUAL_RANGE_H
lib/libcxx/include/__algorithm/fill.h
@@ -0,0 +1,55 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_FILL_H
+#define _LIBCPP___ALGORITHM_FILL_H
+
+#include <__config>
+#include <__algorithm/fill_n.h>
+#include <__iterator/iterator_traits.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+__fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, forward_iterator_tag)
+{
+    for (; __first != __last; ++__first)
+        *__first = __value_;
+}
+
+template <class _RandomAccessIterator, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+__fill(_RandomAccessIterator __first, _RandomAccessIterator __last, const _Tp& __value_, random_access_iterator_tag)
+{
+    _VSTD::fill_n(__first, __last - __first, __value_);
+}
+
+template <class _ForwardIterator, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
+{
+    _VSTD::__fill(__first, __last, __value_, typename iterator_traits<_ForwardIterator>::iterator_category());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_FILL_H
lib/libcxx/include/__algorithm/fill_n.h
@@ -0,0 +1,47 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_FILL_N_H
+#define _LIBCPP___ALGORITHM_FILL_N_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _OutputIterator, class _Size, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+__fill_n(_OutputIterator __first, _Size __n, const _Tp& __value_)
+{
+    for (; __n > 0; ++__first, (void) --__n)
+        *__first = __value_;
+    return __first;
+}
+
+template <class _OutputIterator, class _Size, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+fill_n(_OutputIterator __first, _Size __n, const _Tp& __value_)
+{
+   return _VSTD::__fill_n(__first, _VSTD::__convert_to_integral(__n), __value_);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_FILL_N_H
lib/libcxx/include/__algorithm/find.h
@@ -0,0 +1,37 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_FIND_H
+#define _LIBCPP___ALGORITHM_FIND_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Tp>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _InputIterator
+find(_InputIterator __first, _InputIterator __last, const _Tp& __value_) {
+  for (; __first != __last; ++__first)
+    if (*__first == __value_)
+      break;
+  return __first;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_FIND_H
lib/libcxx/include/__algorithm/find_end.h
@@ -0,0 +1,154 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_FIND_END_OF_H
+#define _LIBCPP___ALGORITHM_FIND_END_OF_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1 __find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
+                                                           _ForwardIterator2 __first2, _ForwardIterator2 __last2,
+                                                           _BinaryPredicate __pred, forward_iterator_tag,
+                                                           forward_iterator_tag) {
+  // modeled after search algorithm
+  _ForwardIterator1 __r = __last1; // __last1 is the "default" answer
+  if (__first2 == __last2)
+    return __r;
+  while (true) {
+    while (true) {
+      if (__first1 == __last1) // if source exhausted return last correct answer
+        return __r;            //    (or __last1 if never found)
+      if (__pred(*__first1, *__first2))
+        break;
+      ++__first1;
+    }
+    // *__first1 matches *__first2, now match elements after here
+    _ForwardIterator1 __m1 = __first1;
+    _ForwardIterator2 __m2 = __first2;
+    while (true) {
+      if (++__m2 == __last2) { // Pattern exhaused, record answer and search for another one
+        __r = __first1;
+        ++__first1;
+        break;
+      }
+      if (++__m1 == __last1) // Source exhausted, return last answer
+        return __r;
+      if (!__pred(*__m1, *__m2)) // mismatch, restart with a new __first
+      {
+        ++__first1;
+        break;
+      } // else there is a match, check next elements
+    }
+  }
+}
+
+template <class _BinaryPredicate, class _BidirectionalIterator1, class _BidirectionalIterator2>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _BidirectionalIterator1 __find_end(
+    _BidirectionalIterator1 __first1, _BidirectionalIterator1 __last1, _BidirectionalIterator2 __first2,
+    _BidirectionalIterator2 __last2, _BinaryPredicate __pred, bidirectional_iterator_tag, bidirectional_iterator_tag) {
+  // modeled after search algorithm (in reverse)
+  if (__first2 == __last2)
+    return __last1; // Everything matches an empty sequence
+  _BidirectionalIterator1 __l1 = __last1;
+  _BidirectionalIterator2 __l2 = __last2;
+  --__l2;
+  while (true) {
+    // Find last element in sequence 1 that matchs *(__last2-1), with a mininum of loop checks
+    while (true) {
+      if (__first1 == __l1) // return __last1 if no element matches *__first2
+        return __last1;
+      if (__pred(*--__l1, *__l2))
+        break;
+    }
+    // *__l1 matches *__l2, now match elements before here
+    _BidirectionalIterator1 __m1 = __l1;
+    _BidirectionalIterator2 __m2 = __l2;
+    while (true) {
+      if (__m2 == __first2) // If pattern exhausted, __m1 is the answer (works for 1 element pattern)
+        return __m1;
+      if (__m1 == __first1) // Otherwise if source exhaused, pattern not found
+        return __last1;
+      if (!__pred(*--__m1, *--__m2)) // if there is a mismatch, restart with a new __l1
+      {
+        break;
+      } // else there is a match, check next elements
+    }
+  }
+}
+
+template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 _RandomAccessIterator1 __find_end(
+    _RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1, _RandomAccessIterator2 __first2,
+    _RandomAccessIterator2 __last2, _BinaryPredicate __pred, random_access_iterator_tag, random_access_iterator_tag) {
+  // Take advantage of knowing source and pattern lengths.  Stop short when source is smaller than pattern
+  typename iterator_traits<_RandomAccessIterator2>::difference_type __len2 = __last2 - __first2;
+  if (__len2 == 0)
+    return __last1;
+  typename iterator_traits<_RandomAccessIterator1>::difference_type __len1 = __last1 - __first1;
+  if (__len1 < __len2)
+    return __last1;
+  const _RandomAccessIterator1 __s = __first1 + (__len2 - 1); // End of pattern match can't go before here
+  _RandomAccessIterator1 __l1 = __last1;
+  _RandomAccessIterator2 __l2 = __last2;
+  --__l2;
+  while (true) {
+    while (true) {
+      if (__s == __l1)
+        return __last1;
+      if (__pred(*--__l1, *__l2))
+        break;
+    }
+    _RandomAccessIterator1 __m1 = __l1;
+    _RandomAccessIterator2 __m2 = __l2;
+    while (true) {
+      if (__m2 == __first2)
+        return __m1;
+      // no need to check range on __m1 because __s guarantees we have enough source
+      if (!__pred(*--__m1, *--__m2)) {
+        break;
+      }
+    }
+  }
+}
+
+template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1
+find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2,
+         _BinaryPredicate __pred) {
+  return _VSTD::__find_end<typename add_lvalue_reference<_BinaryPredicate>::type>(
+      __first1, __last1, __first2, __last2, __pred, typename iterator_traits<_ForwardIterator1>::iterator_category(),
+      typename iterator_traits<_ForwardIterator2>::iterator_category());
+}
+
+template <class _ForwardIterator1, class _ForwardIterator2>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1
+find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2) {
+  typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
+  typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
+  return _VSTD::find_end(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_FIND_END_OF_H
lib/libcxx/include/__algorithm/find_first_of.h
@@ -0,0 +1,57 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_FIND_FIRST_OF_H
+#define _LIBCPP___ALGORITHM_FIND_FIRST_OF_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 _ForwardIterator1 __find_first_of_ce(_ForwardIterator1 __first1,
+                                                                   _ForwardIterator1 __last1,
+                                                                   _ForwardIterator2 __first2,
+                                                                   _ForwardIterator2 __last2, _BinaryPredicate __pred) {
+  for (; __first1 != __last1; ++__first1)
+    for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
+      if (__pred(*__first1, *__j))
+        return __first1;
+  return __last1;
+}
+
+template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1
+find_first_of(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2,
+              _ForwardIterator2 __last2, _BinaryPredicate __pred) {
+  return _VSTD::__find_first_of_ce(__first1, __last1, __first2, __last2, __pred);
+}
+
+template <class _ForwardIterator1, class _ForwardIterator2>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1 find_first_of(
+    _ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2) {
+  typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
+  typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
+  return _VSTD::__find_first_of_ce(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_FIND_FIRST_OF_H
lib/libcxx/include/__algorithm/find_if.h
@@ -0,0 +1,37 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_FIND_IF_H
+#define _LIBCPP___ALGORITHM_FIND_IF_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Predicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _InputIterator
+find_if(_InputIterator __first, _InputIterator __last, _Predicate __pred) {
+  for (; __first != __last; ++__first)
+    if (__pred(*__first))
+      break;
+  return __first;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_FIND_IF_H
lib/libcxx/include/__algorithm/find_if_not.h
@@ -0,0 +1,37 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_FIND_IF_NOT_H
+#define _LIBCPP___ALGORITHM_FIND_IF_NOT_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Predicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _InputIterator
+find_if_not(_InputIterator __first, _InputIterator __last, _Predicate __pred) {
+  for (; __first != __last; ++__first)
+    if (!__pred(*__first))
+      break;
+  return __first;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_FIND_IF_NOT_H
lib/libcxx/include/__algorithm/for_each.h
@@ -0,0 +1,37 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_FOR_EACH_H
+#define _LIBCPP___ALGORITHM_FOR_EACH_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Function>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _Function for_each(_InputIterator __first,
+                                                                                  _InputIterator __last,
+                                                                                  _Function __f) {
+  for (; __first != __last; ++__first)
+    __f(*__first);
+  return __f;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_FOR_EACH_H
lib/libcxx/include/__algorithm/for_each_n.h
@@ -0,0 +1,47 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_FOR_EACH_N_H
+#define _LIBCPP___ALGORITHM_FOR_EACH_N_H
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+
+template <class _InputIterator, class _Size, class _Function>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _InputIterator for_each_n(_InputIterator __first,
+                                                                                         _Size __orig_n,
+                                                                                         _Function __f) {
+  typedef decltype(_VSTD::__convert_to_integral(__orig_n)) _IntegralSize;
+  _IntegralSize __n = __orig_n;
+  while (__n > 0) {
+    __f(*__first);
+    ++__first;
+    --__n;
+  }
+  return __first;
+}
+
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_FOR_EACH_N_H
lib/libcxx/include/__algorithm/generate.h
@@ -0,0 +1,36 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_GENERATE_H
+#define _LIBCPP___ALGORITHM_GENERATE_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Generator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+generate(_ForwardIterator __first, _ForwardIterator __last, _Generator __gen)
+{
+    for (; __first != __last; ++__first)
+        *__first = __gen();
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_GENERATE_H
lib/libcxx/include/__algorithm/generate_n.h
@@ -0,0 +1,40 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_GENERATE_N_H
+#define _LIBCPP___ALGORITHM_GENERATE_N_H
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _OutputIterator, class _Size, class _Generator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+generate_n(_OutputIterator __first, _Size __orig_n, _Generator __gen)
+{
+    typedef decltype(_VSTD::__convert_to_integral(__orig_n)) _IntegralSize;
+    _IntegralSize __n = __orig_n;
+    for (; __n > 0; ++__first, (void) --__n)
+        *__first = __gen();
+    return __first;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_GENERATE_N_H
lib/libcxx/include/__algorithm/half_positive.h
@@ -0,0 +1,54 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_HALF_POSITIVE_H
+#define _LIBCPP___ALGORITHM_HALF_POSITIVE_H
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// Perform division by two quickly for positive integers (llvm.org/PR39129)
+
+template <typename _Integral>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+typename enable_if
+<
+    is_integral<_Integral>::value,
+    _Integral
+>::type
+__half_positive(_Integral __value)
+{
+    return static_cast<_Integral>(static_cast<typename make_unsigned<_Integral>::type>(__value) / 2);
+}
+
+template <typename _Tp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+typename enable_if
+<
+    !is_integral<_Tp>::value,
+    _Tp
+>::type
+__half_positive(_Tp __value)
+{
+    return __value / 2;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_HALF_POSITIVE_H
lib/libcxx/include/__algorithm/includes.h
@@ -0,0 +1,67 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_INCLUDES_H
+#define _LIBCPP___ALGORITHM_INCLUDES_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _InputIterator1, class _InputIterator2>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+__includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2,
+           _Compare __comp)
+{
+    for (; __first2 != __last2; ++__first1)
+    {
+        if (__first1 == __last1 || __comp(*__first2, *__first1))
+            return false;
+        if (!__comp(*__first1, *__first2))
+            ++__first2;
+    }
+    return true;
+}
+
+template <class _InputIterator1, class _InputIterator2, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2,
+         _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__includes<_Comp_ref>(__first1, __last1, __first2, __last2, __comp);
+}
+
+template <class _InputIterator1, class _InputIterator2>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2)
+{
+    return _VSTD::includes(__first1, __last1, __first2, __last2,
+                          __less<typename iterator_traits<_InputIterator1>::value_type,
+                                 typename iterator_traits<_InputIterator2>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_INCLUDES_H
lib/libcxx/include/__algorithm/inplace_merge.h
@@ -0,0 +1,231 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_INPLACE_MERGE_H
+#define _LIBCPP___ALGORITHM_INPLACE_MERGE_H
+
+#include <__config>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/comp.h>
+#include <__algorithm/lower_bound.h>
+#include <__algorithm/min.h>
+#include <__algorithm/move.h>
+#include <__algorithm/rotate.h>
+#include <__algorithm/upper_bound.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/swap.h>
+#include <memory>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Predicate>
+class __invert // invert the sense of a comparison
+{
+private:
+    _Predicate __p_;
+public:
+    _LIBCPP_INLINE_VISIBILITY __invert() {}
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __invert(_Predicate __p) : __p_(__p) {}
+
+    template <class _T1>
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _T1& __x) {return !__p_(__x);}
+
+    template <class _T1, class _T2>
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _T1& __x, const _T2& __y) {return __p_(__y, __x);}
+};
+
+template <class _Compare, class _InputIterator1, class _InputIterator2,
+          class _OutputIterator>
+void __half_inplace_merge(_InputIterator1 __first1, _InputIterator1 __last1,
+                          _InputIterator2 __first2, _InputIterator2 __last2,
+                          _OutputIterator __result, _Compare __comp)
+{
+    for (; __first1 != __last1; ++__result)
+    {
+        if (__first2 == __last2)
+        {
+            _VSTD::move(__first1, __last1, __result);
+            return;
+        }
+
+        if (__comp(*__first2, *__first1))
+        {
+            *__result = _VSTD::move(*__first2);
+            ++__first2;
+        }
+        else
+        {
+            *__result = _VSTD::move(*__first1);
+            ++__first1;
+        }
+    }
+    // __first2 through __last2 are already in the right spot.
+}
+
+template <class _Compare, class _BidirectionalIterator>
+void
+__buffered_inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
+                _Compare __comp, typename iterator_traits<_BidirectionalIterator>::difference_type __len1,
+                                 typename iterator_traits<_BidirectionalIterator>::difference_type __len2,
+                typename iterator_traits<_BidirectionalIterator>::value_type* __buff)
+{
+    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
+    __destruct_n __d(0);
+    unique_ptr<value_type, __destruct_n&> __h2(__buff, __d);
+    if (__len1 <= __len2)
+    {
+        value_type* __p = __buff;
+        for (_BidirectionalIterator __i = __first; __i != __middle; __d.template __incr<value_type>(), (void) ++__i, (void) ++__p)
+            ::new ((void*)__p) value_type(_VSTD::move(*__i));
+        _VSTD::__half_inplace_merge<_Compare>(__buff, __p, __middle, __last, __first, __comp);
+    }
+    else
+    {
+        value_type* __p = __buff;
+        for (_BidirectionalIterator __i = __middle; __i != __last; __d.template __incr<value_type>(), (void) ++__i, (void) ++__p)
+            ::new ((void*)__p) value_type(_VSTD::move(*__i));
+        typedef reverse_iterator<_BidirectionalIterator> _RBi;
+        typedef reverse_iterator<value_type*> _Rv;
+        typedef __invert<_Compare> _Inverted;
+        _VSTD::__half_inplace_merge<_Inverted>(_Rv(__p), _Rv(__buff),
+                                    _RBi(__middle), _RBi(__first),
+                                    _RBi(__last), _Inverted(__comp));
+    }
+}
+
+template <class _Compare, class _BidirectionalIterator>
+void
+__inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
+                _Compare __comp, typename iterator_traits<_BidirectionalIterator>::difference_type __len1,
+                                 typename iterator_traits<_BidirectionalIterator>::difference_type __len2,
+                typename iterator_traits<_BidirectionalIterator>::value_type* __buff, ptrdiff_t __buff_size)
+{
+    typedef typename iterator_traits<_BidirectionalIterator>::difference_type difference_type;
+    while (true)
+    {
+        // if __middle == __last, we're done
+        if (__len2 == 0)
+            return;
+        if (__len1 <= __buff_size || __len2 <= __buff_size)
+            return _VSTD::__buffered_inplace_merge<_Compare>
+                   (__first, __middle, __last, __comp, __len1, __len2, __buff);
+        // shrink [__first, __middle) as much as possible (with no moves), returning if it shrinks to 0
+        for (; true; ++__first, (void) --__len1)
+        {
+            if (__len1 == 0)
+                return;
+            if (__comp(*__middle, *__first))
+                break;
+        }
+        // __first < __middle < __last
+        // *__first > *__middle
+        // partition [__first, __m1) [__m1, __middle) [__middle, __m2) [__m2, __last) such that
+        //     all elements in:
+        //         [__first, __m1)  <= [__middle, __m2)
+        //         [__middle, __m2) <  [__m1, __middle)
+        //         [__m1, __middle) <= [__m2, __last)
+        //     and __m1 or __m2 is in the middle of its range
+        _BidirectionalIterator __m1;  // "median" of [__first, __middle)
+        _BidirectionalIterator __m2;  // "median" of [__middle, __last)
+        difference_type __len11;      // distance(__first, __m1)
+        difference_type __len21;      // distance(__middle, __m2)
+        // binary search smaller range
+        if (__len1 < __len2)
+        {   // __len >= 1, __len2 >= 2
+            __len21 = __len2 / 2;
+            __m2 = __middle;
+            _VSTD::advance(__m2, __len21);
+            __m1 = _VSTD::__upper_bound<_Compare>(__first, __middle, *__m2, __comp);
+            __len11 = _VSTD::distance(__first, __m1);
+        }
+        else
+        {
+            if (__len1 == 1)
+            {   // __len1 >= __len2 && __len2 > 0, therefore __len2 == 1
+                // It is known *__first > *__middle
+                swap(*__first, *__middle);
+                return;
+            }
+            // __len1 >= 2, __len2 >= 1
+            __len11 = __len1 / 2;
+            __m1 = __first;
+            _VSTD::advance(__m1, __len11);
+            __m2 = _VSTD::__lower_bound<_Compare>(__middle, __last, *__m1, __comp);
+            __len21 = _VSTD::distance(__middle, __m2);
+        }
+        difference_type __len12 = __len1 - __len11;  // distance(__m1, __middle)
+        difference_type __len22 = __len2 - __len21;  // distance(__m2, __last)
+        // [__first, __m1) [__m1, __middle) [__middle, __m2) [__m2, __last)
+        // swap middle two partitions
+        __middle = _VSTD::rotate(__m1, __middle, __m2);
+        // __len12 and __len21 now have swapped meanings
+        // merge smaller range with recursive call and larger with tail recursion elimination
+        if (__len11 + __len21 < __len12 + __len22)
+        {
+            _VSTD::__inplace_merge<_Compare>(__first, __m1, __middle, __comp, __len11, __len21, __buff, __buff_size);
+//          _VSTD::__inplace_merge<_Compare>(__middle, __m2, __last, __comp, __len12, __len22, __buff, __buff_size);
+            __first = __middle;
+            __middle = __m2;
+            __len1 = __len12;
+            __len2 = __len22;
+        }
+        else
+        {
+            _VSTD::__inplace_merge<_Compare>(__middle, __m2, __last, __comp, __len12, __len22, __buff, __buff_size);
+//          _VSTD::__inplace_merge<_Compare>(__first, __m1, __middle, __comp, __len11, __len21, __buff, __buff_size);
+            __last = __middle;
+            __middle = __m1;
+            __len1 = __len11;
+            __len2 = __len21;
+        }
+    }
+}
+
+template <class _BidirectionalIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY
+void
+inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
+              _Compare __comp)
+{
+    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
+    typedef typename iterator_traits<_BidirectionalIterator>::difference_type difference_type;
+    difference_type __len1 = _VSTD::distance(__first, __middle);
+    difference_type __len2 = _VSTD::distance(__middle, __last);
+    difference_type __buf_size = _VSTD::min(__len1, __len2);
+    pair<value_type*, ptrdiff_t> __buf = _VSTD::get_temporary_buffer<value_type>(__buf_size);
+    unique_ptr<value_type, __return_temporary_buffer> __h(__buf.first);
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__inplace_merge<_Comp_ref>(__first, __middle, __last, __comp, __len1, __len2,
+                                            __buf.first, __buf.second);
+}
+
+template <class _BidirectionalIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+void
+inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last)
+{
+    _VSTD::inplace_merge(__first, __middle, __last,
+                        __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_INPLACE_MERGE_H
lib/libcxx/include/__algorithm/is_heap.h
@@ -0,0 +1,48 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_IS_HEAP_H
+#define _LIBCPP___ALGORITHM_IS_HEAP_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/is_heap_until.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _RandomAccessIterator, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    return _VSTD::is_heap_until(__first, __last, __comp) == __last;
+}
+
+template<class _RandomAccessIterator>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
+{
+    return _VSTD::is_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_IS_HEAP_H
lib/libcxx/include/__algorithm/is_heap_until.h
@@ -0,0 +1,65 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_IS_HEAP_UNTIL_H
+#define _LIBCPP___ALGORITHM_IS_HEAP_UNTIL_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _RandomAccessIterator, class _Compare>
+_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _RandomAccessIterator
+is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    difference_type __len = __last - __first;
+    difference_type __p = 0;
+    difference_type __c = 1;
+    _RandomAccessIterator __pp = __first;
+    while (__c < __len)
+    {
+        _RandomAccessIterator __cp = __first + __c;
+        if (__comp(*__pp, *__cp))
+            return __cp;
+        ++__c;
+        ++__cp;
+        if (__c == __len)
+            return __last;
+        if (__comp(*__pp, *__cp))
+            return __cp;
+        ++__p;
+        ++__pp;
+        __c = 2 * __p + 1;
+    }
+    return __last;
+}
+
+template<class _RandomAccessIterator>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_RandomAccessIterator
+is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last)
+{
+    return _VSTD::is_heap_until(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_IS_HEAP_UNTIL_H
lib/libcxx/include/__algorithm/is_partitioned.h
@@ -0,0 +1,43 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_IS_PARTITIONED_H
+#define _LIBCPP___ALGORITHM_IS_PARTITIONED_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Predicate>
+_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+is_partitioned(_InputIterator __first, _InputIterator __last, _Predicate __pred)
+{
+    for (; __first != __last; ++__first)
+        if (!__pred(*__first))
+            break;
+    if ( __first == __last )
+        return true;
+    ++__first;
+    for (; __first != __last; ++__first)
+        if (__pred(*__first))
+            return false;
+    return true;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_IS_PARTITIONED_H
lib/libcxx/include/__algorithm/is_permutation.h
@@ -0,0 +1,168 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_IS_PERMUTATION_H
+#define _LIBCPP___ALGORITHM_IS_PERMUTATION_H
+
+#include <__algorithm/comp.h>
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/next.h>
+#include <iterator> // FIXME: replace with <__iterator/distance.h> when it lands
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2,
+               _BinaryPredicate __pred) {
+  //  shorten sequences as much as possible by lopping of any equal prefix
+  for (; __first1 != __last1; ++__first1, (void)++__first2)
+    if (!__pred(*__first1, *__first2))
+      break;
+  if (__first1 == __last1)
+    return true;
+
+  //  __first1 != __last1 && *__first1 != *__first2
+  typedef typename iterator_traits<_ForwardIterator1>::difference_type _D1;
+  _D1 __l1 = _VSTD::distance(__first1, __last1);
+  if (__l1 == _D1(1))
+    return false;
+  _ForwardIterator2 __last2 = _VSTD::next(__first2, __l1);
+  // For each element in [f1, l1) see if there are the same number of
+  //    equal elements in [f2, l2)
+  for (_ForwardIterator1 __i = __first1; __i != __last1; ++__i) {
+    //  Have we already counted the number of *__i in [f1, l1)?
+    _ForwardIterator1 __match = __first1;
+    for (; __match != __i; ++__match)
+      if (__pred(*__match, *__i))
+        break;
+    if (__match == __i) {
+      // Count number of *__i in [f2, l2)
+      _D1 __c2 = 0;
+      for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
+        if (__pred(*__i, *__j))
+          ++__c2;
+      if (__c2 == 0)
+        return false;
+      // Count number of *__i in [__i, l1) (we can start with 1)
+      _D1 __c1 = 1;
+      for (_ForwardIterator1 __j = _VSTD::next(__i); __j != __last1; ++__j)
+        if (__pred(*__i, *__j))
+          ++__c1;
+      if (__c1 != __c2)
+        return false;
+    }
+  }
+  return true;
+}
+
+template <class _ForwardIterator1, class _ForwardIterator2>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2) {
+  typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
+  typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
+  return _VSTD::is_permutation(__first1, __last1, __first2, __equal_to<__v1, __v2>());
+}
+
+#if _LIBCPP_STD_VER > 11
+template <class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+__is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2,
+                 _ForwardIterator2 __last2, _BinaryPredicate __pred, forward_iterator_tag, forward_iterator_tag) {
+  //  shorten sequences as much as possible by lopping of any equal prefix
+  for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void)++__first2)
+    if (!__pred(*__first1, *__first2))
+      break;
+  if (__first1 == __last1)
+    return __first2 == __last2;
+  else if (__first2 == __last2)
+    return false;
+
+  typedef typename iterator_traits<_ForwardIterator1>::difference_type _D1;
+  _D1 __l1 = _VSTD::distance(__first1, __last1);
+
+  typedef typename iterator_traits<_ForwardIterator2>::difference_type _D2;
+  _D2 __l2 = _VSTD::distance(__first2, __last2);
+  if (__l1 != __l2)
+    return false;
+
+  // For each element in [f1, l1) see if there are the same number of
+  //    equal elements in [f2, l2)
+  for (_ForwardIterator1 __i = __first1; __i != __last1; ++__i) {
+    //  Have we already counted the number of *__i in [f1, l1)?
+    _ForwardIterator1 __match = __first1;
+    for (; __match != __i; ++__match)
+      if (__pred(*__match, *__i))
+        break;
+    if (__match == __i) {
+      // Count number of *__i in [f2, l2)
+      _D1 __c2 = 0;
+      for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
+        if (__pred(*__i, *__j))
+          ++__c2;
+      if (__c2 == 0)
+        return false;
+      // Count number of *__i in [__i, l1) (we can start with 1)
+      _D1 __c1 = 1;
+      for (_ForwardIterator1 __j = _VSTD::next(__i); __j != __last1; ++__j)
+        if (__pred(*__i, *__j))
+          ++__c1;
+      if (__c1 != __c2)
+        return false;
+    }
+  }
+  return true;
+}
+
+template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 bool __is_permutation(_RandomAccessIterator1 __first1, _RandomAccessIterator2 __last1,
+                                                    _RandomAccessIterator1 __first2, _RandomAccessIterator2 __last2,
+                                                    _BinaryPredicate __pred, random_access_iterator_tag,
+                                                    random_access_iterator_tag) {
+  if (_VSTD::distance(__first1, __last1) != _VSTD::distance(__first2, __last2))
+    return false;
+  return _VSTD::is_permutation<_RandomAccessIterator1, _RandomAccessIterator2,
+                               typename add_lvalue_reference<_BinaryPredicate>::type>(__first1, __last1, __first2,
+                                                                                      __pred);
+}
+
+template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2,
+               _ForwardIterator2 __last2, _BinaryPredicate __pred) {
+  return _VSTD::__is_permutation<typename add_lvalue_reference<_BinaryPredicate>::type>(
+      __first1, __last1, __first2, __last2, __pred, typename iterator_traits<_ForwardIterator1>::iterator_category(),
+      typename iterator_traits<_ForwardIterator2>::iterator_category());
+}
+
+template <class _ForwardIterator1, class _ForwardIterator2>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2,
+               _ForwardIterator2 __last2) {
+  typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
+  typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
+  return _VSTD::__is_permutation(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>(),
+                                 typename iterator_traits<_ForwardIterator1>::iterator_category(),
+                                 typename iterator_traits<_ForwardIterator2>::iterator_category());
+}
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_IS_PERMUTATION_H
lib/libcxx/include/__algorithm/is_sorted.h
@@ -0,0 +1,48 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_IS_SORTED_H
+#define _LIBCPP___ALGORITHM_IS_SORTED_H
+
+#include <__algorithm/comp.h>
+#include <__algorithm/is_sorted_until.h>
+#include <__config>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+is_sorted(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
+{
+    return _VSTD::is_sorted_until(__first, __last, __comp) == __last;
+}
+
+template<class _ForwardIterator>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+is_sorted(_ForwardIterator __first, _ForwardIterator __last)
+{
+    return _VSTD::is_sorted(__first, __last, __less<typename iterator_traits<_ForwardIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_IS_SORTED_H
lib/libcxx/include/__algorithm/is_sorted_until.h
@@ -0,0 +1,55 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_IS_SORTED_UNTIL_H
+#define _LIBCPP___ALGORITHM_IS_SORTED_UNTIL_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Compare>
+_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+is_sorted_until(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
+{
+    if (__first != __last)
+    {
+        _ForwardIterator __i = __first;
+        while (++__i != __last)
+        {
+            if (__comp(*__i, *__first))
+                return __i;
+            __first = __i;
+        }
+    }
+    return __last;
+}
+
+template<class _ForwardIterator>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_ForwardIterator
+is_sorted_until(_ForwardIterator __first, _ForwardIterator __last)
+{
+    return _VSTD::is_sorted_until(__first, __last, __less<typename iterator_traits<_ForwardIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_IS_SORTED_UNTIL_H
lib/libcxx/include/__algorithm/iter_swap.h
@@ -0,0 +1,37 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_ITER_SWAP_H
+#define _LIBCPP___ALGORITHM_ITER_SWAP_H
+
+#include <__config>
+#include <__utility/declval.h>
+#include <__utility/swap.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator1, class _ForwardIterator2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 void iter_swap(_ForwardIterator1 __a,
+                                                                              _ForwardIterator2 __b)
+    //                                  _NOEXCEPT_(_NOEXCEPT_(swap(*__a, *__b)))
+    _NOEXCEPT_(_NOEXCEPT_(swap(*declval<_ForwardIterator1>(), *declval<_ForwardIterator2>()))) {
+  swap(*__a, *__b);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_ITER_SWAP_H
lib/libcxx/include/__algorithm/lexicographical_compare.h
@@ -0,0 +1,68 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_LEXICOGRAPHICAL_COMPARE_H
+#define _LIBCPP___ALGORITHM_LEXICOGRAPHICAL_COMPARE_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _InputIterator1, class _InputIterator2>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+__lexicographical_compare(_InputIterator1 __first1, _InputIterator1 __last1,
+                          _InputIterator2 __first2, _InputIterator2 __last2, _Compare __comp)
+{
+    for (; __first2 != __last2; ++__first1, (void) ++__first2)
+    {
+        if (__first1 == __last1 || __comp(*__first1, *__first2))
+            return true;
+        if (__comp(*__first2, *__first1))
+            return false;
+    }
+    return false;
+}
+
+template <class _InputIterator1, class _InputIterator2, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+lexicographical_compare(_InputIterator1 __first1, _InputIterator1 __last1,
+                        _InputIterator2 __first2, _InputIterator2 __last2, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__lexicographical_compare<_Comp_ref>(__first1, __last1, __first2, __last2, __comp);
+}
+
+template <class _InputIterator1, class _InputIterator2>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+lexicographical_compare(_InputIterator1 __first1, _InputIterator1 __last1,
+                        _InputIterator2 __first2, _InputIterator2 __last2)
+{
+    return _VSTD::lexicographical_compare(__first1, __last1, __first2, __last2,
+                                         __less<typename iterator_traits<_InputIterator1>::value_type,
+                                                typename iterator_traits<_InputIterator2>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_LEXICOGRAPHICAL_COMPARE_H
lib/libcxx/include/__algorithm/lower_bound.h
@@ -0,0 +1,72 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_LOWER_BOUND_H
+#define _LIBCPP___ALGORITHM_LOWER_BOUND_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/half_positive.h>
+#include <iterator>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _ForwardIterator, class _Tp>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+__lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
+{
+    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
+    difference_type __len = _VSTD::distance(__first, __last);
+    while (__len != 0)
+    {
+        difference_type __l2 = _VSTD::__half_positive(__len);
+        _ForwardIterator __m = __first;
+        _VSTD::advance(__m, __l2);
+        if (__comp(*__m, __value_))
+        {
+            __first = ++__m;
+            __len -= __l2 + 1;
+        }
+        else
+            __len = __l2;
+    }
+    return __first;
+}
+
+template <class _ForwardIterator, class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_ForwardIterator
+lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
+{
+    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
+    return _VSTD::__lower_bound<_Comp_ref>(__first, __last, __value_, __comp);
+}
+
+template <class _ForwardIterator, class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_ForwardIterator
+lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
+{
+    return _VSTD::lower_bound(__first, __last, __value_,
+                             __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_LOWER_BOUND_H
lib/libcxx/include/__algorithm/make_heap.h
@@ -0,0 +1,64 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MAKE_HEAP_H
+#define _LIBCPP___ALGORITHM_MAKE_HEAP_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/sift_down.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _RandomAccessIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 void
+__make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    difference_type __n = __last - __first;
+    if (__n > 1)
+    {
+        // start from the first parent, there is no need to consider children
+        for (difference_type __start = (__n - 2) / 2; __start >= 0; --__start)
+        {
+            _VSTD::__sift_down<_Compare>(__first, __last, __comp, __n, __first + __start);
+        }
+    }
+}
+
+template <class _RandomAccessIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    _VSTD::__make_heap<_Comp_ref>(__first, __last, __comp);
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
+{
+    _VSTD::make_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MAKE_HEAP_H
lib/libcxx/include/__algorithm/max.h
@@ -0,0 +1,70 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MAX_H
+#define _LIBCPP___ALGORITHM_MAX_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/max_element.h>
+#include <initializer_list>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+const _Tp&
+max(const _Tp& __a, const _Tp& __b, _Compare __comp)
+{
+    return __comp(__a, __b) ? __b : __a;
+}
+
+template <class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+const _Tp&
+max(const _Tp& __a, const _Tp& __b)
+{
+    return _VSTD::max(__a, __b, __less<_Tp>());
+}
+
+#ifndef _LIBCPP_CXX03_LANG
+
+template<class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_Tp
+max(initializer_list<_Tp> __t, _Compare __comp)
+{
+    return *_VSTD::max_element(__t.begin(), __t.end(), __comp);
+}
+
+template<class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_Tp
+max(initializer_list<_Tp> __t)
+{
+    return *_VSTD::max_element(__t.begin(), __t.end(), __less<_Tp>());
+}
+
+#endif // _LIBCPP_CXX03_LANG
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MAX_H
lib/libcxx/include/__algorithm/max_element.h
@@ -0,0 +1,58 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MAX_ELEMENT_H
+#define _LIBCPP___ALGORITHM_MAX_ELEMENT_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_ForwardIterator
+max_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
+{
+    static_assert(__is_cpp17_forward_iterator<_ForwardIterator>::value,
+        "std::max_element requires a ForwardIterator");
+    if (__first != __last)
+    {
+        _ForwardIterator __i = __first;
+        while (++__i != __last)
+            if (__comp(*__first, *__i))
+                __first = __i;
+    }
+    return __first;
+}
+
+
+template <class _ForwardIterator>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_ForwardIterator
+max_element(_ForwardIterator __first, _ForwardIterator __last)
+{
+    return _VSTD::max_element(__first, __last,
+              __less<typename iterator_traits<_ForwardIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MAX_ELEMENT_H
lib/libcxx/include/__algorithm/merge.h
@@ -0,0 +1,76 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MERGE_H
+#define _LIBCPP___ALGORITHM_MERGE_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/copy.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+__merge(_InputIterator1 __first1, _InputIterator1 __last1,
+        _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    for (; __first1 != __last1; ++__result)
+    {
+        if (__first2 == __last2)
+            return _VSTD::copy(__first1, __last1, __result);
+        if (__comp(*__first2, *__first1))
+        {
+            *__result = *__first2;
+            ++__first2;
+        }
+        else
+        {
+            *__result = *__first1;
+            ++__first1;
+        }
+    }
+    return _VSTD::copy(__first2, __last2, __result);
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+merge(_InputIterator1 __first1, _InputIterator1 __last1,
+      _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__merge<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+merge(_InputIterator1 __first1, _InputIterator1 __last1,
+      _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
+{
+    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
+    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
+    return _VSTD::merge(__first1, __last1, __first2, __last2, __result, __less<__v1, __v2>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MERGE_H
lib/libcxx/include/__algorithm/min.h
@@ -0,0 +1,70 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MIN_H
+#define _LIBCPP___ALGORITHM_MIN_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/min_element.h>
+#include <initializer_list>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+const _Tp&
+min(const _Tp& __a, const _Tp& __b, _Compare __comp)
+{
+    return __comp(__b, __a) ? __b : __a;
+}
+
+template <class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+const _Tp&
+min(const _Tp& __a, const _Tp& __b)
+{
+    return _VSTD::min(__a, __b, __less<_Tp>());
+}
+
+#ifndef _LIBCPP_CXX03_LANG
+
+template<class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_Tp
+min(initializer_list<_Tp> __t, _Compare __comp)
+{
+    return *_VSTD::min_element(__t.begin(), __t.end(), __comp);
+}
+
+template<class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_Tp
+min(initializer_list<_Tp> __t)
+{
+    return *_VSTD::min_element(__t.begin(), __t.end(), __less<_Tp>());
+}
+
+#endif // _LIBCPP_CXX03_LANG
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MIN_H
lib/libcxx/include/__algorithm/min_element.h
@@ -0,0 +1,57 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MIN_ELEMENT_H
+#define _LIBCPP___ALGORITHM_MIN_ELEMENT_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_ForwardIterator
+min_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
+{
+    static_assert(__is_cpp17_forward_iterator<_ForwardIterator>::value,
+        "std::min_element requires a ForwardIterator");
+    if (__first != __last)
+    {
+        _ForwardIterator __i = __first;
+        while (++__i != __last)
+            if (__comp(*__i, *__first))
+                __first = __i;
+    }
+    return __first;
+}
+
+template <class _ForwardIterator>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_ForwardIterator
+min_element(_ForwardIterator __first, _ForwardIterator __last)
+{
+    return _VSTD::min_element(__first, __last,
+              __less<typename iterator_traits<_ForwardIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MIN_ELEMENT_H
lib/libcxx/include/__algorithm/minmax.h
@@ -0,0 +1,101 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MINMAX_H
+#define _LIBCPP___ALGORITHM_MINMAX_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <initializer_list>
+#include <utility>
+
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template<class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+pair<const _Tp&, const _Tp&>
+minmax(const _Tp& __a, const _Tp& __b, _Compare __comp)
+{
+    return __comp(__b, __a) ? pair<const _Tp&, const _Tp&>(__b, __a) :
+                              pair<const _Tp&, const _Tp&>(__a, __b);
+}
+
+template<class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+pair<const _Tp&, const _Tp&>
+minmax(const _Tp& __a, const _Tp& __b)
+{
+    return _VSTD::minmax(__a, __b, __less<_Tp>());
+}
+
+#ifndef _LIBCPP_CXX03_LANG
+
+template<class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+pair<_Tp, _Tp>
+minmax(initializer_list<_Tp> __t, _Compare __comp)
+{
+    typedef typename initializer_list<_Tp>::const_iterator _Iter;
+    _Iter __first = __t.begin();
+    _Iter __last  = __t.end();
+    pair<_Tp, _Tp> __result(*__first, *__first);
+
+    ++__first;
+    if (__t.size() % 2 == 0)
+    {
+        if (__comp(*__first,  __result.first))
+            __result.first  = *__first;
+        else
+            __result.second = *__first;
+        ++__first;
+    }
+
+    while (__first != __last)
+    {
+        _Tp __prev = *__first++;
+        if (__comp(*__first, __prev)) {
+            if ( __comp(*__first, __result.first)) __result.first  = *__first;
+            if (!__comp(__prev, __result.second))  __result.second = __prev;
+            }
+        else {
+            if ( __comp(__prev, __result.first))    __result.first  = __prev;
+            if (!__comp(*__first, __result.second)) __result.second = *__first;
+            }
+
+        __first++;
+    }
+    return __result;
+}
+
+template<class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+pair<_Tp, _Tp>
+minmax(initializer_list<_Tp> __t)
+{
+    return _VSTD::minmax(__t, __less<_Tp>());
+}
+
+#endif // _LIBCPP_CXX03_LANG
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MINMAX_H
lib/libcxx/include/__algorithm/minmax_element.h
@@ -0,0 +1,90 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MINMAX_ELEMENT_H
+#define _LIBCPP___ALGORITHM_MINMAX_ELEMENT_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Compare>
+_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX11
+pair<_ForwardIterator, _ForwardIterator>
+minmax_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
+{
+  static_assert(__is_cpp17_forward_iterator<_ForwardIterator>::value,
+        "std::minmax_element requires a ForwardIterator");
+  pair<_ForwardIterator, _ForwardIterator> __result(__first, __first);
+  if (__first != __last)
+  {
+      if (++__first != __last)
+      {
+          if (__comp(*__first, *__result.first))
+              __result.first = __first;
+          else
+              __result.second = __first;
+          while (++__first != __last)
+          {
+              _ForwardIterator __i = __first;
+              if (++__first == __last)
+              {
+                  if (__comp(*__i, *__result.first))
+                      __result.first = __i;
+                  else if (!__comp(*__i, *__result.second))
+                      __result.second = __i;
+                  break;
+              }
+              else
+              {
+                  if (__comp(*__first, *__i))
+                  {
+                      if (__comp(*__first, *__result.first))
+                          __result.first = __first;
+                      if (!__comp(*__i, *__result.second))
+                          __result.second = __i;
+                  }
+                  else
+                  {
+                      if (__comp(*__i, *__result.first))
+                          __result.first = __i;
+                      if (!__comp(*__first, *__result.second))
+                          __result.second = __first;
+                  }
+              }
+          }
+      }
+  }
+  return __result;
+}
+
+template <class _ForwardIterator>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+pair<_ForwardIterator, _ForwardIterator>
+minmax_element(_ForwardIterator __first, _ForwardIterator __last)
+{
+    return _VSTD::minmax_element(__first, __last,
+              __less<typename iterator_traits<_ForwardIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MINMAX_ELEMENT_H
lib/libcxx/include/__algorithm/mismatch.h
@@ -0,0 +1,72 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MISMATCH_H
+#define _LIBCPP___ALGORITHM_MISMATCH_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_InputIterator1, _InputIterator2>
+    mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _BinaryPredicate __pred) {
+  for (; __first1 != __last1; ++__first1, (void)++__first2)
+    if (!__pred(*__first1, *__first2))
+      break;
+  return pair<_InputIterator1, _InputIterator2>(__first1, __first2);
+}
+
+template <class _InputIterator1, class _InputIterator2>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_InputIterator1, _InputIterator2>
+    mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2) {
+  typedef typename iterator_traits<_InputIterator1>::value_type __v1;
+  typedef typename iterator_traits<_InputIterator2>::value_type __v2;
+  return _VSTD::mismatch(__first1, __last1, __first2, __equal_to<__v1, __v2>());
+}
+
+#if _LIBCPP_STD_VER > 11
+template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_InputIterator1, _InputIterator2>
+    mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2,
+             _BinaryPredicate __pred) {
+  for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void)++__first2)
+    if (!__pred(*__first1, *__first2))
+      break;
+  return pair<_InputIterator1, _InputIterator2>(__first1, __first2);
+}
+
+template <class _InputIterator1, class _InputIterator2>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_InputIterator1, _InputIterator2>
+    mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2) {
+  typedef typename iterator_traits<_InputIterator1>::value_type __v1;
+  typedef typename iterator_traits<_InputIterator2>::value_type __v2;
+  return _VSTD::mismatch(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
+}
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MISMATCH_H
lib/libcxx/include/__algorithm/move.h
@@ -0,0 +1,83 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MOVE_H
+#define _LIBCPP___ALGORITHM_MOVE_H
+
+#include <__config>
+#include <__algorithm/unwrap_iter.h>
+#include <__utility/move.h>
+#include <cstring>
+#include <utility>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// move
+
+template <class _InputIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+_OutputIterator
+__move_constexpr(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
+{
+    for (; __first != __last; ++__first, (void) ++__result)
+        *__result = _VSTD::move(*__first);
+    return __result;
+}
+
+template <class _InputIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+_OutputIterator
+__move(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
+{
+    return _VSTD::__move_constexpr(__first, __last, __result);
+}
+
+template <class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+typename enable_if
+<
+    is_same<typename remove_const<_Tp>::type, _Up>::value &&
+    is_trivially_move_assignable<_Up>::value,
+    _Up*
+>::type
+__move(_Tp* __first, _Tp* __last, _Up* __result)
+{
+    const size_t __n = static_cast<size_t>(__last - __first);
+    if (__n > 0)
+        _VSTD::memmove(__result, __first, __n * sizeof(_Up));
+    return __result + __n;
+}
+
+template <class _InputIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+move(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
+{
+    if (__libcpp_is_constant_evaluated()) {
+        return _VSTD::__move_constexpr(__first, __last, __result);
+    } else {
+        return _VSTD::__rewrap_iter(__result,
+            _VSTD::__move(_VSTD::__unwrap_iter(__first),
+                          _VSTD::__unwrap_iter(__last),
+                          _VSTD::__unwrap_iter(__result)));
+    }
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MOVE_H
lib/libcxx/include/__algorithm/move_backward.h
@@ -0,0 +1,84 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_MOVE_BACKWARD_H
+#define _LIBCPP___ALGORITHM_MOVE_BACKWARD_H
+
+#include <__config>
+#include <__algorithm/unwrap_iter.h>
+#include <cstring>
+#include <utility>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+_OutputIterator
+__move_backward_constexpr(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
+{
+    while (__first != __last)
+        *--__result = _VSTD::move(*--__last);
+    return __result;
+}
+
+template <class _InputIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+_OutputIterator
+__move_backward(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
+{
+    return _VSTD::__move_backward_constexpr(__first, __last, __result);
+}
+
+template <class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+typename enable_if
+<
+    is_same<typename remove_const<_Tp>::type, _Up>::value &&
+    is_trivially_move_assignable<_Up>::value,
+    _Up*
+>::type
+__move_backward(_Tp* __first, _Tp* __last, _Up* __result)
+{
+    const size_t __n = static_cast<size_t>(__last - __first);
+    if (__n > 0)
+    {
+        __result -= __n;
+        _VSTD::memmove(__result, __first, __n * sizeof(_Up));
+    }
+    return __result;
+}
+
+template <class _BidirectionalIterator1, class _BidirectionalIterator2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_BidirectionalIterator2
+move_backward(_BidirectionalIterator1 __first, _BidirectionalIterator1 __last,
+              _BidirectionalIterator2 __result)
+{
+    if (__libcpp_is_constant_evaluated()) {
+        return _VSTD::__move_backward_constexpr(__first, __last, __result);
+    } else {
+        return _VSTD::__rewrap_iter(__result,
+            _VSTD::__move_backward(_VSTD::__unwrap_iter(__first),
+                                   _VSTD::__unwrap_iter(__last),
+                                   _VSTD::__unwrap_iter(__result)));
+    }
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_MOVE_BACKWARD_H
lib/libcxx/include/__algorithm/next_permutation.h
@@ -0,0 +1,77 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_NEXT_PERMUTATION_H
+#define _LIBCPP___ALGORITHM_NEXT_PERMUTATION_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/reverse.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/swap.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _BidirectionalIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+__next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
+{
+    _BidirectionalIterator __i = __last;
+    if (__first == __last || __first == --__i)
+        return false;
+    while (true)
+    {
+        _BidirectionalIterator __ip1 = __i;
+        if (__comp(*--__i, *__ip1))
+        {
+            _BidirectionalIterator __j = __last;
+            while (!__comp(*__i, *--__j))
+                ;
+            swap(*__i, *__j);
+            _VSTD::reverse(__ip1, __last);
+            return true;
+        }
+        if (__i == __first)
+        {
+            _VSTD::reverse(__first, __last);
+            return false;
+        }
+    }
+}
+
+template <class _BidirectionalIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__next_permutation<_Comp_ref>(__first, __last, __comp);
+}
+
+template <class _BidirectionalIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last)
+{
+    return _VSTD::next_permutation(__first, __last,
+                                  __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_NEXT_PERMUTATION_H
lib/libcxx/include/__algorithm/none_of.h
@@ -0,0 +1,37 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_NONE_OF_H
+#define _LIBCPP___ALGORITHM_NONE_OF_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _Predicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+none_of(_InputIterator __first, _InputIterator __last, _Predicate __pred) {
+  for (; __first != __last; ++__first)
+    if (__pred(*__first))
+      return false;
+  return true;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_NONE_OF_H
lib/libcxx/include/__algorithm/nth_element.h
@@ -0,0 +1,244 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_NTH_ELEMENT_H
+#define _LIBCPP___ALGORITHM_NTH_ELEMENT_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/sort.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/swap.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template<class _Compare, class _RandomAccessIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 bool
+__nth_element_find_guard(_RandomAccessIterator& __i, _RandomAccessIterator& __j,
+                         _RandomAccessIterator __m, _Compare __comp)
+{
+    // manually guard downward moving __j against __i
+    while (true) {
+        if (__i == --__j) {
+            return false;
+        }
+        if (__comp(*__j, *__m)) {
+            return true;  // found guard for downward moving __j, now use unguarded partition
+        }
+    }
+}
+
+template <class _Compare, class _RandomAccessIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 void
+__nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp)
+{
+    // _Compare is known to be a reference type
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    const difference_type __limit = 7;
+    while (true)
+    {
+        if (__nth == __last)
+            return;
+        difference_type __len = __last - __first;
+        switch (__len)
+        {
+        case 0:
+        case 1:
+            return;
+        case 2:
+            if (__comp(*--__last, *__first))
+                swap(*__first, *__last);
+            return;
+        case 3:
+            {
+            _RandomAccessIterator __m = __first;
+            _VSTD::__sort3<_Compare>(__first, ++__m, --__last, __comp);
+            return;
+            }
+        }
+        if (__len <= __limit)
+        {
+            _VSTD::__selection_sort<_Compare>(__first, __last, __comp);
+            return;
+        }
+        // __len > __limit >= 3
+        _RandomAccessIterator __m = __first + __len/2;
+        _RandomAccessIterator __lm1 = __last;
+        unsigned __n_swaps = _VSTD::__sort3<_Compare>(__first, __m, --__lm1, __comp);
+        // *__m is median
+        // partition [__first, __m) < *__m and *__m <= [__m, __last)
+        // (this inhibits tossing elements equivalent to __m around unnecessarily)
+        _RandomAccessIterator __i = __first;
+        _RandomAccessIterator __j = __lm1;
+        // j points beyond range to be tested, *__lm1 is known to be <= *__m
+        // The search going up is known to be guarded but the search coming down isn't.
+        // Prime the downward search with a guard.
+        if (!__comp(*__i, *__m))  // if *__first == *__m
+        {
+            // *__first == *__m, *__first doesn't go in first part
+            if (_VSTD::__nth_element_find_guard<_Compare>(__i, __j, __m, __comp)) {
+                swap(*__i, *__j);
+                ++__n_swaps;
+            } else {
+                // *__first == *__m, *__m <= all other elements
+                // Partition instead into [__first, __i) == *__first and *__first < [__i, __last)
+                ++__i;  // __first + 1
+                __j = __last;
+                if (!__comp(*__first, *--__j)) {  // we need a guard if *__first == *(__last-1)
+                    while (true) {
+                        if (__i == __j) {
+                            return;  // [__first, __last) all equivalent elements
+                        } else if (__comp(*__first, *__i)) {
+                            swap(*__i, *__j);
+                            ++__n_swaps;
+                            ++__i;
+                            break;
+                        }
+                        ++__i;
+                    }
+                }
+                // [__first, __i) == *__first and *__first < [__j, __last) and __j == __last - 1
+                if (__i == __j) {
+                    return;
+                }
+                while (true) {
+                    while (!__comp(*__first, *__i))
+                        ++__i;
+                    while (__comp(*__first, *--__j))
+                        ;
+                    if (__i >= __j)
+                        break;
+                    swap(*__i, *__j);
+                    ++__n_swaps;
+                    ++__i;
+                }
+                // [__first, __i) == *__first and *__first < [__i, __last)
+                // The first part is sorted,
+                if (__nth < __i) {
+                    return;
+                }
+                // __nth_element the second part
+                // _VSTD::__nth_element<_Compare>(__i, __nth, __last, __comp);
+                __first = __i;
+                continue;
+            }
+        }
+        ++__i;
+        // j points beyond range to be tested, *__lm1 is known to be <= *__m
+        // if not yet partitioned...
+        if (__i < __j)
+        {
+            // known that *(__i - 1) < *__m
+            while (true)
+            {
+                // __m still guards upward moving __i
+                while (__comp(*__i, *__m))
+                    ++__i;
+                // It is now known that a guard exists for downward moving __j
+                while (!__comp(*--__j, *__m))
+                    ;
+                if (__i >= __j)
+                    break;
+                swap(*__i, *__j);
+                ++__n_swaps;
+                // It is known that __m != __j
+                // If __m just moved, follow it
+                if (__m == __i)
+                    __m = __j;
+                ++__i;
+            }
+        }
+        // [__first, __i) < *__m and *__m <= [__i, __last)
+        if (__i != __m && __comp(*__m, *__i))
+        {
+            swap(*__i, *__m);
+            ++__n_swaps;
+        }
+        // [__first, __i) < *__i and *__i <= [__i+1, __last)
+        if (__nth == __i)
+            return;
+        if (__n_swaps == 0)
+        {
+            // We were given a perfectly partitioned sequence.  Coincidence?
+            if (__nth < __i)
+            {
+                // Check for [__first, __i) already sorted
+                __j = __m = __first;
+                while (true) {
+                    if (++__j == __i) {
+                        // [__first, __i) sorted
+                        return;
+                    }
+                    if (__comp(*__j, *__m)) {
+                        // not yet sorted, so sort
+                        break;
+                    }
+                    __m = __j;
+                }
+            }
+            else
+            {
+                // Check for [__i, __last) already sorted
+                __j = __m = __i;
+                while (true) {
+                    if (++__j == __last) {
+                        // [__i, __last) sorted
+                        return;
+                    }
+                    if (__comp(*__j, *__m)) {
+                        // not yet sorted, so sort
+                        break;
+                    }
+                    __m = __j;
+                }
+            }
+        }
+        // __nth_element on range containing __nth
+        if (__nth < __i)
+        {
+            // _VSTD::__nth_element<_Compare>(__first, __nth, __i, __comp);
+            __last = __i;
+        }
+        else
+        {
+            // _VSTD::__nth_element<_Compare>(__i+1, __nth, __last, __comp);
+            __first = ++__i;
+        }
+    }
+}
+
+template <class _RandomAccessIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    _VSTD::__nth_element<_Comp_ref>(__first, __nth, __last, __comp);
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last)
+{
+    _VSTD::nth_element(__first, __nth, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_NTH_ELEMENT_H
lib/libcxx/include/__algorithm/partial_sort.h
@@ -0,0 +1,71 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_PARTIAL_SORT_H
+#define _LIBCPP___ALGORITHM_PARTIAL_SORT_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/make_heap.h>
+#include <__algorithm/sift_down.h>
+#include <__algorithm/sort_heap.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/swap.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _RandomAccessIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 void
+__partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
+             _Compare __comp)
+{
+    _VSTD::__make_heap<_Compare>(__first, __middle, __comp);
+    typename iterator_traits<_RandomAccessIterator>::difference_type __len = __middle - __first;
+    for (_RandomAccessIterator __i = __middle; __i != __last; ++__i)
+    {
+        if (__comp(*__i, *__first))
+        {
+            swap(*__i, *__first);
+            _VSTD::__sift_down<_Compare>(__first, __middle, __comp, __len, __first);
+        }
+    }
+    _VSTD::__sort_heap<_Compare>(__first, __middle, __comp);
+}
+
+template <class _RandomAccessIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
+             _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    _VSTD::__partial_sort<_Comp_ref>(__first, __middle, __last, __comp);
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last)
+{
+    _VSTD::partial_sort(__first, __middle, __last,
+                       __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_PARTIAL_SORT_H
lib/libcxx/include/__algorithm/partial_sort_copy.h
@@ -0,0 +1,77 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_PARTIAL_SORT_COPY_H
+#define _LIBCPP___ALGORITHM_PARTIAL_SORT_COPY_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/make_heap.h>
+#include <__algorithm/sift_down.h>
+#include <__algorithm/sort_heap.h>
+#include <__iterator/iterator_traits.h>
+#include <type_traits> // swap
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _InputIterator, class _RandomAccessIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _RandomAccessIterator
+__partial_sort_copy(_InputIterator __first, _InputIterator __last,
+                    _RandomAccessIterator __result_first, _RandomAccessIterator __result_last, _Compare __comp)
+{
+    _RandomAccessIterator __r = __result_first;
+    if (__r != __result_last)
+    {
+        for (; __first != __last && __r != __result_last; ++__first, (void) ++__r)
+            *__r = *__first;
+        _VSTD::__make_heap<_Compare>(__result_first, __r, __comp);
+        typename iterator_traits<_RandomAccessIterator>::difference_type __len = __r - __result_first;
+        for (; __first != __last; ++__first)
+            if (__comp(*__first, *__result_first))
+            {
+                *__result_first = *__first;
+                _VSTD::__sift_down<_Compare>(__result_first, __r, __comp, __len, __result_first);
+            }
+        _VSTD::__sort_heap<_Compare>(__result_first, __r, __comp);
+    }
+    return __r;
+}
+
+template <class _InputIterator, class _RandomAccessIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_RandomAccessIterator
+partial_sort_copy(_InputIterator __first, _InputIterator __last,
+                  _RandomAccessIterator __result_first, _RandomAccessIterator __result_last, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__partial_sort_copy<_Comp_ref>(__first, __last, __result_first, __result_last, __comp);
+}
+
+template <class _InputIterator, class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_RandomAccessIterator
+partial_sort_copy(_InputIterator __first, _InputIterator __last,
+                  _RandomAccessIterator __result_first, _RandomAccessIterator __result_last)
+{
+    return _VSTD::partial_sort_copy(__first, __last, __result_first, __result_last,
+                                   __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_PARTIAL_SORT_COPY_H
lib/libcxx/include/__algorithm/partition.h
@@ -0,0 +1,88 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_PARTITION_H
+#define _LIBCPP___ALGORITHM_PARTITION_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <__utility/swap.h>
+#include <utility> // pair
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Predicate, class _ForwardIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+__partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, forward_iterator_tag)
+{
+    while (true)
+    {
+        if (__first == __last)
+            return __first;
+        if (!__pred(*__first))
+            break;
+        ++__first;
+    }
+    for (_ForwardIterator __p = __first; ++__p != __last;)
+    {
+        if (__pred(*__p))
+        {
+            swap(*__first, *__p);
+            ++__first;
+        }
+    }
+    return __first;
+}
+
+template <class _Predicate, class _BidirectionalIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _BidirectionalIterator
+__partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
+            bidirectional_iterator_tag)
+{
+    while (true)
+    {
+        while (true)
+        {
+            if (__first == __last)
+                return __first;
+            if (!__pred(*__first))
+                break;
+            ++__first;
+        }
+        do
+        {
+            if (__first == --__last)
+                return __first;
+        } while (!__pred(*__last));
+        swap(*__first, *__last);
+        ++__first;
+    }
+}
+
+template <class _ForwardIterator, class _Predicate>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_ForwardIterator
+partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
+{
+    return _VSTD::__partition<typename add_lvalue_reference<_Predicate>::type>
+                            (__first, __last, __pred, typename iterator_traits<_ForwardIterator>::iterator_category());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_PARTITION_H
lib/libcxx/include/__algorithm/partition_copy.h
@@ -0,0 +1,52 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_PARTITION_COPY_H
+#define _LIBCPP___ALGORITHM_PARTITION_COPY_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <utility> // pair
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _OutputIterator1,
+          class _OutputIterator2, class _Predicate>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_OutputIterator1, _OutputIterator2>
+partition_copy(_InputIterator __first, _InputIterator __last,
+               _OutputIterator1 __out_true, _OutputIterator2 __out_false,
+               _Predicate __pred)
+{
+    for (; __first != __last; ++__first)
+    {
+        if (__pred(*__first))
+        {
+            *__out_true = *__first;
+            ++__out_true;
+        }
+        else
+        {
+            *__out_false = *__first;
+            ++__out_false;
+        }
+    }
+    return pair<_OutputIterator1, _OutputIterator2>(__out_true, __out_false);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_PARTITION_COPY_H
lib/libcxx/include/__algorithm/partition_point.h
@@ -0,0 +1,51 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_PARTITION_POINT_H
+#define _LIBCPP___ALGORITHM_PARTITION_POINT_H
+
+#include <__config>
+#include <__algorithm/half_positive.h>
+#include <iterator>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template<class _ForwardIterator, class _Predicate>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+partition_point(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
+{
+    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
+    difference_type __len = _VSTD::distance(__first, __last);
+    while (__len != 0)
+    {
+        difference_type __l2 = _VSTD::__half_positive(__len);
+        _ForwardIterator __m = __first;
+        _VSTD::advance(__m, __l2);
+        if (__pred(*__m))
+        {
+            __first = ++__m;
+            __len -= __l2 + 1;
+        }
+        else
+            __len = __l2;
+    }
+    return __first;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_PARTITION_POINT_H
lib/libcxx/include/__algorithm/pop_heap.h
@@ -0,0 +1,62 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_POP_HEAP_H
+#define _LIBCPP___ALGORITHM_POP_HEAP_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/sift_down.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/swap.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+__pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
+           typename iterator_traits<_RandomAccessIterator>::difference_type __len)
+{
+    if (__len > 1)
+    {
+        swap(*__first, *--__last);
+        _VSTD::__sift_down<_Compare>(__first, __last, __comp, __len - 1, __first);
+    }
+}
+
+template <class _RandomAccessIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    _VSTD::__pop_heap<_Comp_ref>(__first, __last, __comp, __last - __first);
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
+{
+    _VSTD::pop_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_POP_HEAP_H
lib/libcxx/include/__algorithm/prev_permutation.h
@@ -0,0 +1,77 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_PREV_PERMUTATION_H
+#define _LIBCPP___ALGORITHM_PREV_PERMUTATION_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/reverse.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/swap.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _BidirectionalIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
+__prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
+{
+    _BidirectionalIterator __i = __last;
+    if (__first == __last || __first == --__i)
+        return false;
+    while (true)
+    {
+        _BidirectionalIterator __ip1 = __i;
+        if (__comp(*__ip1, *--__i))
+        {
+            _BidirectionalIterator __j = __last;
+            while (!__comp(*--__j, *__i))
+                ;
+            swap(*__i, *__j);
+            _VSTD::reverse(__ip1, __last);
+            return true;
+        }
+        if (__i == __first)
+        {
+            _VSTD::reverse(__first, __last);
+            return false;
+        }
+    }
+}
+
+template <class _BidirectionalIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__prev_permutation<_Comp_ref>(__first, __last, __comp);
+}
+
+template <class _BidirectionalIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool
+prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last)
+{
+    return _VSTD::prev_permutation(__first, __last,
+                                  __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_PREV_PERMUTATION_H
lib/libcxx/include/__algorithm/push_heap.h
@@ -0,0 +1,75 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_PUSH_HEAP_H
+#define _LIBCPP___ALGORITHM_PUSH_HEAP_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _RandomAccessIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 void
+__sift_up(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
+          typename iterator_traits<_RandomAccessIterator>::difference_type __len)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+    if (__len > 1)
+    {
+        __len = (__len - 2) / 2;
+        _RandomAccessIterator __ptr = __first + __len;
+        if (__comp(*__ptr, *--__last))
+        {
+            value_type __t(_VSTD::move(*__last));
+            do
+            {
+                *__last = _VSTD::move(*__ptr);
+                __last = __ptr;
+                if (__len == 0)
+                    break;
+                __len = (__len - 1) / 2;
+                __ptr = __first + __len;
+            } while (__comp(*__ptr, __t));
+            *__last = _VSTD::move(__t);
+        }
+    }
+}
+
+template <class _RandomAccessIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    _VSTD::__sift_up<_Comp_ref>(__first, __last, __comp, __last - __first);
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
+{
+    _VSTD::push_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_PUSH_HEAP_H
lib/libcxx/include/__algorithm/remove.h
@@ -0,0 +1,50 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REMOVE_H
+#define _LIBCPP___ALGORITHM_REMOVE_H
+
+#include <__config>
+#include <__algorithm/find.h>
+#include <__algorithm/find_if.h>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Tp>
+_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+remove(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
+{
+    __first = _VSTD::find(__first, __last, __value_);
+    if (__first != __last)
+    {
+        _ForwardIterator __i = __first;
+        while (++__i != __last)
+        {
+            if (!(*__i == __value_))
+            {
+                *__first = _VSTD::move(*__i);
+                ++__first;
+            }
+        }
+    }
+    return __first;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REMOVE_H
lib/libcxx/include/__algorithm/remove_copy.h
@@ -0,0 +1,43 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REMOVE_COPY_H
+#define _LIBCPP___ALGORITHM_REMOVE_COPY_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _OutputIterator, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+remove_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, const _Tp& __value_)
+{
+    for (; __first != __last; ++__first)
+    {
+        if (!(*__first == __value_))
+        {
+            *__result = *__first;
+            ++__result;
+        }
+    }
+    return __result;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REMOVE_COPY_H
lib/libcxx/include/__algorithm/remove_copy_if.h
@@ -0,0 +1,43 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REMOVE_COPY_IF_H
+#define _LIBCPP___ALGORITHM_REMOVE_COPY_IF_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _OutputIterator, class _Predicate>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+remove_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Predicate __pred)
+{
+    for (; __first != __last; ++__first)
+    {
+        if (!__pred(*__first))
+        {
+            *__result = *__first;
+            ++__result;
+        }
+    }
+    return __result;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REMOVE_COPY_IF_H
lib/libcxx/include/__algorithm/remove_if.h
@@ -0,0 +1,51 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REMOVE_IF_H
+#define _LIBCPP___ALGORITHM_REMOVE_IF_H
+
+#include <__config>
+#include <__algorithm/find_if.h>
+#include <utility>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Predicate>
+_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+remove_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
+{
+    __first = _VSTD::find_if<_ForwardIterator, typename add_lvalue_reference<_Predicate>::type>
+                           (__first, __last, __pred);
+    if (__first != __last)
+    {
+        _ForwardIterator __i = __first;
+        while (++__i != __last)
+        {
+            if (!__pred(*__i))
+            {
+                *__first = _VSTD::move(*__i);
+                ++__first;
+            }
+        }
+    }
+    return __first;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REMOVE_IF_H
lib/libcxx/include/__algorithm/replace.h
@@ -0,0 +1,37 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REPLACE_H
+#define _LIBCPP___ALGORITHM_REPLACE_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+replace(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __old_value, const _Tp& __new_value)
+{
+    for (; __first != __last; ++__first)
+        if (*__first == __old_value)
+            *__first = __new_value;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REPLACE_H
lib/libcxx/include/__algorithm/replace_copy.h
@@ -0,0 +1,41 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REPLACE_COPY_H
+#define _LIBCPP___ALGORITHM_REPLACE_COPY_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _OutputIterator, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+replace_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
+             const _Tp& __old_value, const _Tp& __new_value)
+{
+    for (; __first != __last; ++__first, (void) ++__result)
+        if (*__first == __old_value)
+            *__result = __new_value;
+        else
+            *__result = *__first;
+    return __result;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REPLACE_COPY_H
lib/libcxx/include/__algorithm/replace_copy_if.h
@@ -0,0 +1,41 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REPLACE_COPY_IF_H
+#define _LIBCPP___ALGORITHM_REPLACE_COPY_IF_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _OutputIterator, class _Predicate, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+replace_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
+                _Predicate __pred, const _Tp& __new_value)
+{
+    for (; __first != __last; ++__first, (void) ++__result)
+        if (__pred(*__first))
+            *__result = __new_value;
+        else
+            *__result = *__first;
+    return __result;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REPLACE_COPY_IF_H
lib/libcxx/include/__algorithm/replace_if.h
@@ -0,0 +1,37 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REPLACE_IF_H
+#define _LIBCPP___ALGORITHM_REPLACE_IF_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _Predicate, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+replace_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, const _Tp& __new_value)
+{
+    for (; __first != __last; ++__first)
+        if (__pred(*__first))
+            *__first = __new_value;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REPLACE_IF_H
lib/libcxx/include/__algorithm/reverse.h
@@ -0,0 +1,61 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REVERSE_H
+#define _LIBCPP___ALGORITHM_REVERSE_H
+
+#include <__config>
+#include <__algorithm/iter_swap.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _BidirectionalIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+__reverse(_BidirectionalIterator __first, _BidirectionalIterator __last, bidirectional_iterator_tag)
+{
+    while (__first != __last)
+    {
+        if (__first == --__last)
+            break;
+        _VSTD::iter_swap(__first, __last);
+        ++__first;
+    }
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+__reverse(_RandomAccessIterator __first, _RandomAccessIterator __last, random_access_iterator_tag)
+{
+    if (__first != __last)
+        for (; __first < --__last; ++__first)
+            _VSTD::iter_swap(__first, __last);
+}
+
+template <class _BidirectionalIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+reverse(_BidirectionalIterator __first, _BidirectionalIterator __last)
+{
+    _VSTD::__reverse(__first, __last, typename iterator_traits<_BidirectionalIterator>::iterator_category());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REVERSE_H
lib/libcxx/include/__algorithm/reverse_copy.h
@@ -0,0 +1,37 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_REVERSE_COPY_H
+#define _LIBCPP___ALGORITHM_REVERSE_COPY_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _BidirectionalIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+reverse_copy(_BidirectionalIterator __first, _BidirectionalIterator __last, _OutputIterator __result)
+{
+    for (; __first != __last; ++__result)
+        *__result = *--__last;
+    return __result;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_REVERSE_COPY_H
lib/libcxx/include/__algorithm/rotate.h
@@ -0,0 +1,205 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_ROTATE_H
+#define _LIBCPP___ALGORITHM_ROTATE_H
+
+#include <__algorithm/move.h>
+#include <__algorithm/move_backward.h>
+#include <__algorithm/swap_ranges.h>
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/next.h>
+#include <__iterator/prev.h>
+#include <__utility/swap.h>
+#include <iterator>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 _ForwardIterator
+__rotate_left(_ForwardIterator __first, _ForwardIterator __last)
+{
+    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
+    value_type __tmp = _VSTD::move(*__first);
+    _ForwardIterator __lm1 = _VSTD::move(_VSTD::next(__first), __last, __first);
+    *__lm1 = _VSTD::move(__tmp);
+    return __lm1;
+}
+
+template <class _BidirectionalIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 _BidirectionalIterator
+__rotate_right(_BidirectionalIterator __first, _BidirectionalIterator __last)
+{
+    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
+    _BidirectionalIterator __lm1 = _VSTD::prev(__last);
+    value_type __tmp = _VSTD::move(*__lm1);
+    _BidirectionalIterator __fp1 = _VSTD::move_backward(__first, __lm1, __last);
+    *__first = _VSTD::move(__tmp);
+    return __fp1;
+}
+
+template <class _ForwardIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX14 _ForwardIterator
+__rotate_forward(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last)
+{
+    _ForwardIterator __i = __middle;
+    while (true)
+    {
+        swap(*__first, *__i);
+        ++__first;
+        if (++__i == __last)
+            break;
+        if (__first == __middle)
+            __middle = __i;
+    }
+    _ForwardIterator __r = __first;
+    if (__first != __middle)
+    {
+        __i = __middle;
+        while (true)
+        {
+            swap(*__first, *__i);
+            ++__first;
+            if (++__i == __last)
+            {
+                if (__first == __middle)
+                    break;
+                __i = __middle;
+            }
+            else if (__first == __middle)
+                __middle = __i;
+        }
+    }
+    return __r;
+}
+
+template<typename _Integral>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_CONSTEXPR_AFTER_CXX14 _Integral
+__algo_gcd(_Integral __x, _Integral __y)
+{
+    do
+    {
+        _Integral __t = __x % __y;
+        __x = __y;
+        __y = __t;
+    } while (__y);
+    return __x;
+}
+
+template<typename _RandomAccessIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX14 _RandomAccessIterator
+__rotate_gcd(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+
+    const difference_type __m1 = __middle - __first;
+    const difference_type __m2 = __last - __middle;
+    if (__m1 == __m2)
+    {
+        _VSTD::swap_ranges(__first, __middle, __middle);
+        return __middle;
+    }
+    const difference_type __g = _VSTD::__algo_gcd(__m1, __m2);
+    for (_RandomAccessIterator __p = __first + __g; __p != __first;)
+    {
+        value_type __t(_VSTD::move(*--__p));
+        _RandomAccessIterator __p1 = __p;
+        _RandomAccessIterator __p2 = __p1 + __m1;
+        do
+        {
+            *__p1 = _VSTD::move(*__p2);
+            __p1 = __p2;
+            const difference_type __d = __last - __p2;
+            if (__m1 < __d)
+                __p2 += __m1;
+            else
+                __p2 = __first + (__m1 - __d);
+        } while (__p2 != __p);
+        *__p1 = _VSTD::move(__t);
+    }
+    return __first + __m2;
+}
+
+template <class _ForwardIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_CONSTEXPR_AFTER_CXX11 _ForwardIterator
+__rotate(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last,
+         _VSTD::forward_iterator_tag)
+{
+    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
+    if (is_trivially_move_assignable<value_type>::value)
+    {
+        if (_VSTD::next(__first) == __middle)
+            return _VSTD::__rotate_left(__first, __last);
+    }
+    return _VSTD::__rotate_forward(__first, __middle, __last);
+}
+
+template <class _BidirectionalIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_CONSTEXPR_AFTER_CXX11 _BidirectionalIterator
+__rotate(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
+         bidirectional_iterator_tag)
+{
+    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
+    if (is_trivially_move_assignable<value_type>::value)
+    {
+        if (_VSTD::next(__first) == __middle)
+            return _VSTD::__rotate_left(__first, __last);
+        if (_VSTD::next(__middle) == __last)
+            return _VSTD::__rotate_right(__first, __last);
+    }
+    return _VSTD::__rotate_forward(__first, __middle, __last);
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_CONSTEXPR_AFTER_CXX11 _RandomAccessIterator
+__rotate(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
+         random_access_iterator_tag)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+    if (is_trivially_move_assignable<value_type>::value)
+    {
+        if (_VSTD::next(__first) == __middle)
+            return _VSTD::__rotate_left(__first, __last);
+        if (_VSTD::next(__middle) == __last)
+            return _VSTD::__rotate_right(__first, __last);
+        return _VSTD::__rotate_gcd(__first, __middle, __last);
+    }
+    return _VSTD::__rotate_forward(__first, __middle, __last);
+}
+
+template <class _ForwardIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+rotate(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last)
+{
+    if (__first == __middle)
+        return __last;
+    if (__middle == __last)
+        return __first;
+    return _VSTD::__rotate(__first, __middle, __last,
+                           typename iterator_traits<_ForwardIterator>::iterator_category());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_ROTATE_H
lib/libcxx/include/__algorithm/rotate_copy.h
@@ -0,0 +1,38 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_ROTATE_COPY_H
+#define _LIBCPP___ALGORITHM_ROTATE_COPY_H
+
+#include <__config>
+#include <__algorithm/copy.h>
+#include <iterator>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+rotate_copy(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last, _OutputIterator __result)
+{
+    return _VSTD::copy(__first, __middle, _VSTD::copy(__middle, __last, __result));
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_ROTATE_COPY_H
lib/libcxx/include/__algorithm/sample.h
@@ -0,0 +1,101 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SAMPLE_H
+#define _LIBCPP___ALGORITHM_SAMPLE_H
+
+#include <__config>
+#include <__algorithm/min.h>
+#include <__random/uniform_int_distribution.h>
+#include <iterator>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _PopulationIterator, class _SampleIterator, class _Distance,
+          class _UniformRandomNumberGenerator>
+_LIBCPP_INLINE_VISIBILITY
+_SampleIterator __sample(_PopulationIterator __first,
+                         _PopulationIterator __last, _SampleIterator __output_iter,
+                         _Distance __n,
+                         _UniformRandomNumberGenerator & __g,
+                         input_iterator_tag) {
+
+  _Distance __k = 0;
+  for (; __first != __last && __k < __n; ++__first, (void) ++__k)
+    __output_iter[__k] = *__first;
+  _Distance __sz = __k;
+  for (; __first != __last; ++__first, (void) ++__k) {
+    _Distance __r = uniform_int_distribution<_Distance>(0, __k)(__g);
+    if (__r < __sz)
+      __output_iter[__r] = *__first;
+  }
+  return __output_iter + _VSTD::min(__n, __k);
+}
+
+template <class _PopulationIterator, class _SampleIterator, class _Distance,
+          class _UniformRandomNumberGenerator>
+_LIBCPP_INLINE_VISIBILITY
+_SampleIterator __sample(_PopulationIterator __first,
+                         _PopulationIterator __last, _SampleIterator __output_iter,
+                         _Distance __n,
+                         _UniformRandomNumberGenerator& __g,
+                         forward_iterator_tag) {
+  _Distance __unsampled_sz = _VSTD::distance(__first, __last);
+  for (__n = _VSTD::min(__n, __unsampled_sz); __n != 0; ++__first) {
+    _Distance __r = uniform_int_distribution<_Distance>(0, --__unsampled_sz)(__g);
+    if (__r < __n) {
+      *__output_iter++ = *__first;
+      --__n;
+    }
+  }
+  return __output_iter;
+}
+
+template <class _PopulationIterator, class _SampleIterator, class _Distance,
+          class _UniformRandomNumberGenerator>
+_LIBCPP_INLINE_VISIBILITY
+_SampleIterator __sample(_PopulationIterator __first,
+                         _PopulationIterator __last, _SampleIterator __output_iter,
+                         _Distance __n, _UniformRandomNumberGenerator& __g) {
+  typedef typename iterator_traits<_PopulationIterator>::iterator_category
+        _PopCategory;
+  typedef typename iterator_traits<_PopulationIterator>::difference_type
+        _Difference;
+  static_assert(__is_cpp17_forward_iterator<_PopulationIterator>::value ||
+                __is_cpp17_random_access_iterator<_SampleIterator>::value,
+                "SampleIterator must meet the requirements of RandomAccessIterator");
+  typedef typename common_type<_Distance, _Difference>::type _CommonType;
+  _LIBCPP_ASSERT(__n >= 0, "N must be a positive number.");
+  return _VSTD::__sample(
+      __first, __last, __output_iter, _CommonType(__n),
+      __g, _PopCategory());
+}
+
+#if _LIBCPP_STD_VER > 14
+template <class _PopulationIterator, class _SampleIterator, class _Distance,
+          class _UniformRandomNumberGenerator>
+inline _LIBCPP_INLINE_VISIBILITY
+_SampleIterator sample(_PopulationIterator __first,
+                       _PopulationIterator __last, _SampleIterator __output_iter,
+                       _Distance __n, _UniformRandomNumberGenerator&& __g) {
+    return _VSTD::__sample(__first, __last, __output_iter, __n, __g);
+}
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SAMPLE_H
lib/libcxx/include/__algorithm/search.h
@@ -0,0 +1,131 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SEARCH_H
+#define _LIBCPP___ALGORITHM_SEARCH_H
+
+#include <__algorithm/comp.h>
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <type_traits>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
+pair<_ForwardIterator1, _ForwardIterator1>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 __search(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
+                                           _ForwardIterator2 __first2, _ForwardIterator2 __last2,
+                                           _BinaryPredicate __pred, forward_iterator_tag, forward_iterator_tag) {
+  if (__first2 == __last2)
+    return _VSTD::make_pair(__first1, __first1); // Everything matches an empty sequence
+  while (true) {
+    // Find first element in sequence 1 that matchs *__first2, with a mininum of loop checks
+    while (true) {
+      if (__first1 == __last1) // return __last1 if no element matches *__first2
+        return _VSTD::make_pair(__last1, __last1);
+      if (__pred(*__first1, *__first2))
+        break;
+      ++__first1;
+    }
+    // *__first1 matches *__first2, now match elements after here
+    _ForwardIterator1 __m1 = __first1;
+    _ForwardIterator2 __m2 = __first2;
+    while (true) {
+      if (++__m2 == __last2) // If pattern exhausted, __first1 is the answer (works for 1 element pattern)
+        return _VSTD::make_pair(__first1, __m1);
+      if (++__m1 == __last1) // Otherwise if source exhaused, pattern not found
+        return _VSTD::make_pair(__last1, __last1);
+      if (!__pred(*__m1, *__m2)) // if there is a mismatch, restart with a new __first1
+      {
+        ++__first1;
+        break;
+      } // else there is a match, check next elements
+    }
+  }
+}
+
+template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 pair<_RandomAccessIterator1, _RandomAccessIterator1>
+__search(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1, _RandomAccessIterator2 __first2,
+         _RandomAccessIterator2 __last2, _BinaryPredicate __pred, random_access_iterator_tag,
+         random_access_iterator_tag) {
+  typedef typename iterator_traits<_RandomAccessIterator1>::difference_type _D1;
+  typedef typename iterator_traits<_RandomAccessIterator2>::difference_type _D2;
+  // Take advantage of knowing source and pattern lengths.  Stop short when source is smaller than pattern
+  const _D2 __len2 = __last2 - __first2;
+  if (__len2 == 0)
+    return _VSTD::make_pair(__first1, __first1);
+  const _D1 __len1 = __last1 - __first1;
+  if (__len1 < __len2)
+    return _VSTD::make_pair(__last1, __last1);
+  const _RandomAccessIterator1 __s = __last1 - (__len2 - 1); // Start of pattern match can't go beyond here
+
+  while (true) {
+    while (true) {
+      if (__first1 == __s)
+        return _VSTD::make_pair(__last1, __last1);
+      if (__pred(*__first1, *__first2))
+        break;
+      ++__first1;
+    }
+
+    _RandomAccessIterator1 __m1 = __first1;
+    _RandomAccessIterator2 __m2 = __first2;
+    while (true) {
+      if (++__m2 == __last2)
+        return _VSTD::make_pair(__first1, __first1 + __len2);
+      ++__m1; // no need to check range on __m1 because __s guarantees we have enough source
+      if (!__pred(*__m1, *__m2)) {
+        ++__first1;
+        break;
+      }
+    }
+  }
+}
+
+template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1
+search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2,
+       _BinaryPredicate __pred) {
+  return _VSTD::__search<typename add_lvalue_reference<_BinaryPredicate>::type>(
+             __first1, __last1, __first2, __last2, __pred,
+             typename iterator_traits<_ForwardIterator1>::iterator_category(),
+             typename iterator_traits<_ForwardIterator2>::iterator_category()).first;
+}
+
+template <class _ForwardIterator1, class _ForwardIterator2>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1
+search(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2, _ForwardIterator2 __last2) {
+  typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
+  typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
+  return _VSTD::search(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
+}
+
+#if _LIBCPP_STD_VER > 14
+template <class _ForwardIterator, class _Searcher>
+_LIBCPP_NODISCARD_EXT _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+search(_ForwardIterator __f, _ForwardIterator __l, const _Searcher& __s) {
+  return __s(__f, __l).first;
+}
+
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SEARCH_H
lib/libcxx/include/__algorithm/search_n.h
@@ -0,0 +1,116 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SEARCH_N_H
+#define _LIBCPP___ALGORITHM_SEARCH_N_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _BinaryPredicate, class _ForwardIterator, class _Size, class _Tp>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator __search_n(_ForwardIterator __first, _ForwardIterator __last,
+                                                          _Size __count, const _Tp& __value_, _BinaryPredicate __pred,
+                                                          forward_iterator_tag) {
+  if (__count <= 0)
+    return __first;
+  while (true) {
+    // Find first element in sequence that matchs __value_, with a mininum of loop checks
+    while (true) {
+      if (__first == __last) // return __last if no element matches __value_
+        return __last;
+      if (__pred(*__first, __value_))
+        break;
+      ++__first;
+    }
+    // *__first matches __value_, now match elements after here
+    _ForwardIterator __m = __first;
+    _Size __c(0);
+    while (true) {
+      if (++__c == __count) // If pattern exhausted, __first is the answer (works for 1 element pattern)
+        return __first;
+      if (++__m == __last) // Otherwise if source exhaused, pattern not found
+        return __last;
+      if (!__pred(*__m, __value_)) // if there is a mismatch, restart with a new __first
+      {
+        __first = __m;
+        ++__first;
+        break;
+      } // else there is a match, check next elements
+    }
+  }
+}
+
+template <class _BinaryPredicate, class _RandomAccessIterator, class _Size, class _Tp>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _RandomAccessIterator __search_n(_RandomAccessIterator __first,
+                                                               _RandomAccessIterator __last, _Size __count,
+                                                               const _Tp& __value_, _BinaryPredicate __pred,
+                                                               random_access_iterator_tag) {
+  if (__count <= 0)
+    return __first;
+  _Size __len = static_cast<_Size>(__last - __first);
+  if (__len < __count)
+    return __last;
+  const _RandomAccessIterator __s = __last - (__count - 1); // Start of pattern match can't go beyond here
+  while (true) {
+    // Find first element in sequence that matchs __value_, with a mininum of loop checks
+    while (true) {
+      if (__first >= __s) // return __last if no element matches __value_
+        return __last;
+      if (__pred(*__first, __value_))
+        break;
+      ++__first;
+    }
+    // *__first matches __value_, now match elements after here
+    _RandomAccessIterator __m = __first;
+    _Size __c(0);
+    while (true) {
+      if (++__c == __count) // If pattern exhausted, __first is the answer (works for 1 element pattern)
+        return __first;
+      ++__m;                       // no need to check range on __m because __s guarantees we have enough source
+      if (!__pred(*__m, __value_)) // if there is a mismatch, restart with a new __first
+      {
+        __first = __m;
+        ++__first;
+        break;
+      } // else there is a match, check next elements
+    }
+  }
+}
+
+template <class _ForwardIterator, class _Size, class _Tp, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator search_n(
+    _ForwardIterator __first, _ForwardIterator __last, _Size __count, const _Tp& __value_, _BinaryPredicate __pred) {
+  return _VSTD::__search_n<typename add_lvalue_reference<_BinaryPredicate>::type>(
+      __first, __last, _VSTD::__convert_to_integral(__count), __value_, __pred,
+      typename iterator_traits<_ForwardIterator>::iterator_category());
+}
+
+template <class _ForwardIterator, class _Size, class _Tp>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+search_n(_ForwardIterator __first, _ForwardIterator __last, _Size __count, const _Tp& __value_) {
+  typedef typename iterator_traits<_ForwardIterator>::value_type __v;
+  return _VSTD::search_n(__first, __last, _VSTD::__convert_to_integral(__count), __value_, __equal_to<__v, _Tp>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SEARCH_N_H
lib/libcxx/include/__algorithm/set_difference.h
@@ -0,0 +1,77 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SET_DIFFERENCE_H
+#define _LIBCPP___ALGORITHM_SET_DIFFERENCE_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/copy.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
+__set_difference(_InputIterator1 __first1, _InputIterator1 __last1,
+                 _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    while (__first1 != __last1)
+    {
+        if (__first2 == __last2)
+            return _VSTD::copy(__first1, __last1, __result);
+        if (__comp(*__first1, *__first2))
+        {
+            *__result = *__first1;
+            ++__result;
+            ++__first1;
+        }
+        else
+        {
+            if (!__comp(*__first2, *__first1))
+                ++__first1;
+            ++__first2;
+        }
+    }
+    return __result;
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+set_difference(_InputIterator1 __first1, _InputIterator1 __last1,
+               _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__set_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+set_difference(_InputIterator1 __first1, _InputIterator1 __last1,
+               _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
+{
+    return _VSTD::set_difference(__first1, __last1, __first2, __last2, __result,
+                                __less<typename iterator_traits<_InputIterator1>::value_type,
+                                       typename iterator_traits<_InputIterator2>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SET_DIFFERENCE_H
lib/libcxx/include/__algorithm/set_intersection.h
@@ -0,0 +1,74 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SET_INTERSECTION_H
+#define _LIBCPP___ALGORITHM_SET_INTERSECTION_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
+__set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
+                   _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    while (__first1 != __last1 && __first2 != __last2)
+    {
+        if (__comp(*__first1, *__first2))
+            ++__first1;
+        else
+        {
+            if (!__comp(*__first2, *__first1))
+            {
+                *__result = *__first1;
+                ++__result;
+                ++__first1;
+            }
+            ++__first2;
+        }
+    }
+    return __result;
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
+                 _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__set_intersection<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
+                 _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
+{
+    return _VSTD::set_intersection(__first1, __last1, __first2, __last2, __result,
+                                  __less<typename iterator_traits<_InputIterator1>::value_type,
+                                         typename iterator_traits<_InputIterator2>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SET_INTERSECTION_H
lib/libcxx/include/__algorithm/set_symmetric_difference.h
@@ -0,0 +1,82 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SET_SYMMETRIC_DIFFERENCE_H
+#define _LIBCPP___ALGORITHM_SET_SYMMETRIC_DIFFERENCE_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/copy.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
+__set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1,
+                           _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    while (__first1 != __last1)
+    {
+        if (__first2 == __last2)
+            return _VSTD::copy(__first1, __last1, __result);
+        if (__comp(*__first1, *__first2))
+        {
+            *__result = *__first1;
+            ++__result;
+            ++__first1;
+        }
+        else
+        {
+            if (__comp(*__first2, *__first1))
+            {
+                *__result = *__first2;
+                ++__result;
+            }
+            else
+                ++__first1;
+            ++__first2;
+        }
+    }
+    return _VSTD::copy(__first2, __last2, __result);
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1,
+                         _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__set_symmetric_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1,
+                         _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
+{
+    return _VSTD::set_symmetric_difference(__first1, __last1, __first2, __last2, __result,
+                                          __less<typename iterator_traits<_InputIterator1>::value_type,
+                                                 typename iterator_traits<_InputIterator2>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SET_SYMMETRIC_DIFFERENCE_H
lib/libcxx/include/__algorithm/set_union.h
@@ -0,0 +1,77 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SET_UNION_H
+#define _LIBCPP___ALGORITHM_SET_UNION_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/copy.h>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
+__set_union(_InputIterator1 __first1, _InputIterator1 __last1,
+            _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    for (; __first1 != __last1; ++__result)
+    {
+        if (__first2 == __last2)
+            return _VSTD::copy(__first1, __last1, __result);
+        if (__comp(*__first2, *__first1))
+        {
+            *__result = *__first2;
+            ++__first2;
+        }
+        else
+        {
+            if (!__comp(*__first1, *__first2))
+                ++__first2;
+            *__result = *__first1;
+            ++__first1;
+        }
+    }
+    return _VSTD::copy(__first2, __last2, __result);
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+set_union(_InputIterator1 __first1, _InputIterator1 __last1,
+          _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    return _VSTD::__set_union<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+set_union(_InputIterator1 __first1, _InputIterator1 __last1,
+          _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
+{
+    return _VSTD::set_union(__first1, __last1, __first2, __last2, __result,
+                          __less<typename iterator_traits<_InputIterator1>::value_type,
+                                 typename iterator_traits<_InputIterator2>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SET_UNION_H
lib/libcxx/include/__algorithm/shift_left.h
@@ -0,0 +1,61 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SHIFT_LEFT_H
+#define _LIBCPP___ALGORITHM_SHIFT_LEFT_H
+
+#include <__config>
+#include <__algorithm/move.h>
+#include <__iterator/iterator_traits.h>
+#include <type_traits> // swap
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17
+
+template <class _ForwardIterator>
+inline _LIBCPP_INLINE_VISIBILITY constexpr
+_ForwardIterator
+shift_left(_ForwardIterator __first, _ForwardIterator __last,
+           typename iterator_traits<_ForwardIterator>::difference_type __n)
+{
+    if (__n == 0) {
+        return __last;
+    }
+
+    _ForwardIterator __m = __first;
+    if constexpr (__is_cpp17_random_access_iterator<_ForwardIterator>::value) {
+        if (__n >= __last - __first) {
+            return __first;
+        }
+        __m += __n;
+    } else {
+        for (; __n > 0; --__n) {
+            if (__m == __last) {
+                return __first;
+            }
+            ++__m;
+        }
+    }
+    return _VSTD::move(__m, __last, __first);
+}
+
+#endif // _LIBCPP_STD_VER > 17
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SHIFT_LEFT_H
lib/libcxx/include/__algorithm/shift_right.h
@@ -0,0 +1,106 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SHIFT_RIGHT_H
+#define _LIBCPP___ALGORITHM_SHIFT_RIGHT_H
+
+#include <__config>
+#include <__algorithm/move.h>
+#include <__algorithm/move_backward.h>
+#include <__algorithm/swap_ranges.h>
+#include <__iterator/iterator_traits.h>
+#include <type_traits> // swap
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17
+
+template <class _ForwardIterator>
+inline _LIBCPP_INLINE_VISIBILITY constexpr
+_ForwardIterator
+shift_right(_ForwardIterator __first, _ForwardIterator __last,
+            typename iterator_traits<_ForwardIterator>::difference_type __n)
+{
+    if (__n == 0) {
+        return __first;
+    }
+
+    if constexpr (__is_cpp17_random_access_iterator<_ForwardIterator>::value) {
+        decltype(__n) __d = __last - __first;
+        if (__n >= __d) {
+            return __last;
+        }
+        _ForwardIterator __m = __first + (__d - __n);
+        return _VSTD::move_backward(__first, __m, __last);
+    } else if constexpr (__is_cpp17_bidirectional_iterator<_ForwardIterator>::value) {
+        _ForwardIterator __m = __last;
+        for (; __n > 0; --__n) {
+            if (__m == __first) {
+                return __last;
+            }
+            --__m;
+        }
+        return _VSTD::move_backward(__first, __m, __last);
+    } else {
+        _ForwardIterator __ret = __first;
+        for (; __n > 0; --__n) {
+            if (__ret == __last) {
+                return __last;
+            }
+            ++__ret;
+        }
+
+        // We have an __n-element scratch space from __first to __ret.
+        // Slide an __n-element window [__trail, __lead) from left to right.
+        // We're essentially doing swap_ranges(__first, __ret, __trail, __lead)
+        // over and over; but once __lead reaches __last we needn't bother
+        // to save the values of elements [__trail, __last).
+
+        auto __trail = __first;
+        auto __lead = __ret;
+        while (__trail != __ret) {
+            if (__lead == __last) {
+                _VSTD::move(__first, __trail, __ret);
+                return __ret;
+            }
+            ++__trail;
+            ++__lead;
+        }
+
+        _ForwardIterator __mid = __first;
+        while (true) {
+            if (__lead == __last) {
+                __trail = _VSTD::move(__mid, __ret, __trail);
+                _VSTD::move(__first, __mid, __trail);
+                return __ret;
+            }
+            swap(*__mid, *__trail);
+            ++__mid;
+            ++__trail;
+            ++__lead;
+            if (__mid == __ret) {
+                __mid = __first;
+            }
+        }
+    }
+}
+
+#endif // _LIBCPP_STD_VER > 17
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SHIFT_RIGHT_H
lib/libcxx/include/__algorithm/shuffle.h
@@ -0,0 +1,127 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SHUFFLE_H
+#define _LIBCPP___ALGORITHM_SHUFFLE_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <__random/uniform_int_distribution.h>
+#include <__utility/swap.h>
+#include <cstddef>
+#include <cstdint>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE) \
+  || defined(_LIBCPP_BUILDING_LIBRARY)
+class _LIBCPP_TYPE_VIS __rs_default;
+
+_LIBCPP_FUNC_VIS __rs_default __rs_get();
+
+class _LIBCPP_TYPE_VIS __rs_default
+{
+    static unsigned __c_;
+
+    __rs_default();
+public:
+    typedef uint_fast32_t result_type;
+
+    static const result_type _Min = 0;
+    static const result_type _Max = 0xFFFFFFFF;
+
+    __rs_default(const __rs_default&);
+    ~__rs_default();
+
+    result_type operator()();
+
+    static _LIBCPP_CONSTEXPR result_type min() {return _Min;}
+    static _LIBCPP_CONSTEXPR result_type max() {return _Max;}
+
+    friend _LIBCPP_FUNC_VIS __rs_default __rs_get();
+};
+
+_LIBCPP_FUNC_VIS __rs_default __rs_get();
+
+template <class _RandomAccessIterator>
+_LIBCPP_DEPRECATED_IN_CXX14 void
+random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    typedef uniform_int_distribution<ptrdiff_t> _Dp;
+    typedef typename _Dp::param_type _Pp;
+    difference_type __d = __last - __first;
+    if (__d > 1)
+    {
+        _Dp __uid;
+        __rs_default __g = __rs_get();
+        for (--__last, (void) --__d; __first < __last; ++__first, (void) --__d)
+        {
+            difference_type __i = __uid(__g, _Pp(0, __d));
+            if (__i != difference_type(0))
+                swap(*__first, *(__first + __i));
+        }
+    }
+}
+
+template <class _RandomAccessIterator, class _RandomNumberGenerator>
+_LIBCPP_DEPRECATED_IN_CXX14 void
+random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last,
+#ifndef _LIBCPP_CXX03_LANG
+               _RandomNumberGenerator&& __rand)
+#else
+               _RandomNumberGenerator& __rand)
+#endif
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    difference_type __d = __last - __first;
+    if (__d > 1)
+    {
+        for (--__last; __first < __last; ++__first, (void) --__d)
+        {
+            difference_type __i = __rand(__d);
+            if (__i != difference_type(0))
+              swap(*__first, *(__first + __i));
+        }
+    }
+}
+#endif
+
+template<class _RandomAccessIterator, class _UniformRandomNumberGenerator>
+    void shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last,
+                 _UniformRandomNumberGenerator&& __g)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    typedef uniform_int_distribution<ptrdiff_t> _Dp;
+    typedef typename _Dp::param_type _Pp;
+    difference_type __d = __last - __first;
+    if (__d > 1)
+    {
+        _Dp __uid;
+        for (--__last, (void) --__d; __first < __last; ++__first, (void) --__d)
+        {
+            difference_type __i = __uid(__g, _Pp(0, __d));
+            if (__i != difference_type(0))
+                swap(*__first, *(__first + __i));
+        }
+    }
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SHUFFLE_H
lib/libcxx/include/__algorithm/sift_down.h
@@ -0,0 +1,84 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SIFT_DOWN_H
+#define _LIBCPP___ALGORITHM_SIFT_DOWN_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _RandomAccessIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 void
+__sift_down(_RandomAccessIterator __first, _RandomAccessIterator /*__last*/,
+            _Compare __comp,
+            typename iterator_traits<_RandomAccessIterator>::difference_type __len,
+            _RandomAccessIterator __start)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+    // left-child of __start is at 2 * __start + 1
+    // right-child of __start is at 2 * __start + 2
+    difference_type __child = __start - __first;
+
+    if (__len < 2 || (__len - 2) / 2 < __child)
+        return;
+
+    __child = 2 * __child + 1;
+    _RandomAccessIterator __child_i = __first + __child;
+
+    if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + 1))) {
+        // right-child exists and is greater than left-child
+        ++__child_i;
+        ++__child;
+    }
+
+    // check if we are in heap-order
+    if (__comp(*__child_i, *__start))
+        // we are, __start is larger than it's largest child
+        return;
+
+    value_type __top(_VSTD::move(*__start));
+    do
+    {
+        // we are not in heap-order, swap the parent with its largest child
+        *__start = _VSTD::move(*__child_i);
+        __start = __child_i;
+
+        if ((__len - 2) / 2 < __child)
+            break;
+
+        // recompute the child based off of the updated parent
+        __child = 2 * __child + 1;
+        __child_i = __first + __child;
+
+        if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + 1))) {
+            // right-child exists and is greater than left-child
+            ++__child_i;
+            ++__child;
+        }
+
+        // check if we are in heap-order
+    } while (!__comp(*__child_i, __top));
+    *__start = _VSTD::move(__top);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SIFT_DOWN_H
lib/libcxx/include/__algorithm/sort.h
@@ -0,0 +1,530 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SORT_H
+#define _LIBCPP___ALGORITHM_SORT_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/min_element.h>
+#include <__algorithm/partial_sort.h>
+#include <__algorithm/unwrap_iter.h>
+#include <__utility/swap.h>
+#include <memory>
+#include <type_traits> // swap
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// stable, 2-3 compares, 0-2 swaps
+
+template <class _Compare, class _ForwardIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 unsigned
+__sort3(_ForwardIterator __x, _ForwardIterator __y, _ForwardIterator __z, _Compare __c)
+{
+    unsigned __r = 0;
+    if (!__c(*__y, *__x))          // if x <= y
+    {
+        if (!__c(*__z, *__y))      // if y <= z
+            return __r;            // x <= y && y <= z
+                                   // x <= y && y > z
+        swap(*__y, *__z);          // x <= z && y < z
+        __r = 1;
+        if (__c(*__y, *__x))       // if x > y
+        {
+            swap(*__x, *__y);      // x < y && y <= z
+            __r = 2;
+        }
+        return __r;                // x <= y && y < z
+    }
+    if (__c(*__z, *__y))           // x > y, if y > z
+    {
+        swap(*__x, *__z);          // x < y && y < z
+        __r = 1;
+        return __r;
+    }
+    swap(*__x, *__y);              // x > y && y <= z
+    __r = 1;                       // x < y && x <= z
+    if (__c(*__z, *__y))           // if y > z
+    {
+        swap(*__y, *__z);          // x <= y && y < z
+        __r = 2;
+    }
+    return __r;
+}                                  // x <= y && y <= z
+
+// stable, 3-6 compares, 0-5 swaps
+
+template <class _Compare, class _ForwardIterator>
+unsigned
+__sort4(_ForwardIterator __x1, _ForwardIterator __x2, _ForwardIterator __x3,
+            _ForwardIterator __x4, _Compare __c)
+{
+    unsigned __r = _VSTD::__sort3<_Compare>(__x1, __x2, __x3, __c);
+    if (__c(*__x4, *__x3))
+    {
+        swap(*__x3, *__x4);
+        ++__r;
+        if (__c(*__x3, *__x2))
+        {
+            swap(*__x2, *__x3);
+            ++__r;
+            if (__c(*__x2, *__x1))
+            {
+                swap(*__x1, *__x2);
+                ++__r;
+            }
+        }
+    }
+    return __r;
+}
+
+// stable, 4-10 compares, 0-9 swaps
+
+template <class _Compare, class _ForwardIterator>
+_LIBCPP_HIDDEN
+unsigned
+__sort5(_ForwardIterator __x1, _ForwardIterator __x2, _ForwardIterator __x3,
+            _ForwardIterator __x4, _ForwardIterator __x5, _Compare __c)
+{
+    unsigned __r = _VSTD::__sort4<_Compare>(__x1, __x2, __x3, __x4, __c);
+    if (__c(*__x5, *__x4))
+    {
+        swap(*__x4, *__x5);
+        ++__r;
+        if (__c(*__x4, *__x3))
+        {
+            swap(*__x3, *__x4);
+            ++__r;
+            if (__c(*__x3, *__x2))
+            {
+                swap(*__x2, *__x3);
+                ++__r;
+                if (__c(*__x2, *__x1))
+                {
+                    swap(*__x1, *__x2);
+                    ++__r;
+                }
+            }
+        }
+    }
+    return __r;
+}
+
+// Assumes size > 0
+template <class _Compare, class _BidirectionalIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX11 void
+__selection_sort(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
+{
+    _BidirectionalIterator __lm1 = __last;
+    for (--__lm1; __first != __lm1; ++__first)
+    {
+        _BidirectionalIterator __i = _VSTD::min_element<_BidirectionalIterator,
+                                                        typename add_lvalue_reference<_Compare>::type>
+                                                       (__first, __last, __comp);
+        if (__i != __first)
+            swap(*__first, *__i);
+    }
+}
+
+template <class _Compare, class _BidirectionalIterator>
+void
+__insertion_sort(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
+{
+    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
+    if (__first != __last)
+    {
+        _BidirectionalIterator __i = __first;
+        for (++__i; __i != __last; ++__i)
+        {
+            _BidirectionalIterator __j = __i;
+            value_type __t(_VSTD::move(*__j));
+            for (_BidirectionalIterator __k = __i; __k != __first && __comp(__t,  *--__k); --__j)
+                *__j = _VSTD::move(*__k);
+            *__j = _VSTD::move(__t);
+        }
+    }
+}
+
+template <class _Compare, class _RandomAccessIterator>
+void
+__insertion_sort_3(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+    _RandomAccessIterator __j = __first+2;
+    _VSTD::__sort3<_Compare>(__first, __first+1, __j, __comp);
+    for (_RandomAccessIterator __i = __j+1; __i != __last; ++__i)
+    {
+        if (__comp(*__i, *__j))
+        {
+            value_type __t(_VSTD::move(*__i));
+            _RandomAccessIterator __k = __j;
+            __j = __i;
+            do
+            {
+                *__j = _VSTD::move(*__k);
+                __j = __k;
+            } while (__j != __first && __comp(__t, *--__k));
+            *__j = _VSTD::move(__t);
+        }
+        __j = __i;
+    }
+}
+
+template <class _Compare, class _RandomAccessIterator>
+bool
+__insertion_sort_incomplete(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    switch (__last - __first)
+    {
+    case 0:
+    case 1:
+        return true;
+    case 2:
+        if (__comp(*--__last, *__first))
+            swap(*__first, *__last);
+        return true;
+    case 3:
+        _VSTD::__sort3<_Compare>(__first, __first+1, --__last, __comp);
+        return true;
+    case 4:
+        _VSTD::__sort4<_Compare>(__first, __first+1, __first+2, --__last, __comp);
+        return true;
+    case 5:
+        _VSTD::__sort5<_Compare>(__first, __first+1, __first+2, __first+3, --__last, __comp);
+        return true;
+    }
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+    _RandomAccessIterator __j = __first+2;
+    _VSTD::__sort3<_Compare>(__first, __first+1, __j, __comp);
+    const unsigned __limit = 8;
+    unsigned __count = 0;
+    for (_RandomAccessIterator __i = __j+1; __i != __last; ++__i)
+    {
+        if (__comp(*__i, *__j))
+        {
+            value_type __t(_VSTD::move(*__i));
+            _RandomAccessIterator __k = __j;
+            __j = __i;
+            do
+            {
+                *__j = _VSTD::move(*__k);
+                __j = __k;
+            } while (__j != __first && __comp(__t, *--__k));
+            *__j = _VSTD::move(__t);
+            if (++__count == __limit)
+                return ++__i == __last;
+        }
+        __j = __i;
+    }
+    return true;
+}
+
+template <class _Compare, class _BidirectionalIterator>
+void
+__insertion_sort_move(_BidirectionalIterator __first1, _BidirectionalIterator __last1,
+                      typename iterator_traits<_BidirectionalIterator>::value_type* __first2, _Compare __comp)
+{
+    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
+    if (__first1 != __last1)
+    {
+        __destruct_n __d(0);
+        unique_ptr<value_type, __destruct_n&> __h(__first2, __d);
+        value_type* __last2 = __first2;
+        ::new ((void*)__last2) value_type(_VSTD::move(*__first1));
+        __d.template __incr<value_type>();
+        for (++__last2; ++__first1 != __last1; ++__last2)
+        {
+            value_type* __j2 = __last2;
+            value_type* __i2 = __j2;
+            if (__comp(*__first1, *--__i2))
+            {
+                ::new ((void*)__j2) value_type(_VSTD::move(*__i2));
+                __d.template __incr<value_type>();
+                for (--__j2; __i2 != __first2 && __comp(*__first1,  *--__i2); --__j2)
+                    *__j2 = _VSTD::move(*__i2);
+                *__j2 = _VSTD::move(*__first1);
+            }
+            else
+            {
+                ::new ((void*)__j2) value_type(_VSTD::move(*__first1));
+                __d.template __incr<value_type>();
+            }
+        }
+        __h.release();
+    }
+}
+
+template <class _Compare, class _RandomAccessIterator>
+void
+__sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+    const difference_type __limit = is_trivially_copy_constructible<value_type>::value &&
+                                    is_trivially_copy_assignable<value_type>::value ? 30 : 6;
+    while (true)
+    {
+    __restart:
+        difference_type __len = __last - __first;
+        switch (__len)
+        {
+        case 0:
+        case 1:
+            return;
+        case 2:
+            if (__comp(*--__last, *__first))
+                swap(*__first, *__last);
+            return;
+        case 3:
+            _VSTD::__sort3<_Compare>(__first, __first+1, --__last, __comp);
+            return;
+        case 4:
+            _VSTD::__sort4<_Compare>(__first, __first+1, __first+2, --__last, __comp);
+            return;
+        case 5:
+            _VSTD::__sort5<_Compare>(__first, __first+1, __first+2, __first+3, --__last, __comp);
+            return;
+        }
+        if (__len <= __limit)
+        {
+            _VSTD::__insertion_sort_3<_Compare>(__first, __last, __comp);
+            return;
+        }
+        // __len > 5
+        _RandomAccessIterator __m = __first;
+        _RandomAccessIterator __lm1 = __last;
+        --__lm1;
+        unsigned __n_swaps;
+        {
+        difference_type __delta;
+        if (__len >= 1000)
+        {
+            __delta = __len/2;
+            __m += __delta;
+            __delta /= 2;
+            __n_swaps = _VSTD::__sort5<_Compare>(__first, __first + __delta, __m, __m+__delta, __lm1, __comp);
+        }
+        else
+        {
+            __delta = __len/2;
+            __m += __delta;
+            __n_swaps = _VSTD::__sort3<_Compare>(__first, __m, __lm1, __comp);
+        }
+        }
+        // *__m is median
+        // partition [__first, __m) < *__m and *__m <= [__m, __last)
+        // (this inhibits tossing elements equivalent to __m around unnecessarily)
+        _RandomAccessIterator __i = __first;
+        _RandomAccessIterator __j = __lm1;
+        // j points beyond range to be tested, *__m is known to be <= *__lm1
+        // The search going up is known to be guarded but the search coming down isn't.
+        // Prime the downward search with a guard.
+        if (!__comp(*__i, *__m))  // if *__first == *__m
+        {
+            // *__first == *__m, *__first doesn't go in first part
+            // manually guard downward moving __j against __i
+            while (true)
+            {
+                if (__i == --__j)
+                {
+                    // *__first == *__m, *__m <= all other elements
+                    // Parition instead into [__first, __i) == *__first and *__first < [__i, __last)
+                    ++__i;  // __first + 1
+                    __j = __last;
+                    if (!__comp(*__first, *--__j))  // we need a guard if *__first == *(__last-1)
+                    {
+                        while (true)
+                        {
+                            if (__i == __j)
+                                return;  // [__first, __last) all equivalent elements
+                            if (__comp(*__first, *__i))
+                            {
+                                swap(*__i, *__j);
+                                ++__n_swaps;
+                                ++__i;
+                                break;
+                            }
+                            ++__i;
+                        }
+                    }
+                    // [__first, __i) == *__first and *__first < [__j, __last) and __j == __last - 1
+                    if (__i == __j)
+                        return;
+                    while (true)
+                    {
+                        while (!__comp(*__first, *__i))
+                            ++__i;
+                        while (__comp(*__first, *--__j))
+                            ;
+                        if (__i >= __j)
+                            break;
+                        swap(*__i, *__j);
+                        ++__n_swaps;
+                        ++__i;
+                    }
+                    // [__first, __i) == *__first and *__first < [__i, __last)
+                    // The first part is sorted, sort the second part
+                    // _VSTD::__sort<_Compare>(__i, __last, __comp);
+                    __first = __i;
+                    goto __restart;
+                }
+                if (__comp(*__j, *__m))
+                {
+                    swap(*__i, *__j);
+                    ++__n_swaps;
+                    break;  // found guard for downward moving __j, now use unguarded partition
+                }
+            }
+        }
+        // It is known that *__i < *__m
+        ++__i;
+        // j points beyond range to be tested, *__m is known to be <= *__lm1
+        // if not yet partitioned...
+        if (__i < __j)
+        {
+            // known that *(__i - 1) < *__m
+            // known that __i <= __m
+            while (true)
+            {
+                // __m still guards upward moving __i
+                while (__comp(*__i, *__m))
+                    ++__i;
+                // It is now known that a guard exists for downward moving __j
+                while (!__comp(*--__j, *__m))
+                    ;
+                if (__i > __j)
+                    break;
+                swap(*__i, *__j);
+                ++__n_swaps;
+                // It is known that __m != __j
+                // If __m just moved, follow it
+                if (__m == __i)
+                    __m = __j;
+                ++__i;
+            }
+        }
+        // [__first, __i) < *__m and *__m <= [__i, __last)
+        if (__i != __m && __comp(*__m, *__i))
+        {
+            swap(*__i, *__m);
+            ++__n_swaps;
+        }
+        // [__first, __i) < *__i and *__i <= [__i+1, __last)
+        // If we were given a perfect partition, see if insertion sort is quick...
+        if (__n_swaps == 0)
+        {
+            bool __fs = _VSTD::__insertion_sort_incomplete<_Compare>(__first, __i, __comp);
+            if (_VSTD::__insertion_sort_incomplete<_Compare>(__i+1, __last, __comp))
+            {
+                if (__fs)
+                    return;
+                __last = __i;
+                continue;
+            }
+            else
+            {
+                if (__fs)
+                {
+                    __first = ++__i;
+                    continue;
+                }
+            }
+        }
+        // sort smaller range with recursive call and larger with tail recursion elimination
+        if (__i - __first < __last - __i)
+        {
+            _VSTD::__sort<_Compare>(__first, __i, __comp);
+            // _VSTD::__sort<_Compare>(__i+1, __last, __comp);
+            __first = ++__i;
+        }
+        else
+        {
+            _VSTD::__sort<_Compare>(__i+1, __last, __comp);
+            // _VSTD::__sort<_Compare>(__first, __i, __comp);
+            __last = __i;
+        }
+    }
+}
+
+template <class _Compare, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+void
+__sort(_Tp** __first, _Tp** __last, __less<_Tp*>&)
+{
+    __less<uintptr_t> __comp;
+    _VSTD::__sort<__less<uintptr_t>&, uintptr_t*>((uintptr_t*)__first, (uintptr_t*)__last, __comp);
+}
+
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<char>&, char*>(char*, char*, __less<char>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<short>&, short*>(short*, short*, __less<short>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<int>&, int*>(int*, int*, __less<int>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long>&, long*>(long*, long*, __less<long>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long long>&, long long*>(long long*, long long*, __less<long long>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<float>&, float*>(float*, float*, __less<float>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<double>&, double*>(double*, double*, __less<double>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long double>&, long double*>(long double*, long double*, __less<long double>&))
+
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<char>&, char*>(char*, char*, __less<char>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<short>&, short*>(short*, short*, __less<short>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<int>&, int*>(int*, int*, __less<int>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long>&, long*>(long*, long*, __less<long>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long long>&, long long*>(long long*, long long*, __less<long long>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<float>&, float*>(float*, float*, __less<float>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<double>&, double*>(double*, double*, __less<double>&))
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long double>&, long double*>(long double*, long double*, __less<long double>&))
+
+_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS unsigned __sort5<__less<long double>&, long double*>(long double*, long double*, long double*, long double*, long double*, __less<long double>&))
+
+template <class _RandomAccessIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    if (__libcpp_is_constant_evaluated()) {
+        _VSTD::__partial_sort<_Comp_ref>(__first, __last, __last, _Comp_ref(__comp));
+    } else {
+        _VSTD::__sort<_Comp_ref>(_VSTD::__unwrap_iter(__first), _VSTD::__unwrap_iter(__last), _Comp_ref(__comp));
+    }
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
+{
+    _VSTD::sort(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SORT_H
lib/libcxx/include/__algorithm/sort_heap.h
@@ -0,0 +1,58 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SORT_HEAP_H
+#define _LIBCPP___ALGORITHM_SORT_HEAP_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/pop_heap.h>
+#include <__iterator/iterator_traits.h>
+#include <type_traits> // swap
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _RandomAccessIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 void
+__sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    for (difference_type __n = __last - __first; __n > 1; --__last, (void) --__n)
+        _VSTD::__pop_heap<_Compare>(__first, __last, __comp, __n);
+}
+
+template <class _RandomAccessIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    _VSTD::__sort_heap<_Comp_ref>(__first, __last, __comp);
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void
+sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
+{
+    _VSTD::sort_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SORT_HEAP_H
lib/libcxx/include/__algorithm/stable_partition.h
@@ -0,0 +1,305 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_STABLE_PARTITION_H
+#define _LIBCPP___ALGORITHM_STABLE_PARTITION_H
+
+#include <__config>
+#include <__algorithm/rotate.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/swap.h>
+#include <memory>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Predicate, class _ForwardIterator, class _Distance, class _Pair>
+_ForwardIterator
+__stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred,
+                   _Distance __len, _Pair __p, forward_iterator_tag __fit)
+{
+    // *__first is known to be false
+    // __len >= 1
+    if (__len == 1)
+        return __first;
+    if (__len == 2)
+    {
+        _ForwardIterator __m = __first;
+        if (__pred(*++__m))
+        {
+            swap(*__first, *__m);
+            return __m;
+        }
+        return __first;
+    }
+    if (__len <= __p.second)
+    {   // The buffer is big enough to use
+        typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
+        __destruct_n __d(0);
+        unique_ptr<value_type, __destruct_n&> __h(__p.first, __d);
+        // Move the falses into the temporary buffer, and the trues to the front of the line
+        // Update __first to always point to the end of the trues
+        value_type* __t = __p.first;
+        ::new ((void*)__t) value_type(_VSTD::move(*__first));
+        __d.template __incr<value_type>();
+        ++__t;
+        _ForwardIterator __i = __first;
+        while (++__i != __last)
+        {
+            if (__pred(*__i))
+            {
+                *__first = _VSTD::move(*__i);
+                ++__first;
+            }
+            else
+            {
+                ::new ((void*)__t) value_type(_VSTD::move(*__i));
+                __d.template __incr<value_type>();
+                ++__t;
+            }
+        }
+        // All trues now at start of range, all falses in buffer
+        // Move falses back into range, but don't mess up __first which points to first false
+        __i = __first;
+        for (value_type* __t2 = __p.first; __t2 < __t; ++__t2, (void) ++__i)
+            *__i = _VSTD::move(*__t2);
+        // __h destructs moved-from values out of the temp buffer, but doesn't deallocate buffer
+        return __first;
+    }
+    // Else not enough buffer, do in place
+    // __len >= 3
+    _ForwardIterator __m = __first;
+    _Distance __len2 = __len / 2;  // __len2 >= 2
+    _VSTD::advance(__m, __len2);
+    // recurse on [__first, __m), *__first know to be false
+    // F?????????????????
+    // f       m         l
+    typedef typename add_lvalue_reference<_Predicate>::type _PredRef;
+    _ForwardIterator __first_false = _VSTD::__stable_partition<_PredRef>(__first, __m, __pred, __len2, __p, __fit);
+    // TTTFFFFF??????????
+    // f  ff   m         l
+    // recurse on [__m, __last], except increase __m until *(__m) is false, *__last know to be true
+    _ForwardIterator __m1 = __m;
+    _ForwardIterator __second_false = __last;
+    _Distance __len_half = __len - __len2;
+    while (__pred(*__m1))
+    {
+        if (++__m1 == __last)
+            goto __second_half_done;
+        --__len_half;
+    }
+    // TTTFFFFFTTTF??????
+    // f  ff   m  m1     l
+    __second_false = _VSTD::__stable_partition<_PredRef>(__m1, __last, __pred, __len_half, __p, __fit);
+__second_half_done:
+    // TTTFFFFFTTTTTFFFFF
+    // f  ff   m    sf   l
+    return _VSTD::rotate(__first_false, __m, __second_false);
+    // TTTTTTTTFFFFFFFFFF
+    //         |
+}
+
+template <class _Predicate, class _ForwardIterator>
+_ForwardIterator
+__stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred,
+                   forward_iterator_tag)
+{
+    const unsigned __alloc_limit = 3;  // might want to make this a function of trivial assignment
+    // Either prove all true and return __first or point to first false
+    while (true)
+    {
+        if (__first == __last)
+            return __first;
+        if (!__pred(*__first))
+            break;
+        ++__first;
+    }
+    // We now have a reduced range [__first, __last)
+    // *__first is known to be false
+    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
+    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
+    difference_type __len = _VSTD::distance(__first, __last);
+    pair<value_type*, ptrdiff_t> __p(0, 0);
+    unique_ptr<value_type, __return_temporary_buffer> __h;
+    if (__len >= __alloc_limit)
+    {
+        __p = _VSTD::get_temporary_buffer<value_type>(__len);
+        __h.reset(__p.first);
+    }
+    return _VSTD::__stable_partition<typename add_lvalue_reference<_Predicate>::type>
+                             (__first, __last, __pred, __len, __p, forward_iterator_tag());
+}
+
+template <class _Predicate, class _BidirectionalIterator, class _Distance, class _Pair>
+_BidirectionalIterator
+__stable_partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
+                   _Distance __len, _Pair __p, bidirectional_iterator_tag __bit)
+{
+    // *__first is known to be false
+    // *__last is known to be true
+    // __len >= 2
+    if (__len == 2)
+    {
+        swap(*__first, *__last);
+        return __last;
+    }
+    if (__len == 3)
+    {
+        _BidirectionalIterator __m = __first;
+        if (__pred(*++__m))
+        {
+            swap(*__first, *__m);
+            swap(*__m, *__last);
+            return __last;
+        }
+        swap(*__m, *__last);
+        swap(*__first, *__m);
+        return __m;
+    }
+    if (__len <= __p.second)
+    {   // The buffer is big enough to use
+        typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
+        __destruct_n __d(0);
+        unique_ptr<value_type, __destruct_n&> __h(__p.first, __d);
+        // Move the falses into the temporary buffer, and the trues to the front of the line
+        // Update __first to always point to the end of the trues
+        value_type* __t = __p.first;
+        ::new ((void*)__t) value_type(_VSTD::move(*__first));
+        __d.template __incr<value_type>();
+        ++__t;
+        _BidirectionalIterator __i = __first;
+        while (++__i != __last)
+        {
+            if (__pred(*__i))
+            {
+                *__first = _VSTD::move(*__i);
+                ++__first;
+            }
+            else
+            {
+                ::new ((void*)__t) value_type(_VSTD::move(*__i));
+                __d.template __incr<value_type>();
+                ++__t;
+            }
+        }
+        // move *__last, known to be true
+        *__first = _VSTD::move(*__i);
+        __i = ++__first;
+        // All trues now at start of range, all falses in buffer
+        // Move falses back into range, but don't mess up __first which points to first false
+        for (value_type* __t2 = __p.first; __t2 < __t; ++__t2, (void) ++__i)
+            *__i = _VSTD::move(*__t2);
+        // __h destructs moved-from values out of the temp buffer, but doesn't deallocate buffer
+        return __first;
+    }
+    // Else not enough buffer, do in place
+    // __len >= 4
+    _BidirectionalIterator __m = __first;
+    _Distance __len2 = __len / 2;  // __len2 >= 2
+    _VSTD::advance(__m, __len2);
+    // recurse on [__first, __m-1], except reduce __m-1 until *(__m-1) is true, *__first know to be false
+    // F????????????????T
+    // f       m        l
+    _BidirectionalIterator __m1 = __m;
+    _BidirectionalIterator __first_false = __first;
+    _Distance __len_half = __len2;
+    while (!__pred(*--__m1))
+    {
+        if (__m1 == __first)
+            goto __first_half_done;
+        --__len_half;
+    }
+    // F???TFFF?????????T
+    // f   m1  m        l
+    typedef typename add_lvalue_reference<_Predicate>::type _PredRef;
+    __first_false = _VSTD::__stable_partition<_PredRef>(__first, __m1, __pred, __len_half, __p, __bit);
+__first_half_done:
+    // TTTFFFFF?????????T
+    // f  ff   m        l
+    // recurse on [__m, __last], except increase __m until *(__m) is false, *__last know to be true
+    __m1 = __m;
+    _BidirectionalIterator __second_false = __last;
+    ++__second_false;
+    __len_half = __len - __len2;
+    while (__pred(*__m1))
+    {
+        if (++__m1 == __last)
+            goto __second_half_done;
+        --__len_half;
+    }
+    // TTTFFFFFTTTF?????T
+    // f  ff   m  m1    l
+    __second_false = _VSTD::__stable_partition<_PredRef>(__m1, __last, __pred, __len_half, __p, __bit);
+__second_half_done:
+    // TTTFFFFFTTTTTFFFFF
+    // f  ff   m    sf  l
+    return _VSTD::rotate(__first_false, __m, __second_false);
+    // TTTTTTTTFFFFFFFFFF
+    //         |
+}
+
+template <class _Predicate, class _BidirectionalIterator>
+_BidirectionalIterator
+__stable_partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
+                   bidirectional_iterator_tag)
+{
+    typedef typename iterator_traits<_BidirectionalIterator>::difference_type difference_type;
+    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
+    const difference_type __alloc_limit = 4;  // might want to make this a function of trivial assignment
+    // Either prove all true and return __first or point to first false
+    while (true)
+    {
+        if (__first == __last)
+            return __first;
+        if (!__pred(*__first))
+            break;
+        ++__first;
+    }
+    // __first points to first false, everything prior to __first is already set.
+    // Either prove [__first, __last) is all false and return __first, or point __last to last true
+    do
+    {
+        if (__first == --__last)
+            return __first;
+    } while (!__pred(*__last));
+    // We now have a reduced range [__first, __last]
+    // *__first is known to be false
+    // *__last is known to be true
+    // __len >= 2
+    difference_type __len = _VSTD::distance(__first, __last) + 1;
+    pair<value_type*, ptrdiff_t> __p(0, 0);
+    unique_ptr<value_type, __return_temporary_buffer> __h;
+    if (__len >= __alloc_limit)
+    {
+        __p = _VSTD::get_temporary_buffer<value_type>(__len);
+        __h.reset(__p.first);
+    }
+    return _VSTD::__stable_partition<typename add_lvalue_reference<_Predicate>::type>
+                             (__first, __last, __pred, __len, __p, bidirectional_iterator_tag());
+}
+
+template <class _ForwardIterator, class _Predicate>
+inline _LIBCPP_INLINE_VISIBILITY
+_ForwardIterator
+stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
+{
+    return _VSTD::__stable_partition<typename add_lvalue_reference<_Predicate>::type>
+                             (__first, __last, __pred, typename iterator_traits<_ForwardIterator>::iterator_category());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_STABLE_PARTITION_H
lib/libcxx/include/__algorithm/stable_sort.h
@@ -0,0 +1,235 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_STABLE_SORT_H
+#define _LIBCPP___ALGORITHM_STABLE_SORT_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/inplace_merge.h>
+#include <__algorithm/sort.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/swap.h>
+#include <memory>
+#include <type_traits> // swap
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _InputIterator1, class _InputIterator2>
+void
+__merge_move_construct(_InputIterator1 __first1, _InputIterator1 __last1,
+        _InputIterator2 __first2, _InputIterator2 __last2,
+        typename iterator_traits<_InputIterator1>::value_type* __result, _Compare __comp)
+{
+    typedef typename iterator_traits<_InputIterator1>::value_type value_type;
+    __destruct_n __d(0);
+    unique_ptr<value_type, __destruct_n&> __h(__result, __d);
+    for (; true; ++__result)
+    {
+        if (__first1 == __last1)
+        {
+            for (; __first2 != __last2; ++__first2, ++__result, (void)__d.template __incr<value_type>())
+                ::new ((void*)__result) value_type(_VSTD::move(*__first2));
+            __h.release();
+            return;
+        }
+        if (__first2 == __last2)
+        {
+            for (; __first1 != __last1; ++__first1, ++__result, (void)__d.template __incr<value_type>())
+                ::new ((void*)__result) value_type(_VSTD::move(*__first1));
+            __h.release();
+            return;
+        }
+        if (__comp(*__first2, *__first1))
+        {
+            ::new ((void*)__result) value_type(_VSTD::move(*__first2));
+            __d.template __incr<value_type>();
+            ++__first2;
+        }
+        else
+        {
+            ::new ((void*)__result) value_type(_VSTD::move(*__first1));
+            __d.template __incr<value_type>();
+            ++__first1;
+        }
+    }
+}
+
+template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
+void
+__merge_move_assign(_InputIterator1 __first1, _InputIterator1 __last1,
+        _InputIterator2 __first2, _InputIterator2 __last2,
+        _OutputIterator __result, _Compare __comp)
+{
+    for (; __first1 != __last1; ++__result)
+    {
+        if (__first2 == __last2)
+        {
+            for (; __first1 != __last1; ++__first1, (void) ++__result)
+                *__result = _VSTD::move(*__first1);
+            return;
+        }
+        if (__comp(*__first2, *__first1))
+        {
+            *__result = _VSTD::move(*__first2);
+            ++__first2;
+        }
+        else
+        {
+            *__result = _VSTD::move(*__first1);
+            ++__first1;
+        }
+    }
+    for (; __first2 != __last2; ++__first2, (void) ++__result)
+        *__result = _VSTD::move(*__first2);
+}
+
+template <class _Compare, class _RandomAccessIterator>
+void
+__stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
+              typename iterator_traits<_RandomAccessIterator>::difference_type __len,
+              typename iterator_traits<_RandomAccessIterator>::value_type* __buff, ptrdiff_t __buff_size);
+
+template <class _Compare, class _RandomAccessIterator>
+void
+__stable_sort_move(_RandomAccessIterator __first1, _RandomAccessIterator __last1, _Compare __comp,
+                   typename iterator_traits<_RandomAccessIterator>::difference_type __len,
+                   typename iterator_traits<_RandomAccessIterator>::value_type* __first2)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+    switch (__len)
+    {
+    case 0:
+        return;
+    case 1:
+        ::new ((void*)__first2) value_type(_VSTD::move(*__first1));
+        return;
+    case 2:
+        __destruct_n __d(0);
+        unique_ptr<value_type, __destruct_n&> __h2(__first2, __d);
+        if (__comp(*--__last1, *__first1))
+        {
+            ::new ((void*)__first2) value_type(_VSTD::move(*__last1));
+            __d.template __incr<value_type>();
+            ++__first2;
+            ::new ((void*)__first2) value_type(_VSTD::move(*__first1));
+        }
+        else
+        {
+            ::new ((void*)__first2) value_type(_VSTD::move(*__first1));
+            __d.template __incr<value_type>();
+            ++__first2;
+            ::new ((void*)__first2) value_type(_VSTD::move(*__last1));
+        }
+        __h2.release();
+        return;
+    }
+    if (__len <= 8)
+    {
+        _VSTD::__insertion_sort_move<_Compare>(__first1, __last1, __first2, __comp);
+        return;
+    }
+    typename iterator_traits<_RandomAccessIterator>::difference_type __l2 = __len / 2;
+    _RandomAccessIterator __m = __first1 + __l2;
+    _VSTD::__stable_sort<_Compare>(__first1, __m, __comp, __l2, __first2, __l2);
+    _VSTD::__stable_sort<_Compare>(__m, __last1, __comp, __len - __l2, __first2 + __l2, __len - __l2);
+    _VSTD::__merge_move_construct<_Compare>(__first1, __m, __m, __last1, __first2, __comp);
+}
+
+template <class _Tp>
+struct __stable_sort_switch
+{
+    static const unsigned value = 128*is_trivially_copy_assignable<_Tp>::value;
+};
+
+template <class _Compare, class _RandomAccessIterator>
+void
+__stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
+              typename iterator_traits<_RandomAccessIterator>::difference_type __len,
+              typename iterator_traits<_RandomAccessIterator>::value_type* __buff, ptrdiff_t __buff_size)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    switch (__len)
+    {
+    case 0:
+    case 1:
+        return;
+    case 2:
+        if (__comp(*--__last, *__first))
+            swap(*__first, *__last);
+        return;
+    }
+    if (__len <= static_cast<difference_type>(__stable_sort_switch<value_type>::value))
+    {
+        _VSTD::__insertion_sort<_Compare>(__first, __last, __comp);
+        return;
+    }
+    typename iterator_traits<_RandomAccessIterator>::difference_type __l2 = __len / 2;
+    _RandomAccessIterator __m = __first + __l2;
+    if (__len <= __buff_size)
+    {
+        __destruct_n __d(0);
+        unique_ptr<value_type, __destruct_n&> __h2(__buff, __d);
+        _VSTD::__stable_sort_move<_Compare>(__first, __m, __comp, __l2, __buff);
+        __d.__set(__l2, (value_type*)nullptr);
+        _VSTD::__stable_sort_move<_Compare>(__m, __last, __comp, __len - __l2, __buff + __l2);
+        __d.__set(__len, (value_type*)nullptr);
+        _VSTD::__merge_move_assign<_Compare>(__buff, __buff + __l2, __buff + __l2, __buff + __len, __first, __comp);
+//         _VSTD::__merge<_Compare>(move_iterator<value_type*>(__buff),
+//                                  move_iterator<value_type*>(__buff + __l2),
+//                                  move_iterator<_RandomAccessIterator>(__buff + __l2),
+//                                  move_iterator<_RandomAccessIterator>(__buff + __len),
+//                                  __first, __comp);
+        return;
+    }
+    _VSTD::__stable_sort<_Compare>(__first, __m, __comp, __l2, __buff, __buff_size);
+    _VSTD::__stable_sort<_Compare>(__m, __last, __comp, __len - __l2, __buff, __buff_size);
+    _VSTD::__inplace_merge<_Compare>(__first, __m, __last, __comp, __l2, __len - __l2, __buff, __buff_size);
+}
+
+template <class _RandomAccessIterator, class _Compare>
+inline _LIBCPP_INLINE_VISIBILITY
+void
+stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
+{
+    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
+    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
+    difference_type __len = __last - __first;
+    pair<value_type*, ptrdiff_t> __buf(0, 0);
+    unique_ptr<value_type, __return_temporary_buffer> __h;
+    if (__len > static_cast<difference_type>(__stable_sort_switch<value_type>::value))
+    {
+        __buf = _VSTD::get_temporary_buffer<value_type>(__len);
+        __h.reset(__buf.first);
+    }
+    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
+    _VSTD::__stable_sort<_Comp_ref>(__first, __last, __comp, __len, __buf.first, __buf.second);
+}
+
+template <class _RandomAccessIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+void
+stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
+{
+    _VSTD::stable_sort(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_STABLE_SORT_H
lib/libcxx/include/__algorithm/swap_ranges.h
@@ -0,0 +1,37 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_SWAP_RANGES_H
+#define _LIBCPP___ALGORITHM_SWAP_RANGES_H
+
+#include <__config>
+#include <__utility/swap.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _ForwardIterator1, class _ForwardIterator2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator2
+swap_ranges(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2) {
+  for (; __first1 != __last1; ++__first1, (void)++__first2)
+    swap(*__first1, *__first2);
+  return __first2;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_SWAP_RANGES_H
lib/libcxx/include/__algorithm/transform.h
@@ -0,0 +1,48 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_TRANSFORM_H
+#define _LIBCPP___ALGORITHM_TRANSFORM_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _OutputIterator, class _UnaryOperation>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)
+{
+    for (; __first != __last; ++__first, (void) ++__result)
+        *__result = __op(*__first);
+    return __result;
+}
+
+template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _BinaryOperation>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2,
+          _OutputIterator __result, _BinaryOperation __binary_op)
+{
+    for (; __first1 != __last1; ++__first1, (void) ++__first2, ++__result)
+        *__result = __binary_op(*__first1, *__first2);
+    return __result;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_TRANSFORM_H
lib/libcxx/include/__algorithm/unique.h
@@ -0,0 +1,63 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_UNIQUE_H
+#define _LIBCPP___ALGORITHM_UNIQUE_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/adjacent_find.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/move.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// unique
+
+template <class _ForwardIterator, class _BinaryPredicate>
+_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+unique(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __pred)
+{
+    __first = _VSTD::adjacent_find<_ForwardIterator, typename add_lvalue_reference<_BinaryPredicate>::type>
+                                 (__first, __last, __pred);
+    if (__first != __last)
+    {
+        // ...  a  a  ?  ...
+        //      f     i
+        _ForwardIterator __i = __first;
+        for (++__i; ++__i != __last;)
+            if (!__pred(*__first, *__i))
+                *++__first = _VSTD::move(*__i);
+        ++__first;
+    }
+    return __first;
+}
+
+template <class _ForwardIterator>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_ForwardIterator
+unique(_ForwardIterator __first, _ForwardIterator __last)
+{
+    typedef typename iterator_traits<_ForwardIterator>::value_type __v;
+    return _VSTD::unique(__first, __last, __equal_to<__v>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_UNIQUE_H
lib/libcxx/include/__algorithm/unique_copy.h
@@ -0,0 +1,114 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_UNIQUE_COPY_H
+#define _LIBCPP___ALGORITHM_UNIQUE_COPY_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__iterator/iterator_traits.h>
+#include <utility>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _BinaryPredicate, class _InputIterator, class _OutputIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
+__unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryPredicate __pred,
+              input_iterator_tag, output_iterator_tag)
+{
+    if (__first != __last)
+    {
+        typename iterator_traits<_InputIterator>::value_type __t(*__first);
+        *__result = __t;
+        ++__result;
+        while (++__first != __last)
+        {
+            if (!__pred(__t, *__first))
+            {
+                __t = *__first;
+                *__result = __t;
+                ++__result;
+            }
+        }
+    }
+    return __result;
+}
+
+template <class _BinaryPredicate, class _ForwardIterator, class _OutputIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
+__unique_copy(_ForwardIterator __first, _ForwardIterator __last, _OutputIterator __result, _BinaryPredicate __pred,
+              forward_iterator_tag, output_iterator_tag)
+{
+    if (__first != __last)
+    {
+        _ForwardIterator __i = __first;
+        *__result = *__i;
+        ++__result;
+        while (++__first != __last)
+        {
+            if (!__pred(*__i, *__first))
+            {
+                *__result = *__first;
+                ++__result;
+                __i = __first;
+            }
+        }
+    }
+    return __result;
+}
+
+template <class _BinaryPredicate, class _InputIterator, class _ForwardIterator>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+__unique_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _BinaryPredicate __pred,
+              input_iterator_tag, forward_iterator_tag)
+{
+    if (__first != __last)
+    {
+        *__result = *__first;
+        while (++__first != __last)
+            if (!__pred(*__result, *__first))
+                *++__result = *__first;
+        ++__result;
+    }
+    return __result;
+}
+
+template <class _InputIterator, class _OutputIterator, class _BinaryPredicate>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryPredicate __pred)
+{
+    return _VSTD::__unique_copy<typename add_lvalue_reference<_BinaryPredicate>::type>
+                              (__first, __last, __result, __pred,
+                               typename iterator_traits<_InputIterator>::iterator_category(),
+                               typename iterator_traits<_OutputIterator>::iterator_category());
+}
+
+template <class _InputIterator, class _OutputIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_OutputIterator
+unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
+{
+    typedef typename iterator_traits<_InputIterator>::value_type __v;
+    return _VSTD::unique_copy(__first, __last, __result, __equal_to<__v>());
+}
+
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_UNIQUE_COPY_H
lib/libcxx/include/__algorithm/unwrap_iter.h
@@ -0,0 +1,87 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_UNWRAP_ITER_H
+#define _LIBCPP___ALGORITHM_UNWRAP_ITER_H
+
+#include <__config>
+#include <iterator>
+#include <__memory/pointer_traits.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// The job of __unwrap_iter is to lower contiguous iterators (such as
+// vector<T>::iterator) into pointers, to reduce the number of template
+// instantiations and to enable pointer-based optimizations e.g. in std::copy.
+// For iterators that are not contiguous, it must be a no-op.
+// In debug mode, we don't do this.
+//
+// __unwrap_iter is non-constexpr for user-defined iterators whose
+// `to_address` and/or `operator->` is non-constexpr. This is okay; but we
+// try to avoid doing __unwrap_iter in constant-evaluated contexts anyway.
+//
+// Some algorithms (e.g. std::copy, but not std::sort) need to convert an
+// "unwrapped" result back into a contiguous iterator. Since contiguous iterators
+// are random-access, we can do this portably using iterator arithmetic; this
+// is the job of __rewrap_iter.
+
+template <class _Iter, bool = __is_cpp17_contiguous_iterator<_Iter>::value>
+struct __unwrap_iter_impl {
+    static _LIBCPP_CONSTEXPR _Iter
+    __apply(_Iter __i) _NOEXCEPT {
+        return __i;
+    }
+};
+
+#if _LIBCPP_DEBUG_LEVEL < 2
+
+template <class _Iter>
+struct __unwrap_iter_impl<_Iter, true> {
+    static _LIBCPP_CONSTEXPR decltype(_VSTD::__to_address(declval<_Iter>()))
+    __apply(_Iter __i) _NOEXCEPT {
+        return _VSTD::__to_address(__i);
+    }
+};
+
+#endif // _LIBCPP_DEBUG_LEVEL < 2
+
+template<class _Iter, class _Impl = __unwrap_iter_impl<_Iter> >
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+decltype(_Impl::__apply(declval<_Iter>()))
+__unwrap_iter(_Iter __i) _NOEXCEPT
+{
+    return _Impl::__apply(__i);
+}
+
+template<class _OrigIter>
+_OrigIter __rewrap_iter(_OrigIter, _OrigIter __result)
+{
+    return __result;
+}
+
+template<class _OrigIter, class _UnwrappedIter>
+_OrigIter __rewrap_iter(_OrigIter __first, _UnwrappedIter __result)
+{
+    // Precondition: __result is reachable from __first
+    // Precondition: _OrigIter is a contiguous iterator
+    return __first + (__result - _VSTD::__unwrap_iter(__first));
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_UNWRAP_ITER_H
lib/libcxx/include/__algorithm/upper_bound.h
@@ -0,0 +1,72 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ALGORITHM_UPPER_BOUND_H
+#define _LIBCPP___ALGORITHM_UPPER_BOUND_H
+
+#include <__config>
+#include <__algorithm/comp.h>
+#include <__algorithm/half_positive.h>
+#include <iterator>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Compare, class _ForwardIterator, class _Tp>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
+__upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
+{
+    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
+    difference_type __len = _VSTD::distance(__first, __last);
+    while (__len != 0)
+    {
+        difference_type __l2 = _VSTD::__half_positive(__len);
+        _ForwardIterator __m = __first;
+        _VSTD::advance(__m, __l2);
+        if (__comp(__value_, *__m))
+            __len = __l2;
+        else
+        {
+            __first = ++__m;
+            __len -= __l2 + 1;
+        }
+    }
+    return __first;
+}
+
+template <class _ForwardIterator, class _Tp, class _Compare>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_ForwardIterator
+upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
+{
+    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
+    return _VSTD::__upper_bound<_Comp_ref>(__first, __last, __value_, __comp);
+}
+
+template <class _ForwardIterator, class _Tp>
+_LIBCPP_NODISCARD_EXT inline
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_ForwardIterator
+upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
+{
+    return _VSTD::upper_bound(__first, __last, __value_,
+                             __less<_Tp, typename iterator_traits<_ForwardIterator>::value_type>());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ALGORITHM_UPPER_BOUND_H
lib/libcxx/include/__format/format_error.h
@@ -0,0 +1,56 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FORMAT_FORMAT_ERROR_H
+#define _LIBCPP___FORMAT_FORMAT_ERROR_H
+
+#include <__config>
+#include <stdexcept>
+
+#ifdef _LIBCPP_NO_EXCEPTIONS
+#include <cstdlib>
+#endif
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17
+
+class _LIBCPP_EXCEPTION_ABI format_error : public runtime_error {
+public:
+  _LIBCPP_HIDE_FROM_ABI explicit format_error(const string& __s)
+      : runtime_error(__s) {}
+  _LIBCPP_HIDE_FROM_ABI explicit format_error(const char* __s)
+      : runtime_error(__s) {}
+  virtual ~format_error() noexcept;
+};
+
+_LIBCPP_NORETURN inline _LIBCPP_HIDE_FROM_ABI void
+__throw_format_error(const char* __s) {
+#ifndef _LIBCPP_NO_EXCEPTIONS
+  throw format_error(__s);
+#else
+  (void)__s;
+  _VSTD::abort();
+#endif
+}
+
+#endif //_LIBCPP_STD_VER > 17
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___FORMAT_FORMAT_ERROR_H
lib/libcxx/include/__format/format_parse_context.h
@@ -0,0 +1,113 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FORMAT_FORMAT_PARSE_CONTEXT_H
+#define _LIBCPP___FORMAT_FORMAT_PARSE_CONTEXT_H
+
+#include <__config>
+#include <__format/format_error.h>
+#include <string_view>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17
+
+// TODO FMT Remove this once we require compilers with proper C++20 support.
+// If the compiler has no concepts support, the format header will be disabled.
+// Without concepts support enable_if needs to be used and that too much effort
+// to support compilers with partial C++20 support.
+#if !defined(_LIBCPP_HAS_NO_CONCEPTS) &&                                       \
+    !defined(_LIBCPP_HAS_NO_BUILTIN_IS_CONSTANT_EVALUATED)
+
+template <class _CharT>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_AVAILABILITY_FORMAT basic_format_parse_context {
+public:
+  using char_type = _CharT;
+  using const_iterator = typename basic_string_view<_CharT>::const_iterator;
+  using iterator = const_iterator;
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr explicit basic_format_parse_context(basic_string_view<_CharT> __fmt,
+                                                size_t __num_args = 0) noexcept
+      : __begin_(__fmt.begin()),
+        __end_(__fmt.end()),
+        __indexing_(__unknown),
+        __next_arg_id_(0),
+        __num_args_(__num_args) {}
+
+  basic_format_parse_context(const basic_format_parse_context&) = delete;
+  basic_format_parse_context&
+  operator=(const basic_format_parse_context&) = delete;
+
+  _LIBCPP_HIDE_FROM_ABI constexpr const_iterator begin() const noexcept {
+    return __begin_;
+  }
+  _LIBCPP_HIDE_FROM_ABI constexpr const_iterator end() const noexcept {
+    return __end_;
+  }
+  _LIBCPP_HIDE_FROM_ABI constexpr void advance_to(const_iterator __it) {
+    __begin_ = __it;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI constexpr size_t next_arg_id() {
+    if (__indexing_ == __manual)
+      __throw_format_error("Using automatic argument numbering in manual "
+                           "argument numbering mode");
+
+    if (__indexing_ == __unknown)
+      __indexing_ = __automatic;
+    return __next_arg_id_++;
+  }
+  _LIBCPP_HIDE_FROM_ABI constexpr void check_arg_id(size_t __id) {
+    if (__indexing_ == __automatic)
+      __throw_format_error("Using manual argument numbering in automatic "
+                           "argument numbering mode");
+
+    if (__indexing_ == __unknown)
+      __indexing_ = __manual;
+
+    // Throws an exception to make the expression a non core constant
+    // expression as required by:
+    // [format.parse.ctx]/11
+    //   Remarks: Call expressions where id >= num_args_ are not core constant
+    //   expressions ([expr.const]).
+    // Note: the Throws clause [format.parse.ctx]/10 doesn't specify the
+    // behavior when id >= num_args_.
+    if (is_constant_evaluated() && __id >= __num_args_)
+      __throw_format_error("Argument index outside the valid range");
+  }
+
+private:
+  iterator __begin_;
+  iterator __end_;
+  enum _Indexing { __unknown, __manual, __automatic };
+  _Indexing __indexing_;
+  size_t __next_arg_id_;
+  size_t __num_args_;
+};
+
+using format_parse_context = basic_format_parse_context<char>;
+using wformat_parse_context = basic_format_parse_context<wchar_t>;
+
+#endif // !defined(_LIBCPP_HAS_NO_CONCEPTS) && !defined(_LIBCPP_HAS_NO_BUILTIN_IS_CONSTANT_EVALUATED)
+
+#endif //_LIBCPP_STD_VER > 17
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___FORMAT_FORMAT_PARSE_CONTEXT_H
lib/libcxx/include/__functional/binary_function.h
@@ -0,0 +1,31 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_BINARY_FUNCTION_H
+#define _LIBCPP___FUNCTIONAL_BINARY_FUNCTION_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Arg1, class _Arg2, class _Result>
+struct _LIBCPP_TEMPLATE_VIS binary_function
+{
+    typedef _Arg1   first_argument_type;
+    typedef _Arg2   second_argument_type;
+    typedef _Result result_type;
+};
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_BINARY_FUNCTION_H
lib/libcxx/include/__functional/binary_negate.h
@@ -0,0 +1,50 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_BINARY_NEGATE_H
+#define _LIBCPP___FUNCTIONAL_BINARY_NEGATE_H
+
+#include <__config>
+#include <__functional/binary_function.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_NEGATORS)
+
+template <class _Predicate>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX17 binary_negate
+    : public binary_function<typename _Predicate::first_argument_type,
+                             typename _Predicate::second_argument_type,
+                             bool>
+{
+    _Predicate __pred_;
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit _LIBCPP_CONSTEXPR_AFTER_CXX11
+    binary_negate(const _Predicate& __pred) : __pred_(__pred) {}
+
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const typename _Predicate::first_argument_type& __x,
+                    const typename _Predicate::second_argument_type& __y) const
+        {return !__pred_(__x, __y);}
+};
+
+template <class _Predicate>
+_LIBCPP_DEPRECATED_IN_CXX17 inline _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+binary_negate<_Predicate>
+not2(const _Predicate& __pred) {return binary_negate<_Predicate>(__pred);}
+
+#endif // _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_NEGATORS)
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_BINARY_NEGATE_H
lib/libcxx/include/__functional/bind.h
@@ -0,0 +1,386 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_BIND_H
+#define _LIBCPP___FUNCTIONAL_BIND_H
+
+#include <__config>
+#include <__functional/weak_result_type.h>
+#include <__functional/invoke.h>
+#include <cstddef>
+#include <tuple>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template<class _Tp> struct __is_bind_expression : public false_type {};
+template<class _Tp> struct _LIBCPP_TEMPLATE_VIS is_bind_expression
+    : public __is_bind_expression<typename remove_cv<_Tp>::type> {};
+
+#if _LIBCPP_STD_VER > 14
+template <class _Tp>
+_LIBCPP_INLINE_VAR constexpr size_t is_bind_expression_v = is_bind_expression<_Tp>::value;
+#endif
+
+template<class _Tp> struct __is_placeholder : public integral_constant<int, 0> {};
+template<class _Tp> struct _LIBCPP_TEMPLATE_VIS is_placeholder
+    : public __is_placeholder<typename remove_cv<_Tp>::type> {};
+
+#if _LIBCPP_STD_VER > 14
+template <class _Tp>
+_LIBCPP_INLINE_VAR constexpr size_t is_placeholder_v = is_placeholder<_Tp>::value;
+#endif
+
+namespace placeholders
+{
+
+template <int _Np> struct __ph {};
+
+#if defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
+_LIBCPP_FUNC_VIS extern const __ph<1>   _1;
+_LIBCPP_FUNC_VIS extern const __ph<2>   _2;
+_LIBCPP_FUNC_VIS extern const __ph<3>   _3;
+_LIBCPP_FUNC_VIS extern const __ph<4>   _4;
+_LIBCPP_FUNC_VIS extern const __ph<5>   _5;
+_LIBCPP_FUNC_VIS extern const __ph<6>   _6;
+_LIBCPP_FUNC_VIS extern const __ph<7>   _7;
+_LIBCPP_FUNC_VIS extern const __ph<8>   _8;
+_LIBCPP_FUNC_VIS extern const __ph<9>   _9;
+_LIBCPP_FUNC_VIS extern const __ph<10> _10;
+#else
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<1>   _1{};
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<2>   _2{};
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<3>   _3{};
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<4>   _4{};
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<5>   _5{};
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<6>   _6{};
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<7>   _7{};
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<8>   _8{};
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<9>   _9{};
+/* _LIBCPP_INLINE_VAR */ constexpr __ph<10> _10{};
+#endif // defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
+
+}  // placeholders
+
+template<int _Np>
+struct __is_placeholder<placeholders::__ph<_Np> >
+    : public integral_constant<int, _Np> {};
+
+
+#ifndef _LIBCPP_CXX03_LANG
+
+template <class _Tp, class _Uj>
+inline _LIBCPP_INLINE_VISIBILITY
+_Tp&
+__mu(reference_wrapper<_Tp> __t, _Uj&)
+{
+    return __t.get();
+}
+
+template <class _Ti, class ..._Uj, size_t ..._Indx>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __invoke_of<_Ti&, _Uj...>::type
+__mu_expand(_Ti& __ti, tuple<_Uj...>& __uj, __tuple_indices<_Indx...>)
+{
+    return __ti(_VSTD::forward<_Uj>(_VSTD::get<_Indx>(__uj))...);
+}
+
+template <class _Ti, class ..._Uj>
+inline _LIBCPP_INLINE_VISIBILITY
+typename _EnableIf
+<
+    is_bind_expression<_Ti>::value,
+    __invoke_of<_Ti&, _Uj...>
+>::type
+__mu(_Ti& __ti, tuple<_Uj...>& __uj)
+{
+    typedef typename __make_tuple_indices<sizeof...(_Uj)>::type __indices;
+    return _VSTD::__mu_expand(__ti, __uj, __indices());
+}
+
+template <bool IsPh, class _Ti, class _Uj>
+struct __mu_return2 {};
+
+template <class _Ti, class _Uj>
+struct __mu_return2<true, _Ti, _Uj>
+{
+    typedef typename tuple_element<is_placeholder<_Ti>::value - 1, _Uj>::type type;
+};
+
+template <class _Ti, class _Uj>
+inline _LIBCPP_INLINE_VISIBILITY
+typename enable_if
+<
+    0 < is_placeholder<_Ti>::value,
+    typename __mu_return2<0 < is_placeholder<_Ti>::value, _Ti, _Uj>::type
+>::type
+__mu(_Ti&, _Uj& __uj)
+{
+    const size_t _Indx = is_placeholder<_Ti>::value - 1;
+    return _VSTD::forward<typename tuple_element<_Indx, _Uj>::type>(_VSTD::get<_Indx>(__uj));
+}
+
+template <class _Ti, class _Uj>
+inline _LIBCPP_INLINE_VISIBILITY
+typename enable_if
+<
+    !is_bind_expression<_Ti>::value &&
+    is_placeholder<_Ti>::value == 0 &&
+    !__is_reference_wrapper<_Ti>::value,
+    _Ti&
+>::type
+__mu(_Ti& __ti, _Uj&)
+{
+    return __ti;
+}
+
+template <class _Ti, bool IsReferenceWrapper, bool IsBindEx, bool IsPh,
+          class _TupleUj>
+struct __mu_return_impl;
+
+template <bool _Invokable, class _Ti, class ..._Uj>
+struct __mu_return_invokable  // false
+{
+    typedef __nat type;
+};
+
+template <class _Ti, class ..._Uj>
+struct __mu_return_invokable<true, _Ti, _Uj...>
+{
+    typedef typename __invoke_of<_Ti&, _Uj...>::type type;
+};
+
+template <class _Ti, class ..._Uj>
+struct __mu_return_impl<_Ti, false, true, false, tuple<_Uj...> >
+    : public __mu_return_invokable<__invokable<_Ti&, _Uj...>::value, _Ti, _Uj...>
+{
+};
+
+template <class _Ti, class _TupleUj>
+struct __mu_return_impl<_Ti, false, false, true, _TupleUj>
+{
+    typedef typename tuple_element<is_placeholder<_Ti>::value - 1,
+                                   _TupleUj>::type&& type;
+};
+
+template <class _Ti, class _TupleUj>
+struct __mu_return_impl<_Ti, true, false, false, _TupleUj>
+{
+    typedef typename _Ti::type& type;
+};
+
+template <class _Ti, class _TupleUj>
+struct __mu_return_impl<_Ti, false, false, false, _TupleUj>
+{
+    typedef _Ti& type;
+};
+
+template <class _Ti, class _TupleUj>
+struct __mu_return
+    : public __mu_return_impl<_Ti,
+                              __is_reference_wrapper<_Ti>::value,
+                              is_bind_expression<_Ti>::value,
+                              0 < is_placeholder<_Ti>::value &&
+                              is_placeholder<_Ti>::value <= tuple_size<_TupleUj>::value,
+                              _TupleUj>
+{
+};
+
+template <class _Fp, class _BoundArgs, class _TupleUj>
+struct __is_valid_bind_return
+{
+    static const bool value = false;
+};
+
+template <class _Fp, class ..._BoundArgs, class _TupleUj>
+struct __is_valid_bind_return<_Fp, tuple<_BoundArgs...>, _TupleUj>
+{
+    static const bool value = __invokable<_Fp,
+                    typename __mu_return<_BoundArgs, _TupleUj>::type...>::value;
+};
+
+template <class _Fp, class ..._BoundArgs, class _TupleUj>
+struct __is_valid_bind_return<_Fp, const tuple<_BoundArgs...>, _TupleUj>
+{
+    static const bool value = __invokable<_Fp,
+                    typename __mu_return<const _BoundArgs, _TupleUj>::type...>::value;
+};
+
+template <class _Fp, class _BoundArgs, class _TupleUj,
+          bool = __is_valid_bind_return<_Fp, _BoundArgs, _TupleUj>::value>
+struct __bind_return;
+
+template <class _Fp, class ..._BoundArgs, class _TupleUj>
+struct __bind_return<_Fp, tuple<_BoundArgs...>, _TupleUj, true>
+{
+    typedef typename __invoke_of
+    <
+        _Fp&,
+        typename __mu_return
+        <
+            _BoundArgs,
+            _TupleUj
+        >::type...
+    >::type type;
+};
+
+template <class _Fp, class ..._BoundArgs, class _TupleUj>
+struct __bind_return<_Fp, const tuple<_BoundArgs...>, _TupleUj, true>
+{
+    typedef typename __invoke_of
+    <
+        _Fp&,
+        typename __mu_return
+        <
+            const _BoundArgs,
+            _TupleUj
+        >::type...
+    >::type type;
+};
+
+template <class _Fp, class _BoundArgs, size_t ..._Indx, class _Args>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __bind_return<_Fp, _BoundArgs, _Args>::type
+__apply_functor(_Fp& __f, _BoundArgs& __bound_args, __tuple_indices<_Indx...>,
+                _Args&& __args)
+{
+    return _VSTD::__invoke(__f, _VSTD::__mu(_VSTD::get<_Indx>(__bound_args), __args)...);
+}
+
+template<class _Fp, class ..._BoundArgs>
+class __bind
+#if _LIBCPP_STD_VER <= 17 || !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public __weak_result_type<typename decay<_Fp>::type>
+#endif
+{
+protected:
+    typedef typename decay<_Fp>::type _Fd;
+    typedef tuple<typename decay<_BoundArgs>::type...> _Td;
+private:
+    _Fd __f_;
+    _Td __bound_args_;
+
+    typedef typename __make_tuple_indices<sizeof...(_BoundArgs)>::type __indices;
+public:
+    template <class _Gp, class ..._BA,
+              class = typename enable_if
+                               <
+                                  is_constructible<_Fd, _Gp>::value &&
+                                  !is_same<typename remove_reference<_Gp>::type,
+                                           __bind>::value
+                               >::type>
+      _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+      explicit __bind(_Gp&& __f, _BA&& ...__bound_args)
+        : __f_(_VSTD::forward<_Gp>(__f)),
+          __bound_args_(_VSTD::forward<_BA>(__bound_args)...) {}
+
+    template <class ..._Args>
+        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+        typename __bind_return<_Fd, _Td, tuple<_Args&&...> >::type
+        operator()(_Args&& ...__args)
+        {
+            return _VSTD::__apply_functor(__f_, __bound_args_, __indices(),
+                                  tuple<_Args&&...>(_VSTD::forward<_Args>(__args)...));
+        }
+
+    template <class ..._Args>
+        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+        typename __bind_return<const _Fd, const _Td, tuple<_Args&&...> >::type
+        operator()(_Args&& ...__args) const
+        {
+            return _VSTD::__apply_functor(__f_, __bound_args_, __indices(),
+                                   tuple<_Args&&...>(_VSTD::forward<_Args>(__args)...));
+        }
+};
+
+template<class _Fp, class ..._BoundArgs>
+struct __is_bind_expression<__bind<_Fp, _BoundArgs...> > : public true_type {};
+
+template<class _Rp, class _Fp, class ..._BoundArgs>
+class __bind_r
+    : public __bind<_Fp, _BoundArgs...>
+{
+    typedef __bind<_Fp, _BoundArgs...> base;
+    typedef typename base::_Fd _Fd;
+    typedef typename base::_Td _Td;
+public:
+    typedef _Rp result_type;
+
+
+    template <class _Gp, class ..._BA,
+              class = typename enable_if
+                               <
+                                  is_constructible<_Fd, _Gp>::value &&
+                                  !is_same<typename remove_reference<_Gp>::type,
+                                           __bind_r>::value
+                               >::type>
+      _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+      explicit __bind_r(_Gp&& __f, _BA&& ...__bound_args)
+        : base(_VSTD::forward<_Gp>(__f),
+               _VSTD::forward<_BA>(__bound_args)...) {}
+
+    template <class ..._Args>
+        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+        typename enable_if
+        <
+            is_convertible<typename __bind_return<_Fd, _Td, tuple<_Args&&...> >::type,
+                           result_type>::value || is_void<_Rp>::value,
+            result_type
+        >::type
+        operator()(_Args&& ...__args)
+        {
+            typedef __invoke_void_return_wrapper<_Rp> _Invoker;
+            return _Invoker::__call(static_cast<base&>(*this), _VSTD::forward<_Args>(__args)...);
+        }
+
+    template <class ..._Args>
+        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+        typename enable_if
+        <
+            is_convertible<typename __bind_return<const _Fd, const _Td, tuple<_Args&&...> >::type,
+                           result_type>::value || is_void<_Rp>::value,
+            result_type
+        >::type
+        operator()(_Args&& ...__args) const
+        {
+            typedef __invoke_void_return_wrapper<_Rp> _Invoker;
+            return _Invoker::__call(static_cast<base const&>(*this), _VSTD::forward<_Args>(__args)...);
+        }
+};
+
+template<class _Rp, class _Fp, class ..._BoundArgs>
+struct __is_bind_expression<__bind_r<_Rp, _Fp, _BoundArgs...> > : public true_type {};
+
+template<class _Fp, class ..._BoundArgs>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+__bind<_Fp, _BoundArgs...>
+bind(_Fp&& __f, _BoundArgs&&... __bound_args)
+{
+    typedef __bind<_Fp, _BoundArgs...> type;
+    return type(_VSTD::forward<_Fp>(__f), _VSTD::forward<_BoundArgs>(__bound_args)...);
+}
+
+template<class _Rp, class _Fp, class ..._BoundArgs>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+__bind_r<_Rp, _Fp, _BoundArgs...>
+bind(_Fp&& __f, _BoundArgs&&... __bound_args)
+{
+    typedef __bind_r<_Rp, _Fp, _BoundArgs...> type;
+    return type(_VSTD::forward<_Fp>(__f), _VSTD::forward<_BoundArgs>(__bound_args)...);
+}
+
+#endif // _LIBCPP_CXX03_LANG
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_BIND_H
lib/libcxx/include/__functional/bind_front.h
@@ -0,0 +1,52 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_BIND_FRONT_H
+#define _LIBCPP___FUNCTIONAL_BIND_FRONT_H
+
+#include <__config>
+#include <__functional/perfect_forward.h>
+#include <__functional/invoke.h>
+#include <type_traits>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17
+
+struct __bind_front_op
+{
+    template<class... _Args>
+    constexpr static auto __call(_Args&&... __args)
+    noexcept(noexcept(_VSTD::invoke(_VSTD::forward<_Args>(__args)...)))
+    -> decltype(      _VSTD::invoke(_VSTD::forward<_Args>(__args)...))
+    { return          _VSTD::invoke(_VSTD::forward<_Args>(__args)...); }
+};
+
+template<class _Fn, class... _Args,
+         class = _EnableIf<conjunction<is_constructible<decay_t<_Fn>, _Fn>,
+                                       is_move_constructible<decay_t<_Fn>>,
+                                       is_constructible<decay_t<_Args>, _Args>...,
+                                       is_move_constructible<decay_t<_Args>>...
+                                       >::value>>
+constexpr auto bind_front(_Fn&& __f, _Args&&... __args)
+{
+    return __perfect_forward<__bind_front_op, _Fn, _Args...>(_VSTD::forward<_Fn>(__f),
+                                                             _VSTD::forward<_Args>(__args)...);
+}
+
+#endif // _LIBCPP_STD_VER > 17
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_BIND_FRONT_H
lib/libcxx/include/__functional/binder1st.h
@@ -0,0 +1,54 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_BINDER1ST_H
+#define _LIBCPP___FUNCTIONAL_BINDER1ST_H
+
+#include <__config>
+#include <__functional/unary_function.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
+
+template <class __Operation>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 binder1st
+    : public unary_function<typename __Operation::second_argument_type,
+                            typename __Operation::result_type>
+{
+protected:
+    __Operation                               op;
+    typename __Operation::first_argument_type value;
+public:
+    _LIBCPP_INLINE_VISIBILITY binder1st(const __Operation& __x,
+                               const typename __Operation::first_argument_type __y)
+        : op(__x), value(__y) {}
+    _LIBCPP_INLINE_VISIBILITY typename __Operation::result_type operator()
+        (typename __Operation::second_argument_type& __x) const
+            {return op(value, __x);}
+    _LIBCPP_INLINE_VISIBILITY typename __Operation::result_type operator()
+        (const typename __Operation::second_argument_type& __x) const
+            {return op(value, __x);}
+};
+
+template <class __Operation, class _Tp>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+binder1st<__Operation>
+bind1st(const __Operation& __op, const _Tp& __x)
+    {return binder1st<__Operation>(__op, __x);}
+
+#endif // _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_BINDER1ST_H
lib/libcxx/include/__functional/binder2nd.h
@@ -0,0 +1,54 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_BINDER2ND_H
+#define _LIBCPP___FUNCTIONAL_BINDER2ND_H
+
+#include <__config>
+#include <__functional/unary_function.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
+
+template <class __Operation>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 binder2nd
+    : public unary_function<typename __Operation::first_argument_type,
+                            typename __Operation::result_type>
+{
+protected:
+    __Operation                                op;
+    typename __Operation::second_argument_type value;
+public:
+    _LIBCPP_INLINE_VISIBILITY
+    binder2nd(const __Operation& __x, const typename __Operation::second_argument_type __y)
+        : op(__x), value(__y) {}
+    _LIBCPP_INLINE_VISIBILITY typename __Operation::result_type operator()
+        (      typename __Operation::first_argument_type& __x) const
+            {return op(__x, value);}
+    _LIBCPP_INLINE_VISIBILITY typename __Operation::result_type operator()
+        (const typename __Operation::first_argument_type& __x) const
+            {return op(__x, value);}
+};
+
+template <class __Operation, class _Tp>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+binder2nd<__Operation>
+bind2nd(const __Operation& __op, const _Tp& __x)
+    {return binder2nd<__Operation>(__op, __x);}
+
+#endif // _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_BINDER2ND_H
lib/libcxx/include/__functional/default_searcher.h
@@ -0,0 +1,56 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_DEFAULT_SEARCHER_H
+#define _LIBCPP___FUNCTIONAL_DEFAULT_SEARCHER_H
+
+#include <__algorithm/search.h>
+#include <__config>
+#include <__functional/operations.h>
+#include <__iterator/iterator_traits.h>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+
+// default searcher
+template<class _ForwardIterator, class _BinaryPredicate = equal_to<>>
+class _LIBCPP_TEMPLATE_VIS default_searcher {
+public:
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    default_searcher(_ForwardIterator __f, _ForwardIterator __l,
+                       _BinaryPredicate __p = _BinaryPredicate())
+        : __first_(__f), __last_(__l), __pred_(__p) {}
+
+    template <typename _ForwardIterator2>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    pair<_ForwardIterator2, _ForwardIterator2>
+    operator () (_ForwardIterator2 __f, _ForwardIterator2 __l) const
+    {
+        return _VSTD::__search(__f, __l, __first_, __last_, __pred_,
+            typename iterator_traits<_ForwardIterator>::iterator_category(),
+            typename iterator_traits<_ForwardIterator2>::iterator_category());
+    }
+
+private:
+    _ForwardIterator __first_;
+    _ForwardIterator __last_;
+    _BinaryPredicate __pred_;
+    };
+
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_DEFAULT_SEARCHER_H
lib/libcxx/include/__functional_03 โ†’ lib/libcxx/include/__functional/function.h
@@ -7,15 +7,1229 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef _LIBCPP_FUNCTIONAL_03
-#define _LIBCPP_FUNCTIONAL_03
-
-// manual variadic expansion for <functional>
+#ifndef _LIBCPP___FUNCTIONAL_FUNCTION_H
+#define _LIBCPP___FUNCTIONAL_FUNCTION_H
+
+#include <__config>
+#include <__functional/binary_function.h>
+#include <__functional/invoke.h>
+#include <__functional/unary_function.h>
+#include <__iterator/iterator_traits.h>
+#include <__memory/allocator_traits.h>
+#include <__memory/compressed_pair.h>
+#include <__memory/shared_ptr.h>
+#include <exception>
+#include <memory> // TODO: replace with <__memory/__builtin_new_allocator.h>
+#include <type_traits>
+#include <utility>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
 
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// bad_function_call
+
+class _LIBCPP_EXCEPTION_ABI bad_function_call
+    : public exception
+{
+#ifdef _LIBCPP_ABI_BAD_FUNCTION_CALL_KEY_FUNCTION
+public:
+    virtual ~bad_function_call() _NOEXCEPT;
+
+    virtual const char* what() const _NOEXCEPT;
+#endif
+};
+
+_LIBCPP_NORETURN inline _LIBCPP_INLINE_VISIBILITY
+void __throw_bad_function_call()
+{
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    throw bad_function_call();
+#else
+    _VSTD::abort();
+#endif
+}
+
+#if defined(_LIBCPP_CXX03_LANG) && !defined(_LIBCPP_DISABLE_DEPRECATION_WARNINGS) && __has_attribute(deprecated)
+#   define _LIBCPP_DEPRECATED_CXX03_FUNCTION \
+        __attribute__((deprecated("Using std::function in C++03 is not supported anymore. Please upgrade to C++11 or later, or use a different type")))
+#else
+#   define _LIBCPP_DEPRECATED_CXX03_FUNCTION /* nothing */
+#endif
+
+template<class _Fp> class _LIBCPP_DEPRECATED_CXX03_FUNCTION _LIBCPP_TEMPLATE_VIS function; // undefined
+
+namespace __function
+{
+
+template<class _Rp>
+struct __maybe_derive_from_unary_function
+{
+};
+
+template<class _Rp, class _A1>
+struct __maybe_derive_from_unary_function<_Rp(_A1)>
+    : public unary_function<_A1, _Rp>
+{
+};
+
+template<class _Rp>
+struct __maybe_derive_from_binary_function
+{
+};
+
+template<class _Rp, class _A1, class _A2>
+struct __maybe_derive_from_binary_function<_Rp(_A1, _A2)>
+    : public binary_function<_A1, _A2, _Rp>
+{
+};
+
+template <class _Fp>
+_LIBCPP_INLINE_VISIBILITY
+bool __not_null(_Fp const&) { return true; }
+
+template <class _Fp>
+_LIBCPP_INLINE_VISIBILITY
+bool __not_null(_Fp* __ptr) { return __ptr; }
+
+template <class _Ret, class _Class>
+_LIBCPP_INLINE_VISIBILITY
+bool __not_null(_Ret _Class::*__ptr) { return __ptr; }
+
+template <class _Fp>
+_LIBCPP_INLINE_VISIBILITY
+bool __not_null(function<_Fp> const& __f) { return !!__f; }
+
+#ifdef _LIBCPP_HAS_EXTENSION_BLOCKS
+template <class _Rp, class ..._Args>
+_LIBCPP_INLINE_VISIBILITY
+bool __not_null(_Rp (^__p)(_Args...)) { return __p; }
+#endif
+
+} // namespace __function
+
+#ifndef _LIBCPP_CXX03_LANG
+
+namespace __function {
+
+// __alloc_func holds a functor and an allocator.
+
+template <class _Fp, class _Ap, class _FB> class __alloc_func;
+template <class _Fp, class _FB>
+class __default_alloc_func;
+
+template <class _Fp, class _Ap, class _Rp, class... _ArgTypes>
+class __alloc_func<_Fp, _Ap, _Rp(_ArgTypes...)>
+{
+    __compressed_pair<_Fp, _Ap> __f_;
+
+  public:
+    typedef _LIBCPP_NODEBUG_TYPE _Fp _Target;
+    typedef _LIBCPP_NODEBUG_TYPE _Ap _Alloc;
+
+    _LIBCPP_INLINE_VISIBILITY
+    const _Target& __target() const { return __f_.first(); }
+
+    // WIN32 APIs may define __allocator, so use __get_allocator instead.
+    _LIBCPP_INLINE_VISIBILITY
+    const _Alloc& __get_allocator() const { return __f_.second(); }
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __alloc_func(_Target&& __f)
+        : __f_(piecewise_construct, _VSTD::forward_as_tuple(_VSTD::move(__f)),
+               _VSTD::forward_as_tuple())
+    {
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __alloc_func(const _Target& __f, const _Alloc& __a)
+        : __f_(piecewise_construct, _VSTD::forward_as_tuple(__f),
+               _VSTD::forward_as_tuple(__a))
+    {
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __alloc_func(const _Target& __f, _Alloc&& __a)
+        : __f_(piecewise_construct, _VSTD::forward_as_tuple(__f),
+               _VSTD::forward_as_tuple(_VSTD::move(__a)))
+    {
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __alloc_func(_Target&& __f, _Alloc&& __a)
+        : __f_(piecewise_construct, _VSTD::forward_as_tuple(_VSTD::move(__f)),
+               _VSTD::forward_as_tuple(_VSTD::move(__a)))
+    {
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    _Rp operator()(_ArgTypes&&... __arg)
+    {
+        typedef __invoke_void_return_wrapper<_Rp> _Invoker;
+        return _Invoker::__call(__f_.first(),
+                                _VSTD::forward<_ArgTypes>(__arg)...);
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    __alloc_func* __clone() const
+    {
+        typedef allocator_traits<_Alloc> __alloc_traits;
+        typedef
+            typename __rebind_alloc_helper<__alloc_traits, __alloc_func>::type
+                _AA;
+        _AA __a(__f_.second());
+        typedef __allocator_destructor<_AA> _Dp;
+        unique_ptr<__alloc_func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1));
+        ::new ((void*)__hold.get()) __alloc_func(__f_.first(), _Alloc(__a));
+        return __hold.release();
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    void destroy() _NOEXCEPT { __f_.~__compressed_pair<_Target, _Alloc>(); }
+
+    static void __destroy_and_delete(__alloc_func* __f) {
+      typedef allocator_traits<_Alloc> __alloc_traits;
+      typedef typename __rebind_alloc_helper<__alloc_traits, __alloc_func>::type
+          _FunAlloc;
+      _FunAlloc __a(__f->__get_allocator());
+      __f->destroy();
+      __a.deallocate(__f, 1);
+    }
+};
+
+template <class _Fp, class _Rp, class... _ArgTypes>
+class __default_alloc_func<_Fp, _Rp(_ArgTypes...)> {
+  _Fp __f_;
+
+public:
+  typedef _LIBCPP_NODEBUG_TYPE _Fp _Target;
+
+  _LIBCPP_INLINE_VISIBILITY
+  const _Target& __target() const { return __f_; }
+
+  _LIBCPP_INLINE_VISIBILITY
+  explicit __default_alloc_func(_Target&& __f) : __f_(_VSTD::move(__f)) {}
+
+  _LIBCPP_INLINE_VISIBILITY
+  explicit __default_alloc_func(const _Target& __f) : __f_(__f) {}
+
+  _LIBCPP_INLINE_VISIBILITY
+  _Rp operator()(_ArgTypes&&... __arg) {
+    typedef __invoke_void_return_wrapper<_Rp> _Invoker;
+    return _Invoker::__call(__f_, _VSTD::forward<_ArgTypes>(__arg)...);
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  __default_alloc_func* __clone() const {
+      __builtin_new_allocator::__holder_t __hold =
+        __builtin_new_allocator::__allocate_type<__default_alloc_func>(1);
+    __default_alloc_func* __res =
+        ::new ((void*)__hold.get()) __default_alloc_func(__f_);
+    (void)__hold.release();
+    return __res;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  void destroy() _NOEXCEPT { __f_.~_Target(); }
+
+  static void __destroy_and_delete(__default_alloc_func* __f) {
+    __f->destroy();
+      __builtin_new_allocator::__deallocate_type<__default_alloc_func>(__f, 1);
+  }
+};
+
+// __base provides an abstract interface for copyable functors.
+
+template<class _Fp> class _LIBCPP_TEMPLATE_VIS __base;
+
+template<class _Rp, class ..._ArgTypes>
+class __base<_Rp(_ArgTypes...)>
+{
+    __base(const __base&);
+    __base& operator=(const __base&);
+public:
+    _LIBCPP_INLINE_VISIBILITY __base() {}
+    _LIBCPP_INLINE_VISIBILITY virtual ~__base() {}
+    virtual __base* __clone() const = 0;
+    virtual void __clone(__base*) const = 0;
+    virtual void destroy() _NOEXCEPT = 0;
+    virtual void destroy_deallocate() _NOEXCEPT = 0;
+    virtual _Rp operator()(_ArgTypes&& ...) = 0;
+#ifndef _LIBCPP_NO_RTTI
+    virtual const void* target(const type_info&) const _NOEXCEPT = 0;
+    virtual const std::type_info& target_type() const _NOEXCEPT = 0;
+#endif // _LIBCPP_NO_RTTI
+};
+
+// __func implements __base for a given functor type.
+
+template<class _FD, class _Alloc, class _FB> class __func;
+
+template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
+class __func<_Fp, _Alloc, _Rp(_ArgTypes...)>
+    : public  __base<_Rp(_ArgTypes...)>
+{
+    __alloc_func<_Fp, _Alloc, _Rp(_ArgTypes...)> __f_;
+public:
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __func(_Fp&& __f)
+        : __f_(_VSTD::move(__f)) {}
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __func(const _Fp& __f, const _Alloc& __a)
+        : __f_(__f, __a) {}
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __func(const _Fp& __f, _Alloc&& __a)
+        : __f_(__f, _VSTD::move(__a)) {}
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __func(_Fp&& __f, _Alloc&& __a)
+        : __f_(_VSTD::move(__f), _VSTD::move(__a)) {}
+
+    virtual __base<_Rp(_ArgTypes...)>* __clone() const;
+    virtual void __clone(__base<_Rp(_ArgTypes...)>*) const;
+    virtual void destroy() _NOEXCEPT;
+    virtual void destroy_deallocate() _NOEXCEPT;
+    virtual _Rp operator()(_ArgTypes&&... __arg);
+#ifndef _LIBCPP_NO_RTTI
+    virtual const void* target(const type_info&) const _NOEXCEPT;
+    virtual const std::type_info& target_type() const _NOEXCEPT;
+#endif // _LIBCPP_NO_RTTI
+};
+
+template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
+__base<_Rp(_ArgTypes...)>*
+__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::__clone() const
+{
+    typedef allocator_traits<_Alloc> __alloc_traits;
+    typedef typename __rebind_alloc_helper<__alloc_traits, __func>::type _Ap;
+    _Ap __a(__f_.__get_allocator());
+    typedef __allocator_destructor<_Ap> _Dp;
+    unique_ptr<__func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1));
+    ::new ((void*)__hold.get()) __func(__f_.__target(), _Alloc(__a));
+    return __hold.release();
+}
+
+template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
+void
+__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::__clone(__base<_Rp(_ArgTypes...)>* __p) const
+{
+    ::new ((void*)__p) __func(__f_.__target(), __f_.__get_allocator());
+}
+
+template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
+void
+__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::destroy() _NOEXCEPT
+{
+    __f_.destroy();
+}
+
+template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
+void
+__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::destroy_deallocate() _NOEXCEPT
+{
+    typedef allocator_traits<_Alloc> __alloc_traits;
+    typedef typename __rebind_alloc_helper<__alloc_traits, __func>::type _Ap;
+    _Ap __a(__f_.__get_allocator());
+    __f_.destroy();
+    __a.deallocate(this, 1);
+}
+
+template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
+_Rp
+__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::operator()(_ArgTypes&& ... __arg)
+{
+    return __f_(_VSTD::forward<_ArgTypes>(__arg)...);
+}
+
+#ifndef _LIBCPP_NO_RTTI
+
+template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
+const void*
+__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::target(const type_info& __ti) const _NOEXCEPT
+{
+    if (__ti == typeid(_Fp))
+        return &__f_.__target();
+    return nullptr;
+}
+
+template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
+const std::type_info&
+__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::target_type() const _NOEXCEPT
+{
+    return typeid(_Fp);
+}
+
+#endif // _LIBCPP_NO_RTTI
+
+// __value_func creates a value-type from a __func.
+
+template <class _Fp> class __value_func;
+
+template <class _Rp, class... _ArgTypes> class __value_func<_Rp(_ArgTypes...)>
+{
+    typename aligned_storage<3 * sizeof(void*)>::type __buf_;
+
+    typedef __base<_Rp(_ArgTypes...)> __func;
+    __func* __f_;
+
+    _LIBCPP_NO_CFI static __func* __as_base(void* p)
+    {
+        return reinterpret_cast<__func*>(p);
+    }
+
+  public:
+    _LIBCPP_INLINE_VISIBILITY
+    __value_func() _NOEXCEPT : __f_(nullptr) {}
+
+    template <class _Fp, class _Alloc>
+    _LIBCPP_INLINE_VISIBILITY __value_func(_Fp&& __f, const _Alloc& __a)
+        : __f_(nullptr)
+    {
+        typedef allocator_traits<_Alloc> __alloc_traits;
+        typedef __function::__func<_Fp, _Alloc, _Rp(_ArgTypes...)> _Fun;
+        typedef typename __rebind_alloc_helper<__alloc_traits, _Fun>::type
+            _FunAlloc;
+
+        if (__function::__not_null(__f))
+        {
+            _FunAlloc __af(__a);
+            if (sizeof(_Fun) <= sizeof(__buf_) &&
+                is_nothrow_copy_constructible<_Fp>::value &&
+                is_nothrow_copy_constructible<_FunAlloc>::value)
+            {
+                __f_ =
+                    ::new ((void*)&__buf_) _Fun(_VSTD::move(__f), _Alloc(__af));
+            }
+            else
+            {
+                typedef __allocator_destructor<_FunAlloc> _Dp;
+                unique_ptr<__func, _Dp> __hold(__af.allocate(1), _Dp(__af, 1));
+                ::new ((void*)__hold.get()) _Fun(_VSTD::move(__f), _Alloc(__a));
+                __f_ = __hold.release();
+            }
+        }
+    }
+
+    template <class _Fp,
+        class = typename enable_if<!is_same<typename decay<_Fp>::type, __value_func>::value>::type>
+    _LIBCPP_INLINE_VISIBILITY explicit __value_func(_Fp&& __f)
+        : __value_func(_VSTD::forward<_Fp>(__f), allocator<_Fp>()) {}
+
+    _LIBCPP_INLINE_VISIBILITY
+    __value_func(const __value_func& __f)
+    {
+        if (__f.__f_ == nullptr)
+            __f_ = nullptr;
+        else if ((void*)__f.__f_ == &__f.__buf_)
+        {
+            __f_ = __as_base(&__buf_);
+            __f.__f_->__clone(__f_);
+        }
+        else
+            __f_ = __f.__f_->__clone();
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    __value_func(__value_func&& __f) _NOEXCEPT
+    {
+        if (__f.__f_ == nullptr)
+            __f_ = nullptr;
+        else if ((void*)__f.__f_ == &__f.__buf_)
+        {
+            __f_ = __as_base(&__buf_);
+            __f.__f_->__clone(__f_);
+        }
+        else
+        {
+            __f_ = __f.__f_;
+            __f.__f_ = nullptr;
+        }
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    ~__value_func()
+    {
+        if ((void*)__f_ == &__buf_)
+            __f_->destroy();
+        else if (__f_)
+            __f_->destroy_deallocate();
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    __value_func& operator=(__value_func&& __f)
+    {
+        *this = nullptr;
+        if (__f.__f_ == nullptr)
+            __f_ = nullptr;
+        else if ((void*)__f.__f_ == &__f.__buf_)
+        {
+            __f_ = __as_base(&__buf_);
+            __f.__f_->__clone(__f_);
+        }
+        else
+        {
+            __f_ = __f.__f_;
+            __f.__f_ = nullptr;
+        }
+        return *this;
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    __value_func& operator=(nullptr_t)
+    {
+        __func* __f = __f_;
+        __f_ = nullptr;
+        if ((void*)__f == &__buf_)
+            __f->destroy();
+        else if (__f)
+            __f->destroy_deallocate();
+        return *this;
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    _Rp operator()(_ArgTypes&&... __args) const
+    {
+        if (__f_ == nullptr)
+            __throw_bad_function_call();
+        return (*__f_)(_VSTD::forward<_ArgTypes>(__args)...);
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    void swap(__value_func& __f) _NOEXCEPT
+    {
+        if (&__f == this)
+            return;
+        if ((void*)__f_ == &__buf_ && (void*)__f.__f_ == &__f.__buf_)
+        {
+            typename aligned_storage<sizeof(__buf_)>::type __tempbuf;
+            __func* __t = __as_base(&__tempbuf);
+            __f_->__clone(__t);
+            __f_->destroy();
+            __f_ = nullptr;
+            __f.__f_->__clone(__as_base(&__buf_));
+            __f.__f_->destroy();
+            __f.__f_ = nullptr;
+            __f_ = __as_base(&__buf_);
+            __t->__clone(__as_base(&__f.__buf_));
+            __t->destroy();
+            __f.__f_ = __as_base(&__f.__buf_);
+        }
+        else if ((void*)__f_ == &__buf_)
+        {
+            __f_->__clone(__as_base(&__f.__buf_));
+            __f_->destroy();
+            __f_ = __f.__f_;
+            __f.__f_ = __as_base(&__f.__buf_);
+        }
+        else if ((void*)__f.__f_ == &__f.__buf_)
+        {
+            __f.__f_->__clone(__as_base(&__buf_));
+            __f.__f_->destroy();
+            __f.__f_ = __f_;
+            __f_ = __as_base(&__buf_);
+        }
+        else
+            _VSTD::swap(__f_, __f.__f_);
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit operator bool() const _NOEXCEPT { return __f_ != nullptr; }
+
+#ifndef _LIBCPP_NO_RTTI
+    _LIBCPP_INLINE_VISIBILITY
+    const std::type_info& target_type() const _NOEXCEPT
+    {
+        if (__f_ == nullptr)
+            return typeid(void);
+        return __f_->target_type();
+    }
+
+    template <typename _Tp>
+    _LIBCPP_INLINE_VISIBILITY const _Tp* target() const _NOEXCEPT
+    {
+        if (__f_ == nullptr)
+            return nullptr;
+        return (const _Tp*)__f_->target(typeid(_Tp));
+    }
+#endif // _LIBCPP_NO_RTTI
+};
+
+// Storage for a functor object, to be used with __policy to manage copy and
+// destruction.
+union __policy_storage
+{
+    mutable char __small[sizeof(void*) * 2];
+    void* __large;
+};
+
+// True if _Fun can safely be held in __policy_storage.__small.
+template <typename _Fun>
+struct __use_small_storage
+    : public integral_constant<
+          bool, sizeof(_Fun) <= sizeof(__policy_storage) &&
+                    _LIBCPP_ALIGNOF(_Fun) <= _LIBCPP_ALIGNOF(__policy_storage) &&
+                    is_trivially_copy_constructible<_Fun>::value &&
+                    is_trivially_destructible<_Fun>::value> {};
+
+// Policy contains information about how to copy, destroy, and move the
+// underlying functor. You can think of it as a vtable of sorts.
+struct __policy
+{
+    // Used to copy or destroy __large values. null for trivial objects.
+    void* (*const __clone)(const void*);
+    void (*const __destroy)(void*);
+
+    // True if this is the null policy (no value).
+    const bool __is_null;
+
+    // The target type. May be null if RTTI is disabled.
+    const std::type_info* const __type_info;
+
+    // Returns a pointer to a static policy object suitable for the functor
+    // type.
+    template <typename _Fun>
+    _LIBCPP_INLINE_VISIBILITY static const __policy* __create()
+    {
+        return __choose_policy<_Fun>(__use_small_storage<_Fun>());
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    static const __policy* __create_empty()
+    {
+        static const _LIBCPP_CONSTEXPR __policy __policy_ = {nullptr, nullptr,
+                                                             true,
+#ifndef _LIBCPP_NO_RTTI
+                                                             &typeid(void)
+#else
+                                                             nullptr
+#endif
+        };
+        return &__policy_;
+    }
+
+  private:
+    template <typename _Fun> static void* __large_clone(const void* __s)
+    {
+        const _Fun* __f = static_cast<const _Fun*>(__s);
+        return __f->__clone();
+    }
+
+    template <typename _Fun>
+    static void __large_destroy(void* __s) {
+      _Fun::__destroy_and_delete(static_cast<_Fun*>(__s));
+    }
+
+    template <typename _Fun>
+    _LIBCPP_INLINE_VISIBILITY static const __policy*
+    __choose_policy(/* is_small = */ false_type) {
+      static const _LIBCPP_CONSTEXPR __policy __policy_ = {
+          &__large_clone<_Fun>, &__large_destroy<_Fun>, false,
+#ifndef _LIBCPP_NO_RTTI
+          &typeid(typename _Fun::_Target)
+#else
+          nullptr
+#endif
+      };
+        return &__policy_;
+    }
+
+    template <typename _Fun>
+    _LIBCPP_INLINE_VISIBILITY static const __policy*
+        __choose_policy(/* is_small = */ true_type)
+    {
+        static const _LIBCPP_CONSTEXPR __policy __policy_ = {
+            nullptr, nullptr, false,
+#ifndef _LIBCPP_NO_RTTI
+            &typeid(typename _Fun::_Target)
+#else
+            nullptr
+#endif
+        };
+        return &__policy_;
+    }
+};
+
+// Used to choose between perfect forwarding or pass-by-value. Pass-by-value is
+// faster for types that can be passed in registers.
+template <typename _Tp>
+using __fast_forward =
+    typename conditional<is_scalar<_Tp>::value, _Tp, _Tp&&>::type;
+
+// __policy_invoker calls an instance of __alloc_func held in __policy_storage.
+
+template <class _Fp> struct __policy_invoker;
+
+template <class _Rp, class... _ArgTypes>
+struct __policy_invoker<_Rp(_ArgTypes...)>
+{
+    typedef _Rp (*__Call)(const __policy_storage*,
+                          __fast_forward<_ArgTypes>...);
+
+    __Call __call_;
+
+    // Creates an invoker that throws bad_function_call.
+    _LIBCPP_INLINE_VISIBILITY
+    __policy_invoker() : __call_(&__call_empty) {}
+
+    // Creates an invoker that calls the given instance of __func.
+    template <typename _Fun>
+    _LIBCPP_INLINE_VISIBILITY static __policy_invoker __create()
+    {
+        return __policy_invoker(&__call_impl<_Fun>);
+    }
+
+  private:
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __policy_invoker(__Call __c) : __call_(__c) {}
+
+    static _Rp __call_empty(const __policy_storage*,
+                            __fast_forward<_ArgTypes>...)
+    {
+        __throw_bad_function_call();
+    }
+
+    template <typename _Fun>
+    static _Rp __call_impl(const __policy_storage* __buf,
+                           __fast_forward<_ArgTypes>... __args)
+    {
+        _Fun* __f = reinterpret_cast<_Fun*>(__use_small_storage<_Fun>::value
+                                                ? &__buf->__small
+                                                : __buf->__large);
+        return (*__f)(_VSTD::forward<_ArgTypes>(__args)...);
+    }
+};
+
+// __policy_func uses a __policy and __policy_invoker to create a type-erased,
+// copyable functor.
+
+template <class _Fp> class __policy_func;
+
+template <class _Rp, class... _ArgTypes> class __policy_func<_Rp(_ArgTypes...)>
+{
+    // Inline storage for small objects.
+    __policy_storage __buf_;
+
+    // Calls the value stored in __buf_. This could technically be part of
+    // policy, but storing it here eliminates a level of indirection inside
+    // operator().
+    typedef __function::__policy_invoker<_Rp(_ArgTypes...)> __invoker;
+    __invoker __invoker_;
+
+    // The policy that describes how to move / copy / destroy __buf_. Never
+    // null, even if the function is empty.
+    const __policy* __policy_;
+
+  public:
+    _LIBCPP_INLINE_VISIBILITY
+    __policy_func() : __policy_(__policy::__create_empty()) {}
+
+    template <class _Fp, class _Alloc>
+    _LIBCPP_INLINE_VISIBILITY __policy_func(_Fp&& __f, const _Alloc& __a)
+        : __policy_(__policy::__create_empty())
+    {
+        typedef __alloc_func<_Fp, _Alloc, _Rp(_ArgTypes...)> _Fun;
+        typedef allocator_traits<_Alloc> __alloc_traits;
+        typedef typename __rebind_alloc_helper<__alloc_traits, _Fun>::type
+            _FunAlloc;
+
+        if (__function::__not_null(__f))
+        {
+            __invoker_ = __invoker::template __create<_Fun>();
+            __policy_ = __policy::__create<_Fun>();
+
+            _FunAlloc __af(__a);
+            if (__use_small_storage<_Fun>())
+            {
+                ::new ((void*)&__buf_.__small)
+                    _Fun(_VSTD::move(__f), _Alloc(__af));
+            }
+            else
+            {
+                typedef __allocator_destructor<_FunAlloc> _Dp;
+                unique_ptr<_Fun, _Dp> __hold(__af.allocate(1), _Dp(__af, 1));
+                ::new ((void*)__hold.get())
+                    _Fun(_VSTD::move(__f), _Alloc(__af));
+                __buf_.__large = __hold.release();
+            }
+        }
+    }
+
+    template <class _Fp, class = typename enable_if<!is_same<typename decay<_Fp>::type, __policy_func>::value>::type>
+    _LIBCPP_INLINE_VISIBILITY explicit __policy_func(_Fp&& __f)
+        : __policy_(__policy::__create_empty()) {
+      typedef __default_alloc_func<_Fp, _Rp(_ArgTypes...)> _Fun;
+
+      if (__function::__not_null(__f)) {
+        __invoker_ = __invoker::template __create<_Fun>();
+        __policy_ = __policy::__create<_Fun>();
+        if (__use_small_storage<_Fun>()) {
+          ::new ((void*)&__buf_.__small) _Fun(_VSTD::move(__f));
+        } else {
+          __builtin_new_allocator::__holder_t __hold =
+              __builtin_new_allocator::__allocate_type<_Fun>(1);
+          __buf_.__large = ::new ((void*)__hold.get()) _Fun(_VSTD::move(__f));
+          (void)__hold.release();
+        }
+      }
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    __policy_func(const __policy_func& __f)
+        : __buf_(__f.__buf_), __invoker_(__f.__invoker_),
+          __policy_(__f.__policy_)
+    {
+        if (__policy_->__clone)
+            __buf_.__large = __policy_->__clone(__f.__buf_.__large);
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    __policy_func(__policy_func&& __f)
+        : __buf_(__f.__buf_), __invoker_(__f.__invoker_),
+          __policy_(__f.__policy_)
+    {
+        if (__policy_->__destroy)
+        {
+            __f.__policy_ = __policy::__create_empty();
+            __f.__invoker_ = __invoker();
+        }
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    ~__policy_func()
+    {
+        if (__policy_->__destroy)
+            __policy_->__destroy(__buf_.__large);
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    __policy_func& operator=(__policy_func&& __f)
+    {
+        *this = nullptr;
+        __buf_ = __f.__buf_;
+        __invoker_ = __f.__invoker_;
+        __policy_ = __f.__policy_;
+        __f.__policy_ = __policy::__create_empty();
+        __f.__invoker_ = __invoker();
+        return *this;
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    __policy_func& operator=(nullptr_t)
+    {
+        const __policy* __p = __policy_;
+        __policy_ = __policy::__create_empty();
+        __invoker_ = __invoker();
+        if (__p->__destroy)
+            __p->__destroy(__buf_.__large);
+        return *this;
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    _Rp operator()(_ArgTypes&&... __args) const
+    {
+        return __invoker_.__call_(_VSTD::addressof(__buf_),
+                                  _VSTD::forward<_ArgTypes>(__args)...);
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    void swap(__policy_func& __f)
+    {
+        _VSTD::swap(__invoker_, __f.__invoker_);
+        _VSTD::swap(__policy_, __f.__policy_);
+        _VSTD::swap(__buf_, __f.__buf_);
+    }
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit operator bool() const _NOEXCEPT
+    {
+        return !__policy_->__is_null;
+    }
+
+#ifndef _LIBCPP_NO_RTTI
+    _LIBCPP_INLINE_VISIBILITY
+    const std::type_info& target_type() const _NOEXCEPT
+    {
+        return *__policy_->__type_info;
+    }
+
+    template <typename _Tp>
+    _LIBCPP_INLINE_VISIBILITY const _Tp* target() const _NOEXCEPT
+    {
+        if (__policy_->__is_null || typeid(_Tp) != *__policy_->__type_info)
+            return nullptr;
+        if (__policy_->__clone) // Out of line storage.
+            return reinterpret_cast<const _Tp*>(__buf_.__large);
+        else
+            return reinterpret_cast<const _Tp*>(&__buf_.__small);
+    }
+#endif // _LIBCPP_NO_RTTI
+};
+
+#if defined(_LIBCPP_HAS_BLOCKS_RUNTIME) && !defined(_LIBCPP_HAS_OBJC_ARC)
+
+extern "C" void *_Block_copy(const void *);
+extern "C" void _Block_release(const void *);
+
+template<class _Rp1, class ..._ArgTypes1, class _Alloc, class _Rp, class ..._ArgTypes>
+class __func<_Rp1(^)(_ArgTypes1...), _Alloc, _Rp(_ArgTypes...)>
+    : public  __base<_Rp(_ArgTypes...)>
+{
+    typedef _Rp1(^__block_type)(_ArgTypes1...);
+    __block_type __f_;
+
+public:
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __func(__block_type const& __f)
+        : __f_(reinterpret_cast<__block_type>(__f ? _Block_copy(__f) : nullptr))
+    { }
+
+    // [TODO] add && to save on a retain
+
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __func(__block_type __f, const _Alloc& /* unused */)
+        : __f_(reinterpret_cast<__block_type>(__f ? _Block_copy(__f) : nullptr))
+    { }
+
+    virtual __base<_Rp(_ArgTypes...)>* __clone() const {
+        _LIBCPP_ASSERT(false,
+            "Block pointers are just pointers, so they should always fit into "
+            "std::function's small buffer optimization. This function should "
+            "never be invoked.");
+        return nullptr;
+    }
+
+    virtual void __clone(__base<_Rp(_ArgTypes...)>* __p) const {
+        ::new ((void*)__p) __func(__f_);
+    }
+
+    virtual void destroy() _NOEXCEPT {
+        if (__f_)
+            _Block_release(__f_);
+        __f_ = 0;
+    }
+
+    virtual void destroy_deallocate() _NOEXCEPT {
+        _LIBCPP_ASSERT(false,
+            "Block pointers are just pointers, so they should always fit into "
+            "std::function's small buffer optimization. This function should "
+            "never be invoked.");
+    }
+
+    virtual _Rp operator()(_ArgTypes&& ... __arg) {
+        return _VSTD::__invoke(__f_, _VSTD::forward<_ArgTypes>(__arg)...);
+    }
+
+#ifndef _LIBCPP_NO_RTTI
+    virtual const void* target(type_info const& __ti) const _NOEXCEPT {
+        if (__ti == typeid(__func::__block_type))
+            return &__f_;
+        return (const void*)nullptr;
+    }
+
+    virtual const std::type_info& target_type() const _NOEXCEPT {
+        return typeid(__func::__block_type);
+    }
+#endif // _LIBCPP_NO_RTTI
+};
+
+#endif // _LIBCPP_HAS_EXTENSION_BLOCKS && !_LIBCPP_HAS_OBJC_ARC
+
+}  // __function
+
+template<class _Rp, class ..._ArgTypes>
+class _LIBCPP_TEMPLATE_VIS function<_Rp(_ArgTypes...)>
+#if _LIBCPP_STD_VER <= 17 || !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public __function::__maybe_derive_from_unary_function<_Rp(_ArgTypes...)>,
+      public __function::__maybe_derive_from_binary_function<_Rp(_ArgTypes...)>
+#endif
+{
+#ifndef _LIBCPP_ABI_OPTIMIZED_FUNCTION
+    typedef __function::__value_func<_Rp(_ArgTypes...)> __func;
+#else
+    typedef __function::__policy_func<_Rp(_ArgTypes...)> __func;
+#endif
+
+    __func __f_;
+
+    template <class _Fp, bool = _And<
+        _IsNotSame<__uncvref_t<_Fp>, function>,
+        __invokable<_Fp, _ArgTypes...>
+    >::value>
+    struct __callable;
+    template <class _Fp>
+        struct __callable<_Fp, true>
+        {
+            static const bool value = is_void<_Rp>::value ||
+                __is_core_convertible<typename __invoke_of<_Fp, _ArgTypes...>::type,
+                                      _Rp>::value;
+        };
+    template <class _Fp>
+        struct __callable<_Fp, false>
+        {
+            static const bool value = false;
+        };
+
+  template <class _Fp>
+  using _EnableIfLValueCallable = typename enable_if<__callable<_Fp&>::value>::type;
+public:
+    typedef _Rp result_type;
+
+    // construct/copy/destroy:
+    _LIBCPP_INLINE_VISIBILITY
+    function() _NOEXCEPT { }
+    _LIBCPP_INLINE_VISIBILITY
+    function(nullptr_t) _NOEXCEPT {}
+    function(const function&);
+    function(function&&) _NOEXCEPT;
+    template<class _Fp, class = _EnableIfLValueCallable<_Fp>>
+    function(_Fp);
+
+#if _LIBCPP_STD_VER <= 14
+    template<class _Alloc>
+      _LIBCPP_INLINE_VISIBILITY
+      function(allocator_arg_t, const _Alloc&) _NOEXCEPT {}
+    template<class _Alloc>
+      _LIBCPP_INLINE_VISIBILITY
+      function(allocator_arg_t, const _Alloc&, nullptr_t) _NOEXCEPT {}
+    template<class _Alloc>
+      function(allocator_arg_t, const _Alloc&, const function&);
+    template<class _Alloc>
+      function(allocator_arg_t, const _Alloc&, function&&);
+    template<class _Fp, class _Alloc, class = _EnableIfLValueCallable<_Fp>>
+      function(allocator_arg_t, const _Alloc& __a, _Fp __f);
+#endif
+
+    function& operator=(const function&);
+    function& operator=(function&&) _NOEXCEPT;
+    function& operator=(nullptr_t) _NOEXCEPT;
+    template<class _Fp, class = _EnableIfLValueCallable<typename decay<_Fp>::type>>
+    function& operator=(_Fp&&);
+
+    ~function();
+
+    // function modifiers:
+    void swap(function&) _NOEXCEPT;
+
+#if _LIBCPP_STD_VER <= 14
+    template<class _Fp, class _Alloc>
+      _LIBCPP_INLINE_VISIBILITY
+      void assign(_Fp&& __f, const _Alloc& __a)
+        {function(allocator_arg, __a, _VSTD::forward<_Fp>(__f)).swap(*this);}
+#endif
+
+    // function capacity:
+    _LIBCPP_INLINE_VISIBILITY
+    explicit operator bool() const _NOEXCEPT {
+      return static_cast<bool>(__f_);
+    }
+
+    // deleted overloads close possible hole in the type system
+    template<class _R2, class... _ArgTypes2>
+      bool operator==(const function<_R2(_ArgTypes2...)>&) const = delete;
+    template<class _R2, class... _ArgTypes2>
+      bool operator!=(const function<_R2(_ArgTypes2...)>&) const = delete;
+public:
+    // function invocation:
+    _Rp operator()(_ArgTypes...) const;
+
+#ifndef _LIBCPP_NO_RTTI
+    // function target access:
+    const std::type_info& target_type() const _NOEXCEPT;
+    template <typename _Tp> _Tp* target() _NOEXCEPT;
+    template <typename _Tp> const _Tp* target() const _NOEXCEPT;
+#endif // _LIBCPP_NO_RTTI
+};
+
+#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
+template<class _Rp, class ..._Ap>
+function(_Rp(*)(_Ap...)) -> function<_Rp(_Ap...)>;
+
+template<class _Fp>
+struct __strip_signature;
+
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...)> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) const> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) volatile> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) const volatile> { using type = _Rp(_Ap...); };
+
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) &> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) const &> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) volatile &> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) const volatile &> { using type = _Rp(_Ap...); };
+
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) noexcept> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) const noexcept> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) volatile noexcept> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) const volatile noexcept> { using type = _Rp(_Ap...); };
+
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) & noexcept> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) const & noexcept> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) volatile & noexcept> { using type = _Rp(_Ap...); };
+template<class _Rp, class _Gp, class ..._Ap>
+struct __strip_signature<_Rp (_Gp::*) (_Ap...) const volatile & noexcept> { using type = _Rp(_Ap...); };
+
+template<class _Fp, class _Stripped = typename __strip_signature<decltype(&_Fp::operator())>::type>
+function(_Fp) -> function<_Stripped>;
+#endif // !_LIBCPP_HAS_NO_DEDUCTION_GUIDES
+
+template<class _Rp, class ..._ArgTypes>
+function<_Rp(_ArgTypes...)>::function(const function& __f) : __f_(__f.__f_) {}
+
+#if _LIBCPP_STD_VER <= 14
+template<class _Rp, class ..._ArgTypes>
+template <class _Alloc>
+function<_Rp(_ArgTypes...)>::function(allocator_arg_t, const _Alloc&,
+                                     const function& __f) : __f_(__f.__f_) {}
+#endif
+
+template <class _Rp, class... _ArgTypes>
+function<_Rp(_ArgTypes...)>::function(function&& __f) _NOEXCEPT
+    : __f_(_VSTD::move(__f.__f_)) {}
+
+#if _LIBCPP_STD_VER <= 14
+template<class _Rp, class ..._ArgTypes>
+template <class _Alloc>
+function<_Rp(_ArgTypes...)>::function(allocator_arg_t, const _Alloc&,
+                                      function&& __f)
+    : __f_(_VSTD::move(__f.__f_)) {}
+#endif
+
+template <class _Rp, class... _ArgTypes>
+template <class _Fp, class>
+function<_Rp(_ArgTypes...)>::function(_Fp __f) : __f_(_VSTD::move(__f)) {}
+
+#if _LIBCPP_STD_VER <= 14
+template <class _Rp, class... _ArgTypes>
+template <class _Fp, class _Alloc, class>
+function<_Rp(_ArgTypes...)>::function(allocator_arg_t, const _Alloc& __a,
+                                      _Fp __f)
+    : __f_(_VSTD::move(__f), __a) {}
+#endif
+
+template<class _Rp, class ..._ArgTypes>
+function<_Rp(_ArgTypes...)>&
+function<_Rp(_ArgTypes...)>::operator=(const function& __f)
+{
+    function(__f).swap(*this);
+    return *this;
+}
+
+template<class _Rp, class ..._ArgTypes>
+function<_Rp(_ArgTypes...)>&
+function<_Rp(_ArgTypes...)>::operator=(function&& __f) _NOEXCEPT
+{
+    __f_ = _VSTD::move(__f.__f_);
+    return *this;
+}
+
+template<class _Rp, class ..._ArgTypes>
+function<_Rp(_ArgTypes...)>&
+function<_Rp(_ArgTypes...)>::operator=(nullptr_t) _NOEXCEPT
+{
+    __f_ = nullptr;
+    return *this;
+}
+
+template<class _Rp, class ..._ArgTypes>
+template <class _Fp, class>
+function<_Rp(_ArgTypes...)>&
+function<_Rp(_ArgTypes...)>::operator=(_Fp&& __f)
+{
+    function(_VSTD::forward<_Fp>(__f)).swap(*this);
+    return *this;
+}
+
+template<class _Rp, class ..._ArgTypes>
+function<_Rp(_ArgTypes...)>::~function() {}
+
+template<class _Rp, class ..._ArgTypes>
+void
+function<_Rp(_ArgTypes...)>::swap(function& __f) _NOEXCEPT
+{
+    __f_.swap(__f.__f_);
+}
+
+template<class _Rp, class ..._ArgTypes>
+_Rp
+function<_Rp(_ArgTypes...)>::operator()(_ArgTypes... __arg) const
+{
+    return __f_(_VSTD::forward<_ArgTypes>(__arg)...);
+}
+
+#ifndef _LIBCPP_NO_RTTI
+
+template<class _Rp, class ..._ArgTypes>
+const std::type_info&
+function<_Rp(_ArgTypes...)>::target_type() const _NOEXCEPT
+{
+    return __f_.target_type();
+}
+
+template<class _Rp, class ..._ArgTypes>
+template <typename _Tp>
+_Tp*
+function<_Rp(_ArgTypes...)>::target() _NOEXCEPT
+{
+    return (_Tp*)(__f_.template target<_Tp>());
+}
+
+template<class _Rp, class ..._ArgTypes>
+template <typename _Tp>
+const _Tp*
+function<_Rp(_ArgTypes...)>::target() const _NOEXCEPT
+{
+    return __f_.template target<_Tp>();
+}
+
+#endif // _LIBCPP_NO_RTTI
+
+template <class _Rp, class... _ArgTypes>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator==(const function<_Rp(_ArgTypes...)>& __f, nullptr_t) _NOEXCEPT {return !__f;}
+
+template <class _Rp, class... _ArgTypes>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator==(nullptr_t, const function<_Rp(_ArgTypes...)>& __f) _NOEXCEPT {return !__f;}
+
+template <class _Rp, class... _ArgTypes>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(const function<_Rp(_ArgTypes...)>& __f, nullptr_t) _NOEXCEPT {return (bool)__f;}
+
+template <class _Rp, class... _ArgTypes>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(nullptr_t, const function<_Rp(_ArgTypes...)>& __f) _NOEXCEPT {return (bool)__f;}
+
+template <class _Rp, class... _ArgTypes>
+inline _LIBCPP_INLINE_VISIBILITY
+void
+swap(function<_Rp(_ArgTypes...)>& __x, function<_Rp(_ArgTypes...)>& __y) _NOEXCEPT
+{return __x.swap(__y);}
+
+#else // _LIBCPP_CXX03_LANG
+
 namespace __function {
 
 template<class _Fp> class __base;
@@ -36,7 +1250,7 @@ public:
 #ifndef _LIBCPP_NO_RTTI
     virtual const void* target(const type_info&) const = 0;
     virtual const std::type_info& target_type() const = 0;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Rp, class _A0>
@@ -55,7 +1269,7 @@ public:
 #ifndef _LIBCPP_NO_RTTI
     virtual const void* target(const type_info&) const = 0;
     virtual const std::type_info& target_type() const = 0;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Rp, class _A0, class _A1>
@@ -74,7 +1288,7 @@ public:
 #ifndef _LIBCPP_NO_RTTI
     virtual const void* target(const type_info&) const = 0;
     virtual const std::type_info& target_type() const = 0;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Rp, class _A0, class _A1, class _A2>
@@ -93,7 +1307,7 @@ public:
 #ifndef _LIBCPP_NO_RTTI
     virtual const void* target(const type_info&) const = 0;
     virtual const std::type_info& target_type() const = 0;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _FD, class _Alloc, class _FB> class __func;
@@ -114,7 +1328,7 @@ public:
 #ifndef _LIBCPP_NO_RTTI
     virtual const void* target(const type_info&) const;
     virtual const std::type_info& target_type() const;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Fp, class _Alloc, class _Rp>
@@ -181,7 +1395,7 @@ __func<_Fp, _Alloc, _Rp()>::target_type() const
     return typeid(_Fp);
 }
 
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 
 template<class _Fp, class _Alloc, class _Rp, class _A0>
 class __func<_Fp, _Alloc, _Rp(_A0)>
@@ -200,7 +1414,7 @@ public:
 #ifndef _LIBCPP_NO_RTTI
     virtual const void* target(const type_info&) const;
     virtual const std::type_info& target_type() const;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Fp, class _Alloc, class _Rp, class _A0>
@@ -267,7 +1481,7 @@ __func<_Fp, _Alloc, _Rp(_A0)>::target_type() const
     return typeid(_Fp);
 }
 
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 
 template<class _Fp, class _Alloc, class _Rp, class _A0, class _A1>
 class __func<_Fp, _Alloc, _Rp(_A0, _A1)>
@@ -286,7 +1500,7 @@ public:
 #ifndef _LIBCPP_NO_RTTI
     virtual const void* target(const type_info&) const;
     virtual const std::type_info& target_type() const;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Fp, class _Alloc, class _Rp, class _A0, class _A1>
@@ -353,7 +1567,7 @@ __func<_Fp, _Alloc, _Rp(_A0, _A1)>::target_type() const
     return typeid(_Fp);
 }
 
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 
 template<class _Fp, class _Alloc, class _Rp, class _A0, class _A1, class _A2>
 class __func<_Fp, _Alloc, _Rp(_A0, _A1, _A2)>
@@ -372,7 +1586,7 @@ public:
 #ifndef _LIBCPP_NO_RTTI
     virtual const void* target(const type_info&) const;
     virtual const std::type_info& target_type() const;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Fp, class _Alloc, class _Rp, class _A0, class _A1, class _A2>
@@ -439,7 +1653,7 @@ __func<_Fp, _Alloc, _Rp(_A0, _A1, _A2)>::target_type() const
     return typeid(_Fp);
 }
 
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 
 }  // __function
 
@@ -493,7 +1707,7 @@ public:
         {function(allocator_arg, __a, __f).swap(*this);}
 
     // 20.7.16.2.3, function capacity:
-    _LIBCPP_INLINE_VISIBILITY operator bool() const {return __f_;}
+    _LIBCPP_INLINE_VISIBILITY explicit operator bool() const {return __f_;}
 
 private:
     // deleted overloads close possible hole in the type system
@@ -510,7 +1724,7 @@ public:
     const std::type_info& target_type() const;
     template <typename _Tp> _Tp* target();
     template <typename _Tp> const _Tp* target() const;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Rp>
@@ -720,7 +1934,7 @@ function<_Rp()>::target() const
     return (const _Tp*)__f_->target(typeid(_Tp));
 }
 
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 
 template<class _Rp, class _A0>
 class _LIBCPP_TEMPLATE_VIS function<_Rp(_A0)>
@@ -773,7 +1987,7 @@ public:
         {function(allocator_arg, __a, __f).swap(*this);}
 
     // 20.7.16.2.3, function capacity:
-    _LIBCPP_INLINE_VISIBILITY operator bool() const {return __f_;}
+    _LIBCPP_INLINE_VISIBILITY explicit operator bool() const {return __f_;}
 
 private:
     // deleted overloads close possible hole in the type system
@@ -790,7 +2004,7 @@ public:
     const std::type_info& target_type() const;
     template <typename _Tp> _Tp* target();
     template <typename _Tp> const _Tp* target() const;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Rp, class _A0>
@@ -1000,7 +2214,7 @@ function<_Rp(_A0)>::target() const
     return (const _Tp*)__f_->target(typeid(_Tp));
 }
 
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 
 template<class _Rp, class _A0, class _A1>
 class _LIBCPP_TEMPLATE_VIS function<_Rp(_A0, _A1)>
@@ -1053,7 +2267,7 @@ public:
         {function(allocator_arg, __a, __f).swap(*this);}
 
     // 20.7.16.2.3, function capacity:
-    operator bool() const {return __f_;}
+    _LIBCPP_INLINE_VISIBILITY explicit operator bool() const {return __f_;}
 
 private:
     // deleted overloads close possible hole in the type system
@@ -1070,7 +2284,7 @@ public:
     const std::type_info& target_type() const;
     template <typename _Tp> _Tp* target();
     template <typename _Tp> const _Tp* target() const;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Rp, class _A0, class _A1>
@@ -1280,7 +2494,7 @@ function<_Rp(_A0, _A1)>::target() const
     return (const _Tp*)__f_->target(typeid(_Tp));
 }
 
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 
 template<class _Rp, class _A0, class _A1, class _A2>
 class _LIBCPP_TEMPLATE_VIS function<_Rp(_A0, _A1, _A2)>
@@ -1332,7 +2546,7 @@ public:
         {function(allocator_arg, __a, __f).swap(*this);}
 
     // 20.7.16.2.3, function capacity:
-    _LIBCPP_INLINE_VISIBILITY operator bool() const {return __f_;}
+    _LIBCPP_INLINE_VISIBILITY explicit operator bool() const {return __f_;}
 
 private:
     // deleted overloads close possible hole in the type system
@@ -1349,7 +2563,7 @@ public:
     const std::type_info& target_type() const;
     template <typename _Tp> _Tp* target();
     template <typename _Tp> const _Tp* target() const;
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 };
 
 template<class _Rp, class _A0, class _A1, class _A2>
@@ -1560,7 +2774,7 @@ function<_Rp(_A0, _A1, _A2)>::target() const
     return (const _Tp*)__f_->target(typeid(_Tp));
 }
 
-#endif  // _LIBCPP_NO_RTTI
+#endif // _LIBCPP_NO_RTTI
 
 template <class _Fp>
 inline _LIBCPP_INLINE_VISIBILITY
@@ -1588,4 +2802,8 @@ void
 swap(function<_Fp>& __x, function<_Fp>& __y)
 {return __x.swap(__y);}
 
-#endif  // _LIBCPP_FUNCTIONAL_03
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_FUNCTION_H
lib/libcxx/include/__functional/hash.h
@@ -0,0 +1,873 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_HASH_H
+#define _LIBCPP___FUNCTIONAL_HASH_H
+
+#include <__config>
+#include <__functional/unary_function.h>
+#include <__tuple>
+#include <__utility/forward.h>
+#include <__utility/move.h>
+#include <__utility/pair.h>
+#include <__utility/swap.h>
+#include <cstdint>
+#include <cstring>
+#include <cstddef>
+#include <limits>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Size>
+inline _LIBCPP_INLINE_VISIBILITY
+_Size
+__loadword(const void* __p)
+{
+    _Size __r;
+    _VSTD::memcpy(&__r, __p, sizeof(__r));
+    return __r;
+}
+
+// We use murmur2 when size_t is 32 bits, and cityhash64 when size_t
+// is 64 bits.  This is because cityhash64 uses 64bit x 64bit
+// multiplication, which can be very slow on 32-bit systems.
+template <class _Size, size_t = sizeof(_Size)*__CHAR_BIT__>
+struct __murmur2_or_cityhash;
+
+template <class _Size>
+struct __murmur2_or_cityhash<_Size, 32>
+{
+    inline _Size operator()(const void* __key, _Size __len)
+         _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK;
+};
+
+// murmur2
+template <class _Size>
+_Size
+__murmur2_or_cityhash<_Size, 32>::operator()(const void* __key, _Size __len)
+{
+    const _Size __m = 0x5bd1e995;
+    const _Size __r = 24;
+    _Size __h = __len;
+    const unsigned char* __data = static_cast<const unsigned char*>(__key);
+    for (; __len >= 4; __data += 4, __len -= 4)
+    {
+        _Size __k = __loadword<_Size>(__data);
+        __k *= __m;
+        __k ^= __k >> __r;
+        __k *= __m;
+        __h *= __m;
+        __h ^= __k;
+    }
+    switch (__len)
+    {
+    case 3:
+        __h ^= static_cast<_Size>(__data[2] << 16);
+        _LIBCPP_FALLTHROUGH();
+    case 2:
+        __h ^= static_cast<_Size>(__data[1] << 8);
+        _LIBCPP_FALLTHROUGH();
+    case 1:
+        __h ^= __data[0];
+        __h *= __m;
+    }
+    __h ^= __h >> 13;
+    __h *= __m;
+    __h ^= __h >> 15;
+    return __h;
+}
+
+template <class _Size>
+struct __murmur2_or_cityhash<_Size, 64>
+{
+    inline _Size operator()(const void* __key, _Size __len)  _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK;
+
+ private:
+  // Some primes between 2^63 and 2^64.
+  static const _Size __k0 = 0xc3a5c85c97cb3127ULL;
+  static const _Size __k1 = 0xb492b66fbe98f273ULL;
+  static const _Size __k2 = 0x9ae16a3b2f90404fULL;
+  static const _Size __k3 = 0xc949d7c7509e6557ULL;
+
+  static _Size __rotate(_Size __val, int __shift) {
+    return __shift == 0 ? __val : ((__val >> __shift) | (__val << (64 - __shift)));
+  }
+
+  static _Size __rotate_by_at_least_1(_Size __val, int __shift) {
+    return (__val >> __shift) | (__val << (64 - __shift));
+  }
+
+  static _Size __shift_mix(_Size __val) {
+    return __val ^ (__val >> 47);
+  }
+
+  static _Size __hash_len_16(_Size __u, _Size __v)
+     _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
+  {
+    const _Size __mul = 0x9ddfea08eb382d69ULL;
+    _Size __a = (__u ^ __v) * __mul;
+    __a ^= (__a >> 47);
+    _Size __b = (__v ^ __a) * __mul;
+    __b ^= (__b >> 47);
+    __b *= __mul;
+    return __b;
+  }
+
+  static _Size __hash_len_0_to_16(const char* __s, _Size __len)
+     _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
+  {
+    if (__len > 8) {
+      const _Size __a = __loadword<_Size>(__s);
+      const _Size __b = __loadword<_Size>(__s + __len - 8);
+      return __hash_len_16(__a, __rotate_by_at_least_1(__b + __len, __len)) ^ __b;
+    }
+    if (__len >= 4) {
+      const uint32_t __a = __loadword<uint32_t>(__s);
+      const uint32_t __b = __loadword<uint32_t>(__s + __len - 4);
+      return __hash_len_16(__len + (__a << 3), __b);
+    }
+    if (__len > 0) {
+      const unsigned char __a = static_cast<unsigned char>(__s[0]);
+      const unsigned char __b = static_cast<unsigned char>(__s[__len >> 1]);
+      const unsigned char __c = static_cast<unsigned char>(__s[__len - 1]);
+      const uint32_t __y = static_cast<uint32_t>(__a) +
+                           (static_cast<uint32_t>(__b) << 8);
+      const uint32_t __z = __len + (static_cast<uint32_t>(__c) << 2);
+      return __shift_mix(__y * __k2 ^ __z * __k3) * __k2;
+    }
+    return __k2;
+  }
+
+  static _Size __hash_len_17_to_32(const char *__s, _Size __len)
+     _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
+  {
+    const _Size __a = __loadword<_Size>(__s) * __k1;
+    const _Size __b = __loadword<_Size>(__s + 8);
+    const _Size __c = __loadword<_Size>(__s + __len - 8) * __k2;
+    const _Size __d = __loadword<_Size>(__s + __len - 16) * __k0;
+    return __hash_len_16(__rotate(__a - __b, 43) + __rotate(__c, 30) + __d,
+                         __a + __rotate(__b ^ __k3, 20) - __c + __len);
+  }
+
+  // Return a 16-byte hash for 48 bytes.  Quick and dirty.
+  // Callers do best to use "random-looking" values for a and b.
+  static pair<_Size, _Size> __weak_hash_len_32_with_seeds(
+      _Size __w, _Size __x, _Size __y, _Size __z, _Size __a, _Size __b)
+        _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
+  {
+    __a += __w;
+    __b = __rotate(__b + __a + __z, 21);
+    const _Size __c = __a;
+    __a += __x;
+    __a += __y;
+    __b += __rotate(__a, 44);
+    return pair<_Size, _Size>(__a + __z, __b + __c);
+  }
+
+  // Return a 16-byte hash for s[0] ... s[31], a, and b.  Quick and dirty.
+  static pair<_Size, _Size> __weak_hash_len_32_with_seeds(
+      const char* __s, _Size __a, _Size __b)
+    _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
+  {
+    return __weak_hash_len_32_with_seeds(__loadword<_Size>(__s),
+                                         __loadword<_Size>(__s + 8),
+                                         __loadword<_Size>(__s + 16),
+                                         __loadword<_Size>(__s + 24),
+                                         __a,
+                                         __b);
+  }
+
+  // Return an 8-byte hash for 33 to 64 bytes.
+  static _Size __hash_len_33_to_64(const char *__s, size_t __len)
+    _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
+  {
+    _Size __z = __loadword<_Size>(__s + 24);
+    _Size __a = __loadword<_Size>(__s) +
+                (__len + __loadword<_Size>(__s + __len - 16)) * __k0;
+    _Size __b = __rotate(__a + __z, 52);
+    _Size __c = __rotate(__a, 37);
+    __a += __loadword<_Size>(__s + 8);
+    __c += __rotate(__a, 7);
+    __a += __loadword<_Size>(__s + 16);
+    _Size __vf = __a + __z;
+    _Size __vs = __b + __rotate(__a, 31) + __c;
+    __a = __loadword<_Size>(__s + 16) + __loadword<_Size>(__s + __len - 32);
+    __z += __loadword<_Size>(__s + __len - 8);
+    __b = __rotate(__a + __z, 52);
+    __c = __rotate(__a, 37);
+    __a += __loadword<_Size>(__s + __len - 24);
+    __c += __rotate(__a, 7);
+    __a += __loadword<_Size>(__s + __len - 16);
+    _Size __wf = __a + __z;
+    _Size __ws = __b + __rotate(__a, 31) + __c;
+    _Size __r = __shift_mix((__vf + __ws) * __k2 + (__wf + __vs) * __k0);
+    return __shift_mix(__r * __k0 + __vs) * __k2;
+  }
+};
+
+// cityhash64
+template <class _Size>
+_Size
+__murmur2_or_cityhash<_Size, 64>::operator()(const void* __key, _Size __len)
+{
+  const char* __s = static_cast<const char*>(__key);
+  if (__len <= 32) {
+    if (__len <= 16) {
+      return __hash_len_0_to_16(__s, __len);
+    } else {
+      return __hash_len_17_to_32(__s, __len);
+    }
+  } else if (__len <= 64) {
+    return __hash_len_33_to_64(__s, __len);
+  }
+
+  // For strings over 64 bytes we hash the end first, and then as we
+  // loop we keep 56 bytes of state: v, w, x, y, and z.
+  _Size __x = __loadword<_Size>(__s + __len - 40);
+  _Size __y = __loadword<_Size>(__s + __len - 16) +
+              __loadword<_Size>(__s + __len - 56);
+  _Size __z = __hash_len_16(__loadword<_Size>(__s + __len - 48) + __len,
+                          __loadword<_Size>(__s + __len - 24));
+  pair<_Size, _Size> __v = __weak_hash_len_32_with_seeds(__s + __len - 64, __len, __z);
+  pair<_Size, _Size> __w = __weak_hash_len_32_with_seeds(__s + __len - 32, __y + __k1, __x);
+  __x = __x * __k1 + __loadword<_Size>(__s);
+
+  // Decrease len to the nearest multiple of 64, and operate on 64-byte chunks.
+  __len = (__len - 1) & ~static_cast<_Size>(63);
+  do {
+    __x = __rotate(__x + __y + __v.first + __loadword<_Size>(__s + 8), 37) * __k1;
+    __y = __rotate(__y + __v.second + __loadword<_Size>(__s + 48), 42) * __k1;
+    __x ^= __w.second;
+    __y += __v.first + __loadword<_Size>(__s + 40);
+    __z = __rotate(__z + __w.first, 33) * __k1;
+    __v = __weak_hash_len_32_with_seeds(__s, __v.second * __k1, __x + __w.first);
+    __w = __weak_hash_len_32_with_seeds(__s + 32, __z + __w.second,
+                                        __y + __loadword<_Size>(__s + 16));
+    _VSTD::swap(__z, __x);
+    __s += 64;
+    __len -= 64;
+  } while (__len != 0);
+  return __hash_len_16(
+      __hash_len_16(__v.first, __w.first) + __shift_mix(__y) * __k1 + __z,
+      __hash_len_16(__v.second, __w.second) + __x);
+}
+
+template <class _Tp, size_t = sizeof(_Tp) / sizeof(size_t)>
+struct __scalar_hash;
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp>
+struct __scalar_hash<_Tp, 0>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<_Tp, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(_Tp __v) const _NOEXCEPT
+    {
+        union
+        {
+            _Tp    __t;
+            size_t __a;
+        } __u;
+        __u.__a = 0;
+        __u.__t = __v;
+        return __u.__a;
+    }
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp>
+struct __scalar_hash<_Tp, 1>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<_Tp, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(_Tp __v) const _NOEXCEPT
+    {
+        union
+        {
+            _Tp    __t;
+            size_t __a;
+        } __u;
+        __u.__t = __v;
+        return __u.__a;
+    }
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp>
+struct __scalar_hash<_Tp, 2>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<_Tp, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(_Tp __v) const _NOEXCEPT
+    {
+        union
+        {
+            _Tp __t;
+            struct
+            {
+                size_t __a;
+                size_t __b;
+            } __s;
+        } __u;
+        __u.__t = __v;
+        return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u));
+    }
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp>
+struct __scalar_hash<_Tp, 3>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<_Tp, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(_Tp __v) const _NOEXCEPT
+    {
+        union
+        {
+            _Tp __t;
+            struct
+            {
+                size_t __a;
+                size_t __b;
+                size_t __c;
+            } __s;
+        } __u;
+        __u.__t = __v;
+        return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u));
+    }
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp>
+struct __scalar_hash<_Tp, 4>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<_Tp, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(_Tp __v) const _NOEXCEPT
+    {
+        union
+        {
+            _Tp __t;
+            struct
+            {
+                size_t __a;
+                size_t __b;
+                size_t __c;
+                size_t __d;
+            } __s;
+        } __u;
+        __u.__t = __v;
+        return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u));
+    }
+};
+
+struct _PairT {
+  size_t first;
+  size_t second;
+};
+
+_LIBCPP_INLINE_VISIBILITY
+inline size_t __hash_combine(size_t __lhs, size_t __rhs) _NOEXCEPT {
+    typedef __scalar_hash<_PairT> _HashT;
+    const _PairT __p = {__lhs, __rhs};
+    return _HashT()(__p);
+}
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template<class _Tp>
+struct _LIBCPP_TEMPLATE_VIS hash<_Tp*>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<_Tp*, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp* argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(_Tp* __v) const _NOEXCEPT
+    {
+        union
+        {
+            _Tp* __t;
+            size_t __a;
+        } __u;
+        __u.__t = __v;
+        return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u));
+    }
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<bool>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<bool, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(bool __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<char>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<char, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef char argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(char __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<signed char>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<signed char, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef signed char argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(signed char __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<unsigned char>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<unsigned char, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef unsigned char argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(unsigned char __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<char8_t>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<char8_t, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef char8_t argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(char8_t __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+#endif // !_LIBCPP_HAS_NO_CHAR8_T
+
+#ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<char16_t>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<char16_t, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef char16_t argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(char16_t __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<char32_t>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<char32_t, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef char32_t argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(char32_t __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<wchar_t>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<wchar_t, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef wchar_t argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(wchar_t __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<short>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<short, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef short argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(short __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<unsigned short>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<unsigned short, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef unsigned short argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(unsigned short __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<int>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<int, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef int argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(int __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<unsigned int>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<unsigned int, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef unsigned int argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(unsigned int __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<long>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<long, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef long argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(long __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<unsigned long>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<unsigned long, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef unsigned long argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(unsigned long __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
+};
+
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<long long>
+    : public __scalar_hash<long long>
+{
+};
+
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<unsigned long long>
+    : public __scalar_hash<unsigned long long>
+{
+};
+
+#ifndef _LIBCPP_HAS_NO_INT128
+
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<__int128_t>
+    : public __scalar_hash<__int128_t>
+{
+};
+
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<__uint128_t>
+    : public __scalar_hash<__uint128_t>
+{
+};
+
+#endif
+
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<float>
+    : public __scalar_hash<float>
+{
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(float __v) const _NOEXCEPT
+    {
+        // -0.0 and 0.0 should return same hash
+       if (__v == 0.0f)
+           return 0;
+        return __scalar_hash<float>::operator()(__v);
+    }
+};
+
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<double>
+    : public __scalar_hash<double>
+{
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(double __v) const _NOEXCEPT
+    {
+        // -0.0 and 0.0 should return same hash
+       if (__v == 0.0)
+           return 0;
+        return __scalar_hash<double>::operator()(__v);
+    }
+};
+
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<long double>
+    : public __scalar_hash<long double>
+{
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(long double __v) const _NOEXCEPT
+    {
+        // -0.0 and 0.0 should return same hash
+        if (__v == 0.0L)
+            return 0;
+#if defined(__i386__) || (defined(__x86_64__) && defined(__ILP32__))
+        // Zero out padding bits
+        union
+        {
+            long double __t;
+            struct
+            {
+                size_t __a;
+                size_t __b;
+                size_t __c;
+                size_t __d;
+            } __s;
+        } __u;
+        __u.__s.__a = 0;
+        __u.__s.__b = 0;
+        __u.__s.__c = 0;
+        __u.__s.__d = 0;
+        __u.__t = __v;
+        return __u.__s.__a ^ __u.__s.__b ^ __u.__s.__c ^ __u.__s.__d;
+#elif defined(__x86_64__)
+        // Zero out padding bits
+        union
+        {
+            long double __t;
+            struct
+            {
+                size_t __a;
+                size_t __b;
+            } __s;
+        } __u;
+        __u.__s.__a = 0;
+        __u.__s.__b = 0;
+        __u.__t = __v;
+        return __u.__s.__a ^ __u.__s.__b;
+#else
+        return __scalar_hash<long double>::operator()(__v);
+#endif
+    }
+};
+
+#if _LIBCPP_STD_VER > 11
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp, bool = is_enum<_Tp>::value>
+struct _LIBCPP_TEMPLATE_VIS __enum_hash
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public unary_function<_Tp, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(_Tp __v) const _NOEXCEPT
+    {
+        typedef typename underlying_type<_Tp>::type type;
+        return hash<type>{}(static_cast<type>(__v));
+    }
+};
+template <class _Tp>
+struct _LIBCPP_TEMPLATE_VIS __enum_hash<_Tp, false> {
+    __enum_hash() = delete;
+    __enum_hash(__enum_hash const&) = delete;
+    __enum_hash& operator=(__enum_hash const&) = delete;
+};
+
+template <class _Tp>
+struct _LIBCPP_TEMPLATE_VIS hash : public __enum_hash<_Tp>
+{
+};
+#endif
+
+#if _LIBCPP_STD_VER > 14
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<nullptr_t>
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+  : public unary_function<nullptr_t, size_t>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef nullptr_t argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(nullptr_t) const _NOEXCEPT {
+        return 662607004ull;
+    }
+};
+#endif
+
+#ifndef _LIBCPP_CXX03_LANG
+template <class _Key, class _Hash>
+using __check_hash_requirements _LIBCPP_NODEBUG_TYPE  = integral_constant<bool,
+    is_copy_constructible<_Hash>::value &&
+    is_move_constructible<_Hash>::value &&
+    __invokable_r<size_t, _Hash, _Key const&>::value
+>;
+
+template <class _Key, class _Hash = hash<_Key> >
+using __has_enabled_hash _LIBCPP_NODEBUG_TYPE = integral_constant<bool,
+    __check_hash_requirements<_Key, _Hash>::value &&
+    is_default_constructible<_Hash>::value
+>;
+
+#if _LIBCPP_STD_VER > 14
+template <class _Type, class>
+using __enable_hash_helper_imp _LIBCPP_NODEBUG_TYPE  = _Type;
+
+template <class _Type, class ..._Keys>
+using __enable_hash_helper _LIBCPP_NODEBUG_TYPE  = __enable_hash_helper_imp<_Type,
+  typename enable_if<__all<__has_enabled_hash<_Keys>::value...>::value>::type
+>;
+#else
+template <class _Type, class ...>
+using __enable_hash_helper _LIBCPP_NODEBUG_TYPE = _Type;
+#endif
+
+#endif // !_LIBCPP_CXX03_LANG
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___FUNCTIONAL_HASH_H
lib/libcxx/include/__functional/identity.h
@@ -0,0 +1,37 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_IDENTITY_H
+#define _LIBCPP___FUNCTIONAL_IDENTITY_H
+
+#include <__config>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17
+
+struct identity {
+    template<class _Tp>
+    _LIBCPP_NODISCARD_EXT constexpr _Tp&& operator()(_Tp&& __t) const noexcept
+    {
+        return _VSTD::forward<_Tp>(__t);
+    }
+
+    using is_transparent = void;
+};
+#endif // _LIBCPP_STD_VER > 17
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_IDENTITY_H
lib/libcxx/include/__functional/invoke.h
@@ -0,0 +1,100 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_INVOKE_H
+#define _LIBCPP___FUNCTIONAL_INVOKE_H
+
+#include <__config>
+#include <__functional/weak_result_type.h>
+#include <__utility/forward.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Ret, bool = is_void<_Ret>::value>
+struct __invoke_void_return_wrapper
+{
+#ifndef _LIBCPP_CXX03_LANG
+    template <class ..._Args>
+    static _Ret __call(_Args&&... __args) {
+        return _VSTD::__invoke(_VSTD::forward<_Args>(__args)...);
+    }
+#else
+    template <class _Fn>
+    static _Ret __call(_Fn __f) {
+        return _VSTD::__invoke(__f);
+    }
+
+    template <class _Fn, class _A0>
+    static _Ret __call(_Fn __f, _A0& __a0) {
+        return _VSTD::__invoke(__f, __a0);
+    }
+
+    template <class _Fn, class _A0, class _A1>
+    static _Ret __call(_Fn __f, _A0& __a0, _A1& __a1) {
+        return _VSTD::__invoke(__f, __a0, __a1);
+    }
+
+    template <class _Fn, class _A0, class _A1, class _A2>
+    static _Ret __call(_Fn __f, _A0& __a0, _A1& __a1, _A2& __a2){
+        return _VSTD::__invoke(__f, __a0, __a1, __a2);
+    }
+#endif
+};
+
+template <class _Ret>
+struct __invoke_void_return_wrapper<_Ret, true>
+{
+#ifndef _LIBCPP_CXX03_LANG
+    template <class ..._Args>
+    static void __call(_Args&&... __args) {
+        _VSTD::__invoke(_VSTD::forward<_Args>(__args)...);
+    }
+#else
+    template <class _Fn>
+    static void __call(_Fn __f) {
+        _VSTD::__invoke(__f);
+    }
+
+    template <class _Fn, class _A0>
+    static void __call(_Fn __f, _A0& __a0) {
+        _VSTD::__invoke(__f, __a0);
+    }
+
+    template <class _Fn, class _A0, class _A1>
+    static void __call(_Fn __f, _A0& __a0, _A1& __a1) {
+        _VSTD::__invoke(__f, __a0, __a1);
+    }
+
+    template <class _Fn, class _A0, class _A1, class _A2>
+    static void __call(_Fn __f, _A0& __a0, _A1& __a1, _A2& __a2) {
+        _VSTD::__invoke(__f, __a0, __a1, __a2);
+    }
+#endif
+};
+
+#if _LIBCPP_STD_VER > 14
+
+template <class _Fn, class ..._Args>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 invoke_result_t<_Fn, _Args...>
+invoke(_Fn&& __f, _Args&&... __args)
+    noexcept(is_nothrow_invocable_v<_Fn, _Args...>)
+{
+    return _VSTD::__invoke(_VSTD::forward<_Fn>(__f), _VSTD::forward<_Args>(__args)...);
+}
+
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_INVOKE_H
lib/libcxx/include/__functional/is_transparent.h
@@ -0,0 +1,36 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_IS_TRANSPARENT
+#define _LIBCPP___FUNCTIONAL_IS_TRANSPARENT
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 11
+
+template <class _Tp, class, class = void>
+struct __is_transparent : false_type {};
+
+template <class _Tp, class _Up>
+struct __is_transparent<_Tp, _Up,
+                        typename __void_t<typename _Tp::is_transparent>::type>
+   : true_type {};
+
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_IS_TRANSPARENT
lib/libcxx/include/__functional/mem_fn.h
@@ -0,0 +1,161 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_MEM_FN_H
+#define _LIBCPP___FUNCTIONAL_MEM_FN_H
+
+#include <__config>
+#include <__functional/weak_result_type.h>
+#include <__functional/binary_function.h>
+#include <__functional/invoke.h>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+class __mem_fn
+#if _LIBCPP_STD_VER <= 17 || !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public __weak_result_type<_Tp>
+#endif
+{
+public:
+    // types
+    typedef _Tp type;
+private:
+    type __f_;
+
+public:
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    __mem_fn(type __f) _NOEXCEPT : __f_(__f) {}
+
+#ifndef _LIBCPP_CXX03_LANG
+    // invoke
+    template <class... _ArgTypes>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    typename __invoke_return<type, _ArgTypes...>::type
+    operator() (_ArgTypes&&... __args) const {
+        return _VSTD::__invoke(__f_, _VSTD::forward<_ArgTypes>(__args)...);
+    }
+#else
+
+    template <class _A0>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return0<type, _A0>::type
+    operator() (_A0& __a0) const {
+        return _VSTD::__invoke(__f_, __a0);
+    }
+
+    template <class _A0>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return0<type, _A0 const>::type
+    operator() (_A0 const& __a0) const {
+        return _VSTD::__invoke(__f_, __a0);
+    }
+
+    template <class _A0, class _A1>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return1<type, _A0, _A1>::type
+    operator() (_A0& __a0, _A1& __a1) const {
+        return _VSTD::__invoke(__f_, __a0, __a1);
+    }
+
+    template <class _A0, class _A1>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return1<type, _A0 const, _A1>::type
+    operator() (_A0 const& __a0, _A1& __a1) const {
+        return _VSTD::__invoke(__f_, __a0, __a1);
+    }
+
+    template <class _A0, class _A1>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return1<type, _A0, _A1 const>::type
+    operator() (_A0& __a0, _A1 const& __a1) const {
+        return _VSTD::__invoke(__f_, __a0, __a1);
+    }
+
+    template <class _A0, class _A1>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return1<type, _A0 const, _A1 const>::type
+    operator() (_A0 const& __a0, _A1 const& __a1) const {
+        return _VSTD::__invoke(__f_, __a0, __a1);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0, _A1, _A2>::type
+    operator() (_A0& __a0, _A1& __a1, _A2& __a2) const {
+        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0 const, _A1, _A2>::type
+    operator() (_A0 const& __a0, _A1& __a1, _A2& __a2) const {
+        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0, _A1 const, _A2>::type
+    operator() (_A0& __a0, _A1 const& __a1, _A2& __a2) const {
+        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0, _A1, _A2 const>::type
+    operator() (_A0& __a0, _A1& __a1, _A2 const& __a2) const {
+        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0 const, _A1 const, _A2>::type
+    operator() (_A0 const& __a0, _A1 const& __a1, _A2& __a2) const {
+        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0 const, _A1, _A2 const>::type
+    operator() (_A0 const& __a0, _A1& __a1, _A2 const& __a2) const {
+        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0, _A1 const, _A2 const>::type
+    operator() (_A0& __a0, _A1 const& __a1, _A2 const& __a2) const {
+        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0 const, _A1 const, _A2 const>::type
+    operator() (_A0 const& __a0, _A1 const& __a1, _A2 const& __a2) const {
+        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
+    }
+#endif
+};
+
+template<class _Rp, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+__mem_fn<_Rp _Tp::*>
+mem_fn(_Rp _Tp::* __pm) _NOEXCEPT
+{
+    return __mem_fn<_Rp _Tp::*>(__pm);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_MEM_FN_H
lib/libcxx/include/__functional/mem_fun_ref.h
@@ -0,0 +1,173 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_MEM_FUN_REF_H
+#define _LIBCPP___FUNCTIONAL_MEM_FUN_REF_H
+
+#include <__config>
+#include <__functional/unary_function.h>
+#include <__functional/binary_function.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
+
+template<class _Sp, class _Tp>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 mem_fun_t
+    : public unary_function<_Tp*, _Sp>
+{
+    _Sp (_Tp::*__p_)();
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit mem_fun_t(_Sp (_Tp::*__p)())
+        : __p_(__p) {}
+    _LIBCPP_INLINE_VISIBILITY _Sp operator()(_Tp* __p) const
+        {return (__p->*__p_)();}
+};
+
+template<class _Sp, class _Tp, class _Ap>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 mem_fun1_t
+    : public binary_function<_Tp*, _Ap, _Sp>
+{
+    _Sp (_Tp::*__p_)(_Ap);
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit mem_fun1_t(_Sp (_Tp::*__p)(_Ap))
+        : __p_(__p) {}
+    _LIBCPP_INLINE_VISIBILITY _Sp operator()(_Tp* __p, _Ap __x) const
+        {return (__p->*__p_)(__x);}
+};
+
+template<class _Sp, class _Tp>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+mem_fun_t<_Sp,_Tp>
+mem_fun(_Sp (_Tp::*__f)())
+    {return mem_fun_t<_Sp,_Tp>(__f);}
+
+template<class _Sp, class _Tp, class _Ap>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+mem_fun1_t<_Sp,_Tp,_Ap>
+mem_fun(_Sp (_Tp::*__f)(_Ap))
+    {return mem_fun1_t<_Sp,_Tp,_Ap>(__f);}
+
+template<class _Sp, class _Tp>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 mem_fun_ref_t
+    : public unary_function<_Tp, _Sp>
+{
+    _Sp (_Tp::*__p_)();
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit mem_fun_ref_t(_Sp (_Tp::*__p)())
+        : __p_(__p) {}
+    _LIBCPP_INLINE_VISIBILITY _Sp operator()(_Tp& __p) const
+        {return (__p.*__p_)();}
+};
+
+template<class _Sp, class _Tp, class _Ap>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 mem_fun1_ref_t
+    : public binary_function<_Tp, _Ap, _Sp>
+{
+    _Sp (_Tp::*__p_)(_Ap);
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit mem_fun1_ref_t(_Sp (_Tp::*__p)(_Ap))
+        : __p_(__p) {}
+    _LIBCPP_INLINE_VISIBILITY _Sp operator()(_Tp& __p, _Ap __x) const
+        {return (__p.*__p_)(__x);}
+};
+
+template<class _Sp, class _Tp>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+mem_fun_ref_t<_Sp,_Tp>
+mem_fun_ref(_Sp (_Tp::*__f)())
+    {return mem_fun_ref_t<_Sp,_Tp>(__f);}
+
+template<class _Sp, class _Tp, class _Ap>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+mem_fun1_ref_t<_Sp,_Tp,_Ap>
+mem_fun_ref(_Sp (_Tp::*__f)(_Ap))
+    {return mem_fun1_ref_t<_Sp,_Tp,_Ap>(__f);}
+
+template <class _Sp, class _Tp>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun_t
+    : public unary_function<const _Tp*, _Sp>
+{
+    _Sp (_Tp::*__p_)() const;
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit const_mem_fun_t(_Sp (_Tp::*__p)() const)
+        : __p_(__p) {}
+    _LIBCPP_INLINE_VISIBILITY _Sp operator()(const _Tp* __p) const
+        {return (__p->*__p_)();}
+};
+
+template <class _Sp, class _Tp, class _Ap>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun1_t
+    : public binary_function<const _Tp*, _Ap, _Sp>
+{
+    _Sp (_Tp::*__p_)(_Ap) const;
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit const_mem_fun1_t(_Sp (_Tp::*__p)(_Ap) const)
+        : __p_(__p) {}
+    _LIBCPP_INLINE_VISIBILITY _Sp operator()(const _Tp* __p, _Ap __x) const
+        {return (__p->*__p_)(__x);}
+};
+
+template <class _Sp, class _Tp>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+const_mem_fun_t<_Sp,_Tp>
+mem_fun(_Sp (_Tp::*__f)() const)
+    {return const_mem_fun_t<_Sp,_Tp>(__f);}
+
+template <class _Sp, class _Tp, class _Ap>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+const_mem_fun1_t<_Sp,_Tp,_Ap>
+mem_fun(_Sp (_Tp::*__f)(_Ap) const)
+    {return const_mem_fun1_t<_Sp,_Tp,_Ap>(__f);}
+
+template <class _Sp, class _Tp>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun_ref_t
+    : public unary_function<_Tp, _Sp>
+{
+    _Sp (_Tp::*__p_)() const;
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit const_mem_fun_ref_t(_Sp (_Tp::*__p)() const)
+        : __p_(__p) {}
+    _LIBCPP_INLINE_VISIBILITY _Sp operator()(const _Tp& __p) const
+        {return (__p.*__p_)();}
+};
+
+template <class _Sp, class _Tp, class _Ap>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun1_ref_t
+    : public binary_function<_Tp, _Ap, _Sp>
+{
+    _Sp (_Tp::*__p_)(_Ap) const;
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit const_mem_fun1_ref_t(_Sp (_Tp::*__p)(_Ap) const)
+        : __p_(__p) {}
+    _LIBCPP_INLINE_VISIBILITY _Sp operator()(const _Tp& __p, _Ap __x) const
+        {return (__p.*__p_)(__x);}
+};
+
+template <class _Sp, class _Tp>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+const_mem_fun_ref_t<_Sp,_Tp>
+mem_fun_ref(_Sp (_Tp::*__f)() const)
+    {return const_mem_fun_ref_t<_Sp,_Tp>(__f);}
+
+template <class _Sp, class _Tp, class _Ap>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+const_mem_fun1_ref_t<_Sp,_Tp,_Ap>
+mem_fun_ref(_Sp (_Tp::*__f)(_Ap) const)
+    {return const_mem_fun1_ref_t<_Sp,_Tp,_Ap>(__f);}
+
+#endif // _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_MEM_FUN_REF_H
lib/libcxx/include/__functional/not_fn.h
@@ -0,0 +1,47 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_NOT_FN_H
+#define _LIBCPP___FUNCTIONAL_NOT_FN_H
+
+#include <__config>
+#include <__functional/perfect_forward.h>
+#include <__functional/invoke.h>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+
+struct __not_fn_op
+{
+    template<class... _Args>
+    static _LIBCPP_CONSTEXPR_AFTER_CXX17 auto __call(_Args&&... __args)
+    noexcept(noexcept(!_VSTD::invoke(_VSTD::forward<_Args>(__args)...)))
+    -> decltype(      !_VSTD::invoke(_VSTD::forward<_Args>(__args)...))
+    { return          !_VSTD::invoke(_VSTD::forward<_Args>(__args)...); }
+};
+
+template<class _Fn,
+         class = _EnableIf<is_constructible_v<decay_t<_Fn>, _Fn> &&
+                           is_move_constructible_v<_Fn>>>
+_LIBCPP_CONSTEXPR_AFTER_CXX17 auto not_fn(_Fn&& __f)
+{
+    return __perfect_forward<__not_fn_op, _Fn>(_VSTD::forward<_Fn>(__f));
+}
+
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_NOT_FN_H
lib/libcxx/include/__functional/operations.h
@@ -0,0 +1,729 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_OPERATIONS_H
+#define _LIBCPP___FUNCTIONAL_OPERATIONS_H
+
+#include <__config>
+#include <__functional/binary_function.h>
+#include <__functional/unary_function.h>
+#include <__utility/forward.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// Arithmetic operations
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS plus
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef _Tp __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x + __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS plus<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS minus
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef _Tp __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x - __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS minus<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS multiplies
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef _Tp __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x * __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS multiplies<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS divides
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef _Tp __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x / __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS divides<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS modulus
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef _Tp __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x % __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS modulus<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS negate
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : unary_function<_Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef _Tp __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x) const
+        {return -__x;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS negate<void>
+{
+    template <class _Tp>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_Tp&& __x) const
+    _NOEXCEPT_(noexcept(- _VSTD::forward<_Tp>(__x)))
+    -> decltype        (- _VSTD::forward<_Tp>(__x))
+        { return        - _VSTD::forward<_Tp>(__x); }
+    typedef void is_transparent;
+};
+#endif
+
+// Bitwise operations
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS bit_and
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef _Tp __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x & __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS bit_and<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+#if _LIBCPP_STD_VER > 11
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp = void>
+struct _LIBCPP_TEMPLATE_VIS bit_not
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : unary_function<_Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x) const
+        {return ~__x;}
+};
+
+template <>
+struct _LIBCPP_TEMPLATE_VIS bit_not<void>
+{
+    template <class _Tp>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_Tp&& __x) const
+    _NOEXCEPT_(noexcept(~_VSTD::forward<_Tp>(__x)))
+    -> decltype        (~_VSTD::forward<_Tp>(__x))
+        { return        ~_VSTD::forward<_Tp>(__x); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS bit_or
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef _Tp __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x | __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS bit_or<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS bit_xor
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, _Tp>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef _Tp __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    _Tp operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x ^ __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS bit_xor<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+// Comparison operations
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS equal_to
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef bool __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x == __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS equal_to<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS not_equal_to
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef bool __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x != __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS not_equal_to<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS less
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef bool __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x < __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS less<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS less_equal
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef bool __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x <= __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS less_equal<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS greater_equal
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef bool __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x >= __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS greater_equal<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS greater
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef bool __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x > __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS greater<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+// Logical operations
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS logical_and
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef bool __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x && __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS logical_and<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS logical_not
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : unary_function<_Tp, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef bool __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _Tp& __x) const
+        {return !__x;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS logical_not<void>
+{
+    template <class _Tp>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_Tp&& __x) const
+    _NOEXCEPT_(noexcept(!_VSTD::forward<_Tp>(__x)))
+    -> decltype        (!_VSTD::forward<_Tp>(__x))
+        { return        !_VSTD::forward<_Tp>(__x); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#if _LIBCPP_STD_VER > 11
+template <class _Tp = void>
+#else
+template <class _Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS logical_or
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<_Tp, _Tp, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+    typedef bool __result_type;  // used by valarray
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp second_argument_type;
+#endif
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const _Tp& __x, const _Tp& __y) const
+        {return __x || __y;}
+};
+
+#if _LIBCPP_STD_VER > 11
+template <>
+struct _LIBCPP_TEMPLATE_VIS logical_or<void>
+{
+    template <class _T1, class _T2>
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    auto operator()(_T1&& __t, _T2&& __u) const
+    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u)))
+    -> decltype        (_VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u))
+        { return        _VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u); }
+    typedef void is_transparent;
+};
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_OPERATIONS_H
lib/libcxx/include/__functional/perfect_forward.h
@@ -0,0 +1,88 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_PERFECT_FORWARD_H
+#define _LIBCPP___FUNCTIONAL_PERFECT_FORWARD_H
+
+#include <__config>
+#include <tuple>
+#include <type_traits>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+
+template<class _Op, class _Tuple,
+         class _Idxs = typename __make_tuple_indices<tuple_size<_Tuple>::value>::type>
+struct __perfect_forward_impl;
+
+template<class _Op, class... _Bound, size_t... _Idxs>
+struct __perfect_forward_impl<_Op, __tuple_types<_Bound...>, __tuple_indices<_Idxs...>>
+{
+    tuple<_Bound...> __bound_;
+
+    template<class... _Args>
+    _LIBCPP_INLINE_VISIBILITY constexpr auto operator()(_Args&&... __args) &
+    noexcept(noexcept(_Op::__call(_VSTD::get<_Idxs>(__bound_)..., _VSTD::forward<_Args>(__args)...)))
+    -> decltype(      _Op::__call(_VSTD::get<_Idxs>(__bound_)..., _VSTD::forward<_Args>(__args)...))
+    {return           _Op::__call(_VSTD::get<_Idxs>(__bound_)..., _VSTD::forward<_Args>(__args)...);}
+
+    template<class... _Args>
+    _LIBCPP_INLINE_VISIBILITY constexpr auto operator()(_Args&&... __args) const&
+    noexcept(noexcept(_Op::__call(_VSTD::get<_Idxs>(__bound_)..., _VSTD::forward<_Args>(__args)...)))
+    -> decltype(      _Op::__call(_VSTD::get<_Idxs>(__bound_)..., _VSTD::forward<_Args>(__args)...))
+    {return           _Op::__call(_VSTD::get<_Idxs>(__bound_)..., _VSTD::forward<_Args>(__args)...);}
+
+    template<class... _Args>
+    _LIBCPP_INLINE_VISIBILITY constexpr auto operator()(_Args&&... __args) &&
+    noexcept(noexcept(_Op::__call(_VSTD::get<_Idxs>(_VSTD::move(__bound_))...,
+                                  _VSTD::forward<_Args>(__args)...)))
+    -> decltype(      _Op::__call(_VSTD::get<_Idxs>(_VSTD::move(__bound_))...,
+                                  _VSTD::forward<_Args>(__args)...))
+    {return           _Op::__call(_VSTD::get<_Idxs>(_VSTD::move(__bound_))...,
+                                  _VSTD::forward<_Args>(__args)...);}
+
+    template<class... _Args>
+    _LIBCPP_INLINE_VISIBILITY constexpr auto operator()(_Args&&... __args) const&&
+    noexcept(noexcept(_Op::__call(_VSTD::get<_Idxs>(_VSTD::move(__bound_))...,
+                                  _VSTD::forward<_Args>(__args)...)))
+    -> decltype(      _Op::__call(_VSTD::get<_Idxs>(_VSTD::move(__bound_))...,
+                                  _VSTD::forward<_Args>(__args)...))
+    {return           _Op::__call(_VSTD::get<_Idxs>(_VSTD::move(__bound_))...,
+                                  _VSTD::forward<_Args>(__args)...);}
+
+    template<class _Fn = typename tuple_element<0, tuple<_Bound...>>::type,
+             class = _EnableIf<is_copy_constructible_v<_Fn>>>
+    constexpr __perfect_forward_impl(__perfect_forward_impl const& __other)
+        : __bound_(__other.__bound_) {}
+
+    template<class _Fn = typename tuple_element<0, tuple<_Bound...>>::type,
+             class = _EnableIf<is_move_constructible_v<_Fn>>>
+    constexpr __perfect_forward_impl(__perfect_forward_impl && __other)
+        : __bound_(_VSTD::move(__other.__bound_)) {}
+
+    template<class... _BoundArgs>
+    explicit constexpr __perfect_forward_impl(_BoundArgs&&... __bound) :
+        __bound_(_VSTD::forward<_BoundArgs>(__bound)...) { }
+};
+
+template<class _Op, class... _Args>
+using __perfect_forward =
+    __perfect_forward_impl<_Op, __tuple_types<decay_t<_Args>...>>;
+
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_PERFECT_FORWARD_H
lib/libcxx/include/__functional/pointer_to_binary_function.h
@@ -0,0 +1,46 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_POINTER_TO_BINARY_FUNCTION_H
+#define _LIBCPP___FUNCTIONAL_POINTER_TO_BINARY_FUNCTION_H
+
+#include <__config>
+#include <__functional/binary_function.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
+
+template <class _Arg1, class _Arg2, class _Result>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 pointer_to_binary_function
+    : public binary_function<_Arg1, _Arg2, _Result>
+{
+    _Result (*__f_)(_Arg1, _Arg2);
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit pointer_to_binary_function(_Result (*__f)(_Arg1, _Arg2))
+        : __f_(__f) {}
+    _LIBCPP_INLINE_VISIBILITY _Result operator()(_Arg1 __x, _Arg2 __y) const
+        {return __f_(__x, __y);}
+};
+
+template <class _Arg1, class _Arg2, class _Result>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+pointer_to_binary_function<_Arg1,_Arg2,_Result>
+ptr_fun(_Result (*__f)(_Arg1,_Arg2))
+    {return pointer_to_binary_function<_Arg1,_Arg2,_Result>(__f);}
+
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_POINTER_TO_BINARY_FUNCTION_H
lib/libcxx/include/__functional/pointer_to_unary_function.h
@@ -0,0 +1,46 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_POINTER_TO_UNARY_FUNCTION_H
+#define _LIBCPP___FUNCTIONAL_POINTER_TO_UNARY_FUNCTION_H
+
+#include <__config>
+#include <__functional/unary_function.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
+
+template <class _Arg, class _Result>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 pointer_to_unary_function
+    : public unary_function<_Arg, _Result>
+{
+    _Result (*__f_)(_Arg);
+public:
+    _LIBCPP_INLINE_VISIBILITY explicit pointer_to_unary_function(_Result (*__f)(_Arg))
+        : __f_(__f) {}
+    _LIBCPP_INLINE_VISIBILITY _Result operator()(_Arg __x) const
+        {return __f_(__x);}
+};
+
+template <class _Arg, class _Result>
+_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
+pointer_to_unary_function<_Arg,_Result>
+ptr_fun(_Result (*__f)(_Arg))
+    {return pointer_to_unary_function<_Arg,_Result>(__f);}
+
+#endif // _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_POINTER_TO_UNARY_FUNCTION_H
lib/libcxx/include/__functional/ranges_operations.h
@@ -0,0 +1,97 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_RANGES_OPERATIONS_H
+#define _LIBCPP___FUNCTIONAL_RANGES_OPERATIONS_H
+
+#include <__config>
+#include <concepts>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+namespace ranges {
+
+struct equal_to {
+  template <class _Tp, class _Up>
+  requires equality_comparable_with<_Tp, _Up>
+  [[nodiscard]] constexpr bool operator()(_Tp &&__t, _Up &&__u) const
+      noexcept(noexcept(bool(_VSTD::forward<_Tp>(__t) == _VSTD::forward<_Up>(__u)))) {
+    return _VSTD::forward<_Tp>(__t) == _VSTD::forward<_Up>(__u);
+  }
+
+  using is_transparent = void;
+};
+
+struct not_equal_to {
+  template <class _Tp, class _Up>
+  requires equality_comparable_with<_Tp, _Up>
+  [[nodiscard]] constexpr bool operator()(_Tp &&__t, _Up &&__u) const
+      noexcept(noexcept(bool(!(_VSTD::forward<_Tp>(__t) == _VSTD::forward<_Up>(__u))))) {
+    return !(_VSTD::forward<_Tp>(__t) == _VSTD::forward<_Up>(__u));
+  }
+
+  using is_transparent = void;
+};
+
+struct less {
+  template <class _Tp, class _Up>
+  requires totally_ordered_with<_Tp, _Up>
+  [[nodiscard]] constexpr bool operator()(_Tp &&__t, _Up &&__u) const
+      noexcept(noexcept(bool(_VSTD::forward<_Tp>(__t) < _VSTD::forward<_Up>(__u)))) {
+    return _VSTD::forward<_Tp>(__t) < _VSTD::forward<_Up>(__u);
+  }
+
+  using is_transparent = void;
+};
+
+struct less_equal {
+  template <class _Tp, class _Up>
+  requires totally_ordered_with<_Tp, _Up>
+  [[nodiscard]] constexpr bool operator()(_Tp &&__t, _Up &&__u) const
+      noexcept(noexcept(bool(!(_VSTD::forward<_Up>(__u) < _VSTD::forward<_Tp>(__t))))) {
+    return !(_VSTD::forward<_Up>(__u) < _VSTD::forward<_Tp>(__t));
+  }
+
+  using is_transparent = void;
+};
+
+struct greater {
+  template <class _Tp, class _Up>
+  requires totally_ordered_with<_Tp, _Up>
+  [[nodiscard]] constexpr bool operator()(_Tp &&__t, _Up &&__u) const
+      noexcept(noexcept(bool(_VSTD::forward<_Up>(__u) < _VSTD::forward<_Tp>(__t)))) {
+    return _VSTD::forward<_Up>(__u) < _VSTD::forward<_Tp>(__t);
+  }
+
+  using is_transparent = void;
+};
+
+struct greater_equal {
+  template <class _Tp, class _Up>
+  requires totally_ordered_with<_Tp, _Up>
+  [[nodiscard]] constexpr bool operator()(_Tp &&__t, _Up &&__u) const
+      noexcept(noexcept(bool(!(_VSTD::forward<_Tp>(__t) < _VSTD::forward<_Up>(__u))))) {
+    return !(_VSTD::forward<_Tp>(__t) < _VSTD::forward<_Up>(__u));
+  }
+
+  using is_transparent = void;
+};
+
+} // namespace ranges
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_RANGES_OPERATIONS_H
lib/libcxx/include/__functional/reference_wrapper.h
@@ -0,0 +1,223 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_REFERENCE_WRAPPER_H
+#define _LIBCPP___FUNCTIONAL_REFERENCE_WRAPPER_H
+
+#include <__config>
+#include <__functional/weak_result_type.h>
+#include <__memory/addressof.h>
+#include <__utility/forward.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+class _LIBCPP_TEMPLATE_VIS reference_wrapper
+#if _LIBCPP_STD_VER <= 17 || !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : public __weak_result_type<_Tp>
+#endif
+{
+public:
+    // types
+    typedef _Tp type;
+private:
+    type* __f_;
+
+#ifndef _LIBCPP_CXX03_LANG
+    static void __fun(_Tp&) _NOEXCEPT;
+    static void __fun(_Tp&&) = delete;
+#endif
+
+public:
+    // construct/copy/destroy
+#ifdef _LIBCPP_CXX03_LANG
+    _LIBCPP_INLINE_VISIBILITY
+    reference_wrapper(type& __f) _NOEXCEPT
+        : __f_(_VSTD::addressof(__f)) {}
+#else
+    template <class _Up, class = _EnableIf<!__is_same_uncvref<_Up, reference_wrapper>::value, decltype(__fun(declval<_Up>())) >>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    reference_wrapper(_Up&& __u) _NOEXCEPT_(noexcept(__fun(declval<_Up>()))) {
+        type& __f = static_cast<_Up&&>(__u);
+        __f_ = _VSTD::addressof(__f);
+    }
+#endif
+
+    // access
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    operator type&() const _NOEXCEPT {return *__f_;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    type& get() const _NOEXCEPT {return *__f_;}
+
+#ifndef _LIBCPP_CXX03_LANG
+    // invoke
+    template <class... _ArgTypes>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    typename __invoke_of<type&, _ArgTypes...>::type
+    operator() (_ArgTypes&&... __args) const {
+        return _VSTD::__invoke(get(), _VSTD::forward<_ArgTypes>(__args)...);
+    }
+#else
+
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return<type>::type
+    operator() () const {
+        return _VSTD::__invoke(get());
+    }
+
+    template <class _A0>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return0<type, _A0>::type
+    operator() (_A0& __a0) const {
+        return _VSTD::__invoke(get(), __a0);
+    }
+
+    template <class _A0>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return0<type, _A0 const>::type
+    operator() (_A0 const& __a0) const {
+        return _VSTD::__invoke(get(), __a0);
+    }
+
+    template <class _A0, class _A1>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return1<type, _A0, _A1>::type
+    operator() (_A0& __a0, _A1& __a1) const {
+        return _VSTD::__invoke(get(), __a0, __a1);
+    }
+
+    template <class _A0, class _A1>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return1<type, _A0 const, _A1>::type
+    operator() (_A0 const& __a0, _A1& __a1) const {
+        return _VSTD::__invoke(get(), __a0, __a1);
+    }
+
+    template <class _A0, class _A1>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return1<type, _A0, _A1 const>::type
+    operator() (_A0& __a0, _A1 const& __a1) const {
+        return _VSTD::__invoke(get(), __a0, __a1);
+    }
+
+    template <class _A0, class _A1>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return1<type, _A0 const, _A1 const>::type
+    operator() (_A0 const& __a0, _A1 const& __a1) const {
+        return _VSTD::__invoke(get(), __a0, __a1);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0, _A1, _A2>::type
+    operator() (_A0& __a0, _A1& __a1, _A2& __a2) const {
+        return _VSTD::__invoke(get(), __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0 const, _A1, _A2>::type
+    operator() (_A0 const& __a0, _A1& __a1, _A2& __a2) const {
+        return _VSTD::__invoke(get(), __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0, _A1 const, _A2>::type
+    operator() (_A0& __a0, _A1 const& __a1, _A2& __a2) const {
+        return _VSTD::__invoke(get(), __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0, _A1, _A2 const>::type
+    operator() (_A0& __a0, _A1& __a1, _A2 const& __a2) const {
+        return _VSTD::__invoke(get(), __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0 const, _A1 const, _A2>::type
+    operator() (_A0 const& __a0, _A1 const& __a1, _A2& __a2) const {
+        return _VSTD::__invoke(get(), __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0 const, _A1, _A2 const>::type
+    operator() (_A0 const& __a0, _A1& __a1, _A2 const& __a2) const {
+        return _VSTD::__invoke(get(), __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0, _A1 const, _A2 const>::type
+    operator() (_A0& __a0, _A1 const& __a1, _A2 const& __a2) const {
+        return _VSTD::__invoke(get(), __a0, __a1, __a2);
+    }
+
+    template <class _A0, class _A1, class _A2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename __invoke_return2<type, _A0 const, _A1 const, _A2 const>::type
+    operator() (_A0 const& __a0, _A1 const& __a1, _A2 const& __a2) const {
+        return _VSTD::__invoke(get(), __a0, __a1, __a2);
+    }
+#endif // _LIBCPP_CXX03_LANG
+};
+
+#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
+template <class _Tp>
+reference_wrapper(_Tp&) -> reference_wrapper<_Tp>;
+#endif
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+reference_wrapper<_Tp>
+ref(_Tp& __t) _NOEXCEPT
+{
+    return reference_wrapper<_Tp>(__t);
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+reference_wrapper<_Tp>
+ref(reference_wrapper<_Tp> __t) _NOEXCEPT
+{
+    return _VSTD::ref(__t.get());
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+reference_wrapper<const _Tp>
+cref(const _Tp& __t) _NOEXCEPT
+{
+    return reference_wrapper<const _Tp>(__t);
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+reference_wrapper<const _Tp>
+cref(reference_wrapper<_Tp> __t) _NOEXCEPT
+{
+    return _VSTD::cref(__t.get());
+}
+
+#ifndef _LIBCPP_CXX03_LANG
+template <class _Tp> void ref(const _Tp&&) = delete;
+template <class _Tp> void cref(const _Tp&&) = delete;
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_REFERENCE_WRAPPER_H
lib/libcxx/include/__functional/unary_function.h
@@ -0,0 +1,34 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_UNARY_FUNCTION_H
+#define _LIBCPP___FUNCTIONAL_UNARY_FUNCTION_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Arg, class _Result>
+struct _LIBCPP_TEMPLATE_VIS unary_function
+{
+    typedef _Arg    argument_type;
+    typedef _Result result_type;
+};
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___FUNCTIONAL_UNARY_FUNCTION_H
lib/libcxx/include/__functional/unary_negate.h
@@ -0,0 +1,47 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_UNARY_NEGATE_H
+#define _LIBCPP___FUNCTIONAL_UNARY_NEGATE_H
+
+#include <__config>
+#include <__functional/unary_function.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_NEGATORS)
+
+template <class _Predicate>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX17 unary_negate
+    : public unary_function<typename _Predicate::argument_type, bool>
+{
+    _Predicate __pred_;
+public:
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    explicit unary_negate(const _Predicate& __pred)
+        : __pred_(__pred) {}
+    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+    bool operator()(const typename _Predicate::argument_type& __x) const
+        {return !__pred_(__x);}
+};
+
+template <class _Predicate>
+_LIBCPP_DEPRECATED_IN_CXX17 inline _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+unary_negate<_Predicate>
+not1(const _Predicate& __pred) {return unary_negate<_Predicate>(__pred);}
+
+#endif // _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_NEGATORS)
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_UNARY_NEGATE_H
lib/libcxx/include/__functional/unwrap_ref.h
@@ -0,0 +1,62 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_UNWRAP_REF_H
+#define _LIBCPP___FUNCTIONAL_UNWRAP_REF_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+struct __unwrap_reference { typedef _LIBCPP_NODEBUG_TYPE _Tp type; };
+
+template <class _Tp>
+class reference_wrapper;
+
+template <class _Tp>
+struct __unwrap_reference<reference_wrapper<_Tp> > { typedef _LIBCPP_NODEBUG_TYPE _Tp& type; };
+
+template <class _Tp>
+struct decay;
+
+#if _LIBCPP_STD_VER > 17
+template <class _Tp>
+struct unwrap_reference : __unwrap_reference<_Tp> { };
+
+template <class _Tp>
+using unwrap_reference_t = typename unwrap_reference<_Tp>::type;
+
+template <class _Tp>
+struct unwrap_ref_decay : unwrap_reference<typename decay<_Tp>::type> { };
+
+template <class _Tp>
+using unwrap_ref_decay_t = typename unwrap_ref_decay<_Tp>::type;
+#endif // > C++17
+
+template <class _Tp>
+struct __unwrap_ref_decay
+#if _LIBCPP_STD_VER > 17
+    : unwrap_ref_decay<_Tp>
+#else
+    : __unwrap_reference<typename decay<_Tp>::type>
+#endif
+{ };
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___FUNCTIONAL_UNWRAP_REF_H
lib/libcxx/include/__functional/weak_result_type.h
@@ -0,0 +1,481 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL_WEAK_RESULT_TYPE_H
+#define _LIBCPP___FUNCTIONAL_WEAK_RESULT_TYPE_H
+
+#include <__config>
+#include <__functional/binary_function.h>
+#include <__functional/unary_function.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+struct __has_result_type
+{
+private:
+    struct __two {char __lx; char __lxx;};
+    template <class _Up> static __two __test(...);
+    template <class _Up> static char __test(typename _Up::result_type* = 0);
+public:
+    static const bool value = sizeof(__test<_Tp>(0)) == 1;
+};
+
+// __weak_result_type
+
+template <class _Tp>
+struct __derives_from_unary_function
+{
+private:
+    struct __two {char __lx; char __lxx;};
+    static __two __test(...);
+    template <class _Ap, class _Rp>
+        static unary_function<_Ap, _Rp>
+        __test(const volatile unary_function<_Ap, _Rp>*);
+public:
+    static const bool value = !is_same<decltype(__test((_Tp*)0)), __two>::value;
+    typedef decltype(__test((_Tp*)0)) type;
+};
+
+template <class _Tp>
+struct __derives_from_binary_function
+{
+private:
+    struct __two {char __lx; char __lxx;};
+    static __two __test(...);
+    template <class _A1, class _A2, class _Rp>
+        static binary_function<_A1, _A2, _Rp>
+        __test(const volatile binary_function<_A1, _A2, _Rp>*);
+public:
+    static const bool value = !is_same<decltype(__test((_Tp*)0)), __two>::value;
+    typedef decltype(__test((_Tp*)0)) type;
+};
+
+template <class _Tp, bool = __derives_from_unary_function<_Tp>::value>
+struct __maybe_derive_from_unary_function  // bool is true
+    : public __derives_from_unary_function<_Tp>::type
+{
+};
+
+template <class _Tp>
+struct __maybe_derive_from_unary_function<_Tp, false>
+{
+};
+
+template <class _Tp, bool = __derives_from_binary_function<_Tp>::value>
+struct __maybe_derive_from_binary_function  // bool is true
+    : public __derives_from_binary_function<_Tp>::type
+{
+};
+
+template <class _Tp>
+struct __maybe_derive_from_binary_function<_Tp, false>
+{
+};
+
+template <class _Tp, bool = __has_result_type<_Tp>::value>
+struct __weak_result_type_imp // bool is true
+    : public __maybe_derive_from_unary_function<_Tp>,
+      public __maybe_derive_from_binary_function<_Tp>
+{
+    typedef _LIBCPP_NODEBUG_TYPE typename _Tp::result_type result_type;
+};
+
+template <class _Tp>
+struct __weak_result_type_imp<_Tp, false>
+    : public __maybe_derive_from_unary_function<_Tp>,
+      public __maybe_derive_from_binary_function<_Tp>
+{
+};
+
+template <class _Tp>
+struct __weak_result_type
+    : public __weak_result_type_imp<_Tp>
+{
+};
+
+// 0 argument case
+
+template <class _Rp>
+struct __weak_result_type<_Rp ()>
+{
+    typedef _LIBCPP_NODEBUG_TYPE  _Rp result_type;
+};
+
+template <class _Rp>
+struct __weak_result_type<_Rp (&)()>
+{
+    typedef _LIBCPP_NODEBUG_TYPE  _Rp result_type;
+};
+
+template <class _Rp>
+struct __weak_result_type<_Rp (*)()>
+{
+    typedef _LIBCPP_NODEBUG_TYPE  _Rp result_type;
+};
+
+// 1 argument case
+
+template <class _Rp, class _A1>
+struct __weak_result_type<_Rp (_A1)>
+    : public unary_function<_A1, _Rp>
+{
+};
+
+template <class _Rp, class _A1>
+struct __weak_result_type<_Rp (&)(_A1)>
+    : public unary_function<_A1, _Rp>
+{
+};
+
+template <class _Rp, class _A1>
+struct __weak_result_type<_Rp (*)(_A1)>
+    : public unary_function<_A1, _Rp>
+{
+};
+
+template <class _Rp, class _Cp>
+struct __weak_result_type<_Rp (_Cp::*)()>
+    : public unary_function<_Cp*, _Rp>
+{
+};
+
+template <class _Rp, class _Cp>
+struct __weak_result_type<_Rp (_Cp::*)() const>
+    : public unary_function<const _Cp*, _Rp>
+{
+};
+
+template <class _Rp, class _Cp>
+struct __weak_result_type<_Rp (_Cp::*)() volatile>
+    : public unary_function<volatile _Cp*, _Rp>
+{
+};
+
+template <class _Rp, class _Cp>
+struct __weak_result_type<_Rp (_Cp::*)() const volatile>
+    : public unary_function<const volatile _Cp*, _Rp>
+{
+};
+
+// 2 argument case
+
+template <class _Rp, class _A1, class _A2>
+struct __weak_result_type<_Rp (_A1, _A2)>
+    : public binary_function<_A1, _A2, _Rp>
+{
+};
+
+template <class _Rp, class _A1, class _A2>
+struct __weak_result_type<_Rp (*)(_A1, _A2)>
+    : public binary_function<_A1, _A2, _Rp>
+{
+};
+
+template <class _Rp, class _A1, class _A2>
+struct __weak_result_type<_Rp (&)(_A1, _A2)>
+    : public binary_function<_A1, _A2, _Rp>
+{
+};
+
+template <class _Rp, class _Cp, class _A1>
+struct __weak_result_type<_Rp (_Cp::*)(_A1)>
+    : public binary_function<_Cp*, _A1, _Rp>
+{
+};
+
+template <class _Rp, class _Cp, class _A1>
+struct __weak_result_type<_Rp (_Cp::*)(_A1) const>
+    : public binary_function<const _Cp*, _A1, _Rp>
+{
+};
+
+template <class _Rp, class _Cp, class _A1>
+struct __weak_result_type<_Rp (_Cp::*)(_A1) volatile>
+    : public binary_function<volatile _Cp*, _A1, _Rp>
+{
+};
+
+template <class _Rp, class _Cp, class _A1>
+struct __weak_result_type<_Rp (_Cp::*)(_A1) const volatile>
+    : public binary_function<const volatile _Cp*, _A1, _Rp>
+{
+};
+
+
+#ifndef _LIBCPP_CXX03_LANG
+// 3 or more arguments
+
+template <class _Rp, class _A1, class _A2, class _A3, class ..._A4>
+struct __weak_result_type<_Rp (_A1, _A2, _A3, _A4...)>
+{
+    typedef _Rp result_type;
+};
+
+template <class _Rp, class _A1, class _A2, class _A3, class ..._A4>
+struct __weak_result_type<_Rp (&)(_A1, _A2, _A3, _A4...)>
+{
+    typedef _Rp result_type;
+};
+
+template <class _Rp, class _A1, class _A2, class _A3, class ..._A4>
+struct __weak_result_type<_Rp (*)(_A1, _A2, _A3, _A4...)>
+{
+    typedef _Rp result_type;
+};
+
+template <class _Rp, class _Cp, class _A1, class _A2, class ..._A3>
+struct __weak_result_type<_Rp (_Cp::*)(_A1, _A2, _A3...)>
+{
+    typedef _Rp result_type;
+};
+
+template <class _Rp, class _Cp, class _A1, class _A2, class ..._A3>
+struct __weak_result_type<_Rp (_Cp::*)(_A1, _A2, _A3...) const>
+{
+    typedef _Rp result_type;
+};
+
+template <class _Rp, class _Cp, class _A1, class _A2, class ..._A3>
+struct __weak_result_type<_Rp (_Cp::*)(_A1, _A2, _A3...) volatile>
+{
+    typedef _Rp result_type;
+};
+
+template <class _Rp, class _Cp, class _A1, class _A2, class ..._A3>
+struct __weak_result_type<_Rp (_Cp::*)(_A1, _A2, _A3...) const volatile>
+{
+    typedef _Rp result_type;
+};
+
+template <class _Tp, class ..._Args>
+struct __invoke_return
+{
+    typedef decltype(_VSTD::__invoke(declval<_Tp>(), declval<_Args>()...)) type;
+};
+
+#else // defined(_LIBCPP_CXX03_LANG)
+
+template <class _Ret, class _T1, bool _IsFunc, bool _IsBase>
+struct __enable_invoke_imp;
+
+template <class _Ret, class _T1>
+struct __enable_invoke_imp<_Ret, _T1, true, true> {
+    typedef _Ret _Bullet1;
+    typedef _Bullet1 type;
+};
+
+template <class _Ret, class _T1>
+struct __enable_invoke_imp<_Ret, _T1, true, false>  {
+    typedef _Ret _Bullet2;
+    typedef _Bullet2 type;
+};
+
+template <class _Ret, class _T1>
+struct __enable_invoke_imp<_Ret, _T1, false, true>  {
+    typedef typename add_lvalue_reference<
+                typename __apply_cv<_T1, _Ret>::type
+            >::type _Bullet3;
+    typedef _Bullet3 type;
+};
+
+template <class _Ret, class _T1>
+struct __enable_invoke_imp<_Ret, _T1, false, false>  {
+    typedef typename add_lvalue_reference<
+                typename __apply_cv<decltype(*declval<_T1>()), _Ret>::type
+            >::type _Bullet4;
+    typedef _Bullet4 type;
+};
+
+template <class _Ret, class _T1>
+struct __enable_invoke_imp<_Ret, _T1*, false, false>  {
+    typedef typename add_lvalue_reference<
+                typename __apply_cv<_T1, _Ret>::type
+            >::type _Bullet4;
+    typedef _Bullet4  type;
+};
+
+template <class _Fn, class _T1,
+          class _Traits = __member_pointer_traits<_Fn>,
+          class _Ret = typename _Traits::_ReturnType,
+          class _Class = typename _Traits::_ClassType>
+struct __enable_invoke : __enable_invoke_imp<
+    _Ret, _T1,
+    is_member_function_pointer<_Fn>::value,
+    is_base_of<_Class, typename remove_reference<_T1>::type>::value>
+{
+};
+
+__nat __invoke(__any, ...);
+
+// first bullet
+
+template <class _Fn, class _T1>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet1
+__invoke(_Fn __f, _T1& __t1) {
+    return (__t1.*__f)();
+}
+
+template <class _Fn, class _T1, class _A0>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet1
+__invoke(_Fn __f, _T1& __t1, _A0& __a0) {
+    return (__t1.*__f)(__a0);
+}
+
+template <class _Fn, class _T1, class _A0, class _A1>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet1
+__invoke(_Fn __f, _T1& __t1, _A0& __a0, _A1& __a1) {
+    return (__t1.*__f)(__a0, __a1);
+}
+
+template <class _Fn, class _T1, class _A0, class _A1, class _A2>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet1
+__invoke(_Fn __f, _T1& __t1, _A0& __a0, _A1& __a1, _A2& __a2) {
+    return (__t1.*__f)(__a0, __a1, __a2);
+}
+
+template <class _Fn, class _T1>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet2
+__invoke(_Fn __f, _T1& __t1) {
+    return ((*__t1).*__f)();
+}
+
+template <class _Fn, class _T1, class _A0>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet2
+__invoke(_Fn __f, _T1& __t1, _A0& __a0) {
+    return ((*__t1).*__f)(__a0);
+}
+
+template <class _Fn, class _T1, class _A0, class _A1>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet2
+__invoke(_Fn __f, _T1& __t1, _A0& __a0, _A1& __a1) {
+    return ((*__t1).*__f)(__a0, __a1);
+}
+
+template <class _Fn, class _T1, class _A0, class _A1, class _A2>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet2
+__invoke(_Fn __f, _T1& __t1, _A0& __a0, _A1& __a1, _A2& __a2) {
+    return ((*__t1).*__f)(__a0, __a1, __a2);
+}
+
+template <class _Fn, class _T1>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet3
+__invoke(_Fn __f, _T1& __t1) {
+    return __t1.*__f;
+}
+
+template <class _Fn, class _T1>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __enable_invoke<_Fn, _T1>::_Bullet4
+__invoke(_Fn __f, _T1& __t1) {
+    return (*__t1).*__f;
+}
+
+// fifth bullet
+
+template <class _Fp>
+inline _LIBCPP_INLINE_VISIBILITY
+decltype(declval<_Fp&>()())
+__invoke(_Fp& __f)
+{
+    return __f();
+}
+
+template <class _Fp, class _A0>
+inline _LIBCPP_INLINE_VISIBILITY
+decltype(declval<_Fp&>()(declval<_A0&>()))
+__invoke(_Fp& __f, _A0& __a0)
+{
+    return __f(__a0);
+}
+
+template <class _Fp, class _A0, class _A1>
+inline _LIBCPP_INLINE_VISIBILITY
+decltype(declval<_Fp&>()(declval<_A0&>(), declval<_A1&>()))
+__invoke(_Fp& __f, _A0& __a0, _A1& __a1)
+{
+    return __f(__a0, __a1);
+}
+
+template <class _Fp, class _A0, class _A1, class _A2>
+inline _LIBCPP_INLINE_VISIBILITY
+decltype(declval<_Fp&>()(declval<_A0&>(), declval<_A1&>(), declval<_A2&>()))
+__invoke(_Fp& __f, _A0& __a0, _A1& __a1, _A2& __a2)
+{
+    return __f(__a0, __a1, __a2);
+}
+
+template <class _Fp, bool = __has_result_type<__weak_result_type<_Fp> >::value>
+struct __invoke_return
+{
+    typedef typename __weak_result_type<_Fp>::result_type type;
+};
+
+template <class _Fp>
+struct __invoke_return<_Fp, false>
+{
+    typedef decltype(_VSTD::__invoke(declval<_Fp&>())) type;
+};
+
+template <class _Tp, class _A0>
+struct __invoke_return0
+{
+    typedef decltype(_VSTD::__invoke(declval<_Tp&>(), declval<_A0&>())) type;
+};
+
+template <class _Rp, class _Tp, class _A0>
+struct __invoke_return0<_Rp _Tp::*, _A0>
+{
+    typedef typename __enable_invoke<_Rp _Tp::*, _A0>::type type;
+};
+
+template <class _Tp, class _A0, class _A1>
+struct __invoke_return1
+{
+    typedef decltype(_VSTD::__invoke(declval<_Tp&>(), declval<_A0&>(),
+                                                      declval<_A1&>())) type;
+};
+
+template <class _Rp, class _Class, class _A0, class _A1>
+struct __invoke_return1<_Rp _Class::*, _A0, _A1> {
+    typedef typename __enable_invoke<_Rp _Class::*, _A0>::type type;
+};
+
+template <class _Tp, class _A0, class _A1, class _A2>
+struct __invoke_return2
+{
+    typedef decltype(_VSTD::__invoke(declval<_Tp&>(), declval<_A0&>(),
+                                                      declval<_A1&>(),
+                                                      declval<_A2&>())) type;
+};
+
+template <class _Ret, class _Class, class _A0, class _A1, class _A2>
+struct __invoke_return2<_Ret _Class::*, _A0, _A1, _A2> {
+    typedef typename __enable_invoke<_Ret _Class::*, _A0>::type type;
+};
+
+#endif // !defined(_LIBCPP_CXX03_LANG)
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL_WEAK_RESULT_TYPE_H
lib/libcxx/include/__iterator/access.h
@@ -0,0 +1,134 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_ACCESS_H
+#define _LIBCPP___ITERATOR_ACCESS_H
+
+#include <__config>
+#include <cstddef>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp, size_t _Np>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_Tp*
+begin(_Tp (&__array)[_Np])
+{
+    return __array;
+}
+
+template <class _Tp, size_t _Np>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+_Tp*
+end(_Tp (&__array)[_Np])
+{
+    return __array + _Np;
+}
+
+#if !defined(_LIBCPP_CXX03_LANG)
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto
+begin(_Cp& __c) -> decltype(__c.begin())
+{
+    return __c.begin();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto
+begin(const _Cp& __c) -> decltype(__c.begin())
+{
+    return __c.begin();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto
+end(_Cp& __c) -> decltype(__c.end())
+{
+    return __c.end();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto
+end(const _Cp& __c) -> decltype(__c.end())
+{
+    return __c.end();
+}
+
+#if _LIBCPP_STD_VER > 11
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+auto cbegin(const _Cp& __c) -> decltype(_VSTD::begin(__c))
+{
+    return _VSTD::begin(__c);
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+auto cend(const _Cp& __c) -> decltype(_VSTD::end(__c))
+{
+    return _VSTD::end(__c);
+}
+
+#endif
+
+
+#else  // defined(_LIBCPP_CXX03_LANG)
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY
+typename _Cp::iterator
+begin(_Cp& __c)
+{
+    return __c.begin();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY
+typename _Cp::const_iterator
+begin(const _Cp& __c)
+{
+    return __c.begin();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY
+typename _Cp::iterator
+end(_Cp& __c)
+{
+    return __c.end();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY
+typename _Cp::const_iterator
+end(const _Cp& __c)
+{
+    return __c.end();
+}
+
+#endif // !defined(_LIBCPP_CXX03_LANG)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_ACCESS_H
lib/libcxx/include/__iterator/advance.h
@@ -0,0 +1,200 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_ADVANCE_H
+#define _LIBCPP___ITERATOR_ADVANCE_H
+
+#include <__config>
+#include <__debug>
+#include <__function_like.h>
+#include <__iterator/concepts.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iterator_traits.h>
+#include <__utility/move.h>
+#include <cstdlib>
+#include <concepts>
+#include <limits>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIter>
+_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX14
+void __advance(_InputIter& __i, typename iterator_traits<_InputIter>::difference_type __n, input_iterator_tag) {
+  for (; __n > 0; --__n)
+    ++__i;
+}
+
+template <class _BiDirIter>
+_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX14
+void __advance(_BiDirIter& __i, typename iterator_traits<_BiDirIter>::difference_type __n, bidirectional_iterator_tag) {
+  if (__n >= 0)
+    for (; __n > 0; --__n)
+      ++__i;
+  else
+    for (; __n < 0; ++__n)
+      --__i;
+}
+
+template <class _RandIter>
+_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX14
+void __advance(_RandIter& __i, typename iterator_traits<_RandIter>::difference_type __n, random_access_iterator_tag) {
+  __i += __n;
+}
+
+template <
+    class _InputIter, class _Distance,
+    class _IntegralDistance = decltype(_VSTD::__convert_to_integral(declval<_Distance>())),
+    class = _EnableIf<is_integral<_IntegralDistance>::value> >
+_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX14
+void advance(_InputIter& __i, _Distance __orig_n) {
+  typedef typename iterator_traits<_InputIter>::difference_type _Difference;
+  _Difference __n = static_cast<_Difference>(_VSTD::__convert_to_integral(__orig_n));
+  _LIBCPP_ASSERT(__n >= 0 || __is_cpp17_bidirectional_iterator<_InputIter>::value,
+                 "Attempt to advance(it, n) with negative n on a non-bidirectional iterator");
+  _VSTD::__advance(__i, __n, typename iterator_traits<_InputIter>::iterator_category());
+}
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+// [range.iter.op.advance]
+struct __advance_fn final : private __function_like {
+private:
+  template <class _Tp>
+  _LIBCPP_HIDE_FROM_ABI
+  static constexpr _Tp __magnitude_geq(_Tp __a, _Tp __b) noexcept {
+    return __a < 0 ? (__a <= __b) : (__a >= __b);
+  }
+
+  template <class _Ip>
+  _LIBCPP_HIDE_FROM_ABI
+  static constexpr void __advance_forward(_Ip& __i, iter_difference_t<_Ip> __n) {
+    while (__n > 0) {
+      --__n;
+      ++__i;
+    }
+  }
+
+  template <class _Ip>
+  _LIBCPP_HIDE_FROM_ABI
+  static constexpr void __advance_backward(_Ip& __i, iter_difference_t<_Ip> __n) {
+    while (__n < 0) {
+      ++__n;
+      --__i;
+    }
+  }
+
+public:
+  constexpr explicit __advance_fn(__tag __x) noexcept : __function_like(__x) {}
+
+  // Preconditions: If `I` does not model `bidirectional_iterator`, `n` is not negative.
+  template <input_or_output_iterator _Ip>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr void operator()(_Ip& __i, iter_difference_t<_Ip> __n) const {
+    _LIBCPP_ASSERT(__n >= 0 || bidirectional_iterator<_Ip>,
+                   "If `n < 0`, then `bidirectional_iterator<I>` must be true.");
+
+    // If `I` models `random_access_iterator`, equivalent to `i += n`.
+    if constexpr (random_access_iterator<_Ip>) {
+      __i += __n;
+      return;
+    } else if constexpr (bidirectional_iterator<_Ip>) {
+      // Otherwise, if `n` is non-negative, increments `i` by `n`.
+      __advance_forward(__i, __n);
+      // Otherwise, decrements `i` by `-n`.
+      __advance_backward(__i, __n);
+      return;
+    } else {
+      // Otherwise, if `n` is non-negative, increments `i` by `n`.
+      __advance_forward(__i, __n);
+      return;
+    }
+  }
+
+  // Preconditions: Either `assignable_from<I&, S> || sized_sentinel_for<S, I>` is modeled, or [i, bound) denotes a range.
+  template <input_or_output_iterator _Ip, sentinel_for<_Ip> _Sp>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr void operator()(_Ip& __i, _Sp __bound) const {
+    // If `I` and `S` model `assignable_from<I&, S>`, equivalent to `i = std::move(bound)`.
+    if constexpr (assignable_from<_Ip&, _Sp>) {
+      __i = _VSTD::move(__bound);
+    }
+    // Otherwise, if `S` and `I` model `sized_sentinel_for<S, I>`, equivalent to `ranges::advance(i, bound - i)`.
+    else if constexpr (sized_sentinel_for<_Sp, _Ip>) {
+      (*this)(__i, __bound - __i);
+    }
+    // Otherwise, while `bool(i != bound)` is true, increments `i`.
+    else {
+      while (__i != __bound) {
+        ++__i;
+      }
+    }
+  }
+
+  // Preconditions:
+  //   * If `n > 0`, [i, bound) denotes a range.
+  //   * If `n == 0`, [i, bound) or [bound, i) denotes a range.
+  //   * If `n < 0`, [bound, i) denotes a range, `I` models `bidirectional_iterator`, and `I` and `S` model `same_as<I, S>`.
+  // Returns: `n - M`, where `M` is the difference between the the ending and starting position.
+  template <input_or_output_iterator _Ip, sentinel_for<_Ip> _Sp>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr iter_difference_t<_Ip> operator()(_Ip& __i, iter_difference_t<_Ip> __n, _Sp __bound) const {
+    _LIBCPP_ASSERT((__n >= 0) || (bidirectional_iterator<_Ip> && same_as<_Ip, _Sp>),
+                   "If `n < 0`, then `bidirectional_iterator<I> && same_as<I, S>` must be true.");
+    // If `S` and `I` model `sized_sentinel_for<S, I>`:
+    if constexpr (sized_sentinel_for<_Sp, _Ip>) {
+      // If |n| >= |bound - i|, equivalent to `ranges::advance(i, bound)`.
+      if (const auto __M = __bound - __i; __magnitude_geq(__n, __M)) {
+        (*this)(__i, __bound);
+        return __n - __M;
+      }
+
+      // Otherwise, equivalent to `ranges::advance(i, n)`.
+      (*this)(__i, __n);
+      return 0;
+    } else {
+      // Otherwise, if `n` is non-negative, while `bool(i != bound)` is true, increments `i` but at
+      // most `n` times.
+      while (__i != __bound && __n > 0) {
+        ++__i;
+        --__n;
+      }
+
+      // Otherwise, while `bool(i != bound)` is true, decrements `i` but at most `-n` times.
+      if constexpr (bidirectional_iterator<_Ip> && same_as<_Ip, _Sp>) {
+        while (__i != __bound && __n < 0) {
+          --__i;
+          ++__n;
+        }
+      }
+      return __n;
+    }
+
+    _LIBCPP_UNREACHABLE();
+  }
+};
+
+inline constexpr auto advance = __advance_fn(__function_like::__tag());
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_ADVANCE_H
lib/libcxx/include/__iterator/back_insert_iterator.h
@@ -0,0 +1,75 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_BACK_INSERT_ITERATOR_H
+#define _LIBCPP___ITERATOR_BACK_INSERT_ITERATOR_H
+
+#include <__config>
+#include <__iterator/iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <__memory/addressof.h>
+#include <__utility/move.h>
+#include <cstddef>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Container>
+class _LIBCPP_TEMPLATE_VIS back_insert_iterator
+#if _LIBCPP_STD_VER <= 14 || !defined(_LIBCPP_ABI_NO_ITERATOR_BASES)
+    : public iterator<output_iterator_tag, void, void, void, void>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+protected:
+    _Container* container;
+public:
+    typedef output_iterator_tag iterator_category;
+    typedef void value_type;
+#if _LIBCPP_STD_VER > 17
+    typedef ptrdiff_t difference_type;
+#else
+    typedef void difference_type;
+#endif
+    typedef void pointer;
+    typedef void reference;
+    typedef _Container container_type;
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 explicit back_insert_iterator(_Container& __x) : container(_VSTD::addressof(__x)) {}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator=(const typename _Container::value_type& __value_)
+        {container->push_back(__value_); return *this;}
+#ifndef _LIBCPP_CXX03_LANG
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator=(typename _Container::value_type&& __value_)
+        {container->push_back(_VSTD::move(__value_)); return *this;}
+#endif // _LIBCPP_CXX03_LANG
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator*()     {return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator& operator++()    {return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 back_insert_iterator  operator++(int) {return *this;}
+};
+
+template <class _Container>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+back_insert_iterator<_Container>
+back_inserter(_Container& __x)
+{
+    return back_insert_iterator<_Container>(__x);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_BACK_INSERT_ITERATOR_H
lib/libcxx/include/__iterator/common_iterator.h
@@ -0,0 +1,301 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_COMMON_ITERATOR_H
+#define _LIBCPP___ITERATOR_COMMON_ITERATOR_H
+
+#include <__config>
+#include <__debug>
+#include <__iterator/concepts.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iter_swap.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/readable_traits.h>
+#include <concepts>
+#include <variant>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+template<input_or_output_iterator _Iter, sentinel_for<_Iter> _Sent>
+  requires (!same_as<_Iter, _Sent> && copyable<_Iter>)
+class common_iterator {
+  class __proxy {
+    friend common_iterator;
+
+    iter_value_t<_Iter> __value;
+    // We can move __x because the only caller verifies that __x is not a reference.
+    constexpr __proxy(iter_reference_t<_Iter>&& __x)
+      : __value(_VSTD::move(__x)) {}
+
+  public:
+    const iter_value_t<_Iter>* operator->() const {
+      return _VSTD::addressof(__value);
+    }
+  };
+
+  class __postfix_proxy {
+    friend common_iterator;
+
+    iter_value_t<_Iter> __value;
+    constexpr __postfix_proxy(iter_reference_t<_Iter>&& __x)
+      : __value(_VSTD::forward<iter_reference_t<_Iter>>(__x)) {}
+
+  public:
+    constexpr static bool __valid_for_iter =
+      constructible_from<iter_value_t<_Iter>, iter_reference_t<_Iter>> &&
+      move_constructible<iter_value_t<_Iter>>;
+
+    const iter_value_t<_Iter>& operator*() const {
+      return __value;
+    }
+  };
+
+public:
+  variant<_Iter, _Sent> __hold_;
+
+  common_iterator() requires default_initializable<_Iter> = default;
+
+  constexpr common_iterator(_Iter __i) : __hold_(in_place_type<_Iter>, _VSTD::move(__i)) {}
+  constexpr common_iterator(_Sent __s) : __hold_(in_place_type<_Sent>, _VSTD::move(__s)) {}
+
+  template<class _I2, class _S2>
+    requires convertible_to<const _I2&, _Iter> && convertible_to<const _S2&, _Sent>
+  constexpr common_iterator(const common_iterator<_I2, _S2>& __other)
+    : __hold_([&]() -> variant<_Iter, _Sent> {
+      _LIBCPP_ASSERT(!__other.__hold_.valueless_by_exception(), "Constructed from valueless iterator.");
+      if (__other.__hold_.index() == 0)
+        return variant<_Iter, _Sent>{in_place_index<0>, _VSTD::__unchecked_get<0>(__other.__hold_)};
+      return variant<_Iter, _Sent>{in_place_index<1>, _VSTD::__unchecked_get<1>(__other.__hold_)};
+    }()) {}
+
+  template<class _I2, class _S2>
+    requires convertible_to<const _I2&, _Iter> && convertible_to<const _S2&, _Sent> &&
+             assignable_from<_Iter&, const _I2&> && assignable_from<_Sent&, const _S2&>
+  common_iterator& operator=(const common_iterator<_I2, _S2>& __other) {
+    _LIBCPP_ASSERT(!__other.__hold_.valueless_by_exception(), "Assigned from valueless iterator.");
+
+    auto __idx = __hold_.index();
+    auto __other_idx = __other.__hold_.index();
+
+    // If they're the same index, just assign.
+    if (__idx == 0 && __other_idx == 0)
+      _VSTD::__unchecked_get<0>(__hold_) = _VSTD::__unchecked_get<0>(__other.__hold_);
+    else if (__idx == 1 && __other_idx == 1)
+      _VSTD::__unchecked_get<1>(__hold_) = _VSTD::__unchecked_get<1>(__other.__hold_);
+
+    // Otherwise replace with the oposite element.
+    else if (__other_idx == 1)
+      __hold_.template emplace<1>(_VSTD::__unchecked_get<1>(__other.__hold_));
+    else if (__other_idx == 0)
+      __hold_.template emplace<0>(_VSTD::__unchecked_get<0>(__other.__hold_));
+
+    return *this;
+  }
+
+  decltype(auto) operator*()
+  {
+    _LIBCPP_ASSERT(holds_alternative<_Iter>(__hold_),
+                   "Cannot dereference sentinel. Common iterator not holding an iterator.");
+    return *_VSTD::__unchecked_get<_Iter>(__hold_);
+  }
+
+  decltype(auto) operator*() const
+    requires __dereferenceable<const _Iter>
+  {
+    _LIBCPP_ASSERT(holds_alternative<_Iter>(__hold_),
+                   "Cannot dereference sentinel. Common iterator not holding an iterator.");
+    return *_VSTD::__unchecked_get<_Iter>(__hold_);
+  }
+
+  template<class _I2 = _Iter>
+  decltype(auto) operator->() const
+    requires indirectly_readable<const _I2> &&
+    (requires(const _I2& __i) { __i.operator->(); } ||
+     is_reference_v<iter_reference_t<_I2>> ||
+     constructible_from<iter_value_t<_I2>, iter_reference_t<_I2>>)
+  {
+    _LIBCPP_ASSERT(holds_alternative<_Iter>(__hold_),
+                   "Cannot dereference sentinel. Common iterator not holding an iterator.");
+
+    if constexpr (is_pointer_v<_Iter> || requires(const _Iter& __i) { __i.operator->(); })    {
+      return _VSTD::__unchecked_get<_Iter>(__hold_);
+    } else if constexpr (is_reference_v<iter_reference_t<_Iter>>) {
+      auto&& __tmp = *_VSTD::__unchecked_get<_Iter>(__hold_);
+      return _VSTD::addressof(__tmp);
+    } else {
+      return __proxy(*_VSTD::__unchecked_get<_Iter>(__hold_));
+    }
+  }
+
+  common_iterator& operator++() {
+    _LIBCPP_ASSERT(holds_alternative<_Iter>(__hold_),
+                   "Cannot increment sentinel. Common iterator not holding an iterator.");
+    ++_VSTD::__unchecked_get<_Iter>(__hold_); return *this;
+  }
+
+  decltype(auto) operator++(int) {
+    _LIBCPP_ASSERT(holds_alternative<_Iter>(__hold_),
+                   "Cannot increment sentinel. Common iterator not holding an iterator.");
+
+    if constexpr (forward_iterator<_Iter>) {
+      auto __tmp = *this;
+      ++*this;
+      return __tmp;
+    } else if constexpr (requires (_Iter& __i) { { *__i++ } -> __referenceable; } ||
+                         !__postfix_proxy::__valid_for_iter) {
+      return _VSTD::__unchecked_get<_Iter>(__hold_)++;
+    } else {
+      __postfix_proxy __p(**this);
+      ++*this;
+      return __p;
+    }
+  }
+
+  template<class _I2, sentinel_for<_Iter> _S2>
+    requires sentinel_for<_Sent, _I2>
+  friend bool operator==(const common_iterator& __x, const common_iterator<_I2, _S2>& __y) {
+    _LIBCPP_ASSERT(!__x.__hold_.valueless_by_exception() &&
+                   !__y.__hold_.valueless_by_exception(),
+                   "One or both common_iterators are valueless. (Cannot compare valueless iterators.)");
+
+    auto __x_index = __x.__hold_.index();
+    auto __y_index = __y.__hold_.index();
+
+    if (__x_index == __y_index)
+      return true;
+
+    if (__x_index == 0)
+      return _VSTD::__unchecked_get<_Iter>(__x.__hold_) == _VSTD::__unchecked_get<_S2>(__y.__hold_);
+
+    return _VSTD::__unchecked_get<_Sent>(__x.__hold_) == _VSTD::__unchecked_get<_I2>(__y.__hold_);
+  }
+
+  template<class _I2, sentinel_for<_Iter> _S2>
+    requires sentinel_for<_Sent, _I2> && equality_comparable_with<_Iter, _I2>
+  friend bool operator==(const common_iterator& __x, const common_iterator<_I2, _S2>& __y) {
+    _LIBCPP_ASSERT(!__x.__hold_.valueless_by_exception() &&
+                   !__y.__hold_.valueless_by_exception(),
+                   "One or both common_iterators are valueless. (Cannot compare valueless iterators.)");
+
+    auto __x_index = __x.__hold_.index();
+    auto __y_index = __y.__hold_.index();
+
+    if (__x_index == 1 && __y_index == 1)
+      return true;
+
+    if (__x_index == 0 && __y_index == 0)
+      return  _VSTD::__unchecked_get<_Iter>(__x.__hold_) ==  _VSTD::__unchecked_get<_I2>(__y.__hold_);
+
+    if (__x_index == 0)
+      return  _VSTD::__unchecked_get<_Iter>(__x.__hold_) == _VSTD::__unchecked_get<_S2>(__y.__hold_);
+
+    return _VSTD::__unchecked_get<_Sent>(__x.__hold_) ==  _VSTD::__unchecked_get<_I2>(__y.__hold_);
+  }
+
+  template<sized_sentinel_for<_Iter> _I2, sized_sentinel_for<_Iter> _S2>
+    requires sized_sentinel_for<_Sent, _I2>
+  friend iter_difference_t<_I2> operator-(const common_iterator& __x, const common_iterator<_I2, _S2>& __y) {
+    _LIBCPP_ASSERT(!__x.__hold_.valueless_by_exception() &&
+                   !__y.__hold_.valueless_by_exception(),
+                   "One or both common_iterators are valueless. (Cannot subtract valueless iterators.)");
+
+    auto __x_index = __x.__hold_.index();
+    auto __y_index = __y.__hold_.index();
+
+    if (__x_index == 1 && __y_index == 1)
+      return 0;
+
+    if (__x_index == 0 && __y_index == 0)
+      return  _VSTD::__unchecked_get<_Iter>(__x.__hold_) - _VSTD::__unchecked_get<_I2>(__y.__hold_);
+
+    if (__x_index == 0)
+      return  _VSTD::__unchecked_get<_Iter>(__x.__hold_) - _VSTD::__unchecked_get<_S2>(__y.__hold_);
+
+    return _VSTD::__unchecked_get<_Sent>(__x.__hold_) - _VSTD::__unchecked_get<_I2>(__y.__hold_);
+  }
+
+  friend iter_rvalue_reference_t<_Iter> iter_move(const common_iterator& __i)
+    noexcept(noexcept(ranges::iter_move(declval<const _Iter&>())))
+      requires input_iterator<_Iter>
+  {
+    _LIBCPP_ASSERT(holds_alternative<_Iter>(__i.__hold_),
+                   "Cannot iter_move a sentinel. Common iterator not holding an iterator.");
+    return ranges::iter_move( _VSTD::__unchecked_get<_Iter>(__i.__hold_));
+  }
+
+  template<indirectly_swappable<_Iter> _I2, class _S2>
+  friend void iter_swap(const common_iterator& __x, const common_iterator<_I2, _S2>& __y)
+      noexcept(noexcept(ranges::iter_swap(declval<const _Iter&>(), declval<const _I2&>())))
+  {
+    _LIBCPP_ASSERT(holds_alternative<_Iter>(__x.__hold_),
+                   "Cannot swap __y with a sentinel. Common iterator (__x) not holding an iterator.");
+    _LIBCPP_ASSERT(holds_alternative<_Iter>(__y.__hold_),
+                   "Cannot swap __x with a sentinel. Common iterator (__y) not holding an iterator.");
+    return ranges::iter_swap( _VSTD::__unchecked_get<_Iter>(__x.__hold_),  _VSTD::__unchecked_get<_Iter>(__y.__hold_));
+  }
+};
+
+template<class _Iter, class _Sent>
+struct incrementable_traits<common_iterator<_Iter, _Sent>> {
+  using difference_type = iter_difference_t<_Iter>;
+};
+
+template<class _Iter>
+concept __denotes_forward_iter =
+  requires { typename iterator_traits<_Iter>::iterator_category; } &&
+  derived_from<typename iterator_traits<_Iter>::iterator_category, forward_iterator_tag>;
+
+template<class _Iter, class _Sent>
+concept __common_iter_has_ptr_op = requires(const common_iterator<_Iter, _Sent>& __a) {
+  __a.operator->();
+};
+
+template<class, class>
+struct __arrow_type_or_void {
+    using type = void;
+};
+
+template<class _Iter, class _Sent>
+  requires __common_iter_has_ptr_op<_Iter, _Sent>
+struct __arrow_type_or_void<_Iter, _Sent> {
+    using type = decltype(declval<const common_iterator<_Iter, _Sent>>().operator->());
+};
+
+template<class _Iter, class _Sent>
+struct iterator_traits<common_iterator<_Iter, _Sent>> {
+  using iterator_concept = _If<forward_iterator<_Iter>,
+                               forward_iterator_tag,
+                               input_iterator_tag>;
+  using iterator_category = _If<__denotes_forward_iter<_Iter>,
+                                forward_iterator_tag,
+                                input_iterator_tag>;
+  using pointer = typename __arrow_type_or_void<_Iter, _Sent>::type;
+  using value_type = iter_value_t<_Iter>;
+  using difference_type = iter_difference_t<_Iter>;
+  using reference = iter_reference_t<_Iter>;
+};
+
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_COMMON_ITERATOR_H
lib/libcxx/include/__iterator/concepts.h
@@ -0,0 +1,272 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_CONCEPTS_H
+#define _LIBCPP___ITERATOR_CONCEPTS_H
+
+#include <__config>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/readable_traits.h>
+#include <__memory/pointer_traits.h>
+#include <__utility/forward.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// clang-format off
+
+// [iterator.concept.readable]
+template<class _In>
+concept __indirectly_readable_impl =
+  requires(const _In __i) {
+    typename iter_value_t<_In>;
+    typename iter_reference_t<_In>;
+    typename iter_rvalue_reference_t<_In>;
+    { *__i } -> same_as<iter_reference_t<_In>>;
+    { ranges::iter_move(__i) } -> same_as<iter_rvalue_reference_t<_In>>;
+  } &&
+  common_reference_with<iter_reference_t<_In>&&, iter_value_t<_In>&> &&
+  common_reference_with<iter_reference_t<_In>&&, iter_rvalue_reference_t<_In>&&> &&
+  common_reference_with<iter_rvalue_reference_t<_In>&&, const iter_value_t<_In>&>;
+
+template<class _In>
+concept indirectly_readable = __indirectly_readable_impl<remove_cvref_t<_In>>;
+
+template<indirectly_readable _Tp>
+using iter_common_reference_t = common_reference_t<iter_reference_t<_Tp>, iter_value_t<_Tp>&>;
+
+// [iterator.concept.writable]
+template<class _Out, class _Tp>
+concept indirectly_writable =
+  requires(_Out&& __o, _Tp&& __t) {
+    *__o = _VSTD::forward<_Tp>(__t);                        // not required to be equality-preserving
+    *_VSTD::forward<_Out>(__o) = _VSTD::forward<_Tp>(__t);  // not required to be equality-preserving
+    const_cast<const iter_reference_t<_Out>&&>(*__o) = _VSTD::forward<_Tp>(__t);                       // not required to be equality-preserving
+    const_cast<const iter_reference_t<_Out>&&>(*_VSTD::forward<_Out>(__o)) = _VSTD::forward<_Tp>(__t); // not required to be equality-preserving
+  };
+
+// [iterator.concept.winc]
+template<class _Tp>
+concept __integer_like = integral<_Tp> && !same_as<_Tp, bool>;
+
+template<class _Tp>
+concept __signed_integer_like = signed_integral<_Tp>;
+
+template<class _Ip>
+concept weakly_incrementable =
+  movable<_Ip> &&
+  requires(_Ip __i) {
+    typename iter_difference_t<_Ip>;
+    requires __signed_integer_like<iter_difference_t<_Ip>>;
+    { ++__i } -> same_as<_Ip&>;   // not required to be equality-preserving
+    __i++;                        // not required to be equality-preserving
+  };
+
+// [iterator.concept.inc]
+template<class _Ip>
+concept incrementable =
+  regular<_Ip> &&
+  weakly_incrementable<_Ip> &&
+  requires(_Ip __i) {
+    { __i++ } -> same_as<_Ip>;
+  };
+
+// [iterator.concept.iterator]
+template<class _Ip>
+concept input_or_output_iterator =
+  requires(_Ip __i) {
+    { *__i } -> __referenceable;
+  } &&
+  weakly_incrementable<_Ip>;
+
+// [iterator.concept.sentinel]
+template<class _Sp, class _Ip>
+concept sentinel_for =
+  semiregular<_Sp> &&
+  input_or_output_iterator<_Ip> &&
+  __weakly_equality_comparable_with<_Sp, _Ip>;
+
+template<class, class>
+inline constexpr bool disable_sized_sentinel_for = false;
+
+template<class _Sp, class _Ip>
+concept sized_sentinel_for =
+  sentinel_for<_Sp, _Ip> &&
+  !disable_sized_sentinel_for<remove_cv_t<_Sp>, remove_cv_t<_Ip>> &&
+  requires(const _Ip& __i, const _Sp& __s) {
+    { __s - __i } -> same_as<iter_difference_t<_Ip>>;
+    { __i - __s } -> same_as<iter_difference_t<_Ip>>;
+  };
+
+// [iterator.concept.input]
+template<class _Ip>
+concept input_iterator =
+  input_or_output_iterator<_Ip> &&
+  indirectly_readable<_Ip> &&
+  requires { typename _ITER_CONCEPT<_Ip>; } &&
+  derived_from<_ITER_CONCEPT<_Ip>, input_iterator_tag>;
+
+// [iterator.concept.output]
+template<class _Ip, class _Tp>
+concept output_iterator =
+  input_or_output_iterator<_Ip> &&
+  indirectly_writable<_Ip, _Tp> &&
+  requires (_Ip __it, _Tp&& __t) {
+    *__it++ = _VSTD::forward<_Tp>(__t); // not required to be equality-preserving
+  };
+
+// [iterator.concept.forward]
+template<class _Ip>
+concept forward_iterator =
+  input_iterator<_Ip> &&
+  derived_from<_ITER_CONCEPT<_Ip>, forward_iterator_tag> &&
+  incrementable<_Ip> &&
+  sentinel_for<_Ip, _Ip>;
+
+// [iterator.concept.bidir]
+template<class _Ip>
+concept bidirectional_iterator =
+  forward_iterator<_Ip> &&
+  derived_from<_ITER_CONCEPT<_Ip>, bidirectional_iterator_tag> &&
+  requires(_Ip __i) {
+    { --__i } -> same_as<_Ip&>;
+    { __i-- } -> same_as<_Ip>;
+  };
+
+template<class _Ip>
+concept random_access_iterator =
+  bidirectional_iterator<_Ip> &&
+  derived_from<_ITER_CONCEPT<_Ip>, random_access_iterator_tag> &&
+  totally_ordered<_Ip> &&
+  sized_sentinel_for<_Ip, _Ip> &&
+  requires(_Ip __i, const _Ip __j, const iter_difference_t<_Ip> __n) {
+    { __i += __n } -> same_as<_Ip&>;
+    { __j +  __n } -> same_as<_Ip>;
+    { __n +  __j } -> same_as<_Ip>;
+    { __i -= __n } -> same_as<_Ip&>;
+    { __j -  __n } -> same_as<_Ip>;
+    {  __j[__n]  } -> same_as<iter_reference_t<_Ip>>;
+  };
+
+template<class _Ip>
+concept contiguous_iterator =
+  random_access_iterator<_Ip> &&
+  derived_from<_ITER_CONCEPT<_Ip>, contiguous_iterator_tag> &&
+  is_lvalue_reference_v<iter_reference_t<_Ip>> &&
+  same_as<iter_value_t<_Ip>, remove_cvref_t<iter_reference_t<_Ip>>> &&
+  (is_pointer_v<_Ip> || requires { sizeof(__pointer_traits_element_type<_Ip>); }) &&
+  requires(const _Ip& __i) {
+    { _VSTD::to_address(__i) } -> same_as<add_pointer_t<iter_reference_t<_Ip>>>;
+  };
+
+template<class _Ip>
+concept __has_arrow = input_iterator<_Ip> && (is_pointer_v<_Ip> || requires(_Ip __i) { __i.operator->(); });
+
+// [indirectcallable.indirectinvocable]
+template<class _Fp, class _It>
+concept indirectly_unary_invocable =
+  indirectly_readable<_It> &&
+  copy_constructible<_Fp> &&
+  invocable<_Fp&, iter_value_t<_It>&> &&
+  invocable<_Fp&, iter_reference_t<_It>> &&
+  invocable<_Fp&, iter_common_reference_t<_It>> &&
+  common_reference_with<
+    invoke_result_t<_Fp&, iter_value_t<_It>&>,
+    invoke_result_t<_Fp&, iter_reference_t<_It>>>;
+
+template<class _Fp, class _It>
+concept indirectly_regular_unary_invocable =
+  indirectly_readable<_It> &&
+  copy_constructible<_Fp> &&
+  regular_invocable<_Fp&, iter_value_t<_It>&> &&
+  regular_invocable<_Fp&, iter_reference_t<_It>> &&
+  regular_invocable<_Fp&, iter_common_reference_t<_It>> &&
+  common_reference_with<
+    invoke_result_t<_Fp&, iter_value_t<_It>&>,
+    invoke_result_t<_Fp&, iter_reference_t<_It>>>;
+
+template<class _Fp, class _It>
+concept indirect_unary_predicate =
+  indirectly_readable<_It> &&
+  copy_constructible<_Fp> &&
+  predicate<_Fp&, iter_value_t<_It>&> &&
+  predicate<_Fp&, iter_reference_t<_It>> &&
+  predicate<_Fp&, iter_common_reference_t<_It>>;
+
+template<class _Fp, class _It1, class _It2>
+concept indirect_binary_predicate =
+  indirectly_readable<_It1> && indirectly_readable<_It2> &&
+  copy_constructible<_Fp> &&
+  predicate<_Fp&, iter_value_t<_It1>&, iter_value_t<_It2>&> &&
+  predicate<_Fp&, iter_value_t<_It1>&, iter_reference_t<_It2>> &&
+  predicate<_Fp&, iter_reference_t<_It1>, iter_value_t<_It2>&> &&
+  predicate<_Fp&, iter_reference_t<_It1>, iter_reference_t<_It2>> &&
+  predicate<_Fp&, iter_common_reference_t<_It1>, iter_common_reference_t<_It2>>;
+
+template<class _Fp, class _It1, class _It2 = _It1>
+concept indirect_equivalence_relation =
+  indirectly_readable<_It1> && indirectly_readable<_It2> &&
+  copy_constructible<_Fp> &&
+  equivalence_relation<_Fp&, iter_value_t<_It1>&, iter_value_t<_It2>&> &&
+  equivalence_relation<_Fp&, iter_value_t<_It1>&, iter_reference_t<_It2>> &&
+  equivalence_relation<_Fp&, iter_reference_t<_It1>, iter_value_t<_It2>&> &&
+  equivalence_relation<_Fp&, iter_reference_t<_It1>, iter_reference_t<_It2>> &&
+  equivalence_relation<_Fp&, iter_common_reference_t<_It1>, iter_common_reference_t<_It2>>;
+
+template<class _Fp, class _It1, class _It2 = _It1>
+concept indirect_strict_weak_order =
+  indirectly_readable<_It1> && indirectly_readable<_It2> &&
+  copy_constructible<_Fp> &&
+  strict_weak_order<_Fp&, iter_value_t<_It1>&, iter_value_t<_It2>&> &&
+  strict_weak_order<_Fp&, iter_value_t<_It1>&, iter_reference_t<_It2>> &&
+  strict_weak_order<_Fp&, iter_reference_t<_It1>, iter_value_t<_It2>&> &&
+  strict_weak_order<_Fp&, iter_reference_t<_It1>, iter_reference_t<_It2>> &&
+  strict_weak_order<_Fp&, iter_common_reference_t<_It1>, iter_common_reference_t<_It2>>;
+
+template<class _Fp, class... _Its>
+  requires (indirectly_readable<_Its> && ...) && invocable<_Fp, iter_reference_t<_Its>...>
+using indirect_result_t = invoke_result_t<_Fp, iter_reference_t<_Its>...>;
+
+template<class _In, class _Out>
+concept indirectly_movable =
+  indirectly_readable<_In> &&
+  indirectly_writable<_Out, iter_rvalue_reference_t<_In>>;
+
+template<class _In, class _Out>
+concept indirectly_movable_storable =
+  indirectly_movable<_In, _Out> &&
+  indirectly_writable<_Out, iter_value_t<_In>> &&
+  movable<iter_value_t<_In>> &&
+  constructible_from<iter_value_t<_In>, iter_rvalue_reference_t<_In>> &&
+  assignable_from<iter_value_t<_In>&, iter_rvalue_reference_t<_In>>;
+
+// Note: indirectly_swappable is located in iter_swap.h to prevent a dependency cycle
+// (both iter_swap and indirectly_swappable require indirectly_readable).
+
+// clang-format on
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_CONCEPTS_H
lib/libcxx/include/__iterator/counted_iterator.h
@@ -0,0 +1,306 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___ITERATOR_COUNTED_ITERATOR_H
+#define _LIBCPP___ITERATOR_COUNTED_ITERATOR_H
+
+#include <__config>
+#include <__debug>
+#include <__iterator/concepts.h>
+#include <__iterator/default_sentinel.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iter_swap.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/readable_traits.h>
+#include <__memory/pointer_traits.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+template<class>
+struct __counted_iterator_concept {};
+
+template<class _Iter>
+  requires requires { typename _Iter::iterator_concept; }
+struct __counted_iterator_concept<_Iter> {
+  using iterator_concept = typename _Iter::iterator_concept;
+};
+
+template<class>
+struct __counted_iterator_category {};
+
+template<class _Iter>
+  requires requires { typename _Iter::iterator_category; }
+struct __counted_iterator_category<_Iter> {
+  using iterator_category = typename _Iter::iterator_category;
+};
+
+template<class>
+struct __counted_iterator_value_type {};
+
+template<indirectly_readable _Iter>
+struct __counted_iterator_value_type<_Iter> {
+  using value_type = iter_value_t<_Iter>;
+};
+
+template<input_or_output_iterator _Iter>
+class counted_iterator
+  : public __counted_iterator_concept<_Iter>
+  , public __counted_iterator_category<_Iter>
+  , public __counted_iterator_value_type<_Iter>
+{
+public:
+  [[no_unique_address]] _Iter __current_ = _Iter();
+  iter_difference_t<_Iter> __count_ = 0;
+
+  using iterator_type = _Iter;
+  using difference_type = iter_difference_t<_Iter>;
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator() requires default_initializable<_Iter> = default;
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator(_Iter __iter, iter_difference_t<_Iter> __n)
+   : __current_(_VSTD::move(__iter)), __count_(__n) {
+    _LIBCPP_ASSERT(__n >= 0, "__n must not be negative.");
+  }
+
+  template<class _I2>
+    requires convertible_to<const _I2&, _Iter>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator(const counted_iterator<_I2>& __other)
+   : __current_(__other.__current_), __count_(__other.__count_) {}
+
+  template<class _I2>
+    requires assignable_from<_Iter&, const _I2&>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator& operator=(const counted_iterator<_I2>& __other) {
+    __current_ = __other.__current_;
+    __count_ = __other.__count_;
+    return *this;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr const _Iter& base() const& { return __current_; }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Iter base() && { return _VSTD::move(__current_); }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr iter_difference_t<_Iter> count() const noexcept { return __count_; }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) operator*() {
+    _LIBCPP_ASSERT(__count_ > 0, "Iterator is equal to or past end.");
+    return *__current_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) operator*() const
+    requires __dereferenceable<const _Iter>
+  {
+    _LIBCPP_ASSERT(__count_ > 0, "Iterator is equal to or past end.");
+    return *__current_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto operator->() const noexcept
+    requires contiguous_iterator<_Iter>
+  {
+    return _VSTD::to_address(__current_);
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator& operator++() {
+    _LIBCPP_ASSERT(__count_ > 0, "Iterator already at or past end.");
+    ++__current_;
+    --__count_;
+    return *this;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  decltype(auto) operator++(int) {
+    _LIBCPP_ASSERT(__count_ > 0, "Iterator already at or past end.");
+    --__count_;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try { return __current_++; }
+    catch(...) { ++__count_; throw; }
+#else
+    return __current_++;
+#endif // _LIBCPP_NO_EXCEPTIONS
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator operator++(int)
+    requires forward_iterator<_Iter>
+  {
+    _LIBCPP_ASSERT(__count_ > 0, "Iterator already at or past end.");
+    counted_iterator __tmp = *this;
+    ++*this;
+    return __tmp;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator& operator--()
+    requires bidirectional_iterator<_Iter>
+  {
+    --__current_;
+    ++__count_;
+    return *this;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator operator--(int)
+    requires bidirectional_iterator<_Iter>
+  {
+    counted_iterator __tmp = *this;
+    --*this;
+    return __tmp;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator operator+(iter_difference_t<_Iter> __n) const
+    requires random_access_iterator<_Iter>
+  {
+    return counted_iterator(__current_ + __n, __count_ - __n);
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr counted_iterator operator+(
+    iter_difference_t<_Iter> __n, const counted_iterator& __x)
+    requires random_access_iterator<_Iter>
+  {
+    return __x + __n;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator& operator+=(iter_difference_t<_Iter> __n)
+    requires random_access_iterator<_Iter>
+  {
+    _LIBCPP_ASSERT(__n <= __count_, "Cannot advance iterator past end.");
+    __current_ += __n;
+    __count_ -= __n;
+    return *this;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator operator-(iter_difference_t<_Iter> __n) const
+    requires random_access_iterator<_Iter>
+  {
+    return counted_iterator(__current_ - __n, __count_ + __n);
+  }
+
+  template<common_with<_Iter> _I2>
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr iter_difference_t<_I2> operator-(
+    const counted_iterator& __lhs, const counted_iterator<_I2>& __rhs)
+  {
+    return __rhs.__count_ - __lhs.__count_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr iter_difference_t<_Iter> operator-(
+    const counted_iterator& __lhs, default_sentinel_t)
+  {
+    return -__lhs.__count_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr iter_difference_t<_Iter> operator-(
+    default_sentinel_t, const counted_iterator& __rhs)
+  {
+    return __rhs.__count_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr counted_iterator& operator-=(iter_difference_t<_Iter> __n)
+    requires random_access_iterator<_Iter>
+  {
+    _LIBCPP_ASSERT(-__n <= __count_, "Attempt to subtract too large of a size: "
+                                     "counted_iterator would be decremented before the "
+                                     "first element of its range.");
+    __current_ -= __n;
+    __count_ += __n;
+    return *this;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) operator[](iter_difference_t<_Iter> __n) const
+    requires random_access_iterator<_Iter>
+  {
+    _LIBCPP_ASSERT(__n < __count_, "Subscript argument must be less than size.");
+    return __current_[__n];
+  }
+
+  template<common_with<_Iter> _I2>
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr bool operator==(
+    const counted_iterator& __lhs, const counted_iterator<_I2>& __rhs)
+  {
+    return __lhs.__count_ == __rhs.__count_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr bool operator==(
+    const counted_iterator& __lhs, default_sentinel_t)
+  {
+    return __lhs.__count_ == 0;
+  }
+
+  template<common_with<_Iter> _I2>
+  friend constexpr strong_ordering operator<=>(
+    const counted_iterator& __lhs, const counted_iterator<_I2>& __rhs)
+  {
+    return __rhs.__count_ <=> __lhs.__count_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr iter_rvalue_reference_t<_Iter> iter_move(const counted_iterator& __i)
+    noexcept(noexcept(ranges::iter_move(__i.__current_)))
+      requires input_iterator<_Iter>
+  {
+    _LIBCPP_ASSERT(__i.__count_ > 0, "Iterator must not be past end of range.");
+    return ranges::iter_move(__i.__current_);
+  }
+
+  template<indirectly_swappable<_Iter> _I2>
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr void iter_swap(const counted_iterator& __x, const counted_iterator<_I2>& __y)
+    noexcept(noexcept(ranges::iter_swap(__x.__current_, __y.__current_)))
+  {
+    _LIBCPP_ASSERT(__x.__count_ > 0 && __y.__count_ > 0,
+                   "Iterators must not be past end of range.");
+    return ranges::iter_swap(__x.__current_, __y.__current_);
+  }
+};
+
+template<input_iterator _Iter>
+  requires same_as<_ITER_TRAITS<_Iter>, iterator_traits<_Iter>>
+struct iterator_traits<counted_iterator<_Iter>> : iterator_traits<_Iter> {
+  using pointer = conditional_t<contiguous_iterator<_Iter>,
+                                add_pointer_t<iter_reference_t<_Iter>>, void>;
+};
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_COUNTED_ITERATOR_H
lib/libcxx/include/__iterator/data.h
@@ -0,0 +1,56 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_DATA_H
+#define _LIBCPP___ITERATOR_DATA_H
+
+#include <__config>
+#include <cstddef>
+#include <initializer_list>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+
+template <class _Cont> constexpr
+_LIBCPP_INLINE_VISIBILITY
+auto data(_Cont& __c)
+_NOEXCEPT_(noexcept(__c.data()))
+-> decltype        (__c.data())
+{ return            __c.data(); }
+
+template <class _Cont> constexpr
+_LIBCPP_INLINE_VISIBILITY
+auto data(const _Cont& __c)
+_NOEXCEPT_(noexcept(__c.data()))
+-> decltype        (__c.data())
+{ return            __c.data(); }
+
+template <class _Tp, size_t _Sz>
+_LIBCPP_INLINE_VISIBILITY
+constexpr _Tp* data(_Tp (&__array)[_Sz]) noexcept { return __array; }
+
+template <class _Ep>
+_LIBCPP_INLINE_VISIBILITY
+constexpr const _Ep* data(initializer_list<_Ep> __il) noexcept { return __il.begin(); }
+
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_DATA_H
lib/libcxx/include/__iterator/default_sentinel.h
@@ -0,0 +1,35 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_DEFAULT_SENTINEL_H
+#define _LIBCPP___ITERATOR_DEFAULT_SENTINEL_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+struct default_sentinel_t { };
+inline constexpr default_sentinel_t default_sentinel{};
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_DEFAULT_SENTINEL_H
lib/libcxx/include/__iterator/distance.h
@@ -0,0 +1,56 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_DISTANCE_H
+#define _LIBCPP___ITERATOR_DISTANCE_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIter>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+typename iterator_traits<_InputIter>::difference_type
+__distance(_InputIter __first, _InputIter __last, input_iterator_tag)
+{
+    typename iterator_traits<_InputIter>::difference_type __r(0);
+    for (; __first != __last; ++__first)
+        ++__r;
+    return __r;
+}
+
+template <class _RandIter>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+typename iterator_traits<_RandIter>::difference_type
+__distance(_RandIter __first, _RandIter __last, random_access_iterator_tag)
+{
+    return __last - __first;
+}
+
+template <class _InputIter>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+typename iterator_traits<_InputIter>::difference_type
+distance(_InputIter __first, _InputIter __last)
+{
+    return _VSTD::__distance(__first, __last, typename iterator_traits<_InputIter>::iterator_category());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_DISTANCE_H
lib/libcxx/include/__iterator/empty.h
@@ -0,0 +1,49 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_EMPTY_H
+#define _LIBCPP___ITERATOR_EMPTY_H
+
+#include <__config>
+#include <cstddef>
+#include <initializer_list>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+
+template <class _Cont>
+_LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
+constexpr auto empty(const _Cont& __c)
+_NOEXCEPT_(noexcept(__c.empty()))
+-> decltype        (__c.empty())
+{ return            __c.empty(); }
+
+template <class _Tp, size_t _Sz>
+_LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
+constexpr bool empty(const _Tp (&)[_Sz]) noexcept { return false; }
+
+template <class _Ep>
+_LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
+constexpr bool empty(initializer_list<_Ep> __il) noexcept { return __il.size() == 0; }
+
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_EMPTY_H
lib/libcxx/include/__iterator/erase_if_container.h
@@ -0,0 +1,45 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_ERASE_IF_CONTAINER_H
+#define _LIBCPP___ITERATOR_ERASE_IF_CONTAINER_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Container, class _Predicate>
+_LIBCPP_HIDE_FROM_ABI
+typename _Container::size_type
+__libcpp_erase_if_container(_Container& __c, _Predicate& __pred) {
+  typename _Container::size_type __old_size = __c.size();
+
+  const typename _Container::iterator __last = __c.end();
+  for (typename _Container::iterator __iter = __c.begin(); __iter != __last;) {
+    if (__pred(*__iter))
+      __iter = __c.erase(__iter);
+    else
+      ++__iter;
+  }
+
+  return __old_size - __c.size();
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_ERASE_IF_CONTAINER_H
lib/libcxx/include/__iterator/front_insert_iterator.h
@@ -0,0 +1,75 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_FRONT_INSERT_ITERATOR_H
+#define _LIBCPP___ITERATOR_FRONT_INSERT_ITERATOR_H
+
+#include <__config>
+#include <__iterator/iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <__memory/addressof.h>
+#include <__utility/move.h>
+#include <cstddef>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Container>
+class _LIBCPP_TEMPLATE_VIS front_insert_iterator
+#if _LIBCPP_STD_VER <= 14 || !defined(_LIBCPP_ABI_NO_ITERATOR_BASES)
+    : public iterator<output_iterator_tag, void, void, void, void>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+protected:
+    _Container* container;
+public:
+    typedef output_iterator_tag iterator_category;
+    typedef void value_type;
+#if _LIBCPP_STD_VER > 17
+    typedef ptrdiff_t difference_type;
+#else
+    typedef void difference_type;
+#endif
+    typedef void pointer;
+    typedef void reference;
+    typedef _Container container_type;
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 explicit front_insert_iterator(_Container& __x) : container(_VSTD::addressof(__x)) {}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator=(const typename _Container::value_type& __value_)
+        {container->push_front(__value_); return *this;}
+#ifndef _LIBCPP_CXX03_LANG
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator=(typename _Container::value_type&& __value_)
+        {container->push_front(_VSTD::move(__value_)); return *this;}
+#endif // _LIBCPP_CXX03_LANG
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator*()     {return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator& operator++()    {return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 front_insert_iterator  operator++(int) {return *this;}
+};
+
+template <class _Container>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+front_insert_iterator<_Container>
+front_inserter(_Container& __x)
+{
+    return front_insert_iterator<_Container>(__x);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_FRONT_INSERT_ITERATOR_H
lib/libcxx/include/__iterator/incrementable_traits.h
@@ -0,0 +1,77 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_INCREMENTABLE_TRAITS_H
+#define _LIBCPP___ITERATOR_INCREMENTABLE_TRAITS_H
+
+#include <__config>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// [incrementable.traits]
+template<class> struct incrementable_traits {};
+
+template<class _Tp>
+requires is_object_v<_Tp>
+struct incrementable_traits<_Tp*> {
+  using difference_type = ptrdiff_t;
+};
+
+template<class _Ip>
+struct incrementable_traits<const _Ip> : incrementable_traits<_Ip> {};
+
+template<class _Tp>
+concept __has_member_difference_type = requires { typename _Tp::difference_type; };
+
+template<__has_member_difference_type _Tp>
+struct incrementable_traits<_Tp> {
+  using difference_type = typename _Tp::difference_type;
+};
+
+template<class _Tp>
+concept __has_integral_minus =
+  requires(const _Tp& __x, const _Tp& __y) {
+    { __x - __y } -> integral;
+  };
+
+template<__has_integral_minus _Tp>
+requires (!__has_member_difference_type<_Tp>)
+struct incrementable_traits<_Tp> {
+  using difference_type = make_signed_t<decltype(declval<_Tp>() - declval<_Tp>())>;
+};
+
+template <class>
+struct iterator_traits;
+
+// Let `RI` be `remove_cvref_t<I>`. The type `iter_difference_t<I>` denotes
+// `incrementable_traits<RI>::difference_type` if `iterator_traits<RI>` names a specialization
+// generated from the primary template, and `iterator_traits<RI>::difference_type` otherwise.
+template <class _Ip>
+using iter_difference_t = typename conditional_t<__is_primary_template<iterator_traits<remove_cvref_t<_Ip> > >::value,
+                                                 incrementable_traits<remove_cvref_t<_Ip> >,
+                                                 iterator_traits<remove_cvref_t<_Ip> > >::difference_type;
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_INCREMENTABLE_TRAITS_H
lib/libcxx/include/__iterator/insert_iterator.h
@@ -0,0 +1,77 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_INSERT_ITERATOR_H
+#define _LIBCPP___ITERATOR_INSERT_ITERATOR_H
+
+#include <__config>
+#include <__iterator/iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <__memory/addressof.h>
+#include <__utility/move.h>
+#include <cstddef>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Container>
+class _LIBCPP_TEMPLATE_VIS insert_iterator
+#if _LIBCPP_STD_VER <= 14 || !defined(_LIBCPP_ABI_NO_ITERATOR_BASES)
+    : public iterator<output_iterator_tag, void, void, void, void>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+protected:
+    _Container* container;
+    typename _Container::iterator iter; // FIXME: `ranges::iterator_t<Container>` in C++20 mode
+public:
+    typedef output_iterator_tag iterator_category;
+    typedef void value_type;
+#if _LIBCPP_STD_VER > 17
+    typedef ptrdiff_t difference_type;
+#else
+    typedef void difference_type;
+#endif
+    typedef void pointer;
+    typedef void reference;
+    typedef _Container container_type;
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator(_Container& __x, typename _Container::iterator __i)
+        : container(_VSTD::addressof(__x)), iter(__i) {}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator=(const typename _Container::value_type& __value_)
+        {iter = container->insert(iter, __value_); ++iter; return *this;}
+#ifndef _LIBCPP_CXX03_LANG
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator=(typename _Container::value_type&& __value_)
+        {iter = container->insert(iter, _VSTD::move(__value_)); ++iter; return *this;}
+#endif // _LIBCPP_CXX03_LANG
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator*()        {return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator++()       {return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 insert_iterator& operator++(int)    {return *this;}
+};
+
+template <class _Container>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+insert_iterator<_Container>
+inserter(_Container& __x, typename _Container::iterator __i)
+{
+    return insert_iterator<_Container>(__x, __i);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_INSERT_ITERATOR_H
lib/libcxx/include/__iterator/istream_iterator.h
@@ -0,0 +1,103 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_ISTREAM_ITERATOR_H
+#define _LIBCPP___ITERATOR_ISTREAM_ITERATOR_H
+
+#include <__config>
+#include <__iterator/iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <__memory/addressof.h>
+#include <iosfwd> // for forward declarations of char_traits and basic_istream
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp, class _CharT = char,
+          class _Traits = char_traits<_CharT>, class _Distance = ptrdiff_t>
+class _LIBCPP_TEMPLATE_VIS istream_iterator
+#if _LIBCPP_STD_VER <= 14 || !defined(_LIBCPP_ABI_NO_ITERATOR_BASES)
+    : public iterator<input_iterator_tag, _Tp, _Distance, const _Tp*, const _Tp&>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+public:
+    typedef input_iterator_tag iterator_category;
+    typedef _Tp value_type;
+    typedef _Distance difference_type;
+    typedef const _Tp* pointer;
+    typedef const _Tp& reference;
+    typedef _CharT char_type;
+    typedef _Traits traits_type;
+    typedef basic_istream<_CharT,_Traits> istream_type;
+private:
+    istream_type* __in_stream_;
+    _Tp __value_;
+public:
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR istream_iterator() : __in_stream_(nullptr), __value_() {}
+    _LIBCPP_INLINE_VISIBILITY istream_iterator(istream_type& __s) : __in_stream_(_VSTD::addressof(__s))
+        {
+            if (!(*__in_stream_ >> __value_))
+                __in_stream_ = nullptr;
+        }
+
+    _LIBCPP_INLINE_VISIBILITY const _Tp& operator*() const {return __value_;}
+    _LIBCPP_INLINE_VISIBILITY const _Tp* operator->() const {return _VSTD::addressof((operator*()));}
+    _LIBCPP_INLINE_VISIBILITY istream_iterator& operator++()
+        {
+            if (!(*__in_stream_ >> __value_))
+                __in_stream_ = nullptr;
+            return *this;
+        }
+    _LIBCPP_INLINE_VISIBILITY istream_iterator  operator++(int)
+        {istream_iterator __t(*this); ++(*this); return __t;}
+
+    template <class _Up, class _CharU, class _TraitsU, class _DistanceU>
+    friend _LIBCPP_INLINE_VISIBILITY
+    bool
+    operator==(const istream_iterator<_Up, _CharU, _TraitsU, _DistanceU>& __x,
+               const istream_iterator<_Up, _CharU, _TraitsU, _DistanceU>& __y);
+
+    template <class _Up, class _CharU, class _TraitsU, class _DistanceU>
+    friend _LIBCPP_INLINE_VISIBILITY
+    bool
+    operator==(const istream_iterator<_Up, _CharU, _TraitsU, _DistanceU>& __x,
+               const istream_iterator<_Up, _CharU, _TraitsU, _DistanceU>& __y);
+};
+
+template <class _Tp, class _CharT, class _Traits, class _Distance>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator==(const istream_iterator<_Tp, _CharT, _Traits, _Distance>& __x,
+           const istream_iterator<_Tp, _CharT, _Traits, _Distance>& __y)
+{
+    return __x.__in_stream_ == __y.__in_stream_;
+}
+
+template <class _Tp, class _CharT, class _Traits, class _Distance>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(const istream_iterator<_Tp, _CharT, _Traits, _Distance>& __x,
+           const istream_iterator<_Tp, _CharT, _Traits, _Distance>& __y)
+{
+    return !(__x == __y);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_ISTREAM_ITERATOR_H
lib/libcxx/include/__iterator/istreambuf_iterator.h
@@ -0,0 +1,110 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_ISTREAMBUF_ITERATOR_H
+#define _LIBCPP___ITERATOR_ISTREAMBUF_ITERATOR_H
+
+#include <__config>
+#include <__iterator/iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <iosfwd> // for forward declaration of basic_streambuf
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template<class _CharT, class _Traits>
+class _LIBCPP_TEMPLATE_VIS istreambuf_iterator
+#if _LIBCPP_STD_VER <= 14 || !defined(_LIBCPP_ABI_NO_ITERATOR_BASES)
+    : public iterator<input_iterator_tag, _CharT,
+                      typename _Traits::off_type, _CharT*,
+                      _CharT>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+public:
+    typedef input_iterator_tag              iterator_category;
+    typedef _CharT                          value_type;
+    typedef typename _Traits::off_type      difference_type;
+    typedef _CharT*                         pointer;
+    typedef _CharT                          reference;
+    typedef _CharT                          char_type;
+    typedef _Traits                         traits_type;
+    typedef typename _Traits::int_type      int_type;
+    typedef basic_streambuf<_CharT,_Traits> streambuf_type;
+    typedef basic_istream<_CharT,_Traits>   istream_type;
+private:
+    mutable streambuf_type* __sbuf_;
+
+    class __proxy
+    {
+        char_type __keep_;
+        streambuf_type* __sbuf_;
+        _LIBCPP_INLINE_VISIBILITY __proxy(char_type __c, streambuf_type* __s)
+            : __keep_(__c), __sbuf_(__s) {}
+        friend class istreambuf_iterator;
+    public:
+        _LIBCPP_INLINE_VISIBILITY char_type operator*() const {return __keep_;}
+    };
+
+    _LIBCPP_INLINE_VISIBILITY
+    bool __test_for_eof() const
+    {
+        if (__sbuf_ && traits_type::eq_int_type(__sbuf_->sgetc(), traits_type::eof()))
+            __sbuf_ = nullptr;
+        return __sbuf_ == nullptr;
+    }
+public:
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR istreambuf_iterator() _NOEXCEPT : __sbuf_(nullptr) {}
+    _LIBCPP_INLINE_VISIBILITY istreambuf_iterator(istream_type& __s) _NOEXCEPT
+        : __sbuf_(__s.rdbuf()) {}
+    _LIBCPP_INLINE_VISIBILITY istreambuf_iterator(streambuf_type* __s) _NOEXCEPT
+        : __sbuf_(__s) {}
+    _LIBCPP_INLINE_VISIBILITY istreambuf_iterator(const __proxy& __p) _NOEXCEPT
+        : __sbuf_(__p.__sbuf_) {}
+
+    _LIBCPP_INLINE_VISIBILITY char_type  operator*() const
+        {return static_cast<char_type>(__sbuf_->sgetc());}
+    _LIBCPP_INLINE_VISIBILITY istreambuf_iterator& operator++()
+        {
+            __sbuf_->sbumpc();
+            return *this;
+        }
+    _LIBCPP_INLINE_VISIBILITY __proxy              operator++(int)
+        {
+            return __proxy(__sbuf_->sbumpc(), __sbuf_);
+        }
+
+    _LIBCPP_INLINE_VISIBILITY bool equal(const istreambuf_iterator& __b) const
+        {return __test_for_eof() == __b.__test_for_eof();}
+};
+
+template <class _CharT, class _Traits>
+inline _LIBCPP_INLINE_VISIBILITY
+bool operator==(const istreambuf_iterator<_CharT,_Traits>& __a,
+                const istreambuf_iterator<_CharT,_Traits>& __b)
+                {return __a.equal(__b);}
+
+template <class _CharT, class _Traits>
+inline _LIBCPP_INLINE_VISIBILITY
+bool operator!=(const istreambuf_iterator<_CharT,_Traits>& __a,
+                const istreambuf_iterator<_CharT,_Traits>& __b)
+                {return !__a.equal(__b);}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_ISTREAMBUF_ITERATOR_H
lib/libcxx/include/__iterator/iter_move.h
@@ -0,0 +1,91 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_ITER_MOVE_H
+#define _LIBCPP___ITERATOR_ITER_MOVE_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <__utility/forward.h>
+#include <concepts> // __class_or_enum
+#include <type_traits>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges::__iter_move {
+void iter_move();
+
+template<class _Ip>
+concept __unqualified_iter_move = requires(_Ip&& __i) {
+    iter_move(_VSTD::forward<_Ip>(__i));
+};
+
+// [iterator.cust.move]/1
+// The name ranges::iter_move denotes a customization point object.
+// The expression ranges::iter_move(E) for a subexpression E is
+// expression-equivalent to:
+struct __fn {
+  // [iterator.cust.move]/1.1
+  // iter_move(E), if E has class or enumeration type and iter_move(E) is a
+  // well-formed expression when treated as an unevaluated operand, [...]
+  template<class _Ip>
+    requires __class_or_enum<remove_cvref_t<_Ip>> && __unqualified_iter_move<_Ip>
+  [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) operator()(_Ip&& __i) const
+    noexcept(noexcept(iter_move(_VSTD::forward<_Ip>(__i))))
+  {
+    return iter_move(_VSTD::forward<_Ip>(__i));
+  }
+
+  // [iterator.cust.move]/1.2
+  // Otherwise, if the expression *E is well-formed:
+  //  1.2.1 if *E is an lvalue, std::move(*E);
+  //  1.2.2 otherwise, *E.
+  template<class _Ip>
+    requires (!(__class_or_enum<remove_cvref_t<_Ip>> && __unqualified_iter_move<_Ip>)) &&
+    requires(_Ip&& __i) { *_VSTD::forward<_Ip>(__i); }
+  [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) operator()(_Ip&& __i) const
+    noexcept(noexcept(*_VSTD::forward<_Ip>(__i)))
+  {
+    if constexpr (is_lvalue_reference_v<decltype(*_VSTD::forward<_Ip>(__i))>) {
+      return _VSTD::move(*_VSTD::forward<_Ip>(__i));
+    } else {
+      return *_VSTD::forward<_Ip>(__i);
+    }
+  }
+
+  // [iterator.cust.move]/1.3
+  // Otherwise, ranges::iter_move(E) is ill-formed.
+};
+} // namespace ranges::__iter_move
+
+namespace ranges::inline __cpo {
+  inline constexpr auto iter_move = __iter_move::__fn{};
+}
+
+template<__dereferenceable _Tp>
+requires requires(_Tp& __t) { { ranges::iter_move(__t) } -> __referenceable; }
+using iter_rvalue_reference_t = decltype(ranges::iter_move(declval<_Tp&>()));
+
+#endif // !_LIBCPP_HAS_NO_RANGES
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_ITER_MOVE_H
lib/libcxx/include/__iterator/iter_swap.h
@@ -0,0 +1,107 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___ITERATOR_ITER_SWAP_H
+#define _LIBCPP___ITERATOR_ITER_SWAP_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/readable_traits.h>
+#include <__ranges/access.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+namespace __iter_swap {
+  template<class _I1, class _I2>
+  void iter_swap(_I1, _I2) = delete;
+
+  template<class _T1, class _T2>
+  concept __unqualified_iter_swap = requires(_T1&& __x, _T2&& __y) {
+    iter_swap(_VSTD::forward<_T1>(__x), _VSTD::forward<_T2>(__y));
+  };
+
+  template<class _T1, class _T2>
+  concept __readable_swappable =
+    indirectly_readable<_T1> && indirectly_readable<_T2> &&
+    swappable_with<iter_reference_t<_T1>, iter_reference_t<_T2>>;
+
+  struct __fn {
+    template <class _T1, class _T2>
+      requires __unqualified_iter_swap<_T1, _T2>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr void operator()(_T1&& __x, _T2&& __y) const
+      noexcept(noexcept(iter_swap(_VSTD::forward<_T1>(__x), _VSTD::forward<_T2>(__y))))
+    {
+      (void)iter_swap(_VSTD::forward<_T1>(__x), _VSTD::forward<_T2>(__y));
+    }
+
+    template <class _T1, class _T2>
+      requires (!__unqualified_iter_swap<_T1, _T2>) &&
+               __readable_swappable<_T1, _T2>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr void operator()(_T1&& __x, _T2&& __y) const
+      noexcept(noexcept(ranges::swap(*_VSTD::forward<_T1>(__x), *_VSTD::forward<_T2>(__y))))
+    {
+      ranges::swap(*_VSTD::forward<_T1>(__x), *_VSTD::forward<_T2>(__y));
+    }
+
+    template <class _T1, class _T2>
+      requires (!__unqualified_iter_swap<_T1, _T2> &&
+                !__readable_swappable<_T1, _T2>) &&
+               indirectly_movable_storable<_T1, _T2> &&
+               indirectly_movable_storable<_T2, _T1>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr void operator()(_T1&& __x, _T2&& __y) const
+      noexcept(noexcept(iter_value_t<_T2>(ranges::iter_move(__y))) &&
+               noexcept(*__y = ranges::iter_move(__x)) &&
+               noexcept(*_VSTD::forward<_T1>(__x) = declval<iter_value_t<_T2>>()))
+    {
+      iter_value_t<_T2> __old(ranges::iter_move(__y));
+      *__y = ranges::iter_move(__x);
+      *_VSTD::forward<_T1>(__x) = _VSTD::move(__old);
+    }
+  };
+} // end namespace __iter_swap
+
+inline namespace __cpo {
+  inline constexpr auto iter_swap = __iter_swap::__fn{};
+} // namespace __cpo
+
+} // namespace ranges
+
+template<class _I1, class _I2 = _I1>
+concept indirectly_swappable =
+  indirectly_readable<_I1> && indirectly_readable<_I2> &&
+  requires(const _I1 __i1, const _I2 __i2) {
+    ranges::iter_swap(__i1, __i1);
+    ranges::iter_swap(__i2, __i2);
+    ranges::iter_swap(__i1, __i2);
+    ranges::iter_swap(__i2, __i1);
+  };
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_ITER_SWAP_H
lib/libcxx/include/__iterator/iterator.h
@@ -0,0 +1,40 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_ITERATOR_H
+#define _LIBCPP___ITERATOR_ITERATOR_H
+
+#include <__config>
+#include <cstddef>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template<class _Category, class _Tp, class _Distance = ptrdiff_t,
+         class _Pointer = _Tp*, class _Reference = _Tp&>
+struct _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX17 iterator
+{
+    typedef _Tp        value_type;
+    typedef _Distance  difference_type;
+    typedef _Pointer   pointer;
+    typedef _Reference reference;
+    typedef _Category  iterator_category;
+};
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_ITERATOR_H
lib/libcxx/include/__iterator/iterator_traits.h
@@ -0,0 +1,500 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_ITERATOR_TRAITS_H
+#define _LIBCPP___ITERATOR_ITERATOR_TRAITS_H
+
+#include <__config>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/readable_traits.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+template <class _Tp>
+using __with_reference = _Tp&;
+
+template <class _Tp>
+concept __referenceable = requires {
+  typename __with_reference<_Tp>;
+};
+
+template <class _Tp>
+concept __dereferenceable = requires(_Tp& __t) {
+  { *__t } -> __referenceable; // not required to be equality-preserving
+};
+
+// [iterator.traits]
+template<__dereferenceable _Tp>
+using iter_reference_t = decltype(*declval<_Tp&>());
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+template <class _Iter>
+struct _LIBCPP_TEMPLATE_VIS iterator_traits;
+
+struct _LIBCPP_TEMPLATE_VIS input_iterator_tag {};
+struct _LIBCPP_TEMPLATE_VIS output_iterator_tag {};
+struct _LIBCPP_TEMPLATE_VIS forward_iterator_tag       : public input_iterator_tag {};
+struct _LIBCPP_TEMPLATE_VIS bidirectional_iterator_tag : public forward_iterator_tag {};
+struct _LIBCPP_TEMPLATE_VIS random_access_iterator_tag : public bidirectional_iterator_tag {};
+#if _LIBCPP_STD_VER > 17
+struct _LIBCPP_TEMPLATE_VIS contiguous_iterator_tag    : public random_access_iterator_tag {};
+#endif
+
+template <class _Iter>
+struct __iter_traits_cache {
+  using type = _If<
+    __is_primary_template<iterator_traits<_Iter> >::value,
+    _Iter,
+    iterator_traits<_Iter>
+  >;
+};
+template <class _Iter>
+using _ITER_TRAITS = typename __iter_traits_cache<_Iter>::type;
+
+struct __iter_concept_concept_test {
+  template <class _Iter>
+  using _Apply = typename _ITER_TRAITS<_Iter>::iterator_concept;
+};
+struct __iter_concept_category_test {
+  template <class _Iter>
+  using _Apply = typename _ITER_TRAITS<_Iter>::iterator_category;
+};
+struct __iter_concept_random_fallback {
+  template <class _Iter>
+  using _Apply = _EnableIf<
+                          __is_primary_template<iterator_traits<_Iter> >::value,
+                          random_access_iterator_tag
+                        >;
+};
+
+template <class _Iter, class _Tester> struct __test_iter_concept
+    : _IsValidExpansion<_Tester::template _Apply, _Iter>,
+      _Tester
+{
+};
+
+template <class _Iter>
+struct __iter_concept_cache {
+  using type = _Or<
+    __test_iter_concept<_Iter, __iter_concept_concept_test>,
+    __test_iter_concept<_Iter, __iter_concept_category_test>,
+    __test_iter_concept<_Iter, __iter_concept_random_fallback>
+  >;
+};
+
+template <class _Iter>
+using _ITER_CONCEPT = typename __iter_concept_cache<_Iter>::type::template _Apply<_Iter>;
+
+
+template <class _Tp>
+struct __has_iterator_typedefs
+{
+private:
+    struct __two {char __lx; char __lxx;};
+    template <class _Up> static __two __test(...);
+    template <class _Up> static char __test(typename __void_t<typename _Up::iterator_category>::type* = 0,
+                                            typename __void_t<typename _Up::difference_type>::type* = 0,
+                                            typename __void_t<typename _Up::value_type>::type* = 0,
+                                            typename __void_t<typename _Up::reference>::type* = 0,
+                                            typename __void_t<typename _Up::pointer>::type* = 0);
+public:
+    static const bool value = sizeof(__test<_Tp>(0,0,0,0,0)) == 1;
+};
+
+
+template <class _Tp>
+struct __has_iterator_category
+{
+private:
+    struct __two {char __lx; char __lxx;};
+    template <class _Up> static __two __test(...);
+    template <class _Up> static char __test(typename _Up::iterator_category* = nullptr);
+public:
+    static const bool value = sizeof(__test<_Tp>(nullptr)) == 1;
+};
+
+template <class _Tp>
+struct __has_iterator_concept
+{
+private:
+    struct __two {char __lx; char __lxx;};
+    template <class _Up> static __two __test(...);
+    template <class _Up> static char __test(typename _Up::iterator_concept* = nullptr);
+public:
+    static const bool value = sizeof(__test<_Tp>(nullptr)) == 1;
+};
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// The `cpp17-*-iterator` exposition-only concepts are easily confused with the Cpp17*Iterator tables,
+// so they've been banished to a namespace that makes it obvious they have a niche use-case.
+namespace __iterator_traits_detail {
+template<class _Ip>
+concept __cpp17_iterator =
+  requires(_Ip __i) {
+    {   *__i } -> __referenceable;
+    {  ++__i } -> same_as<_Ip&>;
+    { *__i++ } -> __referenceable;
+  } &&
+  copyable<_Ip>;
+
+template<class _Ip>
+concept __cpp17_input_iterator =
+  __cpp17_iterator<_Ip> &&
+  equality_comparable<_Ip> &&
+  requires(_Ip __i) {
+    typename incrementable_traits<_Ip>::difference_type;
+    typename indirectly_readable_traits<_Ip>::value_type;
+    typename common_reference_t<iter_reference_t<_Ip>&&,
+                                typename indirectly_readable_traits<_Ip>::value_type&>;
+    typename common_reference_t<decltype(*__i++)&&,
+                                typename indirectly_readable_traits<_Ip>::value_type&>;
+    requires signed_integral<typename incrementable_traits<_Ip>::difference_type>;
+  };
+
+template<class _Ip>
+concept __cpp17_forward_iterator =
+  __cpp17_input_iterator<_Ip> &&
+  constructible_from<_Ip> &&
+  is_lvalue_reference_v<iter_reference_t<_Ip>> &&
+  same_as<remove_cvref_t<iter_reference_t<_Ip>>,
+          typename indirectly_readable_traits<_Ip>::value_type> &&
+  requires(_Ip __i) {
+    {  __i++ } -> convertible_to<_Ip const&>;
+    { *__i++ } -> same_as<iter_reference_t<_Ip>>;
+  };
+
+template<class _Ip>
+concept __cpp17_bidirectional_iterator =
+  __cpp17_forward_iterator<_Ip> &&
+  requires(_Ip __i) {
+    {  --__i } -> same_as<_Ip&>;
+    {  __i-- } -> convertible_to<_Ip const&>;
+    { *__i-- } -> same_as<iter_reference_t<_Ip>>;
+  };
+
+template<class _Ip>
+concept __cpp17_random_access_iterator =
+  __cpp17_bidirectional_iterator<_Ip> &&
+  totally_ordered<_Ip> &&
+  requires(_Ip __i, typename incrementable_traits<_Ip>::difference_type __n) {
+    { __i += __n } -> same_as<_Ip&>;
+    { __i -= __n } -> same_as<_Ip&>;
+    { __i +  __n } -> same_as<_Ip>;
+    { __n +  __i } -> same_as<_Ip>;
+    { __i -  __n } -> same_as<_Ip>;
+    { __i -  __i } -> same_as<decltype(__n)>;
+    {  __i[__n]  } -> convertible_to<iter_reference_t<_Ip>>;
+  };
+} // namespace __iterator_traits_detail
+
+template<class _Ip>
+concept __has_member_reference = requires { typename _Ip::reference; };
+
+template<class _Ip>
+concept __has_member_pointer = requires { typename _Ip::pointer; };
+
+template<class _Ip>
+concept __has_member_iterator_category = requires { typename _Ip::iterator_category; };
+
+template<class _Ip>
+concept __specifies_members = requires {
+    typename _Ip::value_type;
+    typename _Ip::difference_type;
+    requires __has_member_reference<_Ip>;
+    requires __has_member_iterator_category<_Ip>;
+  };
+
+template<class>
+struct __iterator_traits_member_pointer_or_void {
+  using type = void;
+};
+
+template<__has_member_pointer _Tp>
+struct __iterator_traits_member_pointer_or_void<_Tp> {
+  using type = typename _Tp::pointer;
+};
+
+template<class _Tp>
+concept __cpp17_iterator_missing_members =
+  !__specifies_members<_Tp> &&
+  __iterator_traits_detail::__cpp17_iterator<_Tp>;
+
+template<class _Tp>
+concept __cpp17_input_iterator_missing_members =
+  __cpp17_iterator_missing_members<_Tp> &&
+  __iterator_traits_detail::__cpp17_input_iterator<_Tp>;
+
+// Otherwise, `pointer` names `void`.
+template<class>
+struct __iterator_traits_member_pointer_or_arrow_or_void { using type = void; };
+
+// [iterator.traits]/3.2.1
+// If the qualified-id `I::pointer` is valid and denotes a type, `pointer` names that type.
+template<__has_member_pointer _Ip>
+struct __iterator_traits_member_pointer_or_arrow_or_void<_Ip> { using type = typename _Ip::pointer; };
+
+// Otherwise, if `decltype(declval<I&>().operator->())` is well-formed, then `pointer` names that
+// type.
+template<class _Ip>
+  requires requires(_Ip& __i) { __i.operator->(); } && (!__has_member_pointer<_Ip>)
+struct __iterator_traits_member_pointer_or_arrow_or_void<_Ip> {
+  using type = decltype(declval<_Ip&>().operator->());
+};
+
+// Otherwise, `reference` names `iter-reference-t<I>`.
+template<class _Ip>
+struct __iterator_traits_member_reference { using type = iter_reference_t<_Ip>; };
+
+// [iterator.traits]/3.2.2
+// If the qualified-id `I::reference` is valid and denotes a type, `reference` names that type.
+template<__has_member_reference _Ip>
+struct __iterator_traits_member_reference<_Ip> { using type = typename _Ip::reference; };
+
+// [iterator.traits]/3.2.3.4
+// input_iterator_tag
+template<class _Ip>
+struct __deduce_iterator_category {
+  using type = input_iterator_tag;
+};
+
+// [iterator.traits]/3.2.3.1
+// `random_access_iterator_tag` if `I` satisfies `cpp17-random-access-iterator`, or otherwise
+template<__iterator_traits_detail::__cpp17_random_access_iterator _Ip>
+struct __deduce_iterator_category<_Ip> {
+  using type = random_access_iterator_tag;
+};
+
+// [iterator.traits]/3.2.3.2
+// `bidirectional_iterator_tag` if `I` satisfies `cpp17-bidirectional-iterator`, or otherwise
+template<__iterator_traits_detail::__cpp17_bidirectional_iterator _Ip>
+struct __deduce_iterator_category<_Ip> {
+  using type = bidirectional_iterator_tag;
+};
+
+// [iterator.traits]/3.2.3.3
+// `forward_iterator_tag` if `I` satisfies `cpp17-forward-iterator`, or otherwise
+template<__iterator_traits_detail::__cpp17_forward_iterator _Ip>
+struct __deduce_iterator_category<_Ip> {
+  using type = forward_iterator_tag;
+};
+
+template<class _Ip>
+struct __iterator_traits_iterator_category : __deduce_iterator_category<_Ip> {};
+
+// [iterator.traits]/3.2.3
+// If the qualified-id `I::iterator-category` is valid and denotes a type, `iterator-category` names
+// that type.
+template<__has_member_iterator_category _Ip>
+struct __iterator_traits_iterator_category<_Ip> {
+  using type = typename _Ip::iterator_category;
+};
+
+// otherwise, it names void.
+template<class>
+struct __iterator_traits_difference_type { using type = void; };
+
+// If the qualified-id `incrementable_traits<I>::difference_type` is valid and denotes a type, then
+// `difference_type` names that type;
+template<class _Ip>
+requires requires { typename incrementable_traits<_Ip>::difference_type; }
+struct __iterator_traits_difference_type<_Ip> {
+  using type = typename incrementable_traits<_Ip>::difference_type;
+};
+
+// [iterator.traits]/3.4
+// Otherwise, `iterator_traits<I>` has no members by any of the above names.
+template<class>
+struct __iterator_traits {};
+
+// [iterator.traits]/3.1
+// If `I` has valid ([temp.deduct]) member types `difference-type`, `value-type`, `reference`, and
+// `iterator-category`, then `iterator-traits<I>` has the following publicly accessible members:
+template<__specifies_members _Ip>
+struct __iterator_traits<_Ip> {
+  using iterator_category  = typename _Ip::iterator_category;
+  using value_type         = typename _Ip::value_type;
+  using difference_type    = typename _Ip::difference_type;
+  using pointer            = typename __iterator_traits_member_pointer_or_void<_Ip>::type;
+  using reference          = typename _Ip::reference;
+};
+
+// [iterator.traits]/3.2
+// Otherwise, if `I` satisfies the exposition-only concept `cpp17-input-iterator`,
+// `iterator-traits<I>` has the following publicly accessible members:
+template<__cpp17_input_iterator_missing_members _Ip>
+struct __iterator_traits<_Ip> {
+  using iterator_category = typename __iterator_traits_iterator_category<_Ip>::type;
+  using value_type        = typename indirectly_readable_traits<_Ip>::value_type;
+  using difference_type   = typename incrementable_traits<_Ip>::difference_type;
+  using pointer           = typename __iterator_traits_member_pointer_or_arrow_or_void<_Ip>::type;
+  using reference         = typename __iterator_traits_member_reference<_Ip>::type;
+};
+
+// Otherwise, if `I` satisfies the exposition-only concept `cpp17-iterator`, then
+// `iterator_traits<I>` has the following publicly accessible members:
+template<__cpp17_iterator_missing_members _Ip>
+struct __iterator_traits<_Ip> {
+  using iterator_category = output_iterator_tag;
+  using value_type        = void;
+  using difference_type   = typename __iterator_traits_difference_type<_Ip>::type;
+  using pointer           = void;
+  using reference         = void;
+};
+
+template<class _Ip>
+struct iterator_traits : __iterator_traits<_Ip> {
+  using __primary_template = iterator_traits;
+};
+
+#else // !defined(_LIBCPP_HAS_NO_RANGES)
+
+template <class _Iter, bool> struct __iterator_traits {};
+
+template <class _Iter, bool> struct __iterator_traits_impl {};
+
+template <class _Iter>
+struct __iterator_traits_impl<_Iter, true>
+{
+    typedef typename _Iter::difference_type   difference_type;
+    typedef typename _Iter::value_type        value_type;
+    typedef typename _Iter::pointer           pointer;
+    typedef typename _Iter::reference         reference;
+    typedef typename _Iter::iterator_category iterator_category;
+};
+
+template <class _Iter>
+struct __iterator_traits<_Iter, true>
+    :  __iterator_traits_impl
+      <
+        _Iter,
+        is_convertible<typename _Iter::iterator_category, input_iterator_tag>::value ||
+        is_convertible<typename _Iter::iterator_category, output_iterator_tag>::value
+      >
+{};
+
+// iterator_traits<Iterator> will only have the nested types if Iterator::iterator_category
+//    exists.  Else iterator_traits<Iterator> will be an empty class.  This is a
+//    conforming extension which allows some programs to compile and behave as
+//    the client expects instead of failing at compile time.
+
+template <class _Iter>
+struct _LIBCPP_TEMPLATE_VIS iterator_traits
+    : __iterator_traits<_Iter, __has_iterator_typedefs<_Iter>::value> {
+
+  using __primary_template = iterator_traits;
+};
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+template<class _Tp>
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+requires is_object_v<_Tp>
+#endif
+struct _LIBCPP_TEMPLATE_VIS iterator_traits<_Tp*>
+{
+    typedef ptrdiff_t difference_type;
+    typedef typename remove_cv<_Tp>::type value_type;
+    typedef _Tp* pointer;
+    typedef _Tp& reference;
+    typedef random_access_iterator_tag iterator_category;
+#if _LIBCPP_STD_VER > 17
+    typedef contiguous_iterator_tag    iterator_concept;
+#endif
+};
+
+template <class _Tp, class _Up, bool = __has_iterator_category<iterator_traits<_Tp> >::value>
+struct __has_iterator_category_convertible_to
+    : is_convertible<typename iterator_traits<_Tp>::iterator_category, _Up>
+{};
+
+template <class _Tp, class _Up>
+struct __has_iterator_category_convertible_to<_Tp, _Up, false> : false_type {};
+
+template <class _Tp, class _Up, bool = __has_iterator_concept<_Tp>::value>
+struct __has_iterator_concept_convertible_to
+    : is_convertible<typename _Tp::iterator_concept, _Up>
+{};
+
+template <class _Tp, class _Up>
+struct __has_iterator_concept_convertible_to<_Tp, _Up, false> : false_type {};
+
+template <class _Tp>
+struct __is_cpp17_input_iterator : public __has_iterator_category_convertible_to<_Tp, input_iterator_tag> {};
+
+template <class _Tp>
+struct __is_cpp17_forward_iterator : public __has_iterator_category_convertible_to<_Tp, forward_iterator_tag> {};
+
+template <class _Tp>
+struct __is_cpp17_bidirectional_iterator : public __has_iterator_category_convertible_to<_Tp, bidirectional_iterator_tag> {};
+
+template <class _Tp>
+struct __is_cpp17_random_access_iterator : public __has_iterator_category_convertible_to<_Tp, random_access_iterator_tag> {};
+
+// __is_cpp17_contiguous_iterator determines if an iterator is known by
+// libc++ to be contiguous, either because it advertises itself as such
+// (in C++20) or because it is a pointer type or a known trivial wrapper
+// around a (possibly fancy) pointer type, such as __wrap_iter<T*>.
+// Such iterators receive special "contiguous" optimizations in
+// std::copy and std::sort.
+//
+#if _LIBCPP_STD_VER > 17
+template <class _Tp>
+struct __is_cpp17_contiguous_iterator : _Or<
+    __has_iterator_category_convertible_to<_Tp, contiguous_iterator_tag>,
+    __has_iterator_concept_convertible_to<_Tp, contiguous_iterator_tag>
+> {};
+#else
+template <class _Tp>
+struct __is_cpp17_contiguous_iterator : false_type {};
+#endif
+
+// Any native pointer which is an iterator is also a contiguous iterator.
+template <class _Up>
+struct __is_cpp17_contiguous_iterator<_Up*> : true_type {};
+
+
+template <class _Tp>
+struct __is_exactly_cpp17_input_iterator
+    : public integral_constant<bool,
+         __has_iterator_category_convertible_to<_Tp, input_iterator_tag>::value &&
+        !__has_iterator_category_convertible_to<_Tp, forward_iterator_tag>::value> {};
+
+#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
+template<class _InputIterator>
+using __iter_value_type = typename iterator_traits<_InputIterator>::value_type;
+
+template<class _InputIterator>
+using __iter_key_type = remove_const_t<typename iterator_traits<_InputIterator>::value_type::first_type>;
+
+template<class _InputIterator>
+using __iter_mapped_type = typename iterator_traits<_InputIterator>::value_type::second_type;
+
+template<class _InputIterator>
+using __iter_to_alloc_type = pair<
+    add_const_t<typename iterator_traits<_InputIterator>::value_type::first_type>,
+    typename iterator_traits<_InputIterator>::value_type::second_type>;
+#endif // _LIBCPP_HAS_NO_DEDUCTION_GUIDES
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_ITERATOR_TRAITS_H
lib/libcxx/include/__iterator/move_iterator.h
@@ -0,0 +1,189 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_MOVE_ITERATOR_H
+#define _LIBCPP___ITERATOR_MOVE_ITERATOR_H
+
+#include <__config>
+#include <__iterator/iterator_traits.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Iter>
+class _LIBCPP_TEMPLATE_VIS move_iterator
+{
+private:
+    _Iter __i;
+public:
+    typedef _Iter                                            iterator_type;
+    typedef typename iterator_traits<iterator_type>::value_type value_type;
+    typedef typename iterator_traits<iterator_type>::difference_type difference_type;
+    typedef iterator_type pointer;
+    typedef _If<__is_cpp17_random_access_iterator<_Iter>::value,
+        random_access_iterator_tag,
+        typename iterator_traits<_Iter>::iterator_category>  iterator_category;
+#if _LIBCPP_STD_VER > 17
+    typedef input_iterator_tag                               iterator_concept;
+#endif
+
+#ifndef _LIBCPP_CXX03_LANG
+    typedef typename iterator_traits<iterator_type>::reference __reference;
+    typedef typename conditional<
+            is_reference<__reference>::value,
+            typename remove_reference<__reference>::type&&,
+            __reference
+        >::type reference;
+#else
+    typedef typename iterator_traits<iterator_type>::reference reference;
+#endif
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator() : __i() {}
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    explicit move_iterator(_Iter __x) : __i(__x) {}
+
+    template <class _Up, class = _EnableIf<
+        !is_same<_Up, _Iter>::value && is_convertible<_Up const&, _Iter>::value
+    > >
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator(const move_iterator<_Up>& __u) : __i(__u.base()) {}
+
+    template <class _Up, class = _EnableIf<
+        !is_same<_Up, _Iter>::value &&
+        is_convertible<_Up const&, _Iter>::value &&
+        is_assignable<_Iter&, _Up const&>::value
+    > >
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator& operator=(const move_iterator<_Up>& __u) {
+        __i = __u.base();
+        return *this;
+    }
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 _Iter base() const {return __i;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reference operator*() const { return static_cast<reference>(*__i); }
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    pointer  operator->() const { return __i;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator& operator++() {++__i; return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator  operator++(int) {move_iterator __tmp(*this); ++__i; return __tmp;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator& operator--() {--__i; return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator  operator--(int) {move_iterator __tmp(*this); --__i; return __tmp;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator  operator+ (difference_type __n) const {return move_iterator(__i + __n);}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator& operator+=(difference_type __n) {__i += __n; return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator  operator- (difference_type __n) const {return move_iterator(__i - __n);}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    move_iterator& operator-=(difference_type __n) {__i -= __n; return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reference operator[](difference_type __n) const { return static_cast<reference>(__i[__n]); }
+};
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator==(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
+{
+    return __x.base() == __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator<(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
+{
+    return __x.base() < __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator!=(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
+{
+    return __x.base() != __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator>(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
+{
+    return __x.base() > __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator>=(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
+{
+    return __x.base() >= __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator<=(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
+{
+    return __x.base() <= __y.base();
+}
+
+#ifndef _LIBCPP_CXX03_LANG
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto
+operator-(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
+-> decltype(__x.base() - __y.base())
+{
+    return __x.base() - __y.base();
+}
+#else
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY
+typename move_iterator<_Iter1>::difference_type
+operator-(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
+{
+    return __x.base() - __y.base();
+}
+#endif
+
+template <class _Iter>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+move_iterator<_Iter>
+operator+(typename move_iterator<_Iter>::difference_type __n, const move_iterator<_Iter>& __x)
+{
+    return move_iterator<_Iter>(__x.base() + __n);
+}
+
+template <class _Iter>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+move_iterator<_Iter>
+make_move_iterator(_Iter __i)
+{
+    return move_iterator<_Iter>(__i);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_MOVE_ITERATOR_H
lib/libcxx/include/__iterator/next.h
@@ -0,0 +1,87 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_NEXT_H
+#define _LIBCPP___ITERATOR_NEXT_H
+
+#include <__config>
+#include <__debug>
+#include <__function_like.h>
+#include <__iterator/advance.h>
+#include <__iterator/concepts.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iterator_traits.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIter>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    typename enable_if<__is_cpp17_input_iterator<_InputIter>::value, _InputIter>::type
+    next(_InputIter __x, typename iterator_traits<_InputIter>::difference_type __n = 1) {
+  _LIBCPP_ASSERT(__n >= 0 || __is_cpp17_bidirectional_iterator<_InputIter>::value,
+                 "Attempt to next(it, n) with negative n on a non-bidirectional iterator");
+
+  _VSTD::advance(__x, __n);
+  return __x;
+}
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+struct __next_fn final : private __function_like {
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr explicit __next_fn(__tag __x) noexcept : __function_like(__x) {}
+
+  template <input_or_output_iterator _Ip>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Ip operator()(_Ip __x) const {
+    ++__x;
+    return __x;
+  }
+
+  template <input_or_output_iterator _Ip>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n) const {
+    ranges::advance(__x, __n);
+    return __x;
+  }
+
+  template <input_or_output_iterator _Ip, sentinel_for<_Ip> _Sp>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Ip operator()(_Ip __x, _Sp __bound) const {
+    ranges::advance(__x, __bound);
+    return __x;
+  }
+
+  template <input_or_output_iterator _Ip, sentinel_for<_Ip> _Sp>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n, _Sp __bound) const {
+    ranges::advance(__x, __n, __bound);
+    return __x;
+  }
+};
+
+inline constexpr auto next = __next_fn(__function_like::__tag());
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_PRIMITIVES_H
lib/libcxx/include/__iterator/ostream_iterator.h
@@ -0,0 +1,75 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_OSTREAM_ITERATOR_H
+#define _LIBCPP___ITERATOR_OSTREAM_ITERATOR_H
+
+#include <__config>
+#include <__iterator/iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <__memory/addressof.h>
+#include <iosfwd> // for forward declarations of char_traits and basic_ostream
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp, class _CharT = char, class _Traits = char_traits<_CharT> >
+class _LIBCPP_TEMPLATE_VIS ostream_iterator
+#if _LIBCPP_STD_VER <= 14 || !defined(_LIBCPP_ABI_NO_ITERATOR_BASES)
+    : public iterator<output_iterator_tag, void, void, void, void>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+public:
+    typedef output_iterator_tag             iterator_category;
+    typedef void                            value_type;
+#if _LIBCPP_STD_VER > 17
+    typedef ptrdiff_t                       difference_type;
+#else
+    typedef void                            difference_type;
+#endif
+    typedef void                            pointer;
+    typedef void                            reference;
+    typedef _CharT                          char_type;
+    typedef _Traits                         traits_type;
+    typedef basic_ostream<_CharT, _Traits>  ostream_type;
+
+private:
+    ostream_type* __out_stream_;
+    const char_type* __delim_;
+public:
+    _LIBCPP_INLINE_VISIBILITY ostream_iterator(ostream_type& __s) _NOEXCEPT
+        : __out_stream_(_VSTD::addressof(__s)), __delim_(nullptr) {}
+    _LIBCPP_INLINE_VISIBILITY ostream_iterator(ostream_type& __s, const _CharT* __delimiter) _NOEXCEPT
+        : __out_stream_(_VSTD::addressof(__s)), __delim_(__delimiter) {}
+    _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator=(const _Tp& __value_)
+        {
+            *__out_stream_ << __value_;
+            if (__delim_)
+                *__out_stream_ << __delim_;
+            return *this;
+        }
+
+    _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator*()     {return *this;}
+    _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator++()    {return *this;}
+    _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator++(int) {return *this;}
+};
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_OSTREAM_ITERATOR_H
lib/libcxx/include/__iterator/ostreambuf_iterator.h
@@ -0,0 +1,81 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_OSTREAMBUF_ITERATOR_H
+#define _LIBCPP___ITERATOR_OSTREAMBUF_ITERATOR_H
+
+#include <__config>
+#include <__iterator/iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <iosfwd> // for forward declaration of basic_streambuf
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _CharT, class _Traits>
+class _LIBCPP_TEMPLATE_VIS ostreambuf_iterator
+#if _LIBCPP_STD_VER <= 14 || !defined(_LIBCPP_ABI_NO_ITERATOR_BASES)
+    : public iterator<output_iterator_tag, void, void, void, void>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+public:
+    typedef output_iterator_tag                 iterator_category;
+    typedef void                                value_type;
+#if _LIBCPP_STD_VER > 17
+    typedef ptrdiff_t                           difference_type;
+#else
+    typedef void                                difference_type;
+#endif
+    typedef void                                pointer;
+    typedef void                                reference;
+    typedef _CharT                              char_type;
+    typedef _Traits                             traits_type;
+    typedef basic_streambuf<_CharT, _Traits>    streambuf_type;
+    typedef basic_ostream<_CharT, _Traits>      ostream_type;
+
+private:
+    streambuf_type* __sbuf_;
+public:
+    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator(ostream_type& __s) _NOEXCEPT
+        : __sbuf_(__s.rdbuf()) {}
+    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator(streambuf_type* __s) _NOEXCEPT
+        : __sbuf_(__s) {}
+    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator& operator=(_CharT __c)
+        {
+            if (__sbuf_ && traits_type::eq_int_type(__sbuf_->sputc(__c), traits_type::eof()))
+                __sbuf_ = nullptr;
+            return *this;
+        }
+    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator& operator*()     {return *this;}
+    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator& operator++()    {return *this;}
+    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator& operator++(int) {return *this;}
+    _LIBCPP_INLINE_VISIBILITY bool failed() const _NOEXCEPT {return __sbuf_ == nullptr;}
+
+    template <class _Ch, class _Tr>
+    friend
+    _LIBCPP_HIDDEN
+    ostreambuf_iterator<_Ch, _Tr>
+    __pad_and_output(ostreambuf_iterator<_Ch, _Tr> __s,
+                     const _Ch* __ob, const _Ch* __op, const _Ch* __oe,
+                     ios_base& __iob, _Ch __fl);
+};
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_OSTREAMBUF_ITERATOR_H
lib/libcxx/include/__iterator/prev.h
@@ -0,0 +1,79 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_PREV_H
+#define _LIBCPP___ITERATOR_PREV_H
+
+#include <__config>
+#include <__debug>
+#include <__function_like.h>
+#include <__iterator/advance.h>
+#include <__iterator/concepts.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iterator_traits.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIter>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    typename enable_if<__is_cpp17_input_iterator<_InputIter>::value, _InputIter>::type
+    prev(_InputIter __x, typename iterator_traits<_InputIter>::difference_type __n = 1) {
+  _LIBCPP_ASSERT(__n <= 0 || __is_cpp17_bidirectional_iterator<_InputIter>::value,
+                 "Attempt to prev(it, n) with a positive n on a non-bidirectional iterator");
+  _VSTD::advance(__x, -__n);
+  return __x;
+}
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+struct __prev_fn final : private __function_like {
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr explicit __prev_fn(__tag __x) noexcept : __function_like(__x) {}
+
+  template <bidirectional_iterator _Ip>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Ip operator()(_Ip __x) const {
+    --__x;
+    return __x;
+  }
+
+  template <bidirectional_iterator _Ip>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n) const {
+    ranges::advance(__x, -__n);
+    return __x;
+  }
+
+  template <bidirectional_iterator _Ip>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Ip operator()(_Ip __x, iter_difference_t<_Ip> __n, _Ip __bound) const {
+    ranges::advance(__x, -__n, __bound);
+    return __x;
+  }
+};
+
+inline constexpr auto prev = __prev_fn(__function_like::__tag());
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_PREV_H
lib/libcxx/include/__iterator/projected.h
@@ -0,0 +1,45 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___ITERATOR_PROJECTED_H
+#define _LIBCPP___ITERATOR_PROJECTED_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/incrementable_traits.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+template<indirectly_readable _It, indirectly_regular_unary_invocable<_It> _Proj>
+struct projected {
+  using value_type = remove_cvref_t<indirect_result_t<_Proj&, _It>>;
+  indirect_result_t<_Proj&, _It> operator*() const; // not defined
+};
+
+template<weakly_incrementable _It, class _Proj>
+struct incrementable_traits<projected<_It, _Proj>> {
+  using difference_type = iter_difference_t<_It>;
+};
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_PROJECTED_H
lib/libcxx/include/__iterator/readable_traits.h
@@ -0,0 +1,91 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_READABLE_TRAITS_H
+#define _LIBCPP___ITERATOR_READABLE_TRAITS_H
+
+#include <__config>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// [readable.traits]
+template<class> struct __cond_value_type {};
+
+template<class _Tp>
+requires is_object_v<_Tp>
+struct __cond_value_type<_Tp> { using value_type = remove_cv_t<_Tp>; };
+
+template<class _Tp>
+concept __has_member_value_type = requires { typename _Tp::value_type; };
+
+template<class _Tp>
+concept __has_member_element_type = requires { typename _Tp::element_type; };
+
+template<class> struct indirectly_readable_traits {};
+
+template<class _Ip>
+requires is_array_v<_Ip>
+struct indirectly_readable_traits<_Ip> {
+  using value_type = remove_cv_t<remove_extent_t<_Ip>>;
+};
+
+template<class _Ip>
+struct indirectly_readable_traits<const _Ip> : indirectly_readable_traits<_Ip> {};
+
+template<class _Tp>
+struct indirectly_readable_traits<_Tp*> : __cond_value_type<_Tp> {};
+
+template<__has_member_value_type _Tp>
+struct indirectly_readable_traits<_Tp>
+  : __cond_value_type<typename _Tp::value_type> {};
+
+template<__has_member_element_type _Tp>
+struct indirectly_readable_traits<_Tp>
+  : __cond_value_type<typename _Tp::element_type> {};
+
+// Pre-emptively applies LWG3541
+template<__has_member_value_type _Tp>
+requires __has_member_element_type<_Tp>
+struct indirectly_readable_traits<_Tp> {};
+template<__has_member_value_type _Tp>
+requires __has_member_element_type<_Tp> &&
+         same_as<remove_cv_t<typename _Tp::element_type>,
+                 remove_cv_t<typename _Tp::value_type>>
+struct indirectly_readable_traits<_Tp>
+  : __cond_value_type<typename _Tp::value_type> {};
+
+template <class>
+struct iterator_traits;
+
+// Let `RI` be `remove_cvref_t<I>`. The type `iter_value_t<I>` denotes
+// `indirectly_readable_traits<RI>::value_type` if `iterator_traits<RI>` names a specialization
+// generated from the primary template, and `iterator_traits<RI>::value_type` otherwise.
+template <class _Ip>
+using iter_value_t = typename conditional_t<__is_primary_template<iterator_traits<remove_cvref_t<_Ip> > >::value,
+                                            indirectly_readable_traits<remove_cvref_t<_Ip> >,
+                                            iterator_traits<remove_cvref_t<_Ip> > >::value_type;
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_READABLE_TRAITS_H
lib/libcxx/include/__iterator/reverse_access.h
@@ -0,0 +1,109 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_REVERSE_ACCESS_H
+#define _LIBCPP___ITERATOR_REVERSE_ACCESS_H
+
+#include <__config>
+#include <__iterator/reverse_iterator.h>
+#include <cstddef>
+#include <initializer_list>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_CXX03_LANG)
+
+#if _LIBCPP_STD_VER > 11
+
+template <class _Tp, size_t _Np>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+reverse_iterator<_Tp*> rbegin(_Tp (&__array)[_Np])
+{
+    return reverse_iterator<_Tp*>(__array + _Np);
+}
+
+template <class _Tp, size_t _Np>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+reverse_iterator<_Tp*> rend(_Tp (&__array)[_Np])
+{
+    return reverse_iterator<_Tp*>(__array);
+}
+
+template <class _Ep>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+reverse_iterator<const _Ep*> rbegin(initializer_list<_Ep> __il)
+{
+    return reverse_iterator<const _Ep*>(__il.end());
+}
+
+template <class _Ep>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+reverse_iterator<const _Ep*> rend(initializer_list<_Ep> __il)
+{
+    return reverse_iterator<const _Ep*>(__il.begin());
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto rbegin(_Cp& __c) -> decltype(__c.rbegin())
+{
+    return __c.rbegin();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto rbegin(const _Cp& __c) -> decltype(__c.rbegin())
+{
+    return __c.rbegin();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto rend(_Cp& __c) -> decltype(__c.rend())
+{
+    return __c.rend();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto rend(const _Cp& __c) -> decltype(__c.rend())
+{
+    return __c.rend();
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto crbegin(const _Cp& __c) -> decltype(_VSTD::rbegin(__c))
+{
+    return _VSTD::rbegin(__c);
+}
+
+template <class _Cp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto crend(const _Cp& __c) -> decltype(_VSTD::rend(__c))
+{
+    return _VSTD::rend(__c);
+}
+
+#endif
+
+#endif // !defined(_LIBCPP_CXX03_LANG)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_REVERSE_ACCESS_H
lib/libcxx/include/__iterator/reverse_iterator.h
@@ -0,0 +1,239 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_REVERSE_ITERATOR_H
+#define _LIBCPP___ITERATOR_REVERSE_ITERATOR_H
+
+#include <__config>
+#include <__iterator/iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <__memory/addressof.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp, class = void>
+struct __is_stashing_iterator : false_type {};
+
+template <class _Tp>
+struct __is_stashing_iterator<_Tp, typename __void_t<typename _Tp::__stashing_iterator_tag>::type>
+  : true_type {};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Iter>
+class _LIBCPP_TEMPLATE_VIS reverse_iterator
+#if _LIBCPP_STD_VER <= 14 || !defined(_LIBCPP_ABI_NO_ITERATOR_BASES)
+    : public iterator<typename iterator_traits<_Iter>::iterator_category,
+                      typename iterator_traits<_Iter>::value_type,
+                      typename iterator_traits<_Iter>::difference_type,
+                      typename iterator_traits<_Iter>::pointer,
+                      typename iterator_traits<_Iter>::reference>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+private:
+#ifndef _LIBCPP_ABI_NO_ITERATOR_BASES
+    _Iter __t; // no longer used as of LWG #2360, not removed due to ABI break
+#endif
+
+    static_assert(!__is_stashing_iterator<_Iter>::value,
+      "The specified iterator type cannot be used with reverse_iterator; "
+      "Using stashing iterators with reverse_iterator causes undefined behavior");
+
+protected:
+    _Iter current;
+public:
+    typedef _Iter                                            iterator_type;
+    typedef typename iterator_traits<_Iter>::difference_type difference_type;
+    typedef typename iterator_traits<_Iter>::reference       reference;
+    typedef typename iterator_traits<_Iter>::pointer         pointer;
+    typedef _If<__is_cpp17_random_access_iterator<_Iter>::value,
+        random_access_iterator_tag,
+        typename iterator_traits<_Iter>::iterator_category>  iterator_category;
+    typedef typename iterator_traits<_Iter>::value_type      value_type;
+
+#if _LIBCPP_STD_VER > 17
+    typedef _If<__is_cpp17_random_access_iterator<_Iter>::value,
+        random_access_iterator_tag,
+        bidirectional_iterator_tag>                          iterator_concept;
+#endif
+
+#ifndef _LIBCPP_ABI_NO_ITERATOR_BASES
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator() : __t(), current() {}
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    explicit reverse_iterator(_Iter __x) : __t(__x), current(__x) {}
+
+    template <class _Up, class = _EnableIf<
+        !is_same<_Up, _Iter>::value && is_convertible<_Up const&, _Iter>::value
+    > >
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator(const reverse_iterator<_Up>& __u)
+        : __t(__u.base()), current(__u.base())
+    { }
+
+    template <class _Up, class = _EnableIf<
+        !is_same<_Up, _Iter>::value &&
+        is_convertible<_Up const&, _Iter>::value &&
+        is_assignable<_Up const&, _Iter>::value
+    > >
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator& operator=(const reverse_iterator<_Up>& __u) {
+        __t = current = __u.base();
+        return *this;
+    }
+#else
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator() : current() {}
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    explicit reverse_iterator(_Iter __x) : current(__x) {}
+
+    template <class _Up, class = _EnableIf<
+        !is_same<_Up, _Iter>::value && is_convertible<_Up const&, _Iter>::value
+    > >
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator(const reverse_iterator<_Up>& __u)
+        : current(__u.base())
+    { }
+
+    template <class _Up, class = _EnableIf<
+        !is_same<_Up, _Iter>::value &&
+        is_convertible<_Up const&, _Iter>::value &&
+        is_assignable<_Up const&, _Iter>::value
+    > >
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator& operator=(const reverse_iterator<_Up>& __u) {
+        current = __u.base();
+        return *this;
+    }
+#endif
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    _Iter base() const {return current;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reference operator*() const {_Iter __tmp = current; return *--__tmp;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    pointer  operator->() const {return _VSTD::addressof(operator*());}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator& operator++() {--current; return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator  operator++(int) {reverse_iterator __tmp(*this); --current; return __tmp;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator& operator--() {++current; return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator  operator--(int) {reverse_iterator __tmp(*this); ++current; return __tmp;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator  operator+ (difference_type __n) const {return reverse_iterator(current - __n);}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator& operator+=(difference_type __n) {current -= __n; return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator  operator- (difference_type __n) const {return reverse_iterator(current + __n);}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reverse_iterator& operator-=(difference_type __n) {current += __n; return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+    reference         operator[](difference_type __n) const {return *(*this + __n);}
+};
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator==(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
+{
+    return __x.base() == __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator<(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
+{
+    return __x.base() > __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator!=(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
+{
+    return __x.base() != __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator>(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
+{
+    return __x.base() < __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator>=(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
+{
+    return __x.base() <= __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+bool
+operator<=(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
+{
+    return __x.base() >= __y.base();
+}
+
+#ifndef _LIBCPP_CXX03_LANG
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+auto
+operator-(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
+-> decltype(__y.base() - __x.base())
+{
+    return __y.base() - __x.base();
+}
+#else
+template <class _Iter1, class _Iter2>
+inline _LIBCPP_INLINE_VISIBILITY
+typename reverse_iterator<_Iter1>::difference_type
+operator-(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
+{
+    return __y.base() - __x.base();
+}
+#endif
+
+template <class _Iter>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+reverse_iterator<_Iter>
+operator+(typename reverse_iterator<_Iter>::difference_type __n, const reverse_iterator<_Iter>& __x)
+{
+    return reverse_iterator<_Iter>(__x.base() - __n);
+}
+
+#if _LIBCPP_STD_VER > 11
+template <class _Iter>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+reverse_iterator<_Iter> make_reverse_iterator(_Iter __i)
+{
+    return reverse_iterator<_Iter>(__i);
+}
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_REVERSE_ITERATOR_H
lib/libcxx/include/__iterator/size.h
@@ -0,0 +1,58 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_SIZE_H
+#define _LIBCPP___ITERATOR_SIZE_H
+
+#include <__config>
+#include <cstddef>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+
+template <class _Cont>
+_LIBCPP_INLINE_VISIBILITY
+constexpr auto size(const _Cont& __c)
+_NOEXCEPT_(noexcept(__c.size()))
+-> decltype        (__c.size())
+{ return            __c.size(); }
+
+template <class _Tp, size_t _Sz>
+_LIBCPP_INLINE_VISIBILITY
+constexpr size_t size(const _Tp (&)[_Sz]) noexcept { return _Sz; }
+
+#if _LIBCPP_STD_VER > 17
+template <class _Cont>
+_LIBCPP_INLINE_VISIBILITY
+constexpr auto ssize(const _Cont& __c)
+_NOEXCEPT_(noexcept(static_cast<common_type_t<ptrdiff_t, make_signed_t<decltype(__c.size())>>>(__c.size())))
+->                              common_type_t<ptrdiff_t, make_signed_t<decltype(__c.size())>>
+{ return            static_cast<common_type_t<ptrdiff_t, make_signed_t<decltype(__c.size())>>>(__c.size()); }
+
+template <class _Tp, ptrdiff_t _Sz>
+_LIBCPP_INLINE_VISIBILITY
+constexpr ptrdiff_t ssize(const _Tp (&)[_Sz]) noexcept { return _Sz; }
+#endif
+
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_SIZE_H
lib/libcxx/include/__iterator/wrap_iter.h
@@ -0,0 +1,300 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_WRAP_ITER_H
+#define _LIBCPP___ITERATOR_WRAP_ITER_H
+
+#include <__config>
+#include <__debug>
+#include <__iterator/iterator_traits.h>
+#include <__memory/pointer_traits.h> // __to_address
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Iter>
+class __wrap_iter
+{
+public:
+    typedef _Iter                                                      iterator_type;
+    typedef typename iterator_traits<iterator_type>::value_type        value_type;
+    typedef typename iterator_traits<iterator_type>::difference_type   difference_type;
+    typedef typename iterator_traits<iterator_type>::pointer           pointer;
+    typedef typename iterator_traits<iterator_type>::reference         reference;
+    typedef typename iterator_traits<iterator_type>::iterator_category iterator_category;
+#if _LIBCPP_STD_VER > 17
+    typedef contiguous_iterator_tag                                    iterator_concept;
+#endif
+
+private:
+    iterator_type __i;
+public:
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter() _NOEXCEPT
+#if _LIBCPP_STD_VER > 11
+                : __i{}
+#endif
+    {
+#if _LIBCPP_DEBUG_LEVEL == 2
+        __get_db()->__insert_i(this);
+#endif
+    }
+    template <class _Up> _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+        __wrap_iter(const __wrap_iter<_Up>& __u,
+            typename enable_if<is_convertible<_Up, iterator_type>::value>::type* = nullptr) _NOEXCEPT
+            : __i(__u.base())
+    {
+#if _LIBCPP_DEBUG_LEVEL == 2
+        __get_db()->__iterator_copy(this, &__u);
+#endif
+    }
+#if _LIBCPP_DEBUG_LEVEL == 2
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+    __wrap_iter(const __wrap_iter& __x)
+        : __i(__x.base())
+    {
+        __get_db()->__iterator_copy(this, &__x);
+    }
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+    __wrap_iter& operator=(const __wrap_iter& __x)
+    {
+        if (this != &__x)
+        {
+            __get_db()->__iterator_copy(this, &__x);
+            __i = __x.__i;
+        }
+        return *this;
+    }
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+    ~__wrap_iter()
+    {
+        __get_db()->__erase_i(this);
+    }
+#endif
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG reference operator*() const _NOEXCEPT
+    {
+#if _LIBCPP_DEBUG_LEVEL == 2
+        _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this),
+                       "Attempted to dereference a non-dereferenceable iterator");
+#endif
+        return *__i;
+    }
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG pointer  operator->() const _NOEXCEPT
+    {
+#if _LIBCPP_DEBUG_LEVEL == 2
+        _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this),
+                       "Attempted to dereference a non-dereferenceable iterator");
+#endif
+        return _VSTD::__to_address(__i);
+    }
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter& operator++() _NOEXCEPT
+    {
+#if _LIBCPP_DEBUG_LEVEL == 2
+        _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this),
+                       "Attempted to increment a non-incrementable iterator");
+#endif
+        ++__i;
+        return *this;
+    }
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter  operator++(int) _NOEXCEPT
+        {__wrap_iter __tmp(*this); ++(*this); return __tmp;}
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter& operator--() _NOEXCEPT
+    {
+#if _LIBCPP_DEBUG_LEVEL == 2
+        _LIBCPP_ASSERT(__get_const_db()->__decrementable(this),
+                       "Attempted to decrement a non-decrementable iterator");
+#endif
+        --__i;
+        return *this;
+    }
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter  operator--(int) _NOEXCEPT
+        {__wrap_iter __tmp(*this); --(*this); return __tmp;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter  operator+ (difference_type __n) const _NOEXCEPT
+        {__wrap_iter __w(*this); __w += __n; return __w;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter& operator+=(difference_type __n) _NOEXCEPT
+    {
+#if _LIBCPP_DEBUG_LEVEL == 2
+        _LIBCPP_ASSERT(__get_const_db()->__addable(this, __n),
+                   "Attempted to add/subtract an iterator outside its valid range");
+#endif
+        __i += __n;
+        return *this;
+    }
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter  operator- (difference_type __n) const _NOEXCEPT
+        {return *this + (-__n);}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter& operator-=(difference_type __n) _NOEXCEPT
+        {*this += -__n; return *this;}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG reference    operator[](difference_type __n) const _NOEXCEPT
+    {
+#if _LIBCPP_DEBUG_LEVEL == 2
+        _LIBCPP_ASSERT(__get_const_db()->__subscriptable(this, __n),
+                   "Attempted to subscript an iterator outside its valid range");
+#endif
+        return __i[__n];
+    }
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG iterator_type base() const _NOEXCEPT {return __i;}
+
+private:
+#if _LIBCPP_DEBUG_LEVEL == 2
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter(const void* __p, iterator_type __x) : __i(__x)
+    {
+        __get_db()->__insert_ic(this, __p);
+    }
+#else
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter(iterator_type __x) _NOEXCEPT : __i(__x) {}
+#endif
+
+    template <class _Up> friend class __wrap_iter;
+    template <class _CharT, class _Traits, class _Alloc> friend class basic_string;
+    template <class _Tp, class _Alloc> friend class _LIBCPP_TEMPLATE_VIS vector;
+    template <class _Tp, size_t> friend class _LIBCPP_TEMPLATE_VIS span;
+};
+
+template <class _Iter1>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator==(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
+{
+    return __x.base() == __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator==(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
+{
+    return __x.base() == __y.base();
+}
+
+template <class _Iter1>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator<(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
+{
+#if _LIBCPP_DEBUG_LEVEL == 2
+    _LIBCPP_ASSERT(__get_const_db()->__less_than_comparable(&__x, &__y),
+                   "Attempted to compare incomparable iterators");
+#endif
+    return __x.base() < __y.base();
+}
+
+template <class _Iter1, class _Iter2>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator<(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
+{
+#if _LIBCPP_DEBUG_LEVEL == 2
+    _LIBCPP_ASSERT(__get_const_db()->__less_than_comparable(&__x, &__y),
+                   "Attempted to compare incomparable iterators");
+#endif
+    return __x.base() < __y.base();
+}
+
+template <class _Iter1>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator!=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
+{
+    return !(__x == __y);
+}
+
+template <class _Iter1, class _Iter2>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator!=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
+{
+    return !(__x == __y);
+}
+
+template <class _Iter1>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator>(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
+{
+    return __y < __x;
+}
+
+template <class _Iter1, class _Iter2>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator>(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
+{
+    return __y < __x;
+}
+
+template <class _Iter1>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator>=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
+{
+    return !(__x < __y);
+}
+
+template <class _Iter1, class _Iter2>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator>=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
+{
+    return !(__x < __y);
+}
+
+template <class _Iter1>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator<=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
+{
+    return !(__y < __x);
+}
+
+template <class _Iter1, class _Iter2>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+bool operator<=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
+{
+    return !(__y < __x);
+}
+
+template <class _Iter1, class _Iter2>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+#ifndef _LIBCPP_CXX03_LANG
+auto operator-(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
+    -> decltype(__x.base() - __y.base())
+#else
+typename __wrap_iter<_Iter1>::difference_type
+operator-(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
+#endif // C++03
+{
+#if _LIBCPP_DEBUG_LEVEL == 2
+    _LIBCPP_ASSERT(__get_const_db()->__less_than_comparable(&__x, &__y),
+                   "Attempted to subtract incompatible iterators");
+#endif
+    return __x.base() - __y.base();
+}
+
+template <class _Iter1>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
+__wrap_iter<_Iter1> operator+(typename __wrap_iter<_Iter1>::difference_type __n, __wrap_iter<_Iter1> __x) _NOEXCEPT
+{
+    __x += __n;
+    return __x;
+}
+
+#if _LIBCPP_STD_VER <= 17
+template <class _It>
+struct __is_cpp17_contiguous_iterator<__wrap_iter<_It> > : true_type {};
+#endif
+
+template <class _Iter>
+_LIBCPP_CONSTEXPR
+decltype(_VSTD::__to_address(declval<_Iter>()))
+__to_address(__wrap_iter<_Iter> __w) _NOEXCEPT {
+    return _VSTD::__to_address(__w.base());
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_WRAP_ITER_H
lib/libcxx/include/__memory/base.h โ†’ lib/libcxx/include/__memory/addressof.h
@@ -7,12 +7,10 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef _LIBCPP___MEMORY_BASE_H
-#define _LIBCPP___MEMORY_BASE_H
+#ifndef _LIBCPP___MEMORY_ADDRESSOF_H
+#define _LIBCPP___MEMORY_ADDRESSOF_H
 
 #include <__config>
-#include <__debug>
-#include <type_traits>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -23,7 +21,6 @@ _LIBCPP_PUSH_MACROS
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-// addressof
 #ifndef _LIBCPP_HAS_NO_BUILTIN_ADDRESSOF
 
 template <class _Tp>
@@ -92,36 +89,8 @@ addressof(__unsafe_unretained _Tp& __x) _NOEXCEPT
 template <class _Tp> _Tp* addressof(const _Tp&&) noexcept = delete;
 #endif
 
-// construct_at
-
-#if _LIBCPP_STD_VER > 17
-
-template<class _Tp, class ..._Args, class = decltype(
-    ::new (_VSTD::declval<void*>()) _Tp(_VSTD::declval<_Args>()...)
-)>
-_LIBCPP_INLINE_VISIBILITY
-constexpr _Tp* construct_at(_Tp* __location, _Args&& ...__args) {
-    _LIBCPP_ASSERT(__location, "null pointer given to construct_at");
-    return ::new ((void*)__location) _Tp(_VSTD::forward<_Args>(__args)...);
-}
-
-#endif
-
-// destroy_at
-
-#if _LIBCPP_STD_VER > 14
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void destroy_at(_Tp* __loc) {
-    _LIBCPP_ASSERT(__loc, "null pointer given to destroy_at");
-    __loc->~_Tp();
-}
-
-#endif
-
 _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP___MEMORY_BASE_H
+#endif // _LIBCPP___MEMORY_ADDRESSOF_H
lib/libcxx/include/__memory/utilities.h โ†’ lib/libcxx/include/__memory/allocation_guard.h
@@ -7,12 +7,13 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef _LIBCPP___MEMORY_UTILITIES_H
-#define _LIBCPP___MEMORY_UTILITIES_H
+#ifndef _LIBCPP___MEMORY_ALLOCATION_GUARD_H
+#define _LIBCPP___MEMORY_ALLOCATION_GUARD_H
 
 #include <__config>
 #include <__memory/allocator_traits.h>
 #include <cstddef>
+#include <utility>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -85,4 +86,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP___MEMORY_UTILITIES_H
+#endif // _LIBCPP___MEMORY_ALLOCATION_GUARD_H
lib/libcxx/include/__memory/allocator.h
@@ -0,0 +1,254 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_ALLOCATOR_H
+#define _LIBCPP___MEMORY_ALLOCATOR_H
+
+#include <__config>
+#include <__memory/allocator_traits.h>
+#include <__utility/forward.h>
+#include <cstddef>
+#include <new>
+#include <stdexcept>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp> class allocator;
+
+#if _LIBCPP_STD_VER <= 17
+template <>
+class _LIBCPP_TEMPLATE_VIS allocator<void>
+{
+public:
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef void*             pointer;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const void*       const_pointer;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef void              value_type;
+
+    template <class _Up> struct _LIBCPP_DEPRECATED_IN_CXX17 rebind {typedef allocator<_Up> other;};
+};
+
+template <>
+class _LIBCPP_TEMPLATE_VIS allocator<const void>
+{
+public:
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const void*       pointer;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const void*       const_pointer;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const void        value_type;
+
+    template <class _Up> struct _LIBCPP_DEPRECATED_IN_CXX17 rebind {typedef allocator<_Up> other;};
+};
+#endif
+
+// This class provides a non-trivial default constructor to the class that derives from it
+// if the condition is satisfied.
+//
+// The second template parameter exists to allow giving a unique type to __non_trivial_if,
+// which makes it possible to avoid breaking the ABI when making this a base class of an
+// existing class. Without that, imagine we have classes D1 and D2, both of which used to
+// have no base classes, but which now derive from __non_trivial_if. The layout of a class
+// that inherits from both D1 and D2 will change because the two __non_trivial_if base
+// classes are not allowed to share the same address.
+//
+// By making those __non_trivial_if base classes unique, we work around this problem and
+// it is safe to start deriving from __non_trivial_if in existing classes.
+template <bool _Cond, class _Unique>
+struct __non_trivial_if { };
+
+template <class _Unique>
+struct __non_trivial_if<true, _Unique> {
+    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_CONSTEXPR __non_trivial_if() _NOEXCEPT { }
+};
+
+// allocator
+//
+// Note: For ABI compatibility between C++20 and previous standards, we make
+//       allocator<void> trivial in C++20.
+
+template <class _Tp>
+class _LIBCPP_TEMPLATE_VIS allocator
+    : private __non_trivial_if<!is_void<_Tp>::value, allocator<_Tp> >
+{
+public:
+    typedef size_t      size_type;
+    typedef ptrdiff_t   difference_type;
+    typedef _Tp         value_type;
+    typedef true_type   propagate_on_container_move_assignment;
+    typedef true_type   is_always_equal;
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    allocator() _NOEXCEPT _LIBCPP_DEFAULT
+
+    template <class _Up>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    allocator(const allocator<_Up>&) _NOEXCEPT { }
+
+    _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    _Tp* allocate(size_t __n) {
+        if (__n > allocator_traits<allocator>::max_size(*this))
+            __throw_length_error("allocator<T>::allocate(size_t n)"
+                                 " 'n' exceeds maximum supported size");
+        if (__libcpp_is_constant_evaluated()) {
+            return static_cast<_Tp*>(::operator new(__n * sizeof(_Tp)));
+        } else {
+            return static_cast<_Tp*>(_VSTD::__libcpp_allocate(__n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp)));
+        }
+    }
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    void deallocate(_Tp* __p, size_t __n) _NOEXCEPT {
+        if (__libcpp_is_constant_evaluated()) {
+            ::operator delete(__p);
+        } else {
+            _VSTD::__libcpp_deallocate((void*)__p, __n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp));
+        }
+    }
+
+    // C++20 Removed members
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp*       pointer;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp* const_pointer;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp&       reference;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp& const_reference;
+
+    template <class _Up>
+    struct _LIBCPP_DEPRECATED_IN_CXX17 rebind {
+        typedef allocator<_Up> other;
+    };
+
+    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
+    pointer address(reference __x) const _NOEXCEPT {
+        return _VSTD::addressof(__x);
+    }
+    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
+    const_pointer address(const_reference __x) const _NOEXCEPT {
+        return _VSTD::addressof(__x);
+    }
+
+    _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_DEPRECATED_IN_CXX17
+    _Tp* allocate(size_t __n, const void*) {
+        return allocate(__n);
+    }
+
+    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY size_type max_size() const _NOEXCEPT {
+        return size_type(~0) / sizeof(_Tp);
+    }
+
+    template <class _Up, class... _Args>
+    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
+    void construct(_Up* __p, _Args&&... __args) {
+        ::new ((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
+    }
+
+    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
+    void destroy(pointer __p) {
+        __p->~_Tp();
+    }
+#endif
+};
+
+template <class _Tp>
+class _LIBCPP_TEMPLATE_VIS allocator<const _Tp>
+    : private __non_trivial_if<!is_void<_Tp>::value, allocator<const _Tp> >
+{
+public:
+    typedef size_t      size_type;
+    typedef ptrdiff_t   difference_type;
+    typedef const _Tp   value_type;
+    typedef true_type   propagate_on_container_move_assignment;
+    typedef true_type   is_always_equal;
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    allocator() _NOEXCEPT _LIBCPP_DEFAULT
+
+    template <class _Up>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    allocator(const allocator<_Up>&) _NOEXCEPT { }
+
+    _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    const _Tp* allocate(size_t __n) {
+        if (__n > allocator_traits<allocator>::max_size(*this))
+            __throw_length_error("allocator<const T>::allocate(size_t n)"
+                                 " 'n' exceeds maximum supported size");
+        if (__libcpp_is_constant_evaluated()) {
+            return static_cast<const _Tp*>(::operator new(__n * sizeof(_Tp)));
+        } else {
+            return static_cast<const _Tp*>(_VSTD::__libcpp_allocate(__n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp)));
+        }
+    }
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    void deallocate(const _Tp* __p, size_t __n) {
+        if (__libcpp_is_constant_evaluated()) {
+            ::operator delete(const_cast<_Tp*>(__p));
+        } else {
+            _VSTD::__libcpp_deallocate((void*) const_cast<_Tp *>(__p), __n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp));
+        }
+    }
+
+    // C++20 Removed members
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp* pointer;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp* const_pointer;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp& reference;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp& const_reference;
+
+    template <class _Up>
+    struct _LIBCPP_DEPRECATED_IN_CXX17 rebind {
+        typedef allocator<_Up> other;
+    };
+
+    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
+    const_pointer address(const_reference __x) const _NOEXCEPT {
+        return _VSTD::addressof(__x);
+    }
+
+    _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_DEPRECATED_IN_CXX17
+    const _Tp* allocate(size_t __n, const void*) {
+        return allocate(__n);
+    }
+
+    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY size_type max_size() const _NOEXCEPT {
+        return size_type(~0) / sizeof(_Tp);
+    }
+
+    template <class _Up, class... _Args>
+    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
+    void construct(_Up* __p, _Args&&... __args) {
+        ::new ((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
+    }
+
+    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
+    void destroy(pointer __p) {
+        __p->~_Tp();
+    }
+#endif
+};
+
+template <class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool operator==(const allocator<_Tp>&, const allocator<_Up>&) _NOEXCEPT {return true;}
+
+template <class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+bool operator!=(const allocator<_Tp>&, const allocator<_Up>&) _NOEXCEPT {return false;}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_ALLOCATOR_H
lib/libcxx/include/__memory/allocator_arg_t.h
@@ -0,0 +1,78 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___FUNCTIONAL___ALLOCATOR_ARG_T_H
+#define _LIBCPP___FUNCTIONAL___ALLOCATOR_ARG_T_H
+
+#include <__config>
+#include <__memory/uses_allocator.h>
+#include <__utility/forward.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+struct _LIBCPP_TEMPLATE_VIS allocator_arg_t { explicit allocator_arg_t() = default; };
+
+#if defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
+extern _LIBCPP_EXPORTED_FROM_ABI const allocator_arg_t allocator_arg;
+#else
+/* _LIBCPP_INLINE_VAR */ constexpr allocator_arg_t allocator_arg = allocator_arg_t();
+#endif
+
+#ifndef _LIBCPP_CXX03_LANG
+
+// allocator construction
+
+template <class _Tp, class _Alloc, class ..._Args>
+struct __uses_alloc_ctor_imp
+{
+    typedef _LIBCPP_NODEBUG_TYPE typename __uncvref<_Alloc>::type _RawAlloc;
+    static const bool __ua = uses_allocator<_Tp, _RawAlloc>::value;
+    static const bool __ic =
+        is_constructible<_Tp, allocator_arg_t, _Alloc, _Args...>::value;
+    static const int value = __ua ? 2 - __ic : 0;
+};
+
+template <class _Tp, class _Alloc, class ..._Args>
+struct __uses_alloc_ctor
+    : integral_constant<int, __uses_alloc_ctor_imp<_Tp, _Alloc, _Args...>::value>
+    {};
+
+template <class _Tp, class _Allocator, class... _Args>
+inline _LIBCPP_INLINE_VISIBILITY
+void __user_alloc_construct_impl (integral_constant<int, 0>, _Tp *__storage, const _Allocator &, _Args &&... __args )
+{
+    new (__storage) _Tp (_VSTD::forward<_Args>(__args)...);
+}
+
+// FIXME: This should have a version which takes a non-const alloc.
+template <class _Tp, class _Allocator, class... _Args>
+inline _LIBCPP_INLINE_VISIBILITY
+void __user_alloc_construct_impl (integral_constant<int, 1>, _Tp *__storage, const _Allocator &__a, _Args &&... __args )
+{
+    new (__storage) _Tp (allocator_arg, __a, _VSTD::forward<_Args>(__args)...);
+}
+
+// FIXME: This should have a version which takes a non-const alloc.
+template <class _Tp, class _Allocator, class... _Args>
+inline _LIBCPP_INLINE_VISIBILITY
+void __user_alloc_construct_impl (integral_constant<int, 2>, _Tp *__storage, const _Allocator &__a, _Args &&... __args )
+{
+    new (__storage) _Tp (_VSTD::forward<_Args>(__args)..., __a);
+}
+
+#endif // _LIBCPP_CXX03_LANG
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___FUNCTIONAL___ALLOCATOR_ARG_T_H
lib/libcxx/include/__memory/allocator_traits.h
@@ -11,8 +11,10 @@
 #define _LIBCPP___MEMORY_ALLOCATOR_TRAITS_H
 
 #include <__config>
-#include <__memory/base.h>
+#include <__memory/construct_at.h>
 #include <__memory/pointer_traits.h>
+#include <__utility/forward.h>
+#include <limits>
 #include <type_traits>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -253,7 +255,7 @@ struct _LIBCPP_TEMPLATE_VIS allocator_traits
     struct rebind_traits {
         using other = allocator_traits<typename rebind_alloc<_Tp>::other>;
     };
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
     static pointer allocate(allocator_type& __a, size_type __n) {
@@ -360,8 +362,10 @@ struct __rebind_alloc_helper {
 template <class _Tp>
 struct __is_default_allocator : false_type { };
 
+template <class> class allocator;
+
 template <class _Tp>
-struct __is_default_allocator<_VSTD::allocator<_Tp> > : true_type { };
+struct __is_default_allocator<allocator<_Tp> > : true_type { };
 
 // __is_cpp17_move_insertable
 template <class _Alloc, class = void>
@@ -398,4 +402,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP___MEMORY_ALLOCATOR_TRAITS_H
+#endif // _LIBCPP___MEMORY_ALLOCATOR_TRAITS_H
lib/libcxx/include/__memory/auto_ptr.h
@@ -0,0 +1,86 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_AUTO_PTR_H
+#define _LIBCPP___MEMORY_AUTO_PTR_H
+
+#include <__config>
+#include <__nullptr>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+struct _LIBCPP_DEPRECATED_IN_CXX11 auto_ptr_ref
+{
+    _Tp* __ptr_;
+};
+
+template<class _Tp>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 auto_ptr
+{
+private:
+    _Tp* __ptr_;
+public:
+    typedef _Tp element_type;
+
+    _LIBCPP_INLINE_VISIBILITY explicit auto_ptr(_Tp* __p = 0) _NOEXCEPT : __ptr_(__p) {}
+    _LIBCPP_INLINE_VISIBILITY auto_ptr(auto_ptr& __p) _NOEXCEPT : __ptr_(__p.release()) {}
+    template<class _Up> _LIBCPP_INLINE_VISIBILITY auto_ptr(auto_ptr<_Up>& __p) _NOEXCEPT
+        : __ptr_(__p.release()) {}
+    _LIBCPP_INLINE_VISIBILITY auto_ptr& operator=(auto_ptr& __p) _NOEXCEPT
+        {reset(__p.release()); return *this;}
+    template<class _Up> _LIBCPP_INLINE_VISIBILITY auto_ptr& operator=(auto_ptr<_Up>& __p) _NOEXCEPT
+        {reset(__p.release()); return *this;}
+    _LIBCPP_INLINE_VISIBILITY auto_ptr& operator=(auto_ptr_ref<_Tp> __p) _NOEXCEPT
+        {reset(__p.__ptr_); return *this;}
+    _LIBCPP_INLINE_VISIBILITY ~auto_ptr() _NOEXCEPT {delete __ptr_;}
+
+    _LIBCPP_INLINE_VISIBILITY _Tp& operator*() const _NOEXCEPT
+        {return *__ptr_;}
+    _LIBCPP_INLINE_VISIBILITY _Tp* operator->() const _NOEXCEPT {return __ptr_;}
+    _LIBCPP_INLINE_VISIBILITY _Tp* get() const _NOEXCEPT {return __ptr_;}
+    _LIBCPP_INLINE_VISIBILITY _Tp* release() _NOEXCEPT
+    {
+        _Tp* __t = __ptr_;
+        __ptr_ = nullptr;
+        return __t;
+    }
+    _LIBCPP_INLINE_VISIBILITY void reset(_Tp* __p = 0) _NOEXCEPT
+    {
+        if (__ptr_ != __p)
+            delete __ptr_;
+        __ptr_ = __p;
+    }
+
+    _LIBCPP_INLINE_VISIBILITY auto_ptr(auto_ptr_ref<_Tp> __p) _NOEXCEPT : __ptr_(__p.__ptr_) {}
+    template<class _Up> _LIBCPP_INLINE_VISIBILITY operator auto_ptr_ref<_Up>() _NOEXCEPT
+        {auto_ptr_ref<_Up> __t; __t.__ptr_ = release(); return __t;}
+    template<class _Up> _LIBCPP_INLINE_VISIBILITY operator auto_ptr<_Up>() _NOEXCEPT
+        {return auto_ptr<_Up>(release());}
+};
+
+template <>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 auto_ptr<void>
+{
+public:
+    typedef void element_type;
+};
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_AUTO_PTR_H
lib/libcxx/include/__memory/compressed_pair.h
@@ -0,0 +1,201 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_COMPRESSED_PAIR_H
+#define _LIBCPP___MEMORY_COMPRESSED_PAIR_H
+
+#include <__config>
+#include <__utility/forward.h>
+#include <tuple> // needed in c++03 for some constructors
+#include <type_traits>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// Tag used to default initialize one or both of the pair's elements.
+struct __default_init_tag {};
+struct __value_init_tag {};
+
+template <class _Tp, int _Idx,
+          bool _CanBeEmptyBase =
+              is_empty<_Tp>::value && !__libcpp_is_final<_Tp>::value>
+struct __compressed_pair_elem {
+  typedef _Tp _ParamT;
+  typedef _Tp& reference;
+  typedef const _Tp& const_reference;
+
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+  __compressed_pair_elem(__default_init_tag) {}
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+  __compressed_pair_elem(__value_init_tag) : __value_() {}
+
+  template <class _Up, class = typename enable_if<
+      !is_same<__compressed_pair_elem, typename decay<_Up>::type>::value
+  >::type>
+  _LIBCPP_INLINE_VISIBILITY
+  _LIBCPP_CONSTEXPR explicit
+  __compressed_pair_elem(_Up&& __u)
+      : __value_(_VSTD::forward<_Up>(__u))
+    {
+    }
+
+
+#ifndef _LIBCPP_CXX03_LANG
+  template <class... _Args, size_t... _Indexes>
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+  __compressed_pair_elem(piecewise_construct_t, tuple<_Args...> __args,
+                         __tuple_indices<_Indexes...>)
+      : __value_(_VSTD::forward<_Args>(_VSTD::get<_Indexes>(__args))...) {}
+#endif
+
+
+  _LIBCPP_INLINE_VISIBILITY reference __get() _NOEXCEPT { return __value_; }
+  _LIBCPP_INLINE_VISIBILITY
+  const_reference __get() const _NOEXCEPT { return __value_; }
+
+private:
+  _Tp __value_;
+};
+
+template <class _Tp, int _Idx>
+struct __compressed_pair_elem<_Tp, _Idx, true> : private _Tp {
+  typedef _Tp _ParamT;
+  typedef _Tp& reference;
+  typedef const _Tp& const_reference;
+  typedef _Tp __value_type;
+
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR __compressed_pair_elem() = default;
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+  __compressed_pair_elem(__default_init_tag) {}
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+  __compressed_pair_elem(__value_init_tag) : __value_type() {}
+
+  template <class _Up, class = typename enable_if<
+        !is_same<__compressed_pair_elem, typename decay<_Up>::type>::value
+  >::type>
+  _LIBCPP_INLINE_VISIBILITY
+  _LIBCPP_CONSTEXPR explicit
+  __compressed_pair_elem(_Up&& __u)
+      : __value_type(_VSTD::forward<_Up>(__u))
+  {}
+
+#ifndef _LIBCPP_CXX03_LANG
+  template <class... _Args, size_t... _Indexes>
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+  __compressed_pair_elem(piecewise_construct_t, tuple<_Args...> __args,
+                         __tuple_indices<_Indexes...>)
+      : __value_type(_VSTD::forward<_Args>(_VSTD::get<_Indexes>(__args))...) {}
+#endif
+
+  _LIBCPP_INLINE_VISIBILITY reference __get() _NOEXCEPT { return *this; }
+  _LIBCPP_INLINE_VISIBILITY
+  const_reference __get() const _NOEXCEPT { return *this; }
+};
+
+template <class _T1, class _T2>
+class __compressed_pair : private __compressed_pair_elem<_T1, 0>,
+                          private __compressed_pair_elem<_T2, 1> {
+public:
+  // NOTE: This static assert should never fire because __compressed_pair
+  // is *almost never* used in a scenario where it's possible for T1 == T2.
+  // (The exception is std::function where it is possible that the function
+  //  object and the allocator have the same type).
+  static_assert((!is_same<_T1, _T2>::value),
+    "__compressed_pair cannot be instantiated when T1 and T2 are the same type; "
+    "The current implementation is NOT ABI-compatible with the previous "
+    "implementation for this configuration");
+
+    typedef _LIBCPP_NODEBUG_TYPE __compressed_pair_elem<_T1, 0> _Base1;
+    typedef _LIBCPP_NODEBUG_TYPE __compressed_pair_elem<_T2, 1> _Base2;
+
+    template <bool _Dummy = true,
+      class = typename enable_if<
+          __dependent_type<is_default_constructible<_T1>, _Dummy>::value &&
+          __dependent_type<is_default_constructible<_T2>, _Dummy>::value
+      >::type
+  >
+  _LIBCPP_INLINE_VISIBILITY
+  _LIBCPP_CONSTEXPR __compressed_pair() : _Base1(__value_init_tag()), _Base2(__value_init_tag()) {}
+
+  template <class _U1, class _U2>
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+  __compressed_pair(_U1&& __t1, _U2&& __t2)
+      : _Base1(_VSTD::forward<_U1>(__t1)), _Base2(_VSTD::forward<_U2>(__t2)) {}
+
+#ifndef _LIBCPP_CXX03_LANG
+  template <class... _Args1, class... _Args2>
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
+  __compressed_pair(piecewise_construct_t __pc, tuple<_Args1...> __first_args,
+                    tuple<_Args2...> __second_args)
+      : _Base1(__pc, _VSTD::move(__first_args),
+               typename __make_tuple_indices<sizeof...(_Args1)>::type()),
+        _Base2(__pc, _VSTD::move(__second_args),
+               typename __make_tuple_indices<sizeof...(_Args2)>::type()) {}
+#endif
+
+  _LIBCPP_INLINE_VISIBILITY
+  typename _Base1::reference first() _NOEXCEPT {
+    return static_cast<_Base1&>(*this).__get();
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  typename _Base1::const_reference first() const _NOEXCEPT {
+    return static_cast<_Base1 const&>(*this).__get();
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  typename _Base2::reference second() _NOEXCEPT {
+    return static_cast<_Base2&>(*this).__get();
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  typename _Base2::const_reference second() const _NOEXCEPT {
+    return static_cast<_Base2 const&>(*this).__get();
+  }
+
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+  static _Base1* __get_first_base(__compressed_pair* __pair) _NOEXCEPT {
+    return static_cast<_Base1*>(__pair);
+  }
+  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+  static _Base2* __get_second_base(__compressed_pair* __pair) _NOEXCEPT {
+    return static_cast<_Base2*>(__pair);
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  void swap(__compressed_pair& __x)
+    _NOEXCEPT_(__is_nothrow_swappable<_T1>::value &&
+               __is_nothrow_swappable<_T2>::value)
+  {
+    using _VSTD::swap;
+    swap(first(), __x.first());
+    swap(second(), __x.second());
+  }
+};
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+void swap(__compressed_pair<_T1, _T2>& __x, __compressed_pair<_T1, _T2>& __y)
+    _NOEXCEPT_(__is_nothrow_swappable<_T1>::value &&
+               __is_nothrow_swappable<_T2>::value) {
+  __x.swap(__y);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_COMPRESSED_PAIR_H
lib/libcxx/include/__memory/construct_at.h
@@ -0,0 +1,59 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_CONSTRUCT_AT_H
+#define _LIBCPP___MEMORY_CONSTRUCT_AT_H
+
+#include <__config>
+#include <__debug>
+#include <__utility/forward.h>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// construct_at
+
+#if _LIBCPP_STD_VER > 17
+
+template<class _Tp, class ..._Args, class = decltype(
+    ::new (declval<void*>()) _Tp(declval<_Args>()...)
+)>
+_LIBCPP_INLINE_VISIBILITY
+constexpr _Tp* construct_at(_Tp* __location, _Args&& ...__args) {
+    _LIBCPP_ASSERT(__location, "null pointer given to construct_at");
+    return ::new ((void*)__location) _Tp(_VSTD::forward<_Args>(__args)...);
+}
+
+#endif
+
+// destroy_at
+
+#if _LIBCPP_STD_VER > 14
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void destroy_at(_Tp* __loc) {
+    _LIBCPP_ASSERT(__loc, "null pointer given to destroy_at");
+    __loc->~_Tp();
+}
+
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_CONSTRUCT_AT_H
lib/libcxx/include/__memory/pointer_safety.h
@@ -0,0 +1,57 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_POINTER_SAFETY_H
+#define _LIBCPP___MEMORY_POINTER_SAFETY_H
+
+#include <__config>
+#include <cstddef>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_CXX03_LANG)
+
+enum class pointer_safety : unsigned char {
+  relaxed,
+  preferred,
+  strict
+};
+
+inline _LIBCPP_INLINE_VISIBILITY
+pointer_safety get_pointer_safety() _NOEXCEPT {
+  return pointer_safety::relaxed;
+}
+
+_LIBCPP_FUNC_VIS void declare_reachable(void* __p);
+_LIBCPP_FUNC_VIS void declare_no_pointers(char* __p, size_t __n);
+_LIBCPP_FUNC_VIS void undeclare_no_pointers(char* __p, size_t __n);
+_LIBCPP_FUNC_VIS void* __undeclare_reachable(void* __p);
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+_Tp*
+undeclare_reachable(_Tp* __p)
+{
+    return static_cast<_Tp*>(__undeclare_reachable(__p));
+}
+
+#endif // !C++03
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_POINTER_SAFETY_H
lib/libcxx/include/__memory/pointer_traits.h
@@ -11,6 +11,7 @@
 #define _LIBCPP___MEMORY_POINTER_TRAITS_H
 
 #include <__config>
+#include <__memory/addressof.h>
 #include <type_traits>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -120,7 +121,7 @@ struct _LIBCPP_TEMPLATE_VIS pointer_traits
 #else
     template <class _Up> struct rebind
         {typedef typename __pointer_traits_rebind<pointer, _Up>::type other;};
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 private:
     struct __nat {};
@@ -162,8 +163,54 @@ struct __rebind_pointer {
 #endif
 };
 
+// to_address
+
+template <class _Pointer, class = void>
+struct __to_address_helper;
+
+template <class _Tp>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+_Tp* __to_address(_Tp* __p) _NOEXCEPT {
+    static_assert(!is_function<_Tp>::value, "_Tp is a function type");
+    return __p;
+}
+
+// enable_if is needed here to avoid instantiating checks for fancy pointers on raw pointers
+template <class _Pointer, class = _EnableIf<!is_pointer<_Pointer>::value> >
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+typename decay<decltype(__to_address_helper<_Pointer>::__call(declval<const _Pointer&>()))>::type
+__to_address(const _Pointer& __p) _NOEXCEPT {
+    return __to_address_helper<_Pointer>::__call(__p);
+}
+
+template <class _Pointer, class>
+struct __to_address_helper {
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+    static decltype(_VSTD::__to_address(declval<const _Pointer&>().operator->()))
+    __call(const _Pointer&__p) _NOEXCEPT {
+        return _VSTD::__to_address(__p.operator->());
+    }
+};
+
+template <class _Pointer>
+struct __to_address_helper<_Pointer, decltype((void)pointer_traits<_Pointer>::to_address(declval<const _Pointer&>()))> {
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+    static decltype(pointer_traits<_Pointer>::to_address(declval<const _Pointer&>()))
+    __call(const _Pointer&__p) _NOEXCEPT {
+        return pointer_traits<_Pointer>::to_address(__p);
+    }
+};
+
+#if _LIBCPP_STD_VER > 17
+template <class _Pointer>
+inline _LIBCPP_INLINE_VISIBILITY constexpr
+auto to_address(const _Pointer& __p) noexcept {
+    return _VSTD::__to_address(__p);
+}
+#endif
+
 _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP___MEMORY_POINTER_TRAITS_H
+#endif // _LIBCPP___MEMORY_POINTER_TRAITS_H
lib/libcxx/include/__memory/raw_storage_iterator.h
@@ -0,0 +1,73 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_RAW_STORAGE_ITERATOR_H
+#define _LIBCPP___MEMORY_RAW_STORAGE_ITERATOR_H
+
+#include <__config>
+#include <__memory/addressof.h>
+#include <cstddef>
+#include <iterator>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_RAW_STORAGE_ITERATOR)
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _OutputIterator, class _Tp>
+class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX17 raw_storage_iterator
+#if _LIBCPP_STD_VER <= 14 || !defined(_LIBCPP_ABI_NO_ITERATOR_BASES)
+    : public iterator<output_iterator_tag, void, void, void, void>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+private:
+    _OutputIterator __x_;
+public:
+    typedef output_iterator_tag iterator_category;
+    typedef void                value_type;
+#if _LIBCPP_STD_VER > 17
+    typedef ptrdiff_t           difference_type;
+#else
+    typedef void                difference_type;
+#endif
+    typedef void                pointer;
+    typedef void                reference;
+
+    _LIBCPP_INLINE_VISIBILITY explicit raw_storage_iterator(_OutputIterator __x) : __x_(__x) {}
+    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator& operator*() {return *this;}
+    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator& operator=(const _Tp& __element)
+        {::new ((void*)_VSTD::addressof(*__x_)) _Tp(__element); return *this;}
+#if _LIBCPP_STD_VER >= 14
+    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator& operator=(_Tp&& __element)
+        {::new ((void*)_VSTD::addressof(*__x_)) _Tp(_VSTD::move(__element)); return *this;}
+#endif
+    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator& operator++() {++__x_; return *this;}
+    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator  operator++(int)
+        {raw_storage_iterator __t(*this); ++__x_; return __t;}
+#if _LIBCPP_STD_VER >= 14
+    _LIBCPP_INLINE_VISIBILITY _OutputIterator base() const { return __x_; }
+#endif
+};
+
+#endif // _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_RAW_STORAGE_ITERATOR)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_RAW_STORAGE_ITERATOR_H
lib/libcxx/include/__memory/shared_ptr.h
@@ -0,0 +1,1879 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_SHARED_PTR_H
+#define _LIBCPP___MEMORY_SHARED_PTR_H
+
+#include <__availability>
+#include <__config>
+#include <__functional_base>
+#include <__functional/binary_function.h>
+#include <__functional/operations.h>
+#include <__functional/reference_wrapper.h>
+#include <__memory/addressof.h>
+#include <__memory/allocation_guard.h>
+#include <__memory/allocator_traits.h>
+#include <__memory/allocator.h>
+#include <__memory/compressed_pair.h>
+#include <__memory/pointer_traits.h>
+#include <__memory/unique_ptr.h>
+#include <__utility/forward.h>
+#include <cstddef>
+#include <cstdlib> // abort
+#include <iosfwd>
+#include <stdexcept>
+#include <typeinfo>
+#include <type_traits>
+#include <utility>
+#if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
+#  include <atomic>
+#endif
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
+#   include <__memory/auto_ptr.h>
+#endif
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Alloc>
+class __allocator_destructor
+{
+    typedef _LIBCPP_NODEBUG_TYPE allocator_traits<_Alloc> __alloc_traits;
+public:
+    typedef _LIBCPP_NODEBUG_TYPE typename __alloc_traits::pointer pointer;
+    typedef _LIBCPP_NODEBUG_TYPE typename __alloc_traits::size_type size_type;
+private:
+    _Alloc& __alloc_;
+    size_type __s_;
+public:
+    _LIBCPP_INLINE_VISIBILITY __allocator_destructor(_Alloc& __a, size_type __s)
+             _NOEXCEPT
+        : __alloc_(__a), __s_(__s) {}
+    _LIBCPP_INLINE_VISIBILITY
+    void operator()(pointer __p) _NOEXCEPT
+        {__alloc_traits::deallocate(__alloc_, __p, __s_);}
+};
+
+// NOTE: Relaxed and acq/rel atomics (for increment and decrement respectively)
+// should be sufficient for thread safety.
+// See https://llvm.org/PR22803
+#if defined(__clang__) && __has_builtin(__atomic_add_fetch)          \
+                       && defined(__ATOMIC_RELAXED)                  \
+                       && defined(__ATOMIC_ACQ_REL)
+#   define _LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT
+#elif defined(_LIBCPP_COMPILER_GCC)
+#   define _LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT
+#endif
+
+template <class _ValueType>
+inline _LIBCPP_INLINE_VISIBILITY
+_ValueType __libcpp_relaxed_load(_ValueType const* __value) {
+#if !defined(_LIBCPP_HAS_NO_THREADS) && \
+    defined(__ATOMIC_RELAXED) &&        \
+    (__has_builtin(__atomic_load_n) || defined(_LIBCPP_COMPILER_GCC))
+    return __atomic_load_n(__value, __ATOMIC_RELAXED);
+#else
+    return *__value;
+#endif
+}
+
+template <class _ValueType>
+inline _LIBCPP_INLINE_VISIBILITY
+_ValueType __libcpp_acquire_load(_ValueType const* __value) {
+#if !defined(_LIBCPP_HAS_NO_THREADS) && \
+    defined(__ATOMIC_ACQUIRE) &&        \
+    (__has_builtin(__atomic_load_n) || defined(_LIBCPP_COMPILER_GCC))
+    return __atomic_load_n(__value, __ATOMIC_ACQUIRE);
+#else
+    return *__value;
+#endif
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _Tp
+__libcpp_atomic_refcount_increment(_Tp& __t) _NOEXCEPT
+{
+#if defined(_LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT) && !defined(_LIBCPP_HAS_NO_THREADS)
+    return __atomic_add_fetch(&__t, 1, __ATOMIC_RELAXED);
+#else
+    return __t += 1;
+#endif
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY _Tp
+__libcpp_atomic_refcount_decrement(_Tp& __t) _NOEXCEPT
+{
+#if defined(_LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT) && !defined(_LIBCPP_HAS_NO_THREADS)
+    return __atomic_add_fetch(&__t, -1, __ATOMIC_ACQ_REL);
+#else
+    return __t -= 1;
+#endif
+}
+
+class _LIBCPP_EXCEPTION_ABI bad_weak_ptr
+    : public std::exception
+{
+public:
+    bad_weak_ptr() _NOEXCEPT = default;
+    bad_weak_ptr(const bad_weak_ptr&) _NOEXCEPT = default;
+    virtual ~bad_weak_ptr() _NOEXCEPT;
+    virtual const char* what() const  _NOEXCEPT;
+};
+
+_LIBCPP_NORETURN inline _LIBCPP_INLINE_VISIBILITY
+void __throw_bad_weak_ptr()
+{
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    throw bad_weak_ptr();
+#else
+    _VSTD::abort();
+#endif
+}
+
+template<class _Tp> class _LIBCPP_TEMPLATE_VIS weak_ptr;
+
+class _LIBCPP_TYPE_VIS __shared_count
+{
+    __shared_count(const __shared_count&);
+    __shared_count& operator=(const __shared_count&);
+
+protected:
+    long __shared_owners_;
+    virtual ~__shared_count();
+private:
+    virtual void __on_zero_shared() _NOEXCEPT = 0;
+
+public:
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __shared_count(long __refs = 0) _NOEXCEPT
+        : __shared_owners_(__refs) {}
+
+#if defined(_LIBCPP_BUILDING_LIBRARY) && \
+    defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
+    void __add_shared() _NOEXCEPT;
+    bool __release_shared() _NOEXCEPT;
+#else
+    _LIBCPP_INLINE_VISIBILITY
+    void __add_shared() _NOEXCEPT {
+      __libcpp_atomic_refcount_increment(__shared_owners_);
+    }
+    _LIBCPP_INLINE_VISIBILITY
+    bool __release_shared() _NOEXCEPT {
+      if (__libcpp_atomic_refcount_decrement(__shared_owners_) == -1) {
+        __on_zero_shared();
+        return true;
+      }
+      return false;
+    }
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    long use_count() const _NOEXCEPT {
+        return __libcpp_relaxed_load(&__shared_owners_) + 1;
+    }
+};
+
+class _LIBCPP_TYPE_VIS __shared_weak_count
+    : private __shared_count
+{
+    long __shared_weak_owners_;
+
+public:
+    _LIBCPP_INLINE_VISIBILITY
+    explicit __shared_weak_count(long __refs = 0) _NOEXCEPT
+        : __shared_count(__refs),
+          __shared_weak_owners_(__refs) {}
+protected:
+    virtual ~__shared_weak_count();
+
+public:
+#if defined(_LIBCPP_BUILDING_LIBRARY) && \
+    defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
+    void __add_shared() _NOEXCEPT;
+    void __add_weak() _NOEXCEPT;
+    void __release_shared() _NOEXCEPT;
+#else
+    _LIBCPP_INLINE_VISIBILITY
+    void __add_shared() _NOEXCEPT {
+      __shared_count::__add_shared();
+    }
+    _LIBCPP_INLINE_VISIBILITY
+    void __add_weak() _NOEXCEPT {
+      __libcpp_atomic_refcount_increment(__shared_weak_owners_);
+    }
+    _LIBCPP_INLINE_VISIBILITY
+    void __release_shared() _NOEXCEPT {
+      if (__shared_count::__release_shared())
+        __release_weak();
+    }
+#endif
+    void __release_weak() _NOEXCEPT;
+    _LIBCPP_INLINE_VISIBILITY
+    long use_count() const _NOEXCEPT {return __shared_count::use_count();}
+    __shared_weak_count* lock() _NOEXCEPT;
+
+    virtual const void* __get_deleter(const type_info&) const _NOEXCEPT;
+private:
+    virtual void __on_zero_shared_weak() _NOEXCEPT = 0;
+};
+
+template <class _Tp, class _Dp, class _Alloc>
+class __shared_ptr_pointer
+    : public __shared_weak_count
+{
+    __compressed_pair<__compressed_pair<_Tp, _Dp>, _Alloc> __data_;
+public:
+    _LIBCPP_INLINE_VISIBILITY
+    __shared_ptr_pointer(_Tp __p, _Dp __d, _Alloc __a)
+        :  __data_(__compressed_pair<_Tp, _Dp>(__p, _VSTD::move(__d)), _VSTD::move(__a)) {}
+
+#ifndef _LIBCPP_NO_RTTI
+    virtual const void* __get_deleter(const type_info&) const _NOEXCEPT;
+#endif
+
+private:
+    virtual void __on_zero_shared() _NOEXCEPT;
+    virtual void __on_zero_shared_weak() _NOEXCEPT;
+};
+
+#ifndef _LIBCPP_NO_RTTI
+
+template <class _Tp, class _Dp, class _Alloc>
+const void*
+__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__get_deleter(const type_info& __t) const _NOEXCEPT
+{
+    return __t == typeid(_Dp) ? _VSTD::addressof(__data_.first().second()) : nullptr;
+}
+
+#endif // _LIBCPP_NO_RTTI
+
+template <class _Tp, class _Dp, class _Alloc>
+void
+__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__on_zero_shared() _NOEXCEPT
+{
+    __data_.first().second()(__data_.first().first());
+    __data_.first().second().~_Dp();
+}
+
+template <class _Tp, class _Dp, class _Alloc>
+void
+__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__on_zero_shared_weak() _NOEXCEPT
+{
+    typedef typename __allocator_traits_rebind<_Alloc, __shared_ptr_pointer>::type _Al;
+    typedef allocator_traits<_Al> _ATraits;
+    typedef pointer_traits<typename _ATraits::pointer> _PTraits;
+
+    _Al __a(__data_.second());
+    __data_.second().~_Alloc();
+    __a.deallocate(_PTraits::pointer_to(*this), 1);
+}
+
+template <class _Tp, class _Alloc>
+struct __shared_ptr_emplace
+    : __shared_weak_count
+{
+    template<class ..._Args>
+    _LIBCPP_HIDE_FROM_ABI
+    explicit __shared_ptr_emplace(_Alloc __a, _Args&& ...__args)
+        : __storage_(_VSTD::move(__a))
+    {
+#if _LIBCPP_STD_VER > 17
+        using _TpAlloc = typename __allocator_traits_rebind<_Alloc, _Tp>::type;
+        _TpAlloc __tmp(*__get_alloc());
+        allocator_traits<_TpAlloc>::construct(__tmp, __get_elem(), _VSTD::forward<_Args>(__args)...);
+#else
+        ::new ((void*)__get_elem()) _Tp(_VSTD::forward<_Args>(__args)...);
+#endif
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    _Alloc* __get_alloc() _NOEXCEPT { return __storage_.__get_alloc(); }
+
+    _LIBCPP_HIDE_FROM_ABI
+    _Tp* __get_elem() _NOEXCEPT { return __storage_.__get_elem(); }
+
+private:
+    virtual void __on_zero_shared() _NOEXCEPT {
+#if _LIBCPP_STD_VER > 17
+        using _TpAlloc = typename __allocator_traits_rebind<_Alloc, _Tp>::type;
+        _TpAlloc __tmp(*__get_alloc());
+        allocator_traits<_TpAlloc>::destroy(__tmp, __get_elem());
+#else
+        __get_elem()->~_Tp();
+#endif
+    }
+
+    virtual void __on_zero_shared_weak() _NOEXCEPT {
+        using _ControlBlockAlloc = typename __allocator_traits_rebind<_Alloc, __shared_ptr_emplace>::type;
+        using _ControlBlockPointer = typename allocator_traits<_ControlBlockAlloc>::pointer;
+        _ControlBlockAlloc __tmp(*__get_alloc());
+        __storage_.~_Storage();
+        allocator_traits<_ControlBlockAlloc>::deallocate(__tmp,
+            pointer_traits<_ControlBlockPointer>::pointer_to(*this), 1);
+    }
+
+    // This class implements the control block for non-array shared pointers created
+    // through `std::allocate_shared` and `std::make_shared`.
+    //
+    // In previous versions of the library, we used a compressed pair to store
+    // both the _Alloc and the _Tp. This implies using EBO, which is incompatible
+    // with Allocator construction for _Tp. To allow implementing P0674 in C++20,
+    // we now use a properly aligned char buffer while making sure that we maintain
+    // the same layout that we had when we used a compressed pair.
+    using _CompressedPair = __compressed_pair<_Alloc, _Tp>;
+    struct _ALIGNAS_TYPE(_CompressedPair) _Storage {
+        char __blob_[sizeof(_CompressedPair)];
+
+        _LIBCPP_HIDE_FROM_ABI explicit _Storage(_Alloc&& __a) {
+            ::new ((void*)__get_alloc()) _Alloc(_VSTD::move(__a));
+        }
+        _LIBCPP_HIDE_FROM_ABI ~_Storage() {
+            __get_alloc()->~_Alloc();
+        }
+        _Alloc* __get_alloc() _NOEXCEPT {
+            _CompressedPair *__as_pair = reinterpret_cast<_CompressedPair*>(__blob_);
+            typename _CompressedPair::_Base1* __first = _CompressedPair::__get_first_base(__as_pair);
+            _Alloc *__alloc = reinterpret_cast<_Alloc*>(__first);
+            return __alloc;
+        }
+        _LIBCPP_NO_CFI _Tp* __get_elem() _NOEXCEPT {
+            _CompressedPair *__as_pair = reinterpret_cast<_CompressedPair*>(__blob_);
+            typename _CompressedPair::_Base2* __second = _CompressedPair::__get_second_base(__as_pair);
+            _Tp *__elem = reinterpret_cast<_Tp*>(__second);
+            return __elem;
+        }
+    };
+
+    static_assert(_LIBCPP_ALIGNOF(_Storage) == _LIBCPP_ALIGNOF(_CompressedPair), "");
+    static_assert(sizeof(_Storage) == sizeof(_CompressedPair), "");
+    _Storage __storage_;
+};
+
+struct __shared_ptr_dummy_rebind_allocator_type;
+template <>
+class _LIBCPP_TEMPLATE_VIS allocator<__shared_ptr_dummy_rebind_allocator_type>
+{
+public:
+    template <class _Other>
+    struct rebind
+    {
+        typedef allocator<_Other> other;
+    };
+};
+
+template<class _Tp> class _LIBCPP_TEMPLATE_VIS enable_shared_from_this;
+
+template<class _Tp, class _Up>
+struct __compatible_with
+#if _LIBCPP_STD_VER > 14
+    : is_convertible<remove_extent_t<_Tp>*, remove_extent_t<_Up>*> {};
+#else
+    : is_convertible<_Tp*, _Up*> {};
+#endif // _LIBCPP_STD_VER > 14
+
+template <class _Ptr, class = void>
+struct __is_deletable : false_type { };
+template <class _Ptr>
+struct __is_deletable<_Ptr, decltype(delete declval<_Ptr>())> : true_type { };
+
+template <class _Ptr, class = void>
+struct __is_array_deletable : false_type { };
+template <class _Ptr>
+struct __is_array_deletable<_Ptr, decltype(delete[] declval<_Ptr>())> : true_type { };
+
+template <class _Dp, class _Pt,
+    class = decltype(declval<_Dp>()(declval<_Pt>()))>
+static true_type __well_formed_deleter_test(int);
+
+template <class, class>
+static false_type __well_formed_deleter_test(...);
+
+template <class _Dp, class _Pt>
+struct __well_formed_deleter : decltype(__well_formed_deleter_test<_Dp, _Pt>(0)) {};
+
+template<class _Dp, class _Tp, class _Yp>
+struct __shared_ptr_deleter_ctor_reqs
+{
+    static const bool value = __compatible_with<_Tp, _Yp>::value &&
+                              is_move_constructible<_Dp>::value &&
+                              __well_formed_deleter<_Dp, _Tp*>::value;
+};
+
+#if defined(_LIBCPP_ABI_ENABLE_SHARED_PTR_TRIVIAL_ABI)
+#  define _LIBCPP_SHARED_PTR_TRIVIAL_ABI __attribute__((trivial_abi))
+#else
+#  define _LIBCPP_SHARED_PTR_TRIVIAL_ABI
+#endif
+
+template<class _Tp>
+class _LIBCPP_SHARED_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS shared_ptr
+{
+public:
+#if _LIBCPP_STD_VER > 14
+    typedef weak_ptr<_Tp> weak_type;
+    typedef remove_extent_t<_Tp> element_type;
+#else
+    typedef _Tp element_type;
+#endif
+
+private:
+    element_type*      __ptr_;
+    __shared_weak_count* __cntrl_;
+
+    struct __nat {int __for_bool_;};
+public:
+    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_CONSTEXPR shared_ptr() _NOEXCEPT;
+    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_CONSTEXPR shared_ptr(nullptr_t) _NOEXCEPT;
+
+    template<class _Yp, class = _EnableIf<
+        _And<
+            __compatible_with<_Yp, _Tp>
+            // In C++03 we get errors when trying to do SFINAE with the
+            // delete operator, so we always pretend that it's deletable.
+            // The same happens on GCC.
+#if !defined(_LIBCPP_CXX03_LANG) && !defined(_LIBCPP_COMPILER_GCC)
+            , _If<is_array<_Tp>::value, __is_array_deletable<_Yp*>, __is_deletable<_Yp*> >
+#endif
+        >::value
+    > >
+    explicit shared_ptr(_Yp* __p) : __ptr_(__p) {
+        unique_ptr<_Yp> __hold(__p);
+        typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
+        typedef __shared_ptr_pointer<_Yp*, __shared_ptr_default_delete<_Tp, _Yp>, _AllocT > _CntrlBlk;
+        __cntrl_ = new _CntrlBlk(__p, __shared_ptr_default_delete<_Tp, _Yp>(), _AllocT());
+        __hold.release();
+        __enable_weak_this(__p, __p);
+    }
+
+    template<class _Yp, class _Dp>
+        shared_ptr(_Yp* __p, _Dp __d,
+                   typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type = __nat());
+    template<class _Yp, class _Dp, class _Alloc>
+        shared_ptr(_Yp* __p, _Dp __d, _Alloc __a,
+                   typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type = __nat());
+    template <class _Dp> shared_ptr(nullptr_t __p, _Dp __d);
+    template <class _Dp, class _Alloc> shared_ptr(nullptr_t __p, _Dp __d, _Alloc __a);
+    template<class _Yp> _LIBCPP_INLINE_VISIBILITY shared_ptr(const shared_ptr<_Yp>& __r, element_type* __p) _NOEXCEPT;
+    _LIBCPP_INLINE_VISIBILITY
+    shared_ptr(const shared_ptr& __r) _NOEXCEPT;
+    template<class _Yp>
+        _LIBCPP_INLINE_VISIBILITY
+        shared_ptr(const shared_ptr<_Yp>& __r,
+                   typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat())
+                       _NOEXCEPT;
+    _LIBCPP_INLINE_VISIBILITY
+    shared_ptr(shared_ptr&& __r) _NOEXCEPT;
+    template<class _Yp> _LIBCPP_INLINE_VISIBILITY  shared_ptr(shared_ptr<_Yp>&& __r,
+                   typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat())
+                       _NOEXCEPT;
+    template<class _Yp> explicit shared_ptr(const weak_ptr<_Yp>& __r,
+                   typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type= __nat());
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
+    template<class _Yp>
+        shared_ptr(auto_ptr<_Yp>&& __r,
+                   typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type = __nat());
+#endif
+    template <class _Yp, class _Dp>
+        shared_ptr(unique_ptr<_Yp, _Dp>&&,
+                   typename enable_if
+                   <
+                       !is_lvalue_reference<_Dp>::value &&
+                       is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
+                       __nat
+                   >::type = __nat());
+    template <class _Yp, class _Dp>
+        shared_ptr(unique_ptr<_Yp, _Dp>&&,
+                   typename enable_if
+                   <
+                       is_lvalue_reference<_Dp>::value &&
+                       is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
+                       __nat
+                   >::type = __nat());
+
+    ~shared_ptr();
+
+    _LIBCPP_INLINE_VISIBILITY
+    shared_ptr& operator=(const shared_ptr& __r) _NOEXCEPT;
+    template<class _Yp>
+        typename enable_if
+        <
+            __compatible_with<_Yp, element_type>::value,
+            shared_ptr&
+        >::type
+        _LIBCPP_INLINE_VISIBILITY
+        operator=(const shared_ptr<_Yp>& __r) _NOEXCEPT;
+    _LIBCPP_INLINE_VISIBILITY
+    shared_ptr& operator=(shared_ptr&& __r) _NOEXCEPT;
+    template<class _Yp>
+        typename enable_if
+        <
+            __compatible_with<_Yp, element_type>::value,
+            shared_ptr&
+        >::type
+        _LIBCPP_INLINE_VISIBILITY
+        operator=(shared_ptr<_Yp>&& __r);
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
+    template<class _Yp>
+        _LIBCPP_INLINE_VISIBILITY
+        typename enable_if
+        <
+            !is_array<_Yp>::value &&
+            is_convertible<_Yp*, element_type*>::value,
+            shared_ptr
+        >::type&
+        operator=(auto_ptr<_Yp>&& __r);
+#endif
+    template <class _Yp, class _Dp>
+        typename enable_if
+        <
+            is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
+            shared_ptr&
+        >::type
+        _LIBCPP_INLINE_VISIBILITY
+        operator=(unique_ptr<_Yp, _Dp>&& __r);
+
+    _LIBCPP_INLINE_VISIBILITY
+    void swap(shared_ptr& __r) _NOEXCEPT;
+    _LIBCPP_INLINE_VISIBILITY
+    void reset() _NOEXCEPT;
+    template<class _Yp>
+        typename enable_if
+        <
+            __compatible_with<_Yp, element_type>::value,
+            void
+        >::type
+        _LIBCPP_INLINE_VISIBILITY
+        reset(_Yp* __p);
+    template<class _Yp, class _Dp>
+        typename enable_if
+        <
+            __compatible_with<_Yp, element_type>::value,
+            void
+        >::type
+        _LIBCPP_INLINE_VISIBILITY
+        reset(_Yp* __p, _Dp __d);
+    template<class _Yp, class _Dp, class _Alloc>
+        typename enable_if
+        <
+            __compatible_with<_Yp, element_type>::value,
+            void
+        >::type
+        _LIBCPP_INLINE_VISIBILITY
+        reset(_Yp* __p, _Dp __d, _Alloc __a);
+
+    _LIBCPP_INLINE_VISIBILITY
+    element_type* get() const _NOEXCEPT {return __ptr_;}
+    _LIBCPP_INLINE_VISIBILITY
+    typename add_lvalue_reference<element_type>::type operator*() const _NOEXCEPT
+        {return *__ptr_;}
+    _LIBCPP_INLINE_VISIBILITY
+    element_type* operator->() const _NOEXCEPT
+    {
+        static_assert(!is_array<_Tp>::value,
+                      "std::shared_ptr<T>::operator-> is only valid when T is not an array type.");
+        return __ptr_;
+    }
+    _LIBCPP_INLINE_VISIBILITY
+    long use_count() const _NOEXCEPT {return __cntrl_ ? __cntrl_->use_count() : 0;}
+    _LIBCPP_INLINE_VISIBILITY
+    bool unique() const _NOEXCEPT {return use_count() == 1;}
+    _LIBCPP_INLINE_VISIBILITY
+    explicit operator bool() const _NOEXCEPT {return get() != nullptr;}
+    template <class _Up>
+        _LIBCPP_INLINE_VISIBILITY
+        bool owner_before(shared_ptr<_Up> const& __p) const _NOEXCEPT
+        {return __cntrl_ < __p.__cntrl_;}
+    template <class _Up>
+        _LIBCPP_INLINE_VISIBILITY
+        bool owner_before(weak_ptr<_Up> const& __p) const _NOEXCEPT
+        {return __cntrl_ < __p.__cntrl_;}
+    _LIBCPP_INLINE_VISIBILITY
+    bool
+    __owner_equivalent(const shared_ptr& __p) const
+        {return __cntrl_ == __p.__cntrl_;}
+
+#if _LIBCPP_STD_VER > 14
+    typename add_lvalue_reference<element_type>::type
+    _LIBCPP_INLINE_VISIBILITY
+    operator[](ptrdiff_t __i) const
+    {
+            static_assert(is_array<_Tp>::value,
+                          "std::shared_ptr<T>::operator[] is only valid when T is an array type.");
+            return __ptr_[__i];
+    }
+#endif
+
+#ifndef _LIBCPP_NO_RTTI
+    template <class _Dp>
+        _LIBCPP_INLINE_VISIBILITY
+        _Dp* __get_deleter() const _NOEXCEPT
+            {return static_cast<_Dp*>(__cntrl_
+                    ? const_cast<void *>(__cntrl_->__get_deleter(typeid(_Dp)))
+                      : nullptr);}
+#endif // _LIBCPP_NO_RTTI
+
+    template<class _Yp, class _CntrlBlk>
+    static shared_ptr<_Tp>
+    __create_with_control_block(_Yp* __p, _CntrlBlk* __cntrl) _NOEXCEPT
+    {
+        shared_ptr<_Tp> __r;
+        __r.__ptr_ = __p;
+        __r.__cntrl_ = __cntrl;
+        __r.__enable_weak_this(__r.__ptr_, __r.__ptr_);
+        return __r;
+    }
+
+private:
+    template <class _Yp, bool = is_function<_Yp>::value>
+        struct __shared_ptr_default_allocator
+        {
+            typedef allocator<_Yp> type;
+        };
+
+    template <class _Yp>
+        struct __shared_ptr_default_allocator<_Yp, true>
+        {
+            typedef allocator<__shared_ptr_dummy_rebind_allocator_type> type;
+        };
+
+    template <class _Yp, class _OrigPtr>
+        _LIBCPP_INLINE_VISIBILITY
+        typename enable_if<is_convertible<_OrigPtr*,
+                                          const enable_shared_from_this<_Yp>*
+        >::value,
+            void>::type
+        __enable_weak_this(const enable_shared_from_this<_Yp>* __e,
+                           _OrigPtr* __ptr) _NOEXCEPT
+        {
+            typedef typename remove_cv<_Yp>::type _RawYp;
+            if (__e && __e->__weak_this_.expired())
+            {
+                __e->__weak_this_ = shared_ptr<_RawYp>(*this,
+                    const_cast<_RawYp*>(static_cast<const _Yp*>(__ptr)));
+            }
+        }
+
+    _LIBCPP_INLINE_VISIBILITY void __enable_weak_this(...) _NOEXCEPT {}
+
+    template <class, class _Yp>
+        struct __shared_ptr_default_delete
+            : default_delete<_Yp> {};
+
+    template <class _Yp, class _Un, size_t _Sz>
+        struct __shared_ptr_default_delete<_Yp[_Sz], _Un>
+            : default_delete<_Yp[]> {};
+
+    template <class _Yp, class _Un>
+        struct __shared_ptr_default_delete<_Yp[], _Un>
+            : default_delete<_Yp[]> {};
+
+    template <class _Up> friend class _LIBCPP_TEMPLATE_VIS shared_ptr;
+    template <class _Up> friend class _LIBCPP_TEMPLATE_VIS weak_ptr;
+};
+
+#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
+template<class _Tp>
+shared_ptr(weak_ptr<_Tp>) -> shared_ptr<_Tp>;
+template<class _Tp, class _Dp>
+shared_ptr(unique_ptr<_Tp, _Dp>) -> shared_ptr<_Tp>;
+#endif
+
+template<class _Tp>
+inline
+_LIBCPP_CONSTEXPR
+shared_ptr<_Tp>::shared_ptr() _NOEXCEPT
+    : __ptr_(nullptr),
+      __cntrl_(nullptr)
+{
+}
+
+template<class _Tp>
+inline
+_LIBCPP_CONSTEXPR
+shared_ptr<_Tp>::shared_ptr(nullptr_t) _NOEXCEPT
+    : __ptr_(nullptr),
+      __cntrl_(nullptr)
+{
+}
+
+template<class _Tp>
+template<class _Yp, class _Dp>
+shared_ptr<_Tp>::shared_ptr(_Yp* __p, _Dp __d,
+                            typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type)
+    : __ptr_(__p)
+{
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try
+    {
+#endif // _LIBCPP_NO_EXCEPTIONS
+        typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
+        typedef __shared_ptr_pointer<_Yp*, _Dp, _AllocT > _CntrlBlk;
+#ifndef _LIBCPP_CXX03_LANG
+        __cntrl_ = new _CntrlBlk(__p, _VSTD::move(__d), _AllocT());
+#else
+        __cntrl_ = new _CntrlBlk(__p, __d, _AllocT());
+#endif // not _LIBCPP_CXX03_LANG
+        __enable_weak_this(__p, __p);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+        __d(__p);
+        throw;
+    }
+#endif // _LIBCPP_NO_EXCEPTIONS
+}
+
+template<class _Tp>
+template<class _Dp>
+shared_ptr<_Tp>::shared_ptr(nullptr_t __p, _Dp __d)
+    : __ptr_(nullptr)
+{
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try
+    {
+#endif // _LIBCPP_NO_EXCEPTIONS
+        typedef typename __shared_ptr_default_allocator<_Tp>::type _AllocT;
+        typedef __shared_ptr_pointer<nullptr_t, _Dp, _AllocT > _CntrlBlk;
+#ifndef _LIBCPP_CXX03_LANG
+        __cntrl_ = new _CntrlBlk(__p, _VSTD::move(__d), _AllocT());
+#else
+        __cntrl_ = new _CntrlBlk(__p, __d, _AllocT());
+#endif // not _LIBCPP_CXX03_LANG
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+        __d(__p);
+        throw;
+    }
+#endif // _LIBCPP_NO_EXCEPTIONS
+}
+
+template<class _Tp>
+template<class _Yp, class _Dp, class _Alloc>
+shared_ptr<_Tp>::shared_ptr(_Yp* __p, _Dp __d, _Alloc __a,
+                            typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type)
+    : __ptr_(__p)
+{
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try
+    {
+#endif // _LIBCPP_NO_EXCEPTIONS
+        typedef __shared_ptr_pointer<_Yp*, _Dp, _Alloc> _CntrlBlk;
+        typedef typename __allocator_traits_rebind<_Alloc, _CntrlBlk>::type _A2;
+        typedef __allocator_destructor<_A2> _D2;
+        _A2 __a2(__a);
+        unique_ptr<_CntrlBlk, _D2> __hold2(__a2.allocate(1), _D2(__a2, 1));
+        ::new ((void*)_VSTD::addressof(*__hold2.get()))
+#ifndef _LIBCPP_CXX03_LANG
+            _CntrlBlk(__p, _VSTD::move(__d), __a);
+#else
+            _CntrlBlk(__p, __d, __a);
+#endif // not _LIBCPP_CXX03_LANG
+        __cntrl_ = _VSTD::addressof(*__hold2.release());
+        __enable_weak_this(__p, __p);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+        __d(__p);
+        throw;
+    }
+#endif // _LIBCPP_NO_EXCEPTIONS
+}
+
+template<class _Tp>
+template<class _Dp, class _Alloc>
+shared_ptr<_Tp>::shared_ptr(nullptr_t __p, _Dp __d, _Alloc __a)
+    : __ptr_(nullptr)
+{
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try
+    {
+#endif // _LIBCPP_NO_EXCEPTIONS
+        typedef __shared_ptr_pointer<nullptr_t, _Dp, _Alloc> _CntrlBlk;
+        typedef typename __allocator_traits_rebind<_Alloc, _CntrlBlk>::type _A2;
+        typedef __allocator_destructor<_A2> _D2;
+        _A2 __a2(__a);
+        unique_ptr<_CntrlBlk, _D2> __hold2(__a2.allocate(1), _D2(__a2, 1));
+        ::new ((void*)_VSTD::addressof(*__hold2.get()))
+#ifndef _LIBCPP_CXX03_LANG
+            _CntrlBlk(__p, _VSTD::move(__d), __a);
+#else
+            _CntrlBlk(__p, __d, __a);
+#endif // not _LIBCPP_CXX03_LANG
+        __cntrl_ = _VSTD::addressof(*__hold2.release());
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+        __d(__p);
+        throw;
+    }
+#endif // _LIBCPP_NO_EXCEPTIONS
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+shared_ptr<_Tp>::shared_ptr(const shared_ptr<_Yp>& __r, element_type *__p) _NOEXCEPT
+    : __ptr_(__p),
+      __cntrl_(__r.__cntrl_)
+{
+    if (__cntrl_)
+        __cntrl_->__add_shared();
+}
+
+template<class _Tp>
+inline
+shared_ptr<_Tp>::shared_ptr(const shared_ptr& __r) _NOEXCEPT
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_)
+{
+    if (__cntrl_)
+        __cntrl_->__add_shared();
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+shared_ptr<_Tp>::shared_ptr(const shared_ptr<_Yp>& __r,
+                            typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
+         _NOEXCEPT
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_)
+{
+    if (__cntrl_)
+        __cntrl_->__add_shared();
+}
+
+template<class _Tp>
+inline
+shared_ptr<_Tp>::shared_ptr(shared_ptr&& __r) _NOEXCEPT
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_)
+{
+    __r.__ptr_ = nullptr;
+    __r.__cntrl_ = nullptr;
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+shared_ptr<_Tp>::shared_ptr(shared_ptr<_Yp>&& __r,
+                            typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
+         _NOEXCEPT
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_)
+{
+    __r.__ptr_ = nullptr;
+    __r.__cntrl_ = nullptr;
+}
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
+template<class _Tp>
+template<class _Yp>
+shared_ptr<_Tp>::shared_ptr(auto_ptr<_Yp>&& __r,
+                            typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type)
+    : __ptr_(__r.get())
+{
+    typedef __shared_ptr_pointer<_Yp*, default_delete<_Yp>, allocator<_Yp> > _CntrlBlk;
+    __cntrl_ = new _CntrlBlk(__r.get(), default_delete<_Yp>(), allocator<_Yp>());
+    __enable_weak_this(__r.get(), __r.get());
+    __r.release();
+}
+#endif
+
+template<class _Tp>
+template <class _Yp, class _Dp>
+shared_ptr<_Tp>::shared_ptr(unique_ptr<_Yp, _Dp>&& __r,
+                            typename enable_if
+                            <
+                                !is_lvalue_reference<_Dp>::value &&
+                                is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
+                                __nat
+                            >::type)
+    : __ptr_(__r.get())
+{
+#if _LIBCPP_STD_VER > 11
+    if (__ptr_ == nullptr)
+        __cntrl_ = nullptr;
+    else
+#endif
+    {
+        typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
+        typedef __shared_ptr_pointer<typename unique_ptr<_Yp, _Dp>::pointer, _Dp, _AllocT > _CntrlBlk;
+        __cntrl_ = new _CntrlBlk(__r.get(), __r.get_deleter(), _AllocT());
+        __enable_weak_this(__r.get(), __r.get());
+    }
+    __r.release();
+}
+
+template<class _Tp>
+template <class _Yp, class _Dp>
+shared_ptr<_Tp>::shared_ptr(unique_ptr<_Yp, _Dp>&& __r,
+                            typename enable_if
+                            <
+                                is_lvalue_reference<_Dp>::value &&
+                                is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
+                                __nat
+                            >::type)
+    : __ptr_(__r.get())
+{
+#if _LIBCPP_STD_VER > 11
+    if (__ptr_ == nullptr)
+        __cntrl_ = nullptr;
+    else
+#endif
+    {
+        typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
+        typedef __shared_ptr_pointer<typename unique_ptr<_Yp, _Dp>::pointer,
+                                     reference_wrapper<typename remove_reference<_Dp>::type>,
+                                     _AllocT > _CntrlBlk;
+        __cntrl_ = new _CntrlBlk(__r.get(), _VSTD::ref(__r.get_deleter()), _AllocT());
+        __enable_weak_this(__r.get(), __r.get());
+    }
+    __r.release();
+}
+
+template<class _Tp>
+shared_ptr<_Tp>::~shared_ptr()
+{
+    if (__cntrl_)
+        __cntrl_->__release_shared();
+}
+
+template<class _Tp>
+inline
+shared_ptr<_Tp>&
+shared_ptr<_Tp>::operator=(const shared_ptr& __r) _NOEXCEPT
+{
+    shared_ptr(__r).swap(*this);
+    return *this;
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+typename enable_if
+<
+    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
+    shared_ptr<_Tp>&
+>::type
+shared_ptr<_Tp>::operator=(const shared_ptr<_Yp>& __r) _NOEXCEPT
+{
+    shared_ptr(__r).swap(*this);
+    return *this;
+}
+
+template<class _Tp>
+inline
+shared_ptr<_Tp>&
+shared_ptr<_Tp>::operator=(shared_ptr&& __r) _NOEXCEPT
+{
+    shared_ptr(_VSTD::move(__r)).swap(*this);
+    return *this;
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+typename enable_if
+<
+    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
+    shared_ptr<_Tp>&
+>::type
+shared_ptr<_Tp>::operator=(shared_ptr<_Yp>&& __r)
+{
+    shared_ptr(_VSTD::move(__r)).swap(*this);
+    return *this;
+}
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
+template<class _Tp>
+template<class _Yp>
+inline
+typename enable_if
+<
+    !is_array<_Yp>::value &&
+    is_convertible<_Yp*, typename shared_ptr<_Tp>::element_type*>::value,
+    shared_ptr<_Tp>
+>::type&
+shared_ptr<_Tp>::operator=(auto_ptr<_Yp>&& __r)
+{
+    shared_ptr(_VSTD::move(__r)).swap(*this);
+    return *this;
+}
+#endif
+
+template<class _Tp>
+template <class _Yp, class _Dp>
+inline
+typename enable_if
+<
+    is_convertible<typename unique_ptr<_Yp, _Dp>::pointer,
+                   typename shared_ptr<_Tp>::element_type*>::value,
+    shared_ptr<_Tp>&
+>::type
+shared_ptr<_Tp>::operator=(unique_ptr<_Yp, _Dp>&& __r)
+{
+    shared_ptr(_VSTD::move(__r)).swap(*this);
+    return *this;
+}
+
+template<class _Tp>
+inline
+void
+shared_ptr<_Tp>::swap(shared_ptr& __r) _NOEXCEPT
+{
+    _VSTD::swap(__ptr_, __r.__ptr_);
+    _VSTD::swap(__cntrl_, __r.__cntrl_);
+}
+
+template<class _Tp>
+inline
+void
+shared_ptr<_Tp>::reset() _NOEXCEPT
+{
+    shared_ptr().swap(*this);
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+typename enable_if
+<
+    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
+    void
+>::type
+shared_ptr<_Tp>::reset(_Yp* __p)
+{
+    shared_ptr(__p).swap(*this);
+}
+
+template<class _Tp>
+template<class _Yp, class _Dp>
+inline
+typename enable_if
+<
+    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
+    void
+>::type
+shared_ptr<_Tp>::reset(_Yp* __p, _Dp __d)
+{
+    shared_ptr(__p, __d).swap(*this);
+}
+
+template<class _Tp>
+template<class _Yp, class _Dp, class _Alloc>
+inline
+typename enable_if
+<
+    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
+    void
+>::type
+shared_ptr<_Tp>::reset(_Yp* __p, _Dp __d, _Alloc __a)
+{
+    shared_ptr(__p, __d, __a).swap(*this);
+}
+
+//
+// std::allocate_shared and std::make_shared
+//
+template<class _Tp, class _Alloc, class ..._Args, class = _EnableIf<!is_array<_Tp>::value> >
+_LIBCPP_HIDE_FROM_ABI
+shared_ptr<_Tp> allocate_shared(const _Alloc& __a, _Args&& ...__args)
+{
+    using _ControlBlock = __shared_ptr_emplace<_Tp, _Alloc>;
+    using _ControlBlockAllocator = typename __allocator_traits_rebind<_Alloc, _ControlBlock>::type;
+    __allocation_guard<_ControlBlockAllocator> __guard(__a, 1);
+    ::new ((void*)_VSTD::addressof(*__guard.__get())) _ControlBlock(__a, _VSTD::forward<_Args>(__args)...);
+    auto __control_block = __guard.__release_ptr();
+    return shared_ptr<_Tp>::__create_with_control_block((*__control_block).__get_elem(), _VSTD::addressof(*__control_block));
+}
+
+template<class _Tp, class ..._Args, class = _EnableIf<!is_array<_Tp>::value> >
+_LIBCPP_HIDE_FROM_ABI
+shared_ptr<_Tp> make_shared(_Args&& ...__args)
+{
+    return _VSTD::allocate_shared<_Tp>(allocator<_Tp>(), _VSTD::forward<_Args>(__args)...);
+}
+
+template<class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator==(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
+{
+    return __x.get() == __y.get();
+}
+
+template<class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
+{
+    return !(__x == __y);
+}
+
+template<class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
+{
+#if _LIBCPP_STD_VER <= 11
+    typedef typename common_type<_Tp*, _Up*>::type _Vp;
+    return less<_Vp>()(__x.get(), __y.get());
+#else
+    return less<>()(__x.get(), __y.get());
+#endif
+
+}
+
+template<class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
+{
+    return __y < __x;
+}
+
+template<class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
+{
+    return !(__y < __x);
+}
+
+template<class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
+{
+    return !(__x < __y);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator==(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
+{
+    return !__x;
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator==(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
+{
+    return !__x;
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
+{
+    return static_cast<bool>(__x);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
+{
+    return static_cast<bool>(__x);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
+{
+    return less<_Tp*>()(__x.get(), nullptr);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
+{
+    return less<_Tp*>()(nullptr, __x.get());
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
+{
+    return nullptr < __x;
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
+{
+    return __x < nullptr;
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
+{
+    return !(nullptr < __x);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
+{
+    return !(__x < nullptr);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
+{
+    return !(__x < nullptr);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
+{
+    return !(nullptr < __x);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+void
+swap(shared_ptr<_Tp>& __x, shared_ptr<_Tp>& __y) _NOEXCEPT
+{
+    __x.swap(__y);
+}
+
+template<class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+shared_ptr<_Tp>
+static_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPT
+{
+    return shared_ptr<_Tp>(__r,
+                           static_cast<
+                               typename shared_ptr<_Tp>::element_type*>(__r.get()));
+}
+
+template<class _Tp, class _Up>
+inline _LIBCPP_INLINE_VISIBILITY
+shared_ptr<_Tp>
+dynamic_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPT
+{
+    typedef typename shared_ptr<_Tp>::element_type _ET;
+    _ET* __p = dynamic_cast<_ET*>(__r.get());
+    return __p ? shared_ptr<_Tp>(__r, __p) : shared_ptr<_Tp>();
+}
+
+template<class _Tp, class _Up>
+shared_ptr<_Tp>
+const_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPT
+{
+    typedef typename shared_ptr<_Tp>::element_type _RTp;
+    return shared_ptr<_Tp>(__r, const_cast<_RTp*>(__r.get()));
+}
+
+template<class _Tp, class _Up>
+shared_ptr<_Tp>
+reinterpret_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPT
+{
+    return shared_ptr<_Tp>(__r,
+                           reinterpret_cast<
+                               typename shared_ptr<_Tp>::element_type*>(__r.get()));
+}
+
+#ifndef _LIBCPP_NO_RTTI
+
+template<class _Dp, class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+_Dp*
+get_deleter(const shared_ptr<_Tp>& __p) _NOEXCEPT
+{
+    return __p.template __get_deleter<_Dp>();
+}
+
+#endif // _LIBCPP_NO_RTTI
+
+template<class _Tp>
+class _LIBCPP_SHARED_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS weak_ptr
+{
+public:
+    typedef _Tp element_type;
+private:
+    element_type*        __ptr_;
+    __shared_weak_count* __cntrl_;
+
+public:
+    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_CONSTEXPR weak_ptr() _NOEXCEPT;
+    template<class _Yp> _LIBCPP_INLINE_VISIBILITY weak_ptr(shared_ptr<_Yp> const& __r,
+                   typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
+                        _NOEXCEPT;
+    _LIBCPP_INLINE_VISIBILITY
+    weak_ptr(weak_ptr const& __r) _NOEXCEPT;
+    template<class _Yp> _LIBCPP_INLINE_VISIBILITY weak_ptr(weak_ptr<_Yp> const& __r,
+                   typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
+                         _NOEXCEPT;
+
+    _LIBCPP_INLINE_VISIBILITY
+    weak_ptr(weak_ptr&& __r) _NOEXCEPT;
+    template<class _Yp> _LIBCPP_INLINE_VISIBILITY weak_ptr(weak_ptr<_Yp>&& __r,
+                   typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
+                         _NOEXCEPT;
+    ~weak_ptr();
+
+    _LIBCPP_INLINE_VISIBILITY
+    weak_ptr& operator=(weak_ptr const& __r) _NOEXCEPT;
+    template<class _Yp>
+        typename enable_if
+        <
+            is_convertible<_Yp*, element_type*>::value,
+            weak_ptr&
+        >::type
+        _LIBCPP_INLINE_VISIBILITY
+        operator=(weak_ptr<_Yp> const& __r) _NOEXCEPT;
+
+    _LIBCPP_INLINE_VISIBILITY
+    weak_ptr& operator=(weak_ptr&& __r) _NOEXCEPT;
+    template<class _Yp>
+        typename enable_if
+        <
+            is_convertible<_Yp*, element_type*>::value,
+            weak_ptr&
+        >::type
+        _LIBCPP_INLINE_VISIBILITY
+        operator=(weak_ptr<_Yp>&& __r) _NOEXCEPT;
+
+    template<class _Yp>
+        typename enable_if
+        <
+            is_convertible<_Yp*, element_type*>::value,
+            weak_ptr&
+        >::type
+        _LIBCPP_INLINE_VISIBILITY
+        operator=(shared_ptr<_Yp> const& __r) _NOEXCEPT;
+
+    _LIBCPP_INLINE_VISIBILITY
+    void swap(weak_ptr& __r) _NOEXCEPT;
+    _LIBCPP_INLINE_VISIBILITY
+    void reset() _NOEXCEPT;
+
+    _LIBCPP_INLINE_VISIBILITY
+    long use_count() const _NOEXCEPT
+        {return __cntrl_ ? __cntrl_->use_count() : 0;}
+    _LIBCPP_INLINE_VISIBILITY
+    bool expired() const _NOEXCEPT
+        {return __cntrl_ == nullptr || __cntrl_->use_count() == 0;}
+    shared_ptr<_Tp> lock() const _NOEXCEPT;
+    template<class _Up>
+        _LIBCPP_INLINE_VISIBILITY
+        bool owner_before(const shared_ptr<_Up>& __r) const _NOEXCEPT
+        {return __cntrl_ < __r.__cntrl_;}
+    template<class _Up>
+        _LIBCPP_INLINE_VISIBILITY
+        bool owner_before(const weak_ptr<_Up>& __r) const _NOEXCEPT
+        {return __cntrl_ < __r.__cntrl_;}
+
+    template <class _Up> friend class _LIBCPP_TEMPLATE_VIS weak_ptr;
+    template <class _Up> friend class _LIBCPP_TEMPLATE_VIS shared_ptr;
+};
+
+#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
+template<class _Tp>
+weak_ptr(shared_ptr<_Tp>) -> weak_ptr<_Tp>;
+#endif
+
+template<class _Tp>
+inline
+_LIBCPP_CONSTEXPR
+weak_ptr<_Tp>::weak_ptr() _NOEXCEPT
+    : __ptr_(nullptr),
+      __cntrl_(nullptr)
+{
+}
+
+template<class _Tp>
+inline
+weak_ptr<_Tp>::weak_ptr(weak_ptr const& __r) _NOEXCEPT
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_)
+{
+    if (__cntrl_)
+        __cntrl_->__add_weak();
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+weak_ptr<_Tp>::weak_ptr(shared_ptr<_Yp> const& __r,
+                        typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
+                         _NOEXCEPT
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_)
+{
+    if (__cntrl_)
+        __cntrl_->__add_weak();
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+weak_ptr<_Tp>::weak_ptr(weak_ptr<_Yp> const& __r,
+                        typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
+         _NOEXCEPT
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_)
+{
+    if (__cntrl_)
+        __cntrl_->__add_weak();
+}
+
+template<class _Tp>
+inline
+weak_ptr<_Tp>::weak_ptr(weak_ptr&& __r) _NOEXCEPT
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_)
+{
+    __r.__ptr_ = nullptr;
+    __r.__cntrl_ = nullptr;
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+weak_ptr<_Tp>::weak_ptr(weak_ptr<_Yp>&& __r,
+                        typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
+         _NOEXCEPT
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_)
+{
+    __r.__ptr_ = nullptr;
+    __r.__cntrl_ = nullptr;
+}
+
+template<class _Tp>
+weak_ptr<_Tp>::~weak_ptr()
+{
+    if (__cntrl_)
+        __cntrl_->__release_weak();
+}
+
+template<class _Tp>
+inline
+weak_ptr<_Tp>&
+weak_ptr<_Tp>::operator=(weak_ptr const& __r) _NOEXCEPT
+{
+    weak_ptr(__r).swap(*this);
+    return *this;
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+typename enable_if
+<
+    is_convertible<_Yp*, _Tp*>::value,
+    weak_ptr<_Tp>&
+>::type
+weak_ptr<_Tp>::operator=(weak_ptr<_Yp> const& __r) _NOEXCEPT
+{
+    weak_ptr(__r).swap(*this);
+    return *this;
+}
+
+template<class _Tp>
+inline
+weak_ptr<_Tp>&
+weak_ptr<_Tp>::operator=(weak_ptr&& __r) _NOEXCEPT
+{
+    weak_ptr(_VSTD::move(__r)).swap(*this);
+    return *this;
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+typename enable_if
+<
+    is_convertible<_Yp*, _Tp*>::value,
+    weak_ptr<_Tp>&
+>::type
+weak_ptr<_Tp>::operator=(weak_ptr<_Yp>&& __r) _NOEXCEPT
+{
+    weak_ptr(_VSTD::move(__r)).swap(*this);
+    return *this;
+}
+
+template<class _Tp>
+template<class _Yp>
+inline
+typename enable_if
+<
+    is_convertible<_Yp*, _Tp*>::value,
+    weak_ptr<_Tp>&
+>::type
+weak_ptr<_Tp>::operator=(shared_ptr<_Yp> const& __r) _NOEXCEPT
+{
+    weak_ptr(__r).swap(*this);
+    return *this;
+}
+
+template<class _Tp>
+inline
+void
+weak_ptr<_Tp>::swap(weak_ptr& __r) _NOEXCEPT
+{
+    _VSTD::swap(__ptr_, __r.__ptr_);
+    _VSTD::swap(__cntrl_, __r.__cntrl_);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+void
+swap(weak_ptr<_Tp>& __x, weak_ptr<_Tp>& __y) _NOEXCEPT
+{
+    __x.swap(__y);
+}
+
+template<class _Tp>
+inline
+void
+weak_ptr<_Tp>::reset() _NOEXCEPT
+{
+    weak_ptr().swap(*this);
+}
+
+template<class _Tp>
+template<class _Yp>
+shared_ptr<_Tp>::shared_ptr(const weak_ptr<_Yp>& __r,
+                            typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type)
+    : __ptr_(__r.__ptr_),
+      __cntrl_(__r.__cntrl_ ? __r.__cntrl_->lock() : __r.__cntrl_)
+{
+    if (__cntrl_ == nullptr)
+        __throw_bad_weak_ptr();
+}
+
+template<class _Tp>
+shared_ptr<_Tp>
+weak_ptr<_Tp>::lock() const _NOEXCEPT
+{
+    shared_ptr<_Tp> __r;
+    __r.__cntrl_ = __cntrl_ ? __cntrl_->lock() : __cntrl_;
+    if (__r.__cntrl_)
+        __r.__ptr_ = __ptr_;
+    return __r;
+}
+
+#if _LIBCPP_STD_VER > 14
+template <class _Tp = void> struct owner_less;
+#else
+template <class _Tp> struct owner_less;
+#endif
+
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp>
+struct _LIBCPP_TEMPLATE_VIS owner_less<shared_ptr<_Tp> >
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<shared_ptr<_Tp>, shared_ptr<_Tp>, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef shared_ptr<_Tp> first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef shared_ptr<_Tp> second_argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(shared_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(shared_ptr<_Tp> const& __x,   weak_ptr<_Tp> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(  weak_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+};
+
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp>
+struct _LIBCPP_TEMPLATE_VIS owner_less<weak_ptr<_Tp> >
+#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
+    : binary_function<weak_ptr<_Tp>, weak_ptr<_Tp>, bool>
+#endif
+{
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef weak_ptr<_Tp> first_argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef weak_ptr<_Tp> second_argument_type;
+#endif
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(  weak_ptr<_Tp> const& __x,   weak_ptr<_Tp> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(shared_ptr<_Tp> const& __x,   weak_ptr<_Tp> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(  weak_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+};
+
+#if _LIBCPP_STD_VER > 14
+template <>
+struct _LIBCPP_TEMPLATE_VIS owner_less<void>
+{
+    template <class _Tp, class _Up>
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()( shared_ptr<_Tp> const& __x, shared_ptr<_Up> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+    template <class _Tp, class _Up>
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()( shared_ptr<_Tp> const& __x,   weak_ptr<_Up> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+    template <class _Tp, class _Up>
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(   weak_ptr<_Tp> const& __x, shared_ptr<_Up> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+    template <class _Tp, class _Up>
+    _LIBCPP_INLINE_VISIBILITY
+    bool operator()(   weak_ptr<_Tp> const& __x,   weak_ptr<_Up> const& __y) const _NOEXCEPT
+        {return __x.owner_before(__y);}
+    typedef void is_transparent;
+};
+#endif
+
+template<class _Tp>
+class _LIBCPP_TEMPLATE_VIS enable_shared_from_this
+{
+    mutable weak_ptr<_Tp> __weak_this_;
+protected:
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+    enable_shared_from_this() _NOEXCEPT {}
+    _LIBCPP_INLINE_VISIBILITY
+    enable_shared_from_this(enable_shared_from_this const&) _NOEXCEPT {}
+    _LIBCPP_INLINE_VISIBILITY
+    enable_shared_from_this& operator=(enable_shared_from_this const&) _NOEXCEPT
+        {return *this;}
+    _LIBCPP_INLINE_VISIBILITY
+    ~enable_shared_from_this() {}
+public:
+    _LIBCPP_INLINE_VISIBILITY
+    shared_ptr<_Tp> shared_from_this()
+        {return shared_ptr<_Tp>(__weak_this_);}
+    _LIBCPP_INLINE_VISIBILITY
+    shared_ptr<_Tp const> shared_from_this() const
+        {return shared_ptr<const _Tp>(__weak_this_);}
+
+#if _LIBCPP_STD_VER > 14
+    _LIBCPP_INLINE_VISIBILITY
+    weak_ptr<_Tp> weak_from_this() _NOEXCEPT
+       { return __weak_this_; }
+
+    _LIBCPP_INLINE_VISIBILITY
+    weak_ptr<const _Tp> weak_from_this() const _NOEXCEPT
+        { return __weak_this_; }
+#endif // _LIBCPP_STD_VER > 14
+
+    template <class _Up> friend class shared_ptr;
+};
+
+template <class _Tp> struct _LIBCPP_TEMPLATE_VIS hash;
+
+template <class _Tp>
+struct _LIBCPP_TEMPLATE_VIS hash<shared_ptr<_Tp> >
+{
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef shared_ptr<_Tp> argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t          result_type;
+#endif
+
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(const shared_ptr<_Tp>& __ptr) const _NOEXCEPT
+    {
+        return hash<typename shared_ptr<_Tp>::element_type*>()(__ptr.get());
+    }
+};
+
+template<class _CharT, class _Traits, class _Yp>
+inline _LIBCPP_INLINE_VISIBILITY
+basic_ostream<_CharT, _Traits>&
+operator<<(basic_ostream<_CharT, _Traits>& __os, shared_ptr<_Yp> const& __p);
+
+
+#if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
+
+class _LIBCPP_TYPE_VIS __sp_mut
+{
+    void* __lx;
+public:
+    void lock() _NOEXCEPT;
+    void unlock() _NOEXCEPT;
+
+private:
+    _LIBCPP_CONSTEXPR __sp_mut(void*) _NOEXCEPT;
+    __sp_mut(const __sp_mut&);
+    __sp_mut& operator=(const __sp_mut&);
+
+    friend _LIBCPP_FUNC_VIS __sp_mut& __get_sp_mut(const void*);
+};
+
+_LIBCPP_FUNC_VIS _LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+__sp_mut& __get_sp_mut(const void*);
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+atomic_is_lock_free(const shared_ptr<_Tp>*)
+{
+    return false;
+}
+
+template <class _Tp>
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+shared_ptr<_Tp>
+atomic_load(const shared_ptr<_Tp>* __p)
+{
+    __sp_mut& __m = __get_sp_mut(__p);
+    __m.lock();
+    shared_ptr<_Tp> __q = *__p;
+    __m.unlock();
+    return __q;
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+shared_ptr<_Tp>
+atomic_load_explicit(const shared_ptr<_Tp>* __p, memory_order)
+{
+    return atomic_load(__p);
+}
+
+template <class _Tp>
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+void
+atomic_store(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r)
+{
+    __sp_mut& __m = __get_sp_mut(__p);
+    __m.lock();
+    __p->swap(__r);
+    __m.unlock();
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+void
+atomic_store_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order)
+{
+    atomic_store(__p, __r);
+}
+
+template <class _Tp>
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+shared_ptr<_Tp>
+atomic_exchange(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r)
+{
+    __sp_mut& __m = __get_sp_mut(__p);
+    __m.lock();
+    __p->swap(__r);
+    __m.unlock();
+    return __r;
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+shared_ptr<_Tp>
+atomic_exchange_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order)
+{
+    return atomic_exchange(__p, __r);
+}
+
+template <class _Tp>
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+bool
+atomic_compare_exchange_strong(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w)
+{
+    shared_ptr<_Tp> __temp;
+    __sp_mut& __m = __get_sp_mut(__p);
+    __m.lock();
+    if (__p->__owner_equivalent(*__v))
+    {
+        _VSTD::swap(__temp, *__p);
+        *__p = __w;
+        __m.unlock();
+        return true;
+    }
+    _VSTD::swap(__temp, *__v);
+    *__v = *__p;
+    __m.unlock();
+    return false;
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+bool
+atomic_compare_exchange_weak(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w)
+{
+    return atomic_compare_exchange_strong(__p, __v, __w);
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+bool
+atomic_compare_exchange_strong_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v,
+                                        shared_ptr<_Tp> __w, memory_order, memory_order)
+{
+    return atomic_compare_exchange_strong(__p, __v, __w);
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
+bool
+atomic_compare_exchange_weak_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v,
+                                      shared_ptr<_Tp> __w, memory_order, memory_order)
+{
+    return atomic_compare_exchange_weak(__p, __v, __w);
+}
+
+#endif // !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_SHARED_PTR_H
lib/libcxx/include/__memory/temporary_buffer.h
@@ -0,0 +1,89 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_TEMPORARY_BUFFER_H
+#define _LIBCPP___MEMORY_TEMPORARY_BUFFER_H
+
+#include <__config>
+#include <cstddef>
+#include <new>
+#include <utility> // pair
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+_LIBCPP_NODISCARD_EXT _LIBCPP_NO_CFI
+pair<_Tp*, ptrdiff_t>
+get_temporary_buffer(ptrdiff_t __n) _NOEXCEPT
+{
+    pair<_Tp*, ptrdiff_t> __r(0, 0);
+    const ptrdiff_t __m = (~ptrdiff_t(0) ^
+                           ptrdiff_t(ptrdiff_t(1) << (sizeof(ptrdiff_t) * __CHAR_BIT__ - 1)))
+                           / sizeof(_Tp);
+    if (__n > __m)
+        __n = __m;
+    while (__n > 0)
+    {
+#if !defined(_LIBCPP_HAS_NO_ALIGNED_ALLOCATION)
+    if (__is_overaligned_for_new(_LIBCPP_ALIGNOF(_Tp)))
+        {
+            align_val_t __al =
+                align_val_t(alignment_of<_Tp>::value);
+            __r.first = static_cast<_Tp*>(::operator new(
+                __n * sizeof(_Tp), __al, nothrow));
+        } else {
+            __r.first = static_cast<_Tp*>(::operator new(
+                __n * sizeof(_Tp), nothrow));
+        }
+#else
+    if (__is_overaligned_for_new(_LIBCPP_ALIGNOF(_Tp)))
+        {
+            // Since aligned operator new is unavailable, return an empty
+            // buffer rather than one with invalid alignment.
+            return __r;
+        }
+
+        __r.first = static_cast<_Tp*>(::operator new(__n * sizeof(_Tp), nothrow));
+#endif
+
+        if (__r.first)
+        {
+            __r.second = __n;
+            break;
+        }
+        __n /= 2;
+    }
+    return __r;
+}
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+void return_temporary_buffer(_Tp* __p) _NOEXCEPT
+{
+  _VSTD::__libcpp_deallocate_unsized((void*)__p, _LIBCPP_ALIGNOF(_Tp));
+}
+
+struct __return_temporary_buffer
+{
+    template <class _Tp>
+    _LIBCPP_INLINE_VISIBILITY void operator()(_Tp* __p) const {_VSTD::return_temporary_buffer(__p);}
+};
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_TEMPORARY_BUFFER_H
lib/libcxx/include/__memory/uninitialized_algorithms.h
@@ -0,0 +1,261 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_UNINITIALIZED_ALGORITHMS_H
+#define _LIBCPP___MEMORY_UNINITIALIZED_ALGORITHMS_H
+
+#include <__config>
+#include <__memory/addressof.h>
+#include <__memory/construct_at.h>
+#include <iterator>
+#include <utility>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _InputIterator, class _ForwardIterator>
+_ForwardIterator
+uninitialized_copy(_InputIterator __f, _InputIterator __l, _ForwardIterator __r)
+{
+    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    _ForwardIterator __s = __r;
+    try
+    {
+#endif
+        for (; __f != __l; ++__f, (void) ++__r)
+            ::new ((void*)_VSTD::addressof(*__r)) value_type(*__f);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+        for (; __s != __r; ++__s)
+            __s->~value_type();
+        throw;
+    }
+#endif
+    return __r;
+}
+
+template <class _InputIterator, class _Size, class _ForwardIterator>
+_ForwardIterator
+uninitialized_copy_n(_InputIterator __f, _Size __n, _ForwardIterator __r)
+{
+    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    _ForwardIterator __s = __r;
+    try
+    {
+#endif
+        for (; __n > 0; ++__f, (void) ++__r, (void) --__n)
+            ::new ((void*)_VSTD::addressof(*__r)) value_type(*__f);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+        for (; __s != __r; ++__s)
+            __s->~value_type();
+        throw;
+    }
+#endif
+    return __r;
+}
+
+template <class _ForwardIterator, class _Tp>
+void
+uninitialized_fill(_ForwardIterator __f, _ForwardIterator __l, const _Tp& __x)
+{
+    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    _ForwardIterator __s = __f;
+    try
+    {
+#endif
+        for (; __f != __l; ++__f)
+            ::new ((void*)_VSTD::addressof(*__f)) value_type(__x);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+        for (; __s != __f; ++__s)
+            __s->~value_type();
+        throw;
+    }
+#endif
+}
+
+template <class _ForwardIterator, class _Size, class _Tp>
+_ForwardIterator
+uninitialized_fill_n(_ForwardIterator __f, _Size __n, const _Tp& __x)
+{
+    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    _ForwardIterator __s = __f;
+    try
+    {
+#endif
+        for (; __n > 0; ++__f, (void) --__n)
+            ::new ((void*)_VSTD::addressof(*__f)) value_type(__x);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+        for (; __s != __f; ++__s)
+            __s->~value_type();
+        throw;
+    }
+#endif
+    return __f;
+}
+
+#if _LIBCPP_STD_VER > 14
+
+template <class _ForwardIterator>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+void destroy(_ForwardIterator __first, _ForwardIterator __last) {
+    for (; __first != __last; ++__first)
+        _VSTD::destroy_at(_VSTD::addressof(*__first));
+}
+
+template <class _ForwardIterator, class _Size>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_ForwardIterator destroy_n(_ForwardIterator __first, _Size __n) {
+    for (; __n > 0; (void)++__first, --__n)
+        _VSTD::destroy_at(_VSTD::addressof(*__first));
+    return __first;
+}
+
+template <class _ForwardIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+void uninitialized_default_construct(_ForwardIterator __first, _ForwardIterator __last) {
+    using _Vt = typename iterator_traits<_ForwardIterator>::value_type;
+    auto __idx = __first;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try {
+#endif
+    for (; __idx != __last; ++__idx)
+        ::new ((void*)_VSTD::addressof(*__idx)) _Vt;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    } catch (...) {
+        _VSTD::destroy(__first, __idx);
+        throw;
+    }
+#endif
+}
+
+template <class _ForwardIterator, class _Size>
+inline _LIBCPP_INLINE_VISIBILITY
+_ForwardIterator uninitialized_default_construct_n(_ForwardIterator __first, _Size __n) {
+    using _Vt = typename iterator_traits<_ForwardIterator>::value_type;
+    auto __idx = __first;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try {
+#endif
+    for (; __n > 0; (void)++__idx, --__n)
+        ::new ((void*)_VSTD::addressof(*__idx)) _Vt;
+    return __idx;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    } catch (...) {
+        _VSTD::destroy(__first, __idx);
+        throw;
+    }
+#endif
+}
+
+
+template <class _ForwardIterator>
+inline _LIBCPP_INLINE_VISIBILITY
+void uninitialized_value_construct(_ForwardIterator __first, _ForwardIterator __last) {
+    using _Vt = typename iterator_traits<_ForwardIterator>::value_type;
+    auto __idx = __first;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try {
+#endif
+    for (; __idx != __last; ++__idx)
+        ::new ((void*)_VSTD::addressof(*__idx)) _Vt();
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    } catch (...) {
+        _VSTD::destroy(__first, __idx);
+        throw;
+    }
+#endif
+}
+
+template <class _ForwardIterator, class _Size>
+inline _LIBCPP_INLINE_VISIBILITY
+_ForwardIterator uninitialized_value_construct_n(_ForwardIterator __first, _Size __n) {
+    using _Vt = typename iterator_traits<_ForwardIterator>::value_type;
+    auto __idx = __first;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try {
+#endif
+    for (; __n > 0; (void)++__idx, --__n)
+        ::new ((void*)_VSTD::addressof(*__idx)) _Vt();
+    return __idx;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    } catch (...) {
+        _VSTD::destroy(__first, __idx);
+        throw;
+    }
+#endif
+}
+
+
+template <class _InputIt, class _ForwardIt>
+inline _LIBCPP_INLINE_VISIBILITY
+_ForwardIt uninitialized_move(_InputIt __first, _InputIt __last, _ForwardIt __first_res) {
+    using _Vt = typename iterator_traits<_ForwardIt>::value_type;
+    auto __idx = __first_res;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try {
+#endif
+    for (; __first != __last; (void)++__idx, ++__first)
+        ::new ((void*)_VSTD::addressof(*__idx)) _Vt(_VSTD::move(*__first));
+    return __idx;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    } catch (...) {
+        _VSTD::destroy(__first_res, __idx);
+        throw;
+    }
+#endif
+}
+
+template <class _InputIt, class _Size, class _ForwardIt>
+inline _LIBCPP_INLINE_VISIBILITY
+pair<_InputIt, _ForwardIt>
+uninitialized_move_n(_InputIt __first, _Size __n, _ForwardIt __first_res) {
+    using _Vt = typename iterator_traits<_ForwardIt>::value_type;
+    auto __idx = __first_res;
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try {
+#endif
+    for (; __n > 0; ++__idx, (void)++__first, --__n)
+        ::new ((void*)_VSTD::addressof(*__idx)) _Vt(_VSTD::move(*__first));
+    return {__first, __idx};
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    } catch (...) {
+        _VSTD::destroy(__first_res, __idx);
+        throw;
+    }
+#endif
+}
+
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_UNINITIALIZED_ALGORITHMS_H
lib/libcxx/include/__memory/unique_ptr.h
@@ -0,0 +1,773 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_UNIQUE_PTR_H
+#define _LIBCPP___MEMORY_UNIQUE_PTR_H
+
+#include <__config>
+#include <__functional_base>
+#include <__functional/hash.h>
+#include <__functional/operations.h>
+#include <__memory/allocator_traits.h> // __pointer
+#include <__memory/compressed_pair.h>
+#include <__utility/forward.h>
+#include <cstddef>
+#include <type_traits>
+#include <utility>
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
+#   include <__memory/auto_ptr.h>
+#endif
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+struct _LIBCPP_TEMPLATE_VIS default_delete {
+    static_assert(!is_function<_Tp>::value,
+                  "default_delete cannot be instantiated for function types");
+#ifndef _LIBCPP_CXX03_LANG
+  _LIBCPP_INLINE_VISIBILITY constexpr default_delete() _NOEXCEPT = default;
+#else
+  _LIBCPP_INLINE_VISIBILITY default_delete() {}
+#endif
+  template <class _Up>
+  _LIBCPP_INLINE_VISIBILITY
+  default_delete(const default_delete<_Up>&,
+                 typename enable_if<is_convertible<_Up*, _Tp*>::value>::type* =
+                     0) _NOEXCEPT {}
+
+  _LIBCPP_INLINE_VISIBILITY void operator()(_Tp* __ptr) const _NOEXCEPT {
+    static_assert(sizeof(_Tp) > 0,
+                  "default_delete can not delete incomplete type");
+    static_assert(!is_void<_Tp>::value,
+                  "default_delete can not delete incomplete type");
+    delete __ptr;
+  }
+};
+
+template <class _Tp>
+struct _LIBCPP_TEMPLATE_VIS default_delete<_Tp[]> {
+private:
+  template <class _Up>
+  struct _EnableIfConvertible
+      : enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value> {};
+
+public:
+#ifndef _LIBCPP_CXX03_LANG
+  _LIBCPP_INLINE_VISIBILITY constexpr default_delete() _NOEXCEPT = default;
+#else
+  _LIBCPP_INLINE_VISIBILITY default_delete() {}
+#endif
+
+  template <class _Up>
+  _LIBCPP_INLINE_VISIBILITY
+  default_delete(const default_delete<_Up[]>&,
+                 typename _EnableIfConvertible<_Up>::type* = 0) _NOEXCEPT {}
+
+  template <class _Up>
+  _LIBCPP_INLINE_VISIBILITY
+  typename _EnableIfConvertible<_Up>::type
+  operator()(_Up* __ptr) const _NOEXCEPT {
+    static_assert(sizeof(_Tp) > 0,
+                  "default_delete can not delete incomplete type");
+    static_assert(!is_void<_Tp>::value,
+                  "default_delete can not delete void type");
+    delete[] __ptr;
+  }
+};
+
+template <class _Deleter>
+struct __unique_ptr_deleter_sfinae {
+  static_assert(!is_reference<_Deleter>::value, "incorrect specialization");
+  typedef const _Deleter& __lval_ref_type;
+  typedef _Deleter&& __good_rval_ref_type;
+  typedef true_type __enable_rval_overload;
+};
+
+template <class _Deleter>
+struct __unique_ptr_deleter_sfinae<_Deleter const&> {
+  typedef const _Deleter& __lval_ref_type;
+  typedef const _Deleter&& __bad_rval_ref_type;
+  typedef false_type __enable_rval_overload;
+};
+
+template <class _Deleter>
+struct __unique_ptr_deleter_sfinae<_Deleter&> {
+  typedef _Deleter& __lval_ref_type;
+  typedef _Deleter&& __bad_rval_ref_type;
+  typedef false_type __enable_rval_overload;
+};
+
+#if defined(_LIBCPP_ABI_ENABLE_UNIQUE_PTR_TRIVIAL_ABI)
+#  define _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI __attribute__((trivial_abi))
+#else
+#  define _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI
+#endif
+
+template <class _Tp, class _Dp = default_delete<_Tp> >
+class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS unique_ptr {
+public:
+  typedef _Tp element_type;
+  typedef _Dp deleter_type;
+  typedef _LIBCPP_NODEBUG_TYPE typename __pointer<_Tp, deleter_type>::type pointer;
+
+  static_assert(!is_rvalue_reference<deleter_type>::value,
+                "the specified deleter type cannot be an rvalue reference");
+
+private:
+  __compressed_pair<pointer, deleter_type> __ptr_;
+
+  struct __nat { int __for_bool_; };
+
+  typedef _LIBCPP_NODEBUG_TYPE __unique_ptr_deleter_sfinae<_Dp> _DeleterSFINAE;
+
+  template <bool _Dummy>
+  using _LValRefType _LIBCPP_NODEBUG_TYPE =
+      typename __dependent_type<_DeleterSFINAE, _Dummy>::__lval_ref_type;
+
+  template <bool _Dummy>
+  using _GoodRValRefType _LIBCPP_NODEBUG_TYPE =
+      typename __dependent_type<_DeleterSFINAE, _Dummy>::__good_rval_ref_type;
+
+  template <bool _Dummy>
+  using _BadRValRefType _LIBCPP_NODEBUG_TYPE  =
+      typename __dependent_type<_DeleterSFINAE, _Dummy>::__bad_rval_ref_type;
+
+  template <bool _Dummy, class _Deleter = typename __dependent_type<
+                             __identity<deleter_type>, _Dummy>::type>
+  using _EnableIfDeleterDefaultConstructible _LIBCPP_NODEBUG_TYPE =
+      typename enable_if<is_default_constructible<_Deleter>::value &&
+                         !is_pointer<_Deleter>::value>::type;
+
+  template <class _ArgType>
+  using _EnableIfDeleterConstructible _LIBCPP_NODEBUG_TYPE  =
+      typename enable_if<is_constructible<deleter_type, _ArgType>::value>::type;
+
+  template <class _UPtr, class _Up>
+  using _EnableIfMoveConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
+      is_convertible<typename _UPtr::pointer, pointer>::value &&
+      !is_array<_Up>::value
+  >::type;
+
+  template <class _UDel>
+  using _EnableIfDeleterConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
+      (is_reference<_Dp>::value && is_same<_Dp, _UDel>::value) ||
+      (!is_reference<_Dp>::value && is_convertible<_UDel, _Dp>::value)
+    >::type;
+
+  template <class _UDel>
+  using _EnableIfDeleterAssignable = typename enable_if<
+      is_assignable<_Dp&, _UDel&&>::value
+    >::type;
+
+public:
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
+  _LIBCPP_INLINE_VISIBILITY
+  _LIBCPP_CONSTEXPR unique_ptr() _NOEXCEPT : __ptr_(pointer(), __default_init_tag()) {}
+
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
+  _LIBCPP_INLINE_VISIBILITY
+  _LIBCPP_CONSTEXPR unique_ptr(nullptr_t) _NOEXCEPT : __ptr_(pointer(), __default_init_tag()) {}
+
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
+  _LIBCPP_INLINE_VISIBILITY
+  explicit unique_ptr(pointer __p) _NOEXCEPT : __ptr_(__p, __default_init_tag()) {}
+
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> > >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(pointer __p, _LValRefType<_Dummy> __d) _NOEXCEPT
+      : __ptr_(__p, __d) {}
+
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> > >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(pointer __p, _GoodRValRefType<_Dummy> __d) _NOEXCEPT
+      : __ptr_(__p, _VSTD::move(__d)) {
+    static_assert(!is_reference<deleter_type>::value,
+                  "rvalue deleter bound to reference");
+  }
+
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterConstructible<_BadRValRefType<_Dummy> > >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(pointer __p, _BadRValRefType<_Dummy> __d) = delete;
+
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(unique_ptr&& __u) _NOEXCEPT
+      : __ptr_(__u.release(), _VSTD::forward<deleter_type>(__u.get_deleter())) {
+  }
+
+  template <class _Up, class _Ep,
+      class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
+      class = _EnableIfDeleterConvertible<_Ep>
+  >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPT
+      : __ptr_(__u.release(), _VSTD::forward<_Ep>(__u.get_deleter())) {}
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
+  template <class _Up>
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(auto_ptr<_Up>&& __p,
+             typename enable_if<is_convertible<_Up*, _Tp*>::value &&
+                                    is_same<_Dp, default_delete<_Tp> >::value,
+                                __nat>::type = __nat()) _NOEXCEPT
+      : __ptr_(__p.release(), __default_init_tag()) {}
+#endif
+
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr& operator=(unique_ptr&& __u) _NOEXCEPT {
+    reset(__u.release());
+    __ptr_.second() = _VSTD::forward<deleter_type>(__u.get_deleter());
+    return *this;
+  }
+
+  template <class _Up, class _Ep,
+      class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
+      class = _EnableIfDeleterAssignable<_Ep>
+  >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr& operator=(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPT {
+    reset(__u.release());
+    __ptr_.second() = _VSTD::forward<_Ep>(__u.get_deleter());
+    return *this;
+  }
+
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
+  template <class _Up>
+  _LIBCPP_INLINE_VISIBILITY
+      typename enable_if<is_convertible<_Up*, _Tp*>::value &&
+                             is_same<_Dp, default_delete<_Tp> >::value,
+                         unique_ptr&>::type
+      operator=(auto_ptr<_Up> __p) {
+    reset(__p.release());
+    return *this;
+  }
+#endif
+
+#ifdef _LIBCPP_CXX03_LANG
+  unique_ptr(unique_ptr const&) = delete;
+  unique_ptr& operator=(unique_ptr const&) = delete;
+#endif
+
+
+  _LIBCPP_INLINE_VISIBILITY
+  ~unique_ptr() { reset(); }
+
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr& operator=(nullptr_t) _NOEXCEPT {
+    reset();
+    return *this;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  typename add_lvalue_reference<_Tp>::type
+  operator*() const {
+    return *__ptr_.first();
+  }
+  _LIBCPP_INLINE_VISIBILITY
+  pointer operator->() const _NOEXCEPT {
+    return __ptr_.first();
+  }
+  _LIBCPP_INLINE_VISIBILITY
+  pointer get() const _NOEXCEPT {
+    return __ptr_.first();
+  }
+  _LIBCPP_INLINE_VISIBILITY
+  deleter_type& get_deleter() _NOEXCEPT {
+    return __ptr_.second();
+  }
+  _LIBCPP_INLINE_VISIBILITY
+  const deleter_type& get_deleter() const _NOEXCEPT {
+    return __ptr_.second();
+  }
+  _LIBCPP_INLINE_VISIBILITY
+  explicit operator bool() const _NOEXCEPT {
+    return __ptr_.first() != nullptr;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  pointer release() _NOEXCEPT {
+    pointer __t = __ptr_.first();
+    __ptr_.first() = pointer();
+    return __t;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  void reset(pointer __p = pointer()) _NOEXCEPT {
+    pointer __tmp = __ptr_.first();
+    __ptr_.first() = __p;
+    if (__tmp)
+      __ptr_.second()(__tmp);
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  void swap(unique_ptr& __u) _NOEXCEPT {
+    __ptr_.swap(__u.__ptr_);
+  }
+};
+
+
+template <class _Tp, class _Dp>
+class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS unique_ptr<_Tp[], _Dp> {
+public:
+  typedef _Tp element_type;
+  typedef _Dp deleter_type;
+  typedef typename __pointer<_Tp, deleter_type>::type pointer;
+
+private:
+  __compressed_pair<pointer, deleter_type> __ptr_;
+
+  template <class _From>
+  struct _CheckArrayPointerConversion : is_same<_From, pointer> {};
+
+  template <class _FromElem>
+  struct _CheckArrayPointerConversion<_FromElem*>
+      : integral_constant<bool,
+          is_same<_FromElem*, pointer>::value ||
+            (is_same<pointer, element_type*>::value &&
+             is_convertible<_FromElem(*)[], element_type(*)[]>::value)
+      >
+  {};
+
+  typedef __unique_ptr_deleter_sfinae<_Dp> _DeleterSFINAE;
+
+  template <bool _Dummy>
+  using _LValRefType _LIBCPP_NODEBUG_TYPE =
+      typename __dependent_type<_DeleterSFINAE, _Dummy>::__lval_ref_type;
+
+  template <bool _Dummy>
+  using _GoodRValRefType _LIBCPP_NODEBUG_TYPE =
+      typename __dependent_type<_DeleterSFINAE, _Dummy>::__good_rval_ref_type;
+
+  template <bool _Dummy>
+  using _BadRValRefType _LIBCPP_NODEBUG_TYPE =
+      typename __dependent_type<_DeleterSFINAE, _Dummy>::__bad_rval_ref_type;
+
+  template <bool _Dummy, class _Deleter = typename __dependent_type<
+                             __identity<deleter_type>, _Dummy>::type>
+  using _EnableIfDeleterDefaultConstructible _LIBCPP_NODEBUG_TYPE  =
+      typename enable_if<is_default_constructible<_Deleter>::value &&
+                         !is_pointer<_Deleter>::value>::type;
+
+  template <class _ArgType>
+  using _EnableIfDeleterConstructible _LIBCPP_NODEBUG_TYPE  =
+      typename enable_if<is_constructible<deleter_type, _ArgType>::value>::type;
+
+  template <class _Pp>
+  using _EnableIfPointerConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
+      _CheckArrayPointerConversion<_Pp>::value
+  >::type;
+
+  template <class _UPtr, class _Up,
+        class _ElemT = typename _UPtr::element_type>
+  using _EnableIfMoveConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
+      is_array<_Up>::value &&
+      is_same<pointer, element_type*>::value &&
+      is_same<typename _UPtr::pointer, _ElemT*>::value &&
+      is_convertible<_ElemT(*)[], element_type(*)[]>::value
+    >::type;
+
+  template <class _UDel>
+  using _EnableIfDeleterConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
+      (is_reference<_Dp>::value && is_same<_Dp, _UDel>::value) ||
+      (!is_reference<_Dp>::value && is_convertible<_UDel, _Dp>::value)
+    >::type;
+
+  template <class _UDel>
+  using _EnableIfDeleterAssignable _LIBCPP_NODEBUG_TYPE  = typename enable_if<
+      is_assignable<_Dp&, _UDel&&>::value
+    >::type;
+
+public:
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
+  _LIBCPP_INLINE_VISIBILITY
+  _LIBCPP_CONSTEXPR unique_ptr() _NOEXCEPT : __ptr_(pointer(), __default_init_tag()) {}
+
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
+  _LIBCPP_INLINE_VISIBILITY
+  _LIBCPP_CONSTEXPR unique_ptr(nullptr_t) _NOEXCEPT : __ptr_(pointer(), __default_init_tag()) {}
+
+  template <class _Pp, bool _Dummy = true,
+            class = _EnableIfDeleterDefaultConstructible<_Dummy>,
+            class = _EnableIfPointerConvertible<_Pp> >
+  _LIBCPP_INLINE_VISIBILITY
+  explicit unique_ptr(_Pp __p) _NOEXCEPT
+      : __ptr_(__p, __default_init_tag()) {}
+
+  template <class _Pp, bool _Dummy = true,
+            class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> >,
+            class = _EnableIfPointerConvertible<_Pp> >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(_Pp __p, _LValRefType<_Dummy> __d) _NOEXCEPT
+      : __ptr_(__p, __d) {}
+
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> > >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(nullptr_t, _LValRefType<_Dummy> __d) _NOEXCEPT
+      : __ptr_(nullptr, __d) {}
+
+  template <class _Pp, bool _Dummy = true,
+            class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> >,
+            class = _EnableIfPointerConvertible<_Pp> >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(_Pp __p, _GoodRValRefType<_Dummy> __d) _NOEXCEPT
+      : __ptr_(__p, _VSTD::move(__d)) {
+    static_assert(!is_reference<deleter_type>::value,
+                  "rvalue deleter bound to reference");
+  }
+
+  template <bool _Dummy = true,
+            class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> > >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(nullptr_t, _GoodRValRefType<_Dummy> __d) _NOEXCEPT
+      : __ptr_(nullptr, _VSTD::move(__d)) {
+    static_assert(!is_reference<deleter_type>::value,
+                  "rvalue deleter bound to reference");
+  }
+
+  template <class _Pp, bool _Dummy = true,
+            class = _EnableIfDeleterConstructible<_BadRValRefType<_Dummy> >,
+            class = _EnableIfPointerConvertible<_Pp> >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(_Pp __p, _BadRValRefType<_Dummy> __d) = delete;
+
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(unique_ptr&& __u) _NOEXCEPT
+      : __ptr_(__u.release(), _VSTD::forward<deleter_type>(__u.get_deleter())) {
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr& operator=(unique_ptr&& __u) _NOEXCEPT {
+    reset(__u.release());
+    __ptr_.second() = _VSTD::forward<deleter_type>(__u.get_deleter());
+    return *this;
+  }
+
+  template <class _Up, class _Ep,
+      class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
+      class = _EnableIfDeleterConvertible<_Ep>
+  >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPT
+      : __ptr_(__u.release(), _VSTD::forward<_Ep>(__u.get_deleter())) {
+  }
+
+  template <class _Up, class _Ep,
+      class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
+      class = _EnableIfDeleterAssignable<_Ep>
+  >
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr&
+  operator=(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPT {
+    reset(__u.release());
+    __ptr_.second() = _VSTD::forward<_Ep>(__u.get_deleter());
+    return *this;
+  }
+
+#ifdef _LIBCPP_CXX03_LANG
+  unique_ptr(unique_ptr const&) = delete;
+  unique_ptr& operator=(unique_ptr const&) = delete;
+#endif
+
+public:
+  _LIBCPP_INLINE_VISIBILITY
+  ~unique_ptr() { reset(); }
+
+  _LIBCPP_INLINE_VISIBILITY
+  unique_ptr& operator=(nullptr_t) _NOEXCEPT {
+    reset();
+    return *this;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  typename add_lvalue_reference<_Tp>::type
+  operator[](size_t __i) const {
+    return __ptr_.first()[__i];
+  }
+  _LIBCPP_INLINE_VISIBILITY
+  pointer get() const _NOEXCEPT {
+    return __ptr_.first();
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  deleter_type& get_deleter() _NOEXCEPT {
+    return __ptr_.second();
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  const deleter_type& get_deleter() const _NOEXCEPT {
+    return __ptr_.second();
+  }
+  _LIBCPP_INLINE_VISIBILITY
+  explicit operator bool() const _NOEXCEPT {
+    return __ptr_.first() != nullptr;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  pointer release() _NOEXCEPT {
+    pointer __t = __ptr_.first();
+    __ptr_.first() = pointer();
+    return __t;
+  }
+
+  template <class _Pp>
+  _LIBCPP_INLINE_VISIBILITY
+  typename enable_if<
+      _CheckArrayPointerConversion<_Pp>::value
+  >::type
+  reset(_Pp __p) _NOEXCEPT {
+    pointer __tmp = __ptr_.first();
+    __ptr_.first() = __p;
+    if (__tmp)
+      __ptr_.second()(__tmp);
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  void reset(nullptr_t = nullptr) _NOEXCEPT {
+    pointer __tmp = __ptr_.first();
+    __ptr_.first() = nullptr;
+    if (__tmp)
+      __ptr_.second()(__tmp);
+  }
+
+  _LIBCPP_INLINE_VISIBILITY
+  void swap(unique_ptr& __u) _NOEXCEPT {
+    __ptr_.swap(__u.__ptr_);
+  }
+
+};
+
+template <class _Tp, class _Dp>
+inline _LIBCPP_INLINE_VISIBILITY
+typename enable_if<
+    __is_swappable<_Dp>::value,
+    void
+>::type
+swap(unique_ptr<_Tp, _Dp>& __x, unique_ptr<_Tp, _Dp>& __y) _NOEXCEPT {__x.swap(__y);}
+
+template <class _T1, class _D1, class _T2, class _D2>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator==(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return __x.get() == __y.get();}
+
+template <class _T1, class _D1, class _T2, class _D2>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__x == __y);}
+
+template <class _T1, class _D1, class _T2, class _D2>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator< (const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y)
+{
+    typedef typename unique_ptr<_T1, _D1>::pointer _P1;
+    typedef typename unique_ptr<_T2, _D2>::pointer _P2;
+    typedef typename common_type<_P1, _P2>::type _Vp;
+    return less<_Vp>()(__x.get(), __y.get());
+}
+
+template <class _T1, class _D1, class _T2, class _D2>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator> (const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return __y < __x;}
+
+template <class _T1, class _D1, class _T2, class _D2>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__y < __x);}
+
+template <class _T1, class _D1, class _T2, class _D2>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__x < __y);}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator==(const unique_ptr<_T1, _D1>& __x, nullptr_t) _NOEXCEPT
+{
+    return !__x;
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator==(nullptr_t, const unique_ptr<_T1, _D1>& __x) _NOEXCEPT
+{
+    return !__x;
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(const unique_ptr<_T1, _D1>& __x, nullptr_t) _NOEXCEPT
+{
+    return static_cast<bool>(__x);
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(nullptr_t, const unique_ptr<_T1, _D1>& __x) _NOEXCEPT
+{
+    return static_cast<bool>(__x);
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<(const unique_ptr<_T1, _D1>& __x, nullptr_t)
+{
+    typedef typename unique_ptr<_T1, _D1>::pointer _P1;
+    return less<_P1>()(__x.get(), nullptr);
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<(nullptr_t, const unique_ptr<_T1, _D1>& __x)
+{
+    typedef typename unique_ptr<_T1, _D1>::pointer _P1;
+    return less<_P1>()(nullptr, __x.get());
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>(const unique_ptr<_T1, _D1>& __x, nullptr_t)
+{
+    return nullptr < __x;
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>(nullptr_t, const unique_ptr<_T1, _D1>& __x)
+{
+    return __x < nullptr;
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<=(const unique_ptr<_T1, _D1>& __x, nullptr_t)
+{
+    return !(nullptr < __x);
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<=(nullptr_t, const unique_ptr<_T1, _D1>& __x)
+{
+    return !(__x < nullptr);
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>=(const unique_ptr<_T1, _D1>& __x, nullptr_t)
+{
+    return !(__x < nullptr);
+}
+
+template <class _T1, class _D1>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>=(nullptr_t, const unique_ptr<_T1, _D1>& __x)
+{
+    return !(nullptr < __x);
+}
+
+#if _LIBCPP_STD_VER > 11
+
+template<class _Tp>
+struct __unique_if
+{
+    typedef unique_ptr<_Tp> __unique_single;
+};
+
+template<class _Tp>
+struct __unique_if<_Tp[]>
+{
+    typedef unique_ptr<_Tp[]> __unique_array_unknown_bound;
+};
+
+template<class _Tp, size_t _Np>
+struct __unique_if<_Tp[_Np]>
+{
+    typedef void __unique_array_known_bound;
+};
+
+template<class _Tp, class... _Args>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __unique_if<_Tp>::__unique_single
+make_unique(_Args&&... __args)
+{
+    return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...));
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+typename __unique_if<_Tp>::__unique_array_unknown_bound
+make_unique(size_t __n)
+{
+    typedef typename remove_extent<_Tp>::type _Up;
+    return unique_ptr<_Tp>(new _Up[__n]());
+}
+
+template<class _Tp, class... _Args>
+    typename __unique_if<_Tp>::__unique_array_known_bound
+    make_unique(_Args&&...) = delete;
+
+#endif // _LIBCPP_STD_VER > 11
+
+template <class _Tp> struct _LIBCPP_TEMPLATE_VIS hash;
+
+template <class _Tp, class _Dp>
+#ifdef _LIBCPP_CXX03_LANG
+struct _LIBCPP_TEMPLATE_VIS hash<unique_ptr<_Tp, _Dp> >
+#else
+struct _LIBCPP_TEMPLATE_VIS hash<__enable_hash_helper<
+    unique_ptr<_Tp, _Dp>, typename unique_ptr<_Tp, _Dp>::pointer> >
+#endif
+{
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef unique_ptr<_Tp, _Dp> argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t               result_type;
+#endif
+
+    _LIBCPP_INLINE_VISIBILITY
+    size_t operator()(const unique_ptr<_Tp, _Dp>& __ptr) const
+    {
+        typedef typename unique_ptr<_Tp, _Dp>::pointer pointer;
+        return hash<pointer>()(__ptr.get());
+    }
+};
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___MEMORY_UNIQUE_PTR_H
lib/libcxx/include/__memory/uses_allocator.h
@@ -0,0 +1,60 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___MEMORY_USES_ALLOCATOR_H
+#define _LIBCPP___MEMORY_USES_ALLOCATOR_H
+
+#include <__config>
+#include <cstddef>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+struct __has_allocator_type
+{
+private:
+    struct __two {char __lx; char __lxx;};
+    template <class _Up> static __two __test(...);
+    template <class _Up> static char __test(typename _Up::allocator_type* = 0);
+public:
+    static const bool value = sizeof(__test<_Tp>(0)) == 1;
+};
+
+template <class _Tp, class _Alloc, bool = __has_allocator_type<_Tp>::value>
+struct __uses_allocator
+    : public integral_constant<bool,
+        is_convertible<_Alloc, typename _Tp::allocator_type>::value>
+{
+};
+
+template <class _Tp, class _Alloc>
+struct __uses_allocator<_Tp, _Alloc, false>
+    : public false_type
+{
+};
+
+template <class _Tp, class _Alloc>
+struct _LIBCPP_TEMPLATE_VIS uses_allocator
+    : public __uses_allocator<_Tp, _Alloc>
+{
+};
+
+#if _LIBCPP_STD_VER > 14
+template <class _Tp, class _Alloc>
+_LIBCPP_INLINE_VAR constexpr size_t uses_allocator_v = uses_allocator<_Tp, _Alloc>::value;
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+#endif // _LIBCPP___MEMORY_USES_ALLOCATOR_H
lib/libcxx/include/__random/uniform_int_distribution.h
@@ -0,0 +1,316 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___RANDOM_UNIFORM_INT_DISTRIBUTION_H
+#define _LIBCPP___RANDOM_UNIFORM_INT_DISTRIBUTION_H
+
+#include <__bits>
+#include <__config>
+#include <cstddef>
+#include <cstdint>
+#include <iosfwd>
+#include <limits>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// __independent_bits_engine
+
+template <unsigned long long _Xp, size_t _Rp>
+struct __log2_imp
+{
+    static const size_t value = _Xp & ((unsigned long long)(1) << _Rp) ? _Rp
+                                           : __log2_imp<_Xp, _Rp - 1>::value;
+};
+
+template <unsigned long long _Xp>
+struct __log2_imp<_Xp, 0>
+{
+    static const size_t value = 0;
+};
+
+template <size_t _Rp>
+struct __log2_imp<0, _Rp>
+{
+    static const size_t value = _Rp + 1;
+};
+
+template <class _UIntType, _UIntType _Xp>
+struct __log2
+{
+    static const size_t value = __log2_imp<_Xp,
+                                         sizeof(_UIntType) * __CHAR_BIT__ - 1>::value;
+};
+
+template<class _Engine, class _UIntType>
+class __independent_bits_engine
+{
+public:
+    // types
+    typedef _UIntType result_type;
+
+private:
+    typedef typename _Engine::result_type _Engine_result_type;
+    typedef typename conditional
+        <
+            sizeof(_Engine_result_type) <= sizeof(result_type),
+                result_type,
+                _Engine_result_type
+        >::type _Working_result_type;
+
+    _Engine& __e_;
+    size_t __w_;
+    size_t __w0_;
+    size_t __n_;
+    size_t __n0_;
+    _Working_result_type __y0_;
+    _Working_result_type __y1_;
+    _Engine_result_type __mask0_;
+    _Engine_result_type __mask1_;
+
+#ifdef _LIBCPP_CXX03_LANG
+    static const _Working_result_type _Rp = _Engine::_Max - _Engine::_Min
+                                          + _Working_result_type(1);
+#else
+    static _LIBCPP_CONSTEXPR const _Working_result_type _Rp = _Engine::max() - _Engine::min()
+                                                      + _Working_result_type(1);
+#endif
+    static _LIBCPP_CONSTEXPR const size_t __m = __log2<_Working_result_type, _Rp>::value;
+    static _LIBCPP_CONSTEXPR const size_t _WDt = numeric_limits<_Working_result_type>::digits;
+    static _LIBCPP_CONSTEXPR const size_t _EDt = numeric_limits<_Engine_result_type>::digits;
+
+public:
+    // constructors and seeding functions
+    __independent_bits_engine(_Engine& __e, size_t __w);
+
+    // generating functions
+    result_type operator()() {return __eval(integral_constant<bool, _Rp != 0>());}
+
+private:
+    result_type __eval(false_type);
+    result_type __eval(true_type);
+};
+
+template<class _Engine, class _UIntType>
+__independent_bits_engine<_Engine, _UIntType>
+    ::__independent_bits_engine(_Engine& __e, size_t __w)
+        : __e_(__e),
+          __w_(__w)
+{
+    __n_ = __w_ / __m + (__w_ % __m != 0);
+    __w0_ = __w_ / __n_;
+    if (_Rp == 0)
+        __y0_ = _Rp;
+    else if (__w0_ < _WDt)
+        __y0_ = (_Rp >> __w0_) << __w0_;
+    else
+        __y0_ = 0;
+    if (_Rp - __y0_ > __y0_ / __n_)
+    {
+        ++__n_;
+        __w0_ = __w_ / __n_;
+        if (__w0_ < _WDt)
+            __y0_ = (_Rp >> __w0_) << __w0_;
+        else
+            __y0_ = 0;
+    }
+    __n0_ = __n_ - __w_ % __n_;
+    if (__w0_ < _WDt - 1)
+        __y1_ = (_Rp >> (__w0_ + 1)) << (__w0_ + 1);
+    else
+        __y1_ = 0;
+    __mask0_ = __w0_ > 0 ? _Engine_result_type(~0) >> (_EDt - __w0_) :
+                          _Engine_result_type(0);
+    __mask1_ = __w0_ < _EDt - 1 ?
+                               _Engine_result_type(~0) >> (_EDt - (__w0_ + 1)) :
+                               _Engine_result_type(~0);
+}
+
+template<class _Engine, class _UIntType>
+inline
+_UIntType
+__independent_bits_engine<_Engine, _UIntType>::__eval(false_type)
+{
+    return static_cast<result_type>(__e_() & __mask0_);
+}
+
+template<class _Engine, class _UIntType>
+_UIntType
+__independent_bits_engine<_Engine, _UIntType>::__eval(true_type)
+{
+    const size_t _WRt = numeric_limits<result_type>::digits;
+    result_type _Sp = 0;
+    for (size_t __k = 0; __k < __n0_; ++__k)
+    {
+        _Engine_result_type __u;
+        do
+        {
+            __u = __e_() - _Engine::min();
+        } while (__u >= __y0_);
+        if (__w0_ < _WRt)
+            _Sp <<= __w0_;
+        else
+            _Sp = 0;
+        _Sp += __u & __mask0_;
+    }
+    for (size_t __k = __n0_; __k < __n_; ++__k)
+    {
+        _Engine_result_type __u;
+        do
+        {
+            __u = __e_() - _Engine::min();
+        } while (__u >= __y1_);
+        if (__w0_ < _WRt - 1)
+            _Sp <<= __w0_ + 1;
+        else
+            _Sp = 0;
+        _Sp += __u & __mask1_;
+    }
+    return _Sp;
+}
+
+template<class _IntType = int>
+class uniform_int_distribution
+{
+public:
+    // types
+    typedef _IntType result_type;
+
+    class param_type
+    {
+        result_type __a_;
+        result_type __b_;
+    public:
+        typedef uniform_int_distribution distribution_type;
+
+        explicit param_type(result_type __a = 0,
+                            result_type __b = numeric_limits<result_type>::max())
+            : __a_(__a), __b_(__b) {}
+
+        result_type a() const {return __a_;}
+        result_type b() const {return __b_;}
+
+        friend bool operator==(const param_type& __x, const param_type& __y)
+            {return __x.__a_ == __y.__a_ && __x.__b_ == __y.__b_;}
+        friend bool operator!=(const param_type& __x, const param_type& __y)
+            {return !(__x == __y);}
+    };
+
+private:
+    param_type __p_;
+
+public:
+    // constructors and reset functions
+#ifndef _LIBCPP_CXX03_LANG
+    uniform_int_distribution() : uniform_int_distribution(0) {}
+    explicit uniform_int_distribution(
+        result_type __a, result_type __b = numeric_limits<result_type>::max())
+        : __p_(param_type(__a, __b)) {}
+#else
+    explicit uniform_int_distribution(
+        result_type __a = 0,
+        result_type __b = numeric_limits<result_type>::max())
+        : __p_(param_type(__a, __b)) {}
+#endif
+    explicit uniform_int_distribution(const param_type& __p) : __p_(__p) {}
+    void reset() {}
+
+    // generating functions
+    template<class _URNG> result_type operator()(_URNG& __g)
+        {return (*this)(__g, __p_);}
+    template<class _URNG> result_type operator()(_URNG& __g, const param_type& __p);
+
+    // property functions
+    result_type a() const {return __p_.a();}
+    result_type b() const {return __p_.b();}
+
+    param_type param() const {return __p_;}
+    void param(const param_type& __p) {__p_ = __p;}
+
+    result_type min() const {return a();}
+    result_type max() const {return b();}
+
+    friend bool operator==(const uniform_int_distribution& __x,
+                           const uniform_int_distribution& __y)
+        {return __x.__p_ == __y.__p_;}
+    friend bool operator!=(const uniform_int_distribution& __x,
+                           const uniform_int_distribution& __y)
+            {return !(__x == __y);}
+};
+
+template<class _IntType>
+template<class _URNG>
+typename uniform_int_distribution<_IntType>::result_type
+uniform_int_distribution<_IntType>::operator()(_URNG& __g, const param_type& __p)
+_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
+{
+    typedef typename conditional<sizeof(result_type) <= sizeof(uint32_t),
+                                            uint32_t, uint64_t>::type _UIntType;
+    const _UIntType _Rp = _UIntType(__p.b()) - _UIntType(__p.a()) + _UIntType(1);
+    if (_Rp == 1)
+        return __p.a();
+    const size_t _Dt = numeric_limits<_UIntType>::digits;
+    typedef __independent_bits_engine<_URNG, _UIntType> _Eng;
+    if (_Rp == 0)
+        return static_cast<result_type>(_Eng(__g, _Dt)());
+    size_t __w = _Dt - __libcpp_clz(_Rp) - 1;
+    if ((_Rp & (numeric_limits<_UIntType>::max() >> (_Dt - __w))) != 0)
+        ++__w;
+    _Eng __e(__g, __w);
+    _UIntType __u;
+    do
+    {
+        __u = __e();
+    } while (__u >= _Rp);
+    return static_cast<result_type>(__u + __p.a());
+}
+
+template <class _CharT, class _Traits, class _IT>
+basic_ostream<_CharT, _Traits>&
+operator<<(basic_ostream<_CharT, _Traits>& __os,
+           const uniform_int_distribution<_IT>& __x)
+{
+    __save_flags<_CharT, _Traits> __lx(__os);
+    typedef basic_ostream<_CharT, _Traits> _Ostream;
+    __os.flags(_Ostream::dec | _Ostream::left);
+    _CharT __sp = __os.widen(' ');
+    __os.fill(__sp);
+    return __os << __x.a() << __sp << __x.b();
+}
+
+template <class _CharT, class _Traits, class _IT>
+basic_istream<_CharT, _Traits>&
+operator>>(basic_istream<_CharT, _Traits>& __is,
+           uniform_int_distribution<_IT>& __x)
+{
+    typedef uniform_int_distribution<_IT> _Eng;
+    typedef typename _Eng::result_type result_type;
+    typedef typename _Eng::param_type param_type;
+    __save_flags<_CharT, _Traits> __lx(__is);
+    typedef basic_istream<_CharT, _Traits> _Istream;
+    __is.flags(_Istream::dec | _Istream::skipws);
+    result_type __a;
+    result_type __b;
+    __is >> __a >> __b;
+    if (!__is.fail())
+        __x.param(param_type(__a, __b));
+    return __is;
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANDOM_UNIFORM_INT_DISTRIBUTION_H
lib/libcxx/include/__ranges/access.h
@@ -0,0 +1,222 @@
+// -*- C++ -*-
+//===------------------------ __ranges/access.h ---------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_ACCESS_H
+#define _LIBCPP___RANGES_ACCESS_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/readable_traits.h>
+#include <__ranges/enable_borrowed_range.h>
+#include <__utility/__decay_copy.h>
+#include <__utility/forward.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// clang-format off
+
+namespace ranges {
+  template <class _Tp>
+  concept __can_borrow =
+      is_lvalue_reference_v<_Tp> || enable_borrowed_range<remove_cvref_t<_Tp> >;
+
+  template<class _Tp>
+  concept __is_complete = requires { sizeof(_Tp); };
+} // namespace ranges
+
+// [range.access.begin]
+namespace ranges::__begin {
+  template <class _Tp>
+  concept __member_begin =
+    __can_borrow<_Tp> &&
+    requires(_Tp&& __t) {
+      { _VSTD::__decay_copy(__t.begin()) } -> input_or_output_iterator;
+    };
+
+  void begin(auto&) = delete;
+  void begin(const auto&) = delete;
+
+  template <class _Tp>
+  concept __unqualified_begin =
+    !__member_begin<_Tp> &&
+    __can_borrow<_Tp> &&
+    __class_or_enum<remove_cvref_t<_Tp> > &&
+    requires(_Tp && __t) {
+      { _VSTD::__decay_copy(begin(__t)) } -> input_or_output_iterator;
+    };
+
+  struct __fn {
+    template <class _Tp>
+    requires is_array_v<remove_cv_t<_Tp>>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp& __t) const noexcept {
+      constexpr bool __complete = __is_complete<iter_value_t<_Tp> >;
+      if constexpr (__complete) { // used to disable cryptic diagnostic
+        return __t + 0;
+      }
+      else {
+        static_assert(__complete, "`std::ranges::begin` is SFINAE-unfriendly on arrays of an incomplete type.");
+      }
+    }
+
+    template <class _Tp>
+    requires __member_begin<_Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp&& __t) const
+    noexcept(noexcept(_VSTD::__decay_copy(__t.begin())))
+    {
+      return __t.begin();
+    }
+
+    template <class _Tp>
+    requires __unqualified_begin<_Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp&& __t) const
+    noexcept(noexcept(_VSTD::__decay_copy(begin(__t))))
+    {
+      return begin(__t);
+    }
+
+    void operator()(auto&&) const = delete;
+  };
+} // namespace ranges::__begin
+
+namespace ranges {
+  inline namespace __cpo {
+    inline constexpr auto begin = __begin::__fn{};
+  } // namespace __cpo
+
+  template <class _Tp>
+  using iterator_t = decltype(ranges::begin(declval<_Tp&>()));
+} // namespace ranges
+
+// [range.access.end]
+namespace ranges::__end {
+  template <class _Tp>
+  concept __member_end =
+    __can_borrow<_Tp> &&
+    requires(_Tp&& __t) {
+      typename iterator_t<_Tp>;
+      { _VSTD::__decay_copy(_VSTD::forward<_Tp>(__t).end()) } -> sentinel_for<iterator_t<_Tp> >;
+    };
+
+  void end(auto&) = delete;
+  void end(const auto&) = delete;
+
+  template <class _Tp>
+  concept __unqualified_end =
+    !__member_end<_Tp> &&
+    __can_borrow<_Tp> &&
+    __class_or_enum<remove_cvref_t<_Tp> > &&
+    requires(_Tp && __t) {
+      typename iterator_t<_Tp>;
+      { _VSTD::__decay_copy(end(_VSTD::forward<_Tp>(__t))) } -> sentinel_for<iterator_t<_Tp> >;
+    };
+
+  class __fn {
+  public:
+    template <class _Tp, size_t _Np>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp (&__t)[_Np]) const noexcept {
+      constexpr bool __complete = __is_complete<remove_cv_t<_Tp> >;
+      if constexpr (__complete) { // used to disable cryptic diagnostic
+        return __t + _Np;
+      }
+      else {
+        static_assert(__complete, "`std::ranges::end` is SFINAE-unfriendly on arrays of an incomplete type.");
+      }
+    }
+
+    template <class _Tp>
+    requires __member_end<_Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp&& __t) const
+    noexcept(noexcept(_VSTD::__decay_copy(__t.end())))
+    {
+      return _VSTD::forward<_Tp>(__t).end();
+    }
+
+    template <class _Tp>
+    requires __unqualified_end<_Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp&& __t) const
+    noexcept(noexcept(_VSTD::__decay_copy(end(__t))))
+    {
+      return end(__t);
+    }
+
+    void operator()(auto&&) const = delete;
+  };
+} // namespace ranges::__end
+
+namespace ranges::inline __cpo {
+  inline constexpr auto end = __end::__fn{};
+} // namespace ranges::__cpo
+
+namespace ranges::__cbegin {
+  struct __fn {
+    template <class _Tp>
+    requires invocable<decltype(ranges::begin), _Tp const&>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp& __t) const
+    noexcept(noexcept(ranges::begin(_VSTD::as_const(__t))))
+    {
+      return ranges::begin(_VSTD::as_const(__t));
+    }
+
+    template <class _Tp>
+    requires is_rvalue_reference_v<_Tp> && invocable<decltype(ranges::begin), _Tp const&&>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp&& __t) const
+    noexcept(noexcept(ranges::begin(static_cast<_Tp const&&>(__t))))
+    {
+      return ranges::begin(static_cast<_Tp const&&>(__t));
+    }
+  };
+} // namespace ranges::__cbegin
+
+namespace ranges::inline __cpo {
+  inline constexpr auto cbegin = __cbegin::__fn{};
+} // namespace ranges::__cpo
+
+namespace ranges::__cend {
+  struct __fn {
+    template <class _Tp>
+    requires invocable<decltype(ranges::end), _Tp const&>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp& __t) const
+    noexcept(noexcept(ranges::end(_VSTD::as_const(__t))))
+    {
+      return ranges::end(_VSTD::as_const(__t));
+    }
+
+    template <class _Tp>
+    requires is_rvalue_reference_v<_Tp> && invocable<decltype(ranges::end), _Tp const&&>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr auto operator()(_Tp&& __t) const
+    noexcept(noexcept(ranges::end(static_cast<_Tp const&&>(__t))))
+    {
+      return ranges::end(static_cast<_Tp const&&>(__t));
+    }
+  };
+} // namespace ranges::__cend
+
+namespace ranges::inline __cpo {
+  inline constexpr auto cend = __cend::__fn{};
+} // namespace ranges::__cpo
+
+// clang-format off
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_ACCESS_H
lib/libcxx/include/__ranges/all.h
@@ -0,0 +1,86 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_ALL_H
+#define _LIBCPP___RANGES_ALL_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/iterator_traits.h>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <__ranges/ref_view.h>
+#include <__ranges/subrange.h>
+#include <__utility/__decay_copy.h>
+#include <__utility/declval.h>
+#include <__utility/forward.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace views {
+
+namespace __all {
+  struct __fn {
+    template<class _Tp>
+      requires ranges::view<decay_t<_Tp>>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto operator()(_Tp&& __t) const
+      noexcept(noexcept(_VSTD::__decay_copy(_VSTD::forward<_Tp>(__t))))
+    {
+      return _VSTD::forward<_Tp>(__t);
+    }
+
+    template<class _Tp>
+      requires (!ranges::view<decay_t<_Tp>>) &&
+               requires (_Tp&& __t) { ranges::ref_view{_VSTD::forward<_Tp>(__t)}; }
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto operator()(_Tp&& __t) const
+      noexcept(noexcept(ranges::ref_view{_VSTD::forward<_Tp>(__t)}))
+    {
+      return ranges::ref_view{_VSTD::forward<_Tp>(__t)};
+    }
+
+    template<class _Tp>
+      requires (!ranges::view<decay_t<_Tp>> &&
+                !requires (_Tp&& __t) { ranges::ref_view{_VSTD::forward<_Tp>(__t)}; } &&
+                 requires (_Tp&& __t) { ranges::subrange{_VSTD::forward<_Tp>(__t)}; })
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto operator()(_Tp&& __t) const
+      noexcept(noexcept(ranges::subrange{_VSTD::forward<_Tp>(__t)}))
+    {
+      return ranges::subrange{_VSTD::forward<_Tp>(__t)};
+    }
+  };
+}
+
+inline namespace __cpo {
+  inline constexpr auto all = __all::__fn{};
+} // namespace __cpo
+
+template<ranges::viewable_range _Range>
+using all_t = decltype(views::all(declval<_Range>()));
+
+} // namespace views
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_ALL_H
lib/libcxx/include/__ranges/common_view.h
@@ -0,0 +1,113 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_COMMON_VIEW_H
+#define _LIBCPP___RANGES_COMMON_VIEW_H
+
+#include <__config>
+#include <__iterator/common_iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <__ranges/access.h>
+#include <__ranges/all.h>
+#include <__ranges/concepts.h>
+#include <__ranges/enable_borrowed_range.h>
+#include <__ranges/size.h>
+#include <__ranges/view_interface.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+
+template<view _View>
+  requires (!common_range<_View> && copyable<iterator_t<_View>>)
+class common_view : public view_interface<common_view<_View>> {
+  _View __base_ = _View();
+
+public:
+  _LIBCPP_HIDE_FROM_ABI
+  common_view() requires default_initializable<_View> = default;
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr explicit common_view(_View __v) : __base_(_VSTD::move(__v)) { }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _View base() const& requires copy_constructible<_View> { return __base_; }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _View base() && { return _VSTD::move(__base_); }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto begin() {
+    if constexpr (random_access_range<_View> && sized_range<_View>)
+      return ranges::begin(__base_);
+    else
+      return common_iterator<iterator_t<_View>, sentinel_t<_View>>(ranges::begin(__base_));
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto begin() const requires range<const _View> {
+    if constexpr (random_access_range<const _View> && sized_range<const _View>)
+      return ranges::begin(__base_);
+    else
+      return common_iterator<iterator_t<const _View>, sentinel_t<const _View>>(ranges::begin(__base_));
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto end() {
+    if constexpr (random_access_range<_View> && sized_range<_View>)
+      return ranges::begin(__base_) + ranges::size(__base_);
+    else
+      return common_iterator<iterator_t<_View>, sentinel_t<_View>>(ranges::end(__base_));
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto end() const requires range<const _View> {
+    if constexpr (random_access_range<const _View> && sized_range<const _View>)
+      return ranges::begin(__base_) + ranges::size(__base_);
+    else
+      return common_iterator<iterator_t<const _View>, sentinel_t<const _View>>(ranges::end(__base_));
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto size() requires sized_range<_View> {
+    return ranges::size(__base_);
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto size() const requires sized_range<const _View> {
+    return ranges::size(__base_);
+  }
+};
+
+template<class _Range>
+common_view(_Range&&)
+  -> common_view<views::all_t<_Range>>;
+
+template<class _View>
+inline constexpr bool enable_borrowed_range<common_view<_View>> = enable_borrowed_range<_View>;
+
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_COMMON_VIEW_H
lib/libcxx/include/__ranges/concepts.h
@@ -0,0 +1,138 @@
+// -*- C++ -*-
+//===--------------------- __ranges/concepts.h ----------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_CONCEPTS_H
+#define _LIBCPP___RANGES_CONCEPTS_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/readable_traits.h>
+#include <__ranges/access.h>
+#include <__ranges/enable_borrowed_range.h>
+#include <__ranges/data.h>
+#include <__ranges/enable_view.h>
+#include <__ranges/size.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// clang-format off
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+  // [range.range]
+  template <class _Tp>
+  concept range = requires(_Tp& __t) {
+    ranges::begin(__t); // sometimes equality-preserving
+    ranges::end(__t);
+  };
+
+  template<class _Range>
+  concept borrowed_range = range<_Range> &&
+    (is_lvalue_reference_v<_Range> || enable_borrowed_range<remove_cvref_t<_Range>>);
+
+  // `iterator_t` defined in <__ranges/access.h>
+
+  template <range _Rp>
+  using sentinel_t = decltype(ranges::end(declval<_Rp&>()));
+
+  template <range _Rp>
+  using range_difference_t = iter_difference_t<iterator_t<_Rp>>;
+
+  template <range _Rp>
+  using range_value_t = iter_value_t<iterator_t<_Rp>>;
+
+  template <range _Rp>
+  using range_reference_t = iter_reference_t<iterator_t<_Rp>>;
+
+  template <range _Rp>
+  using range_rvalue_reference_t = iter_rvalue_reference_t<iterator_t<_Rp>>;
+
+  // [range.sized]
+  template <class _Tp>
+  concept sized_range = range<_Tp> && requires(_Tp& __t) { ranges::size(__t); };
+
+  template<sized_range _Rp>
+  using range_size_t = decltype(ranges::size(declval<_Rp&>()));
+
+  // `disable_sized_range` defined in `<__ranges/size.h>`
+
+  // [range.view], views
+
+  // `enable_view` defined in <__ranges/enable_view.h>
+  // `view_base` defined in <__ranges/enable_view.h>
+
+  template <class _Tp>
+  concept view =
+    range<_Tp> &&
+    movable<_Tp> &&
+    enable_view<_Tp>;
+
+  template<class _Range>
+  concept __simple_view =
+    view<_Range> && range<const _Range> &&
+    same_as<iterator_t<_Range>, iterator_t<const _Range>> &&
+    same_as<sentinel_t<_Range>, iterator_t<const _Range>>;
+
+  // [range.refinements], other range refinements
+  template <class _Rp, class _Tp>
+  concept output_range = range<_Rp> && output_iterator<iterator_t<_Rp>, _Tp>;
+
+  template <class _Tp>
+  concept input_range = range<_Tp> && input_iterator<iterator_t<_Tp>>;
+
+  template <class _Tp>
+  concept forward_range = input_range<_Tp> && forward_iterator<iterator_t<_Tp>>;
+
+  template <class _Tp>
+  concept bidirectional_range = forward_range<_Tp> && bidirectional_iterator<iterator_t<_Tp>>;
+
+  template <class _Tp>
+  concept random_access_range =
+      bidirectional_range<_Tp> && random_access_iterator<iterator_t<_Tp>>;
+
+  template<class _Tp>
+  concept contiguous_range =
+    random_access_range<_Tp> &&
+    contiguous_iterator<iterator_t<_Tp>> &&
+    requires(_Tp& __t) {
+      { ranges::data(__t) } -> same_as<add_pointer_t<range_reference_t<_Tp>>>;
+    };
+
+  template <class _Tp>
+  concept common_range = range<_Tp> && same_as<iterator_t<_Tp>, sentinel_t<_Tp>>;
+
+  template<class _Tp>
+  concept viewable_range =
+    range<_Tp> && (
+      (view<remove_cvref_t<_Tp>> && constructible_from<remove_cvref_t<_Tp>, _Tp>) ||
+      (!view<remove_cvref_t<_Tp>> && borrowed_range<_Tp>)
+    );
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+// clang-format on
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_CONCEPTS_H
lib/libcxx/include/__ranges/copyable_box.h
@@ -0,0 +1,175 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___RANGES_COPYABLE_BOX_H
+#define _LIBCPP___RANGES_COPYABLE_BOX_H
+
+#include <__config>
+#include <__memory/addressof.h>
+#include <__memory/construct_at.h>
+#include <__utility/move.h>
+#include <concepts>
+#include <optional>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// __copyable_box allows turning a type that is copy-constructible (but maybe not copy-assignable) into
+// a type that is both copy-constructible and copy-assignable. It does that by introducing an empty state
+// and basically doing destroy-then-copy-construct in the assignment operator. The empty state is necessary
+// to handle the case where the copy construction fails after destroying the object.
+//
+// In some cases, we can completely avoid the use of an empty state; we provide a specialization of
+// __copyable_box that does this, see below for the details.
+
+template<class _Tp>
+concept __copy_constructible_object = copy_constructible<_Tp> && is_object_v<_Tp>;
+
+namespace ranges {
+  // Primary template - uses std::optional and introduces an empty state in case assignment fails.
+  template<__copy_constructible_object _Tp>
+  class __copyable_box {
+    [[no_unique_address]] optional<_Tp> __val_;
+
+  public:
+    template<class ..._Args>
+      requires is_constructible_v<_Tp, _Args...>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr explicit __copyable_box(in_place_t, _Args&& ...__args)
+      noexcept(is_nothrow_constructible_v<_Tp, _Args...>)
+      : __val_(in_place, _VSTD::forward<_Args>(__args)...)
+    { }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __copyable_box() noexcept(is_nothrow_default_constructible_v<_Tp>)
+      requires default_initializable<_Tp>
+      : __val_(in_place)
+    { }
+
+    _LIBCPP_HIDE_FROM_ABI __copyable_box(__copyable_box const&) = default;
+    _LIBCPP_HIDE_FROM_ABI __copyable_box(__copyable_box&&) = default;
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __copyable_box& operator=(__copyable_box const& __other)
+      noexcept(is_nothrow_copy_constructible_v<_Tp>)
+    {
+      if (this != _VSTD::addressof(__other)) {
+        if (__other.__has_value()) __val_.emplace(*__other);
+        else                       __val_.reset();
+      }
+      return *this;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    __copyable_box& operator=(__copyable_box&&) requires movable<_Tp> = default;
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __copyable_box& operator=(__copyable_box&& __other)
+      noexcept(is_nothrow_move_constructible_v<_Tp>)
+    {
+      if (this != _VSTD::addressof(__other)) {
+        if (__other.__has_value()) __val_.emplace(_VSTD::move(*__other));
+        else                       __val_.reset();
+      }
+      return *this;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI constexpr _Tp const& operator*() const noexcept { return *__val_; }
+    _LIBCPP_HIDE_FROM_ABI constexpr _Tp& operator*() noexcept { return *__val_; }
+    _LIBCPP_HIDE_FROM_ABI constexpr bool __has_value() const noexcept { return __val_.has_value(); }
+  };
+
+  // This partial specialization implements an optimization for when we know we don't need to store
+  // an empty state to represent failure to perform an assignment. For copy-assignment, this happens:
+  //
+  // 1. If the type is copyable (which includes copy-assignment), we can use the type's own assignment operator
+  //    directly and avoid using std::optional.
+  // 2. If the type is not copyable, but it is nothrow-copy-constructible, then we can implement assignment as
+  //    destroy-and-then-construct and we know it will never fail, so we don't need an empty state.
+  //
+  // The exact same reasoning can be applied for move-assignment, with copyable replaced by movable and
+  // nothrow-copy-constructible replaced by nothrow-move-constructible. This specialization is enabled
+  // whenever we can apply any of these optimizations for both the copy assignment and the move assignment
+  // operator.
+  template<class _Tp>
+  concept __doesnt_need_empty_state_for_copy = copyable<_Tp> || is_nothrow_copy_constructible_v<_Tp>;
+
+  template<class _Tp>
+  concept __doesnt_need_empty_state_for_move = movable<_Tp> || is_nothrow_move_constructible_v<_Tp>;
+
+  template<__copy_constructible_object _Tp>
+    requires __doesnt_need_empty_state_for_copy<_Tp> && __doesnt_need_empty_state_for_move<_Tp>
+  class __copyable_box<_Tp> {
+    [[no_unique_address]] _Tp __val_;
+
+  public:
+    template<class ..._Args>
+      requires is_constructible_v<_Tp, _Args...>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr explicit __copyable_box(in_place_t, _Args&& ...__args)
+      noexcept(is_nothrow_constructible_v<_Tp, _Args...>)
+      : __val_(_VSTD::forward<_Args>(__args)...)
+    { }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __copyable_box() noexcept(is_nothrow_default_constructible_v<_Tp>)
+      requires default_initializable<_Tp>
+      : __val_()
+    { }
+
+    _LIBCPP_HIDE_FROM_ABI __copyable_box(__copyable_box const&) = default;
+    _LIBCPP_HIDE_FROM_ABI __copyable_box(__copyable_box&&) = default;
+
+    // Implementation of assignment operators in case we perform optimization (1)
+    _LIBCPP_HIDE_FROM_ABI __copyable_box& operator=(__copyable_box const&) requires copyable<_Tp> = default;
+    _LIBCPP_HIDE_FROM_ABI __copyable_box& operator=(__copyable_box&&) requires movable<_Tp> = default;
+
+    // Implementation of assignment operators in case we perform optimization (2)
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __copyable_box& operator=(__copyable_box const& __other) noexcept {
+      static_assert(is_nothrow_copy_constructible_v<_Tp>);
+      if (this != _VSTD::addressof(__other)) {
+        _VSTD::destroy_at(_VSTD::addressof(__val_));
+        _VSTD::construct_at(_VSTD::addressof(__val_), __other.__val_);
+      }
+      return *this;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __copyable_box& operator=(__copyable_box&& __other) noexcept {
+      static_assert(is_nothrow_move_constructible_v<_Tp>);
+      if (this != _VSTD::addressof(__other)) {
+        _VSTD::destroy_at(_VSTD::addressof(__val_));
+        _VSTD::construct_at(_VSTD::addressof(__val_), _VSTD::move(__other.__val_));
+      }
+      return *this;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI constexpr _Tp const& operator*() const noexcept { return __val_; }
+    _LIBCPP_HIDE_FROM_ABI constexpr _Tp& operator*() noexcept { return __val_; }
+    _LIBCPP_HIDE_FROM_ABI constexpr bool __has_value() const noexcept { return true; }
+  };
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_COPYABLE_BOX_H
lib/libcxx/include/__ranges/dangling.h
@@ -0,0 +1,47 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___RANGES_DANGLING_H
+#define _LIBCPP___RANGES_DANGLING_H
+
+#include <__config>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+struct dangling {
+  dangling() = default;
+  _LIBCPP_HIDE_FROM_ABI constexpr dangling(auto&&...) noexcept {}
+};
+
+template <range _Rp>
+using borrowed_iterator_t = _If<borrowed_range<_Rp>, iterator_t<_Rp>, dangling>;
+
+// borrowed_subrange_t defined in <__ranges/subrange.h>
+} // namespace ranges
+
+#endif // !_LIBCPP_HAS_NO_RANGES
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_DANGLING_H
lib/libcxx/include/__ranges/data.h
@@ -0,0 +1,86 @@
+// -*- C++ -*-
+//===------------------------ __ranges/data.h ------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_DATA_H
+#define _LIBCPP___RANGES_DATA_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/iterator_traits.h>
+#include <__memory/pointer_traits.h>
+#include <__ranges/access.h>
+#include <__utility/forward.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// clang-format off
+namespace ranges {
+// [range.prim.data]
+namespace __data {
+  template <class _Tp>
+  concept __ptr_to_object = is_pointer_v<_Tp> && is_object_v<remove_pointer_t<_Tp>>;
+
+  template <class _Tp>
+  concept __member_data =
+    requires(_Tp&& __t) {
+      { _VSTD::forward<_Tp>(__t) } -> __can_borrow;
+      { __t.data() } -> __ptr_to_object;
+    };
+
+  template <class _Tp>
+  concept __ranges_begin_invocable =
+    !__member_data<_Tp> &&
+    requires(_Tp&& __t) {
+      { _VSTD::forward<_Tp>(__t) } -> __can_borrow;
+      { ranges::begin(_VSTD::forward<_Tp>(__t)) } -> contiguous_iterator;
+    };
+
+  struct __fn {
+    template <__member_data _Tp>
+      requires __can_borrow<_Tp>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __ptr_to_object auto operator()(_Tp&& __t) const
+        noexcept(noexcept(__t.data())) {
+      return __t.data();
+    }
+
+    template<__ranges_begin_invocable _Tp>
+      requires __can_borrow<_Tp>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __ptr_to_object auto operator()(_Tp&& __t) const
+        noexcept(noexcept(_VSTD::to_address(ranges::begin(_VSTD::forward<_Tp>(__t))))) {
+      return _VSTD::to_address(ranges::begin(_VSTD::forward<_Tp>(__t)));
+    }
+  };
+} // end namespace __data
+
+inline namespace __cpo {
+  inline constexpr const auto data = __data::__fn{};
+} // namespace __cpo
+} // namespace ranges
+
+// clang-format off
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_DATA_H
lib/libcxx/include/__ranges/drop_view.h
@@ -0,0 +1,131 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_DROP_VIEW_H
+#define _LIBCPP___RANGES_DROP_VIEW_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/next.h>
+#include <__ranges/access.h>
+#include <__ranges/all.h>
+#include <__ranges/concepts.h>
+#include <__ranges/enable_borrowed_range.h>
+#include <__ranges/non_propagating_cache.h>
+#include <__ranges/size.h>
+#include <__ranges/view_interface.h>
+#include <__utility/move.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+  template<view _View>
+  class drop_view
+    : public view_interface<drop_view<_View>>
+  {
+    // We cache begin() whenever ranges::next is not guaranteed O(1) to provide an
+    // amortized O(1) begin() method. If this is an input_range, then we cannot cache
+    // begin because begin is not equality preserving.
+    // Note: drop_view<input-range>::begin() is still trivially amortized O(1) because
+    // one can't call begin() on it more than once.
+    static constexpr bool _UseCache = forward_range<_View> && !(random_access_range<_View> && sized_range<_View>);
+    using _Cache = _If<_UseCache, __non_propagating_cache<iterator_t<_View>>, __empty_cache>;
+    [[no_unique_address]] _Cache __cached_begin_ = _Cache();
+    range_difference_t<_View> __count_ = 0;
+    _View __base_ = _View();
+
+public:
+    drop_view() requires default_initializable<_View> = default;
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr drop_view(_View __base, range_difference_t<_View> __count)
+      : __count_(__count)
+      , __base_(_VSTD::move(__base))
+    {
+      _LIBCPP_ASSERT(__count_ >= 0, "count must be greater than or equal to zero.");
+    }
+
+    _LIBCPP_HIDE_FROM_ABI constexpr _View base() const& requires copy_constructible<_View> { return __base_; }
+    _LIBCPP_HIDE_FROM_ABI constexpr _View base() && { return _VSTD::move(__base_); }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto begin()
+      requires (!(__simple_view<_View> &&
+                  random_access_range<const _View> && sized_range<const _View>))
+    {
+      if constexpr (_UseCache)
+        if (__cached_begin_.__has_value())
+          return *__cached_begin_;
+
+      auto __tmp = ranges::next(ranges::begin(__base_), __count_, ranges::end(__base_));
+      if constexpr (_UseCache)
+        __cached_begin_.__set(__tmp);
+      return __tmp;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto begin() const
+      requires random_access_range<const _View> && sized_range<const _View>
+    {
+      return ranges::next(ranges::begin(__base_), __count_, ranges::end(__base_));
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto end()
+      requires (!__simple_view<_View>)
+    { return ranges::end(__base_); }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto end() const
+      requires range<const _View>
+    { return ranges::end(__base_); }
+
+    _LIBCPP_HIDE_FROM_ABI
+    static constexpr auto __size(auto& __self) {
+      const auto __s = ranges::size(__self.__base_);
+      const auto __c = static_cast<decltype(__s)>(__self.__count_);
+      return __s < __c ? 0 : __s - __c;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto size()
+      requires sized_range<_View>
+    { return __size(*this); }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto size() const
+      requires sized_range<const _View>
+    { return __size(*this); }
+  };
+
+  template<class _Range>
+  drop_view(_Range&&, range_difference_t<_Range>) -> drop_view<views::all_t<_Range>>;
+
+  template<class _Tp>
+  inline constexpr bool enable_borrowed_range<drop_view<_Tp>> = enable_borrowed_range<_Tp>;
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_DROP_VIEW_H
lib/libcxx/include/__ranges/empty.h
@@ -0,0 +1,86 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_EMPTY_H
+#define _LIBCPP___RANGES_EMPTY_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__ranges/access.h>
+#include <__ranges/size.h>
+#include <__utility/forward.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// clang-format off
+namespace ranges {
+// [range.prim.empty]
+namespace __empty {
+  template <class _Tp>
+  concept __member_empty = requires(_Tp&& __t) {
+    bool(_VSTD::forward<_Tp>(__t).empty());
+  };
+
+  template<class _Tp>
+  concept __can_invoke_size =
+    !__member_empty<_Tp> &&
+    requires(_Tp&& __t) { ranges::size(_VSTD::forward<_Tp>(__t)); };
+
+  template <class _Tp>
+  concept __can_compare_begin_end =
+    !__member_empty<_Tp> &&
+    !__can_invoke_size<_Tp> &&
+    requires(_Tp&& __t) {
+      bool(ranges::begin(__t) == ranges::end(__t));
+      { ranges::begin(__t) } -> forward_iterator;
+    };
+
+  struct __fn {
+    template <__member_empty _Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool operator()(_Tp&& __t) const
+        noexcept(noexcept(bool(__t.empty()))) {
+      return __t.empty();
+    }
+
+    template <__can_invoke_size _Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool operator()(_Tp&& __t) const
+        noexcept(noexcept(ranges::size(_VSTD::forward<_Tp>(__t)))) {
+      return ranges::size(_VSTD::forward<_Tp>(__t)) == 0;
+    }
+
+    template<__can_compare_begin_end _Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool operator()(_Tp&& __t) const
+        noexcept(noexcept(bool(ranges::begin(__t) == ranges::end(__t)))) {
+      return ranges::begin(__t) == ranges::end(__t);
+    }
+  };
+}
+
+inline namespace __cpo {
+  inline constexpr auto empty = __empty::__fn{};
+} // namespace __cpo
+} // namespace ranges
+// clang-format off
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_EMPTY_H
lib/libcxx/include/__ranges/empty_view.h
@@ -0,0 +1,46 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_EMPTY_VIEW_H
+#define _LIBCPP___RANGES_EMPTY_VIEW_H
+
+#include <__config>
+#include <__ranges/view_interface.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+  template<class _Tp>
+    requires is_object_v<_Tp>
+  class empty_view : public view_interface<empty_view<_Tp>> {
+  public:
+    _LIBCPP_HIDE_FROM_ABI static constexpr _Tp* begin() noexcept { return nullptr; }
+    _LIBCPP_HIDE_FROM_ABI static constexpr _Tp* end() noexcept { return nullptr; }
+    _LIBCPP_HIDE_FROM_ABI static constexpr _Tp* data() noexcept { return nullptr; }
+    _LIBCPP_HIDE_FROM_ABI static constexpr size_t size() noexcept { return 0; }
+    _LIBCPP_HIDE_FROM_ABI static constexpr bool empty() noexcept { return true; }
+  };
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_EMPTY_VIEW_H
lib/libcxx/include/__ranges/enable_borrowed_range.h
@@ -0,0 +1,46 @@
+// -*- C++ -*-
+//===------------------ __ranges/enable_borrowed_range.h ------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___RANGES_ENABLE_BORROWED_RANGE_H
+#define _LIBCPP___RANGES_ENABLE_BORROWED_RANGE_H
+
+// These customization variables are used in <span> and <string_view>. The
+// separate header is used to avoid including the entire <ranges> header in
+// <span> and <string_view>.
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges
+{
+
+// [range.range], ranges
+
+template <class>
+inline constexpr bool enable_borrowed_range = false;
+
+} // namespace ranges
+
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_ENABLE_BORROWED_RANGE_H
lib/libcxx/include/__ranges/enable_view.h
@@ -0,0 +1,42 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___RANGES_ENABLE_VIEW_H
+#define _LIBCPP___RANGES_ENABLE_VIEW_H
+
+#include <__config>
+#include <concepts>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+
+struct view_base { };
+
+template <class _Tp>
+inline constexpr bool enable_view = derived_from<_Tp, view_base>;
+
+} // end namespace ranges
+
+#endif // !_LIBCPP_HAS_NO_RANGES
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_ENABLE_VIEW_H
lib/libcxx/include/__ranges/non_propagating_cache.h
@@ -0,0 +1,99 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_NON_PROPAGATING_CACHE_H
+#define _LIBCPP___RANGES_NON_PROPAGATING_CACHE_H
+
+#include <__config>
+#include <__iterator/concepts.h>        // indirectly_readable
+#include <__iterator/iterator_traits.h> // iter_reference_t
+#include <__memory/addressof.h>
+#include <concepts>                     // constructible_from
+#include <optional>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// clang-format off
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+  // __non_propagating_cache is a helper type that allows storing an optional value in it,
+  // but which does not copy the source's value when it is copy constructed/assigned to,
+  // and which resets the source's value when it is moved-from.
+  //
+  // This type is used as an implementation detail of some views that need to cache the
+  // result of `begin()` in order to provide an amortized O(1) begin() method. Typically,
+  // we don't want to propagate the value of the cache upon copy because the cached iterator
+  // may refer to internal details of the source view.
+  template<class _Tp>
+    requires is_object_v<_Tp>
+  class _LIBCPP_TEMPLATE_VIS __non_propagating_cache {
+    optional<_Tp> __value_ = nullopt;
+
+  public:
+    _LIBCPP_HIDE_FROM_ABI __non_propagating_cache() = default;
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __non_propagating_cache(__non_propagating_cache const&) noexcept
+      : __value_(nullopt)
+    { }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __non_propagating_cache(__non_propagating_cache&& __other) noexcept
+      : __value_(nullopt)
+    {
+      __other.__value_.reset();
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __non_propagating_cache& operator=(__non_propagating_cache const& __other) noexcept {
+      if (this != _VSTD::addressof(__other)) {
+        __value_.reset();
+      }
+      return *this;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __non_propagating_cache& operator=(__non_propagating_cache&& __other) noexcept {
+      __value_.reset();
+      __other.__value_.reset();
+      return *this;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr _Tp& operator*() { return *__value_; }
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr _Tp const& operator*() const { return *__value_; }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr bool __has_value() const { return __value_.has_value(); }
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr void __set(_Tp const& __value) { __value_.emplace(__value); }
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr void __set(_Tp&& __value) { __value_.emplace(_VSTD::move(__value)); }
+  };
+
+  struct __empty_cache { };
+} // namespace ranges
+
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_NON_PROPAGATING_CACHE_H
lib/libcxx/include/__ranges/ref_view.h
@@ -0,0 +1,87 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_REF_VIEW_H
+#define _LIBCPP___RANGES_REF_VIEW_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iterator_traits.h>
+#include <__memory/addressof.h>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <__ranges/data.h>
+#include <__ranges/empty.h>
+#include <__ranges/size.h>
+#include <__ranges/view_interface.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+  template<range _Range>
+    requires is_object_v<_Range>
+  class ref_view : public view_interface<ref_view<_Range>> {
+    _Range *__range_;
+
+    static void __fun(_Range&);
+    static void __fun(_Range&&) = delete;
+
+public:
+    template<class _Tp>
+      requires __different_from<_Tp, ref_view> &&
+        convertible_to<_Tp, _Range&> && requires { __fun(declval<_Tp>()); }
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr ref_view(_Tp&& __t)
+      : __range_(_VSTD::addressof(static_cast<_Range&>(_VSTD::forward<_Tp>(__t))))
+    {}
+
+    _LIBCPP_HIDE_FROM_ABI constexpr _Range& base() const { return *__range_; }
+
+    _LIBCPP_HIDE_FROM_ABI constexpr iterator_t<_Range> begin() const { return ranges::begin(*__range_); }
+    _LIBCPP_HIDE_FROM_ABI constexpr sentinel_t<_Range> end() const { return ranges::end(*__range_); }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr bool empty() const
+      requires requires { ranges::empty(*__range_); }
+    { return ranges::empty(*__range_); }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto size() const
+      requires sized_range<_Range>
+    { return ranges::size(*__range_); }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr auto data() const
+      requires contiguous_range<_Range>
+    { return ranges::data(*__range_); }
+  };
+
+  template<class _Range>
+  ref_view(_Range&) -> ref_view<_Range>;
+
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_REF_VIEW_H
lib/libcxx/include/__ranges/size.h
@@ -0,0 +1,132 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_SIZE_H
+#define _LIBCPP___RANGES_SIZE_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/iterator_traits.h>
+#include <__ranges/access.h>
+#include <__utility/__decay_copy.h>
+#include <__utility/forward.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// clang-format off
+namespace ranges {
+template<class>
+inline constexpr bool disable_sized_range = false;
+
+// [range.prim.size]
+namespace __size {
+  void size(auto&) = delete;
+  void size(const auto&) = delete;
+
+  template <class _Tp>
+  concept __size_enabled = !disable_sized_range<remove_cvref_t<_Tp>>;
+
+  template <class _Tp>
+  concept __member_size = __size_enabled<_Tp> && requires(_Tp&& __t) {
+    { _VSTD::__decay_copy(_VSTD::forward<_Tp>(__t).size()) } -> __integer_like;
+  };
+
+  template <class _Tp>
+  concept __unqualified_size =
+    __size_enabled<_Tp> &&
+    !__member_size<_Tp> &&
+    __class_or_enum<remove_cvref_t<_Tp>> &&
+    requires(_Tp&& __t) {
+      { _VSTD::__decay_copy(size(_VSTD::forward<_Tp>(__t))) } -> __integer_like;
+    };
+
+  template <class _Tp>
+  concept __difference =
+    !__member_size<_Tp> &&
+    !__unqualified_size<_Tp> &&
+    __class_or_enum<remove_cvref_t<_Tp>> &&
+    requires(_Tp&& __t) {
+      { ranges::begin(__t) } -> forward_iterator;
+      { ranges::end(__t) } -> sized_sentinel_for<decltype(ranges::begin(declval<_Tp>()))>;
+    };
+
+  struct __fn {
+    template <class _Tp, size_t _Sz>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr size_t operator()(_Tp (&&)[_Sz]) const noexcept {
+      return _Sz;
+    }
+
+    template <class _Tp, size_t _Sz>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr size_t operator()(_Tp (&)[_Sz]) const noexcept {
+      return _Sz;
+    }
+
+    template <__member_size _Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr __integer_like auto operator()(_Tp&& __t) const
+        noexcept(noexcept(_VSTD::forward<_Tp>(__t).size())) {
+      return _VSTD::forward<_Tp>(__t).size();
+    }
+
+    template <__unqualified_size _Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr __integer_like auto operator()(_Tp&& __t) const
+        noexcept(noexcept(size(_VSTD::forward<_Tp>(__t)))) {
+      return size(_VSTD::forward<_Tp>(__t));
+    }
+
+    template<__difference _Tp>
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr __integer_like auto operator()(_Tp&& __t) const
+        noexcept(noexcept(ranges::end(__t) - ranges::begin(__t))) {
+      return _VSTD::__to_unsigned_like(ranges::end(__t) - ranges::begin(__t));
+    }
+  };
+} // end namespace __size
+
+inline namespace __cpo {
+  inline constexpr auto size = __size::__fn{};
+} // namespace __cpo
+
+namespace __ssize {
+  struct __fn {
+    template<class _Tp>
+      requires requires (_Tp&& __t) { ranges::size(__t); }
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr integral auto operator()(_Tp&& __t) const
+        noexcept(noexcept(ranges::size(__t))) {
+      using _Signed = make_signed_t<decltype(ranges::size(__t))>;
+      if constexpr (sizeof(ptrdiff_t) > sizeof(_Signed))
+        return static_cast<ptrdiff_t>(ranges::size(__t));
+      else
+        return static_cast<_Signed>(ranges::size(__t));
+    }
+  };
+}
+
+inline namespace __cpo {
+  inline constexpr const auto ssize = __ssize::__fn{};
+} // namespace __cpo
+} // namespace ranges
+
+// clang-format off
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_SIZE_H
lib/libcxx/include/__ranges/subrange.h
@@ -0,0 +1,267 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_SUBRANGE_H
+#define _LIBCPP___RANGES_SUBRANGE_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/advance.h>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <__ranges/dangling.h>
+#include <__ranges/enable_borrowed_range.h>
+#include <__ranges/size.h>
+#include <__ranges/view_interface.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+// clang-format off
+namespace ranges {
+  template<class _From, class _To>
+  concept __convertible_to_non_slicing =
+    convertible_to<_From, _To> &&
+    // If they're both pointers, they must have the same element type.
+    !(is_pointer_v<decay_t<_From>> &&
+      is_pointer_v<decay_t<_To>> &&
+      __different_from<remove_pointer_t<decay_t<_From>>, remove_pointer_t<decay_t<_To>>>);
+
+  template<class _Tp>
+  concept __pair_like =
+    !is_reference_v<_Tp> && requires(_Tp __t) {
+      typename tuple_size<_Tp>::type; // Ensures `tuple_size<T>` is complete.
+      requires derived_from<tuple_size<_Tp>, integral_constant<size_t, 2>>;
+      typename tuple_element_t<0, remove_const_t<_Tp>>;
+      typename tuple_element_t<1, remove_const_t<_Tp>>;
+      { _VSTD::get<0>(__t) } -> convertible_to<const tuple_element_t<0, _Tp>&>;
+      { _VSTD::get<1>(__t) } -> convertible_to<const tuple_element_t<1, _Tp>&>;
+    };
+
+  template<class _Pair, class _Iter, class _Sent>
+  concept __pair_like_convertible_from =
+    !range<_Pair> && __pair_like<_Pair> &&
+    constructible_from<_Pair, _Iter, _Sent> &&
+    __convertible_to_non_slicing<_Iter, tuple_element_t<0, _Pair>> &&
+    convertible_to<_Sent, tuple_element_t<1, _Pair>>;
+
+  enum class _LIBCPP_ENUM_VIS subrange_kind : bool { unsized, sized };
+
+  template<class _Iter, class _Sent, bool>
+  struct __subrange_base {
+    static constexpr bool __store_size = false;
+    _Iter __begin_ = _Iter();
+    _Sent __end_ = _Sent();
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __subrange_base() = default;
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __subrange_base(_Iter __iter, _Sent __sent, make_unsigned_t<iter_difference_t<_Iter>> = 0)
+      : __begin_(_VSTD::move(__iter)), __end_(__sent) { }
+  };
+
+  template<class _Iter, class _Sent>
+  struct __subrange_base<_Iter, _Sent, true> {
+    static constexpr bool __store_size = true;
+    _Iter __begin_ = _Iter();
+    _Sent __end_ = _Sent();
+    make_unsigned_t<iter_difference_t<_Iter>> __size_ = 0;
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __subrange_base() = default;
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __subrange_base(_Iter __iter, _Sent __sent, decltype(__size_) __size)
+      : __begin_(_VSTD::move(__iter)), __end_(__sent), __size_(__size) { }
+  };
+
+  template<input_or_output_iterator _Iter, sentinel_for<_Iter> _Sent = _Iter,
+           subrange_kind _Kind = sized_sentinel_for<_Sent, _Iter>
+             ? subrange_kind::sized
+             : subrange_kind::unsized>
+    requires (_Kind == subrange_kind::sized || !sized_sentinel_for<_Sent, _Iter>)
+  struct _LIBCPP_TEMPLATE_VIS subrange
+    : public view_interface<subrange<_Iter, _Sent, _Kind>>,
+      private __subrange_base<_Iter, _Sent, _Kind == subrange_kind::sized && !sized_sentinel_for<_Sent, _Iter>> {
+
+    using _Base = __subrange_base<_Iter, _Sent, _Kind == subrange_kind::sized && !sized_sentinel_for<_Sent, _Iter>>;
+
+    _LIBCPP_HIDE_FROM_ABI
+    subrange() requires default_initializable<_Iter> = default;
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr subrange(__convertible_to_non_slicing<_Iter> auto __iter, _Sent __sent)
+      requires (!_Base::__store_size)
+      : _Base(_VSTD::move(__iter), __sent) {}
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr subrange(__convertible_to_non_slicing<_Iter> auto __iter, _Sent __sent,
+                       make_unsigned_t<iter_difference_t<_Iter>> __n)
+      requires (_Kind == subrange_kind::sized)
+      : _Base(_VSTD::move(__iter), __sent, __n) { }
+
+    template<__different_from<subrange> _Range>
+      requires borrowed_range<_Range> &&
+               __convertible_to_non_slicing<iterator_t<_Range>, _Iter> &&
+               convertible_to<sentinel_t<_Range>, _Sent>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr subrange(_Range&& __range)
+      requires (!_Base::__store_size)
+      : subrange(ranges::begin(__range), ranges::end(__range)) { }
+
+    template<__different_from<subrange> _Range>
+      requires borrowed_range<_Range> &&
+               __convertible_to_non_slicing<iterator_t<_Range>, _Iter> &&
+               convertible_to<sentinel_t<_Range>, _Sent>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr subrange(_Range&& __range)
+      requires _Base::__store_size && sized_range<_Range>
+      : subrange(__range, ranges::size(__range)) { }
+
+
+    template<borrowed_range _Range>
+      requires __convertible_to_non_slicing<iterator_t<_Range>, _Iter> &&
+               convertible_to<sentinel_t<_Range>, _Sent>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr subrange(_Range&& __range, make_unsigned_t<iter_difference_t<_Iter>> __n)
+      requires (_Kind == subrange_kind::sized)
+      : subrange(ranges::begin(__range), ranges::end(__range), __n) { }
+
+    template<__different_from<subrange> _Pair>
+      requires __pair_like_convertible_from<_Pair, const _Iter&, const _Sent&>
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr operator _Pair() const { return _Pair(this->__begin_, this->__end_); }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr _Iter begin() const requires copyable<_Iter> {
+      return this->__begin_;
+    }
+
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr _Iter begin() requires (!copyable<_Iter>) {
+      return _VSTD::move(this->__begin_);
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr _Sent end() const { return this->__end_; }
+
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool empty() const { return this->__begin_ == this->__end_; }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr make_unsigned_t<iter_difference_t<_Iter>> size() const
+      requires (_Kind == subrange_kind::sized)
+    {
+      if constexpr (_Base::__store_size)
+        return this->__size_;
+      else
+        return __to_unsigned_like(this->__end_ - this->__begin_);
+    }
+
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr subrange next(iter_difference_t<_Iter> __n = 1) const&
+      requires forward_iterator<_Iter> {
+      auto __tmp = *this;
+      __tmp.advance(__n);
+      return __tmp;
+    }
+
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr subrange next(iter_difference_t<_Iter> __n = 1) && {
+      advance(__n);
+      return _VSTD::move(*this);
+    }
+
+    [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr subrange prev(iter_difference_t<_Iter> __n = 1) const
+      requires bidirectional_iterator<_Iter> {
+      auto __tmp = *this;
+      __tmp.advance(-__n);
+      return __tmp;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr subrange& advance(iter_difference_t<_Iter> __n) {
+      if constexpr (bidirectional_iterator<_Iter>) {
+        if (__n < 0) {
+          ranges::advance(this->__begin_, __n);
+          if constexpr (_Base::__store_size)
+            this->__size_ += _VSTD::__to_unsigned_like(-__n);
+          return *this;
+        }
+      }
+
+      auto __d = __n - ranges::advance(this->__begin_, __n, this->__end_);
+      if constexpr (_Base::__store_size)
+        this->__size_ -= _VSTD::__to_unsigned_like(__d);
+      return *this;
+    }
+  };
+
+  template<input_or_output_iterator _Iter, sentinel_for<_Iter> _Sent>
+  subrange(_Iter, _Sent) -> subrange<_Iter, _Sent>;
+
+  template<input_or_output_iterator _Iter, sentinel_for<_Iter> _Sent>
+  subrange(_Iter, _Sent, make_unsigned_t<iter_difference_t<_Iter>>)
+    -> subrange<_Iter, _Sent, subrange_kind::sized>;
+
+  template<borrowed_range _Range>
+  subrange(_Range&&) -> subrange<iterator_t<_Range>, sentinel_t<_Range>,
+                                 (sized_range<_Range> || sized_sentinel_for<sentinel_t<_Range>, iterator_t<_Range>>)
+                                   ? subrange_kind::sized : subrange_kind::unsized>;
+
+  template<borrowed_range _Range>
+  subrange(_Range&&, make_unsigned_t<range_difference_t<_Range>>)
+    -> subrange<iterator_t<_Range>, sentinel_t<_Range>, subrange_kind::sized>;
+
+  template<size_t _Index, class _Iter, class _Sent, subrange_kind _Kind>
+    requires (_Index < 2)
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto get(const subrange<_Iter, _Sent, _Kind>& __subrange) {
+    if constexpr (_Index == 0)
+      return __subrange.begin();
+    else
+      return __subrange.end();
+  }
+
+  template<size_t _Index, class _Iter, class _Sent, subrange_kind _Kind>
+    requires (_Index < 2)
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto get(subrange<_Iter, _Sent, _Kind>&& __subrange) {
+    if constexpr (_Index == 0)
+      return __subrange.begin();
+    else
+      return __subrange.end();
+  }
+
+  template<class _Ip, class _Sp, subrange_kind _Kp>
+  inline constexpr bool enable_borrowed_range<subrange<_Ip, _Sp, _Kp>> = true;
+
+  template<range _Rp>
+  using borrowed_subrange_t = _If<borrowed_range<_Rp>, subrange<iterator_t<_Rp> >, dangling>;
+} // namespace ranges
+
+using ranges::get;
+
+// clang-format off
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_SUBRANGE_H
lib/libcxx/include/__ranges/transform_view.h
@@ -0,0 +1,408 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_TRANSFORM_VIEW_H
+#define _LIBCPP___RANGES_TRANSFORM_VIEW_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/iter_swap.h>
+#include <__iterator/iterator_traits.h>
+#include <__ranges/access.h>
+#include <__ranges/all.h>
+#include <__ranges/concepts.h>
+#include <__ranges/copyable_box.h>
+#include <__ranges/empty.h>
+#include <__ranges/size.h>
+#include <__ranges/view_interface.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+
+template<class _View, class _Fn>
+concept __transform_view_constraints =
+           view<_View> && is_object_v<_Fn> &&
+           regular_invocable<_Fn&, range_reference_t<_View>> &&
+           __referenceable<invoke_result_t<_Fn&, range_reference_t<_View>>>;
+
+template<input_range _View, copy_constructible _Fn>
+  requires __transform_view_constraints<_View, _Fn>
+class transform_view : public view_interface<transform_view<_View, _Fn>> {
+  template<bool> class __iterator;
+  template<bool> class __sentinel;
+
+  [[no_unique_address]] __copyable_box<_Fn> __func_;
+  [[no_unique_address]] _View __base_ = _View();
+
+public:
+  _LIBCPP_HIDE_FROM_ABI
+  transform_view()
+    requires default_initializable<_View> && default_initializable<_Fn> = default;
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr transform_view(_View __base, _Fn __func)
+    : __func_(_VSTD::in_place, _VSTD::move(__func)), __base_(_VSTD::move(__base)) {}
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _View base() const& requires copy_constructible<_View> { return __base_; }
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _View base() && { return _VSTD::move(__base_); }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator<false> begin() {
+    return __iterator<false>{*this, ranges::begin(__base_)};
+  }
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator<true> begin() const
+    requires range<const _View> &&
+             regular_invocable<const _Fn&, range_reference_t<const _View>>
+  {
+    return __iterator<true>(*this, ranges::begin(__base_));
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __sentinel<false> end() {
+    return __sentinel<false>(ranges::end(__base_));
+  }
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator<false> end()
+    requires common_range<_View>
+  {
+    return __iterator<false>(*this, ranges::end(__base_));
+  }
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __sentinel<true> end() const
+    requires range<const _View> &&
+             regular_invocable<const _Fn&, range_reference_t<const _View>>
+  {
+    return __sentinel<true>(ranges::end(__base_));
+  }
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator<true> end() const
+    requires common_range<const _View> &&
+             regular_invocable<const _Fn&, range_reference_t<const _View>>
+  {
+    return __iterator<true>(*this, ranges::end(__base_));
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto size() requires sized_range<_View> { return ranges::size(__base_); }
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto size() const requires sized_range<const _View> { return ranges::size(__base_); }
+};
+
+template<class _Range, class _Fn>
+transform_view(_Range&&, _Fn) -> transform_view<views::all_t<_Range>, _Fn>;
+
+template<class _View>
+struct __transform_view_iterator_concept { using type = input_iterator_tag; };
+
+template<random_access_range _View>
+struct __transform_view_iterator_concept<_View> { using type = random_access_iterator_tag; };
+
+template<bidirectional_range _View>
+struct __transform_view_iterator_concept<_View> { using type = bidirectional_iterator_tag; };
+
+template<forward_range _View>
+struct __transform_view_iterator_concept<_View> { using type = forward_iterator_tag; };
+
+template<class, class>
+struct __transform_view_iterator_category_base {};
+
+template<forward_range _View, class _Fn>
+struct __transform_view_iterator_category_base<_View, _Fn> {
+  using _Cat = typename iterator_traits<iterator_t<_View>>::iterator_category;
+
+  using iterator_category = conditional_t<
+    is_lvalue_reference_v<invoke_result_t<_Fn&, range_reference_t<_View>>>,
+    conditional_t<
+      derived_from<_Cat, contiguous_iterator_tag>,
+      random_access_iterator_tag,
+      _Cat
+    >,
+    input_iterator_tag
+  >;
+};
+
+template<input_range _View, copy_constructible _Fn>
+  requires __transform_view_constraints<_View, _Fn>
+template<bool _Const>
+class transform_view<_View, _Fn>::__iterator
+  : public __transform_view_iterator_category_base<_View, _Fn> {
+
+  using _Parent = __maybe_const<_Const, transform_view>;
+  using _Base = __maybe_const<_Const, _View>;
+
+  _Parent *__parent_ = nullptr;
+
+  template<bool>
+  friend class transform_view<_View, _Fn>::__iterator;
+
+  template<bool>
+  friend class transform_view<_View, _Fn>::__sentinel;
+
+public:
+  iterator_t<_Base> __current_ = iterator_t<_Base>();
+
+  using iterator_concept = typename __transform_view_iterator_concept<_View>::type;
+  using value_type = remove_cvref_t<invoke_result_t<_Fn&, range_reference_t<_Base>>>;
+  using difference_type = range_difference_t<_Base>;
+
+  _LIBCPP_HIDE_FROM_ABI
+  __iterator() requires default_initializable<iterator_t<_Base>> = default;
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator(_Parent& __parent, iterator_t<_Base> __current)
+    : __parent_(_VSTD::addressof(__parent)), __current_(_VSTD::move(__current)) {}
+
+  // Note: `__i` should always be `__iterator<false>`, but directly using
+  // `__iterator<false>` is ill-formed when `_Const` is false
+  // (see http://wg21.link/class.copy.ctor#5).
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator(__iterator<!_Const> __i)
+    requires _Const && convertible_to<iterator_t<_View>, iterator_t<_Base>>
+    : __parent_(__i.__parent_), __current_(_VSTD::move(__i.__current_)) {}
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr iterator_t<_Base> base() const&
+    requires copyable<iterator_t<_Base>>
+  {
+    return __current_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr iterator_t<_Base> base() && {
+    return _VSTD::move(__current_);
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) operator*() const
+    noexcept(noexcept(_VSTD::invoke(*__parent_->__func_, *__current_)))
+  {
+    return _VSTD::invoke(*__parent_->__func_, *__current_);
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator& operator++() {
+    ++__current_;
+    return *this;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr void operator++(int) { ++__current_; }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator operator++(int)
+    requires forward_range<_Base>
+  {
+    auto __tmp = *this;
+    ++*this;
+    return __tmp;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator& operator--()
+    requires bidirectional_range<_Base>
+  {
+    --__current_;
+    return *this;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator operator--(int)
+    requires bidirectional_range<_Base>
+  {
+    auto __tmp = *this;
+    --*this;
+    return __tmp;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator& operator+=(difference_type __n)
+    requires random_access_range<_Base>
+  {
+    __current_ += __n;
+    return *this;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __iterator& operator-=(difference_type __n)
+    requires random_access_range<_Base>
+  {
+    __current_ -= __n;
+    return *this;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) operator[](difference_type __n) const
+    noexcept(noexcept(_VSTD::invoke(*__parent_->__func_, __current_[__n])))
+    requires random_access_range<_Base>
+  {
+    return _VSTD::invoke(*__parent_->__func_, __current_[__n]);
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr bool operator==(const __iterator& __x, const __iterator& __y)
+    requires equality_comparable<iterator_t<_Base>>
+  {
+    return __x.__current_ == __y.__current_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr bool operator<(const __iterator& __x, const __iterator& __y)
+    requires random_access_range<_Base>
+  {
+    return __x.__current_ < __y.__current_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr bool operator>(const __iterator& __x, const __iterator& __y)
+    requires random_access_range<_Base>
+  {
+    return __x.__current_ > __y.__current_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr bool operator<=(const __iterator& __x, const __iterator& __y)
+    requires random_access_range<_Base>
+  {
+    return __x.__current_ <= __y.__current_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr bool operator>=(const __iterator& __x, const __iterator& __y)
+    requires random_access_range<_Base>
+  {
+    return __x.__current_ >= __y.__current_;
+  }
+
+// TODO: Fix this as soon as soon as three_way_comparable is implemented.
+//   _LIBCPP_HIDE_FROM_ABI
+//   friend constexpr auto operator<=>(const __iterator& __x, const __iterator& __y)
+//     requires random_access_range<_Base> && three_way_comparable<iterator_t<_Base>>
+//   {
+//     return __x.__current_ <=> __y.__current_;
+//   }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr __iterator operator+(__iterator __i, difference_type __n)
+    requires random_access_range<_Base>
+  {
+    return __iterator{*__i.__parent_, __i.__current_ + __n};
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr __iterator operator+(difference_type __n, __iterator __i)
+    requires random_access_range<_Base>
+  {
+    return __iterator{*__i.__parent_, __i.__current_ + __n};
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr __iterator operator-(__iterator __i, difference_type __n)
+    requires random_access_range<_Base>
+  {
+    return __iterator{*__i.__parent_, __i.__current_ - __n};
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr difference_type operator-(const __iterator& __x, const __iterator& __y)
+    requires sized_sentinel_for<iterator_t<_Base>, iterator_t<_Base>>
+  {
+    return __x.__current_ - __y.__current_;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr decltype(auto) iter_move(const __iterator& __i)
+    noexcept(noexcept(*__i))
+  {
+    if constexpr (is_lvalue_reference_v<decltype(*__i)>)
+      return _VSTD::move(*__i);
+    else
+      return *__i;
+  }
+};
+
+template<input_range _View, copy_constructible _Fn>
+  requires __transform_view_constraints<_View, _Fn>
+template<bool _Const>
+class transform_view<_View, _Fn>::__sentinel {
+  using _Parent = __maybe_const<_Const, transform_view>;
+  using _Base = __maybe_const<_Const, _View>;
+
+  sentinel_t<_Base> __end_ = sentinel_t<_Base>();
+
+  template<bool>
+  friend class transform_view<_View, _Fn>::__iterator;
+
+  template<bool>
+  friend class transform_view<_View, _Fn>::__sentinel;
+
+public:
+  _LIBCPP_HIDE_FROM_ABI
+  __sentinel() = default;
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr explicit __sentinel(sentinel_t<_Base> __end) : __end_(__end) {}
+
+  // Note: `__i` should always be `__sentinel<false>`, but directly using
+  // `__sentinel<false>` is ill-formed when `_Const` is false
+  // (see http://wg21.link/class.copy.ctor#5).
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr __sentinel(__sentinel<!_Const> __i)
+    requires _Const && convertible_to<sentinel_t<_View>, sentinel_t<_Base>>
+    : __end_(_VSTD::move(__i.__end_)) {}
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr sentinel_t<_Base> base() const { return __end_; }
+
+  template<bool _OtherConst>
+    requires sentinel_for<sentinel_t<_Base>, iterator_t<__maybe_const<_OtherConst, _View>>>
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr bool operator==(const __iterator<_OtherConst>& __x, const __sentinel& __y) {
+    return __x.__current_ == __y.__end_;
+  }
+
+  template<bool _OtherConst>
+    requires sized_sentinel_for<sentinel_t<_Base>, iterator_t<__maybe_const<_OtherConst, _View>>>
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr range_difference_t<__maybe_const<_OtherConst, _View>>
+  operator-(const __iterator<_OtherConst>& __x, const __sentinel& __y) {
+    return __x.__current_ - __y.__end_;
+  }
+
+  template<bool _OtherConst>
+    requires sized_sentinel_for<sentinel_t<_Base>, iterator_t<__maybe_const<_OtherConst, _View>>>
+  _LIBCPP_HIDE_FROM_ABI
+  friend constexpr range_difference_t<__maybe_const<_OtherConst, _View>>
+  operator-(const __sentinel& __x, const __iterator<_OtherConst>& __y) {
+    return __x.__end_ - __y.__current_;
+  }
+};
+
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_TRANSFORM_VIEW_H
lib/libcxx/include/__ranges/view_interface.h
@@ -0,0 +1,198 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_VIEW_INTERFACE_H
+#define _LIBCPP___RANGES_VIEW_INTERFACE_H
+
+#include <__config>
+#include <__iterator/concepts.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/prev.h>
+#include <__memory/pointer_traits.h>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <__ranges/empty.h>
+#include <__ranges/enable_view.h>
+#include <concepts>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+
+template<class _Tp>
+concept __can_empty = requires(_Tp __t) { ranges::empty(__t); };
+
+template<class _Tp>
+void __implicitly_convert_to(type_identity_t<_Tp>) noexcept;
+
+template<class _Derived>
+  requires is_class_v<_Derived> && same_as<_Derived, remove_cv_t<_Derived>>
+class view_interface : public view_base {
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Derived& __derived() noexcept {
+    return static_cast<_Derived&>(*this);
+  }
+
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr _Derived const& __derived() const noexcept {
+    return static_cast<_Derived const&>(*this);
+  }
+
+public:
+  template<class _D2 = _Derived>
+  [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool empty()
+    noexcept(noexcept(__implicitly_convert_to<bool>(ranges::begin(__derived()) == ranges::end(__derived()))))
+    requires forward_range<_D2>
+  {
+    return ranges::begin(__derived()) == ranges::end(__derived());
+  }
+
+  template<class _D2 = _Derived>
+  [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool empty() const
+    noexcept(noexcept(__implicitly_convert_to<bool>(ranges::begin(__derived()) == ranges::end(__derived()))))
+    requires forward_range<const _D2>
+  {
+    return ranges::begin(__derived()) == ranges::end(__derived());
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr explicit operator bool()
+    noexcept(noexcept(ranges::empty(declval<_D2>())))
+    requires __can_empty<_D2>
+  {
+    return !ranges::empty(__derived());
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr explicit operator bool() const
+    noexcept(noexcept(ranges::empty(declval<const _D2>())))
+    requires __can_empty<const _D2>
+  {
+    return !ranges::empty(__derived());
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto data()
+    noexcept(noexcept(_VSTD::to_address(ranges::begin(__derived()))))
+    requires contiguous_iterator<iterator_t<_D2>>
+  {
+    return _VSTD::to_address(ranges::begin(__derived()));
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto data() const
+    noexcept(noexcept(_VSTD::to_address(ranges::begin(__derived()))))
+    requires range<const _D2> && contiguous_iterator<iterator_t<const _D2>>
+  {
+    return _VSTD::to_address(ranges::begin(__derived()));
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto size()
+    noexcept(noexcept(ranges::end(__derived()) - ranges::begin(__derived())))
+    requires forward_range<_D2>
+      && sized_sentinel_for<sentinel_t<_D2>, iterator_t<_D2>>
+  {
+    return ranges::end(__derived()) - ranges::begin(__derived());
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr auto size() const
+    noexcept(noexcept(ranges::end(__derived()) - ranges::begin(__derived())))
+    requires forward_range<const _D2>
+      && sized_sentinel_for<sentinel_t<const _D2>, iterator_t<const _D2>>
+  {
+    return ranges::end(__derived()) - ranges::begin(__derived());
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) front()
+    noexcept(noexcept(*ranges::begin(__derived())))
+    requires forward_range<_D2>
+  {
+    _LIBCPP_ASSERT(!empty(),
+        "Precondition `!empty()` not satisfied. `.front()` called on an empty view.");
+    return *ranges::begin(__derived());
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) front() const
+    noexcept(noexcept(*ranges::begin(__derived())))
+    requires forward_range<const _D2>
+  {
+    _LIBCPP_ASSERT(!empty(),
+        "Precondition `!empty()` not satisfied. `.front()` called on an empty view.");
+    return *ranges::begin(__derived());
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) back()
+    noexcept(noexcept(*ranges::prev(ranges::end(__derived()))))
+    requires bidirectional_range<_D2> && common_range<_D2>
+  {
+    _LIBCPP_ASSERT(!empty(),
+        "Precondition `!empty()` not satisfied. `.back()` called on an empty view.");
+    return *ranges::prev(ranges::end(__derived()));
+  }
+
+  template<class _D2 = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) back() const
+    noexcept(noexcept(*ranges::prev(ranges::end(__derived()))))
+    requires bidirectional_range<const _D2> && common_range<const _D2>
+  {
+    _LIBCPP_ASSERT(!empty(),
+        "Precondition `!empty()` not satisfied. `.back()` called on an empty view.");
+    return *ranges::prev(ranges::end(__derived()));
+  }
+
+  template<random_access_range _RARange = _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) operator[](range_difference_t<_RARange> __index)
+    noexcept(noexcept(ranges::begin(__derived())[__index]))
+  {
+    return ranges::begin(__derived())[__index];
+  }
+
+  template<random_access_range _RARange = const _Derived>
+  _LIBCPP_HIDE_FROM_ABI
+  constexpr decltype(auto) operator[](range_difference_t<_RARange> __index) const
+    noexcept(noexcept(ranges::begin(__derived())[__index]))
+  {
+    return ranges::begin(__derived())[__index];
+  }
+};
+
+}
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_VIEW_INTERFACE_H
lib/libcxx/include/__support/ibm/gettod_zos.h
@@ -0,0 +1,53 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP_SUPPORT_IBM_GETTOD_ZOS_H
+#define _LIBCPP_SUPPORT_IBM_GETTOD_ZOS_H
+
+#include <time.h>
+
+static inline int gettimeofdayMonotonic(struct timespec64* Output) {
+
+  // The POSIX gettimeofday() function is not available on z/OS. Therefore,
+  // we will call stcke and other hardware instructions in implement equivalent.
+  // Note that nanoseconds alone will overflow when reaching new epoch in 2042.
+
+  struct _t {
+    uint64_t Hi;
+    uint64_t Lo;
+  };
+  struct _t Value = {0, 0};
+  uint64_t CC = 0;
+  asm(" stcke %0\n"
+      " ipm %1\n"
+      " srlg %1,%1,28\n"
+      : "=m"(Value), "+r"(CC)::);
+
+  if (CC != 0) {
+    errno = EMVSTODNOTSET;
+    return CC;
+  }
+  uint64_t us = (Value.Hi >> 4);
+  uint64_t ns = ((Value.Hi & 0x0F) << 8) + (Value.Lo >> 56);
+  ns = (ns * 1000) >> 12;
+  us = us - 2208988800000000;
+
+  register uint64_t DivPair0 asm("r0"); // dividend (upper half), remainder
+  DivPair0 = 0;
+  register uint64_t DivPair1 asm("r1"); // dividend (lower half), quotient
+  DivPair1 = us;
+  uint64_t Divisor = 1000000;
+  asm(" dlgr %0,%2" : "+r"(DivPair0), "+r"(DivPair1) : "r"(Divisor) :);
+
+  Output->tv_sec = DivPair1;
+  Output->tv_nsec = DivPair0 * 1000 + ns;
+  return 0;
+}
+
+#endif // _LIBCPP_SUPPORT_IBM_GETTOD_ZOS_H
lib/libcxx/include/__support/ibm/locale_mgmt_zos.h
@@ -0,0 +1,53 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP_SUPPORT_IBM_LOCALE_MGMT_ZOS_H
+#define _LIBCPP_SUPPORT_IBM_LOCALE_MGMT_ZOS_H
+
+#if defined(__MVS__)
+#include <locale.h>
+#include <string>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define _LC_MAX           LC_MESSAGES          /* highest real category */
+#define _NCAT             (_LC_MAX + 1)        /* maximum + 1 */
+
+#define _CATMASK(n)       (1 << (n))
+#define LC_COLLATE_MASK   _CATMASK(LC_COLLATE)
+#define LC_CTYPE_MASK     _CATMASK(LC_CTYPE)
+#define LC_MONETARY_MASK  _CATMASK(LC_MONETARY)
+#define LC_NUMERIC_MASK   _CATMASK(LC_NUMERIC)
+#define LC_TIME_MASK      _CATMASK(LC_TIME)
+#define LC_MESSAGES_MASK  _CATMASK(LC_MESSAGES)
+#define LC_ALL_MASK       (_CATMASK(_NCAT) - 1)
+
+typedef struct locale_struct {
+  int category_mask;
+  std::string lc_collate;
+  std::string lc_ctype;
+  std::string lc_monetary;
+  std::string lc_numeric;
+  std::string lc_time;
+  std::string lc_messages;
+} * locale_t;
+
+// z/OS does not have newlocale, freelocale and uselocale.
+// The functions below are workarounds in single thread mode.
+locale_t newlocale(int category_mask, const char* locale, locale_t base);
+void freelocale(locale_t locobj);
+locale_t uselocale(locale_t newloc);
+
+#ifdef __cplusplus
+}
+#endif
+#endif // defined(__MVS__)
+#endif // _LIBCPP_SUPPORT_IBM_LOCALE_MGMT_ZOS_H
lib/libcxx/include/__support/ibm/nanosleep.h
@@ -12,27 +12,45 @@
 
 #include <unistd.h>
 
-inline int nanosleep(const struct timespec* req, struct timespec* rem)
-{
-   // The nanosleep() function is not available on z/OS. Therefore, we will call
-   // sleep() to sleep for whole seconds and usleep() to sleep for any remaining
-   // fraction of a second. Any remaining nanoseconds will round up to the next
-   // microsecond.
-
-   useconds_t __micro_sec = (rem->tv_nsec + 999) / 1000;
-   if (__micro_sec > 999999)
-   {
-     ++rem->tv_sec;
-     __micro_sec -= 1000000;
-   }
-   while (rem->tv_sec)
-      rem->tv_sec = sleep(rem->tv_sec);
-   if (__micro_sec) {
-     rem->tv_nsec = __micro_sec * 1000;
-     return usleep(__micro_sec);
-   }
-   rem->tv_nsec = 0;
-   return 0;
+inline int nanosleep(const struct timespec* __req, struct timespec* __rem) {
+  // The nanosleep() function is not available on z/OS. Therefore, we will call
+  // sleep() to sleep for whole seconds and usleep() to sleep for any remaining
+  // fraction of a second. Any remaining nanoseconds will round up to the next
+  // microsecond.
+  if (__req->tv_sec < 0 || __req->tv_nsec < 0 || __req->tv_nsec > 999999999) {
+    errno = EINVAL;
+    return -1;
+  }
+  useconds_t __micro_sec =
+      static_cast<useconds_t>((__req->tv_nsec + 999) / 1000);
+  time_t __sec = __req->tv_sec;
+  if (__micro_sec > 999999) {
+    ++__sec;
+    __micro_sec -= 1000000;
+  }
+  __sec = sleep(static_cast<unsigned int>(__sec));
+  if (__sec) {
+    if (__rem) {
+      // Updating the remaining time to sleep in case of unsuccessful call to sleep().
+      __rem->tv_sec = __sec;
+      __rem->tv_nsec = __micro_sec * 1000;
+    }
+    errno = EINTR;
+    return -1;
+  }
+  if (__micro_sec) {
+    int __rt = usleep(__micro_sec);
+    if (__rt != 0 && __rem) {
+      // The usleep() does not provide the amount of remaining time upon its failure,
+      // so the time slept will be ignored.
+      __rem->tv_sec = 0;
+      __rem->tv_nsec = __micro_sec * 1000;
+      // The errno is already set.
+      return -1;
+    }
+    return __rt;
+  }
+  return 0;
 }
 
 #endif // _LIBCPP_SUPPORT_IBM_NANOSLEEP_H
lib/libcxx/include/__support/ibm/xlocale.h
@@ -11,6 +11,8 @@
 #define _LIBCPP_SUPPORT_IBM_XLOCALE_H
 
 #include <__support/ibm/locale_mgmt_aix.h>
+#include <__support/ibm/locale_mgmt_zos.h>
+#include <stdarg.h>
 
 #include "cstdlib"
 
@@ -210,11 +212,13 @@ size_t wcsxfrm_l(wchar_t *__ws1, const wchar_t *__ws2, size_t __n,
 
 // strftime_l() is defined by POSIX. However, AIX 7.1 and z/OS do not have it
 // implemented yet. z/OS retrieves it from the POSIX fallbacks.
+#if !defined(_AIX72)
 static inline
 size_t strftime_l(char *__s, size_t __size, const char *__fmt,
                   const struct tm *__tm, locale_t locale) {
   return __xstrftime(locale, __s, __size, __fmt, __tm);
 }
+#endif
 
 #elif defined(__MVS__)
 #include <wctype.h>
@@ -222,47 +226,101 @@ size_t strftime_l(char *__s, size_t __size, const char *__fmt,
 #include <__support/xlocale/__posix_l_fallback.h>
 #endif // defined(__MVS__)
 
+namespace {
+
+struct __setAndRestore {
+  explicit __setAndRestore(locale_t locale) {
+    if (locale == (locale_t)0) {
+      __cloc = newlocale(LC_ALL_MASK, "C", /* base */ (locale_t)0);
+      __stored = uselocale(__cloc);
+    } else {
+      __stored = uselocale(locale);
+    }
+  }
+
+  ~__setAndRestore() {
+    uselocale(__stored);
+    if (__cloc)
+      freelocale(__cloc);
+  }
+
+private:
+  locale_t __stored = (locale_t)0;
+  locale_t __cloc = (locale_t)0;
+};
+
+} // namespace
+
 // The following are not POSIX routines.  These are quick-and-dirty hacks
 // to make things pretend to work
 static inline
 long long strtoll_l(const char *__nptr, char **__endptr,
     int __base, locale_t locale) {
+  __setAndRestore __newloc(locale);
   return strtoll(__nptr, __endptr, __base);
 }
+
 static inline
 long strtol_l(const char *__nptr, char **__endptr,
     int __base, locale_t locale) {
+  __setAndRestore __newloc(locale);
   return strtol(__nptr, __endptr, __base);
 }
+
+static inline
+double strtod_l(const char *__nptr, char **__endptr,
+    locale_t locale) {
+  __setAndRestore __newloc(locale);
+  return strtod(__nptr, __endptr);
+}
+
+static inline
+float strtof_l(const char *__nptr, char **__endptr,
+    locale_t locale) {
+  __setAndRestore __newloc(locale);
+  return strtof(__nptr, __endptr);
+}
+
 static inline
 long double strtold_l(const char *__nptr, char **__endptr,
     locale_t locale) {
+  __setAndRestore __newloc(locale);
   return strtold(__nptr, __endptr);
 }
+
 static inline
 unsigned long long strtoull_l(const char *__nptr, char **__endptr,
     int __base, locale_t locale) {
+  __setAndRestore __newloc(locale);
   return strtoull(__nptr, __endptr, __base);
 }
+
 static inline
 unsigned long strtoul_l(const char *__nptr, char **__endptr,
     int __base, locale_t locale) {
+  __setAndRestore __newloc(locale);
   return strtoul(__nptr, __endptr, __base);
 }
 
 static inline
-int vasprintf(char **strp, const char *fmt, va_list ap)
-{
+int vasprintf(char **strp, const char *fmt, va_list ap) {
   const size_t buff_size = 256;
-  int str_size;
-  if ((*strp = (char *)malloc(buff_size)) == NULL)
-  {
+  if ((*strp = (char *)malloc(buff_size)) == NULL) {
     return -1;
   }
-  if ((str_size = vsnprintf(*strp, buff_size, fmt,  ap)) >= buff_size)
-  {
-    if ((*strp = (char *)realloc(*strp, str_size + 1)) == NULL)
-    {
+
+  va_list ap_copy;
+  // va_copy may not be provided by the C library in C++ 03 mode.
+#if defined(_LIBCPP_CXX03_LANG) && __has_builtin(__builtin_va_copy)
+  __builtin_va_copy(ap_copy, ap);
+#else
+  va_copy(ap_copy, ap);
+#endif
+  int str_size = vsnprintf(*strp, buff_size, fmt,  ap_copy);
+  va_end(ap_copy);
+
+  if ((size_t) str_size >= buff_size) {
+    if ((*strp = (char *)realloc(*strp, str_size + 1)) == NULL) {
       return -1;
     }
     str_size = vsnprintf(*strp, str_size + 1, fmt,  ap);
lib/libcxx/include/__support/openbsd/xlocale.h
@@ -10,10 +10,10 @@
 #ifndef _LIBCPP_SUPPORT_OPENBSD_XLOCALE_H
 #define _LIBCPP_SUPPORT_OPENBSD_XLOCALE_H
 
-#include <cstdlib>
+#include <__support/xlocale/__strtonum_fallback.h>
 #include <clocale>
-#include <cwctype>
+#include <cstdlib>
 #include <ctype.h>
-#include <__support/xlocale/__strtonum_fallback.h>
+#include <cwctype>
 
 #endif
lib/libcxx/include/__support/win32/limits_msvc_win32.h
@@ -17,8 +17,8 @@
 #error "This header should only be included when using Microsofts C1XX frontend"
 #endif
 
-#include <limits.h> // CHAR_BIT
 #include <float.h> // limit constants
+#include <limits.h> // CHAR_BIT
 #include <math.h> // HUGE_VAL
 #include <ymath.h> // internal MSVC header providing the needed functionality
 
lib/libcxx/include/__support/win32/locale_win32.h
@@ -11,9 +11,28 @@
 #define _LIBCPP_SUPPORT_WIN32_LOCALE_WIN32_H
 
 #include <__config>
-#include <stdio.h>
-#include <xlocinfo.h> // _locale_t
 #include <__nullptr>
+#include <locale.h> // _locale_t
+#include <stdio.h>
+
+#define _X_ALL LC_ALL
+#define _X_COLLATE LC_COLLATE
+#define _X_CTYPE LC_CTYPE
+#define _X_MONETARY LC_MONETARY
+#define _X_NUMERIC LC_NUMERIC
+#define _X_TIME LC_TIME
+#define _X_MAX LC_MAX
+#define _X_MESSAGES 6
+#define _NCAT (_X_MESSAGES + 1)
+
+#define _CATMASK(n) ((1 << (n)) >> 1)
+#define _M_COLLATE _CATMASK(_X_COLLATE)
+#define _M_CTYPE _CATMASK(_X_CTYPE)
+#define _M_MONETARY _CATMASK(_X_MONETARY)
+#define _M_NUMERIC _CATMASK(_X_NUMERIC)
+#define _M_TIME _CATMASK(_X_TIME)
+#define _M_MESSAGES _CATMASK(_X_MESSAGES)
+#define _M_ALL (_CATMASK(_NCAT) - 1)
 
 #define LC_COLLATE_MASK _M_COLLATE
 #define LC_CTYPE_MASK _M_CTYPE
lib/libcxx/include/__utility/__decay_copy.h
@@ -0,0 +1,39 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___TYPE_TRAITS_DECAY_COPY_H
+#define _LIBCPP___TYPE_TRAITS_DECAY_COPY_H
+
+#include <__config>
+#include <__utility/forward.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY typename decay<_Tp>::type __decay_copy(_Tp&& __t)
+#if _LIBCPP_STD_VER > 17
+    noexcept(is_nothrow_convertible_v<_Tp, remove_reference_t<_Tp> >)
+#endif
+{
+  return _VSTD::forward<_Tp>(__t);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___TYPE_TRAITS_DECAY_COPY_H
lib/libcxx/include/__utility/as_const.h
@@ -0,0 +1,38 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_AS_CONST_H
+#define _LIBCPP___UTILITY_AS_CONST_H
+
+#include <__config>
+#include <__utility/forward.h>
+#include <__utility/move.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+template <class _Tp>
+_LIBCPP_NODISCARD_EXT constexpr add_const_t<_Tp>& as_const(_Tp& __t) noexcept { return __t; }
+
+template <class _Tp>
+void as_const(const _Tp&&) = delete;
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_AS_CONST_H
lib/libcxx/include/__utility/cmp.h
@@ -0,0 +1,107 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_CMP_H
+#define _LIBCPP___UTILITY_CMP_H
+
+#include <__config>
+#include <__utility/forward.h>
+#include <__utility/move.h>
+#include <limits>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CONCEPTS)
+template<class _Tp, class... _Up>
+struct _IsSameAsAny : _Or<_IsSame<_Tp, _Up>...> {};
+
+template<class _Tp>
+concept __is_safe_integral_cmp = is_integral_v<_Tp> &&
+                      !_IsSameAsAny<_Tp, bool, char,
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
+                                    char8_t,
+#endif
+#ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
+                                    char16_t, char32_t,
+#endif
+                                    wchar_t>::value;
+
+template<__is_safe_integral_cmp _Tp, __is_safe_integral_cmp _Up>
+_LIBCPP_INLINE_VISIBILITY constexpr
+bool cmp_equal(_Tp __t, _Up __u) noexcept
+{
+  if constexpr (is_signed_v<_Tp> == is_signed_v<_Up>)
+    return __t == __u;
+  else if constexpr (is_signed_v<_Tp>)
+    return __t < 0 ? false : make_unsigned_t<_Tp>(__t) == __u;
+  else
+    return __u < 0 ? false : __t == make_unsigned_t<_Up>(__u);
+}
+
+template<__is_safe_integral_cmp _Tp, __is_safe_integral_cmp _Up>
+_LIBCPP_INLINE_VISIBILITY constexpr
+bool cmp_not_equal(_Tp __t, _Up __u) noexcept
+{
+  return !_VSTD::cmp_equal(__t, __u);
+}
+
+template<__is_safe_integral_cmp _Tp, __is_safe_integral_cmp _Up>
+_LIBCPP_INLINE_VISIBILITY constexpr
+bool cmp_less(_Tp __t, _Up __u) noexcept
+{
+  if constexpr (is_signed_v<_Tp> == is_signed_v<_Up>)
+    return __t < __u;
+  else if constexpr (is_signed_v<_Tp>)
+    return __t < 0 ? true : make_unsigned_t<_Tp>(__t) < __u;
+  else
+    return __u < 0 ? false : __t < make_unsigned_t<_Up>(__u);
+}
+
+template<__is_safe_integral_cmp _Tp, __is_safe_integral_cmp _Up>
+_LIBCPP_INLINE_VISIBILITY constexpr
+bool cmp_greater(_Tp __t, _Up __u) noexcept
+{
+  return _VSTD::cmp_less(__u, __t);
+}
+
+template<__is_safe_integral_cmp _Tp, __is_safe_integral_cmp _Up>
+_LIBCPP_INLINE_VISIBILITY constexpr
+bool cmp_less_equal(_Tp __t, _Up __u) noexcept
+{
+  return !_VSTD::cmp_greater(__t, __u);
+}
+
+template<__is_safe_integral_cmp _Tp, __is_safe_integral_cmp _Up>
+_LIBCPP_INLINE_VISIBILITY constexpr
+bool cmp_greater_equal(_Tp __t, _Up __u) noexcept
+{
+  return !_VSTD::cmp_less(__t, __u);
+}
+
+template<__is_safe_integral_cmp _Tp, __is_safe_integral_cmp _Up>
+_LIBCPP_INLINE_VISIBILITY constexpr
+bool in_range(_Up __u) noexcept
+{
+  return _VSTD::cmp_less_equal(__u, numeric_limits<_Tp>::max()) &&
+         _VSTD::cmp_greater_equal(__u, numeric_limits<_Tp>::min());
+}
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_CMP_H
lib/libcxx/include/__utility/declval.h
@@ -0,0 +1,39 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_DECLVAL_H
+#define _LIBCPP___UTILITY_DECLVAL_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// Suppress deprecation notice for volatile-qualified return type resulting
+// from volatile-qualified types _Tp.
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
+template <class _Tp>
+_Tp&& __declval(int);
+template <class _Tp>
+_Tp __declval(long);
+_LIBCPP_SUPPRESS_DEPRECATED_POP
+
+template <class _Tp>
+decltype(__declval<_Tp>(0)) declval() _NOEXCEPT;
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_DECLVAL_H
lib/libcxx/include/__utility/exchange.h
@@ -0,0 +1,40 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_EXCHANGE_H
+#define _LIBCPP___UTILITY_EXCHANGE_H
+
+#include <__config>
+#include <__utility/forward.h>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 11
+template<class _T1, class _T2 = _T1>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+_T1 exchange(_T1& __obj, _T2 && __new_value)
+{
+    _T1 __old_value = _VSTD::move(__obj);
+    __obj = _VSTD::forward<_T2>(__new_value);
+    return __old_value;
+}
+#endif // _LIBCPP_STD_VER > 11
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_EXCHANGE_H
lib/libcxx/include/__utility/forward.h
@@ -0,0 +1,42 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_FORWARD_H
+#define _LIBCPP___UTILITY_FORWARD_H
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR _Tp&&
+forward(typename remove_reference<_Tp>::type& __t) _NOEXCEPT {
+  return static_cast<_Tp&&>(__t);
+}
+
+template <class _Tp>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR _Tp&&
+forward(typename remove_reference<_Tp>::type&& __t) _NOEXCEPT {
+  static_assert(!is_lvalue_reference<_Tp>::value, "cannot forward an rvalue as an lvalue");
+  return static_cast<_Tp&&>(__t);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_FORWARD_H
lib/libcxx/include/__utility/in_place.h
@@ -0,0 +1,63 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_IN_PLACE_H
+#define _LIBCPP___UTILITY_IN_PLACE_H
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+
+struct _LIBCPP_TYPE_VIS in_place_t {
+    explicit in_place_t() = default;
+};
+_LIBCPP_INLINE_VAR constexpr in_place_t in_place{};
+
+template <class _Tp>
+struct _LIBCPP_TEMPLATE_VIS in_place_type_t {
+    explicit in_place_type_t() = default;
+};
+template <class _Tp>
+_LIBCPP_INLINE_VAR constexpr in_place_type_t<_Tp> in_place_type{};
+
+template <size_t _Idx>
+struct _LIBCPP_TEMPLATE_VIS in_place_index_t {
+    explicit in_place_index_t() = default;
+};
+template <size_t _Idx>
+_LIBCPP_INLINE_VAR constexpr in_place_index_t<_Idx> in_place_index{};
+
+template <class _Tp> struct __is_inplace_type_imp : false_type {};
+template <class _Tp> struct __is_inplace_type_imp<in_place_type_t<_Tp>> : true_type {};
+
+template <class _Tp>
+using __is_inplace_type = __is_inplace_type_imp<__uncvref_t<_Tp>>;
+
+template <class _Tp> struct __is_inplace_index_imp : false_type {};
+template <size_t _Idx> struct __is_inplace_index_imp<in_place_index_t<_Idx>> : true_type {};
+
+template <class _Tp>
+using __is_inplace_index = __is_inplace_index_imp<__uncvref_t<_Tp>>;
+
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_IN_PLACE_H
lib/libcxx/include/__utility/integer_sequence.h
@@ -0,0 +1,83 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_INTEGER_SEQUENCE_H
+#define _LIBCPP___UTILITY_INTEGER_SEQUENCE_H
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 11
+
+template<class _Tp, _Tp... _Ip>
+struct _LIBCPP_TEMPLATE_VIS integer_sequence
+{
+    typedef _Tp value_type;
+    static_assert( is_integral<_Tp>::value,
+                  "std::integer_sequence can only be instantiated with an integral type" );
+    static
+    _LIBCPP_INLINE_VISIBILITY
+    constexpr
+    size_t
+    size() noexcept { return sizeof...(_Ip); }
+};
+
+template<size_t... _Ip>
+    using index_sequence = integer_sequence<size_t, _Ip...>;
+
+#if __has_builtin(__make_integer_seq) && !defined(_LIBCPP_TESTING_FALLBACK_MAKE_INTEGER_SEQUENCE)
+
+template <class _Tp, _Tp _Ep>
+using __make_integer_sequence _LIBCPP_NODEBUG_TYPE = __make_integer_seq<integer_sequence, _Tp, _Ep>;
+
+#else
+
+template<typename _Tp, _Tp _Np> using __make_integer_sequence_unchecked _LIBCPP_NODEBUG_TYPE  =
+  typename __detail::__make<_Np>::type::template __convert<integer_sequence, _Tp>;
+
+template <class _Tp, _Tp _Ep>
+struct __make_integer_sequence_checked
+{
+    static_assert(is_integral<_Tp>::value,
+                  "std::make_integer_sequence can only be instantiated with an integral type" );
+    static_assert(0 <= _Ep, "std::make_integer_sequence must have a non-negative sequence length");
+    // Workaround GCC bug by preventing bad installations when 0 <= _Ep
+    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68929
+    typedef _LIBCPP_NODEBUG_TYPE  __make_integer_sequence_unchecked<_Tp, 0 <= _Ep ? _Ep : 0> type;
+};
+
+template <class _Tp, _Tp _Ep>
+using __make_integer_sequence _LIBCPP_NODEBUG_TYPE = typename __make_integer_sequence_checked<_Tp, _Ep>::type;
+
+#endif
+
+template<class _Tp, _Tp _Np>
+    using make_integer_sequence = __make_integer_sequence<_Tp, _Np>;
+
+template<size_t _Np>
+    using make_index_sequence = make_integer_sequence<size_t, _Np>;
+
+template<class... _Tp>
+    using index_sequence_for = make_index_sequence<sizeof...(_Tp)>;
+
+#endif // _LIBCPP_STD_VER > 11
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_INTEGER_SEQUENCE_H
lib/libcxx/include/__utility/move.h
@@ -0,0 +1,52 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_MOVE_H
+#define _LIBCPP___UTILITY_MOVE_H
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+template <class _Tp>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR typename remove_reference<_Tp>::type&&
+move(_Tp&& __t) _NOEXCEPT {
+  typedef _LIBCPP_NODEBUG_TYPE typename remove_reference<_Tp>::type _Up;
+  return static_cast<_Up&&>(__t);
+}
+
+#ifndef _LIBCPP_CXX03_LANG
+template <class _Tp>
+using __move_if_noexcept_result_t =
+    typename conditional<!is_nothrow_move_constructible<_Tp>::value && is_copy_constructible<_Tp>::value, const _Tp&,
+                         _Tp&&>::type;
+#else // _LIBCPP_CXX03_LANG
+template <class _Tp>
+using __move_if_noexcept_result_t = const _Tp&;
+#endif
+
+template <class _Tp>
+_LIBCPP_NODISCARD_EXT inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 __move_if_noexcept_result_t<_Tp>
+move_if_noexcept(_Tp& __x) _NOEXCEPT {
+  return _VSTD::move(__x);
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_MOVE_H
lib/libcxx/include/__utility/pair.h
@@ -0,0 +1,585 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_PAIR_H
+#define _LIBCPP___UTILITY_PAIR_H
+
+#include <__config>
+#include <__functional/unwrap_ref.h>
+#include <__tuple>
+#include <__utility/forward.h>
+#include <__utility/move.h>
+#include <__utility/piecewise_construct.h>
+#include <cstddef>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+
+#if defined(_LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR)
+template <class, class>
+struct __non_trivially_copyable_base {
+  _LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
+  __non_trivially_copyable_base() _NOEXCEPT {}
+  _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
+  __non_trivially_copyable_base(__non_trivially_copyable_base const&) _NOEXCEPT {}
+};
+#endif
+
+template <class _T1, class _T2>
+struct _LIBCPP_TEMPLATE_VIS pair
+#if defined(_LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR)
+: private __non_trivially_copyable_base<_T1, _T2>
+#endif
+{
+    typedef _T1 first_type;
+    typedef _T2 second_type;
+
+    _T1 first;
+    _T2 second;
+
+#if !defined(_LIBCPP_CXX03_LANG)
+    pair(pair const&) = default;
+    pair(pair&&) = default;
+#else
+  // Use the implicitly declared copy constructor in C++03
+#endif
+
+#ifdef _LIBCPP_CXX03_LANG
+    _LIBCPP_INLINE_VISIBILITY
+    pair() : first(), second() {}
+
+    _LIBCPP_INLINE_VISIBILITY
+    pair(_T1 const& __t1, _T2 const& __t2) : first(__t1), second(__t2) {}
+
+    template <class _U1, class _U2>
+    _LIBCPP_INLINE_VISIBILITY
+    pair(const pair<_U1, _U2>& __p) : first(__p.first), second(__p.second) {}
+
+    _LIBCPP_INLINE_VISIBILITY
+    pair& operator=(pair const& __p) {
+        first = __p.first;
+        second = __p.second;
+        return *this;
+    }
+#else
+    template <bool _Val>
+    using _EnableB _LIBCPP_NODEBUG_TYPE = typename enable_if<_Val, bool>::type;
+
+    struct _CheckArgs {
+      template <int&...>
+      static constexpr bool __enable_explicit_default() {
+          return is_default_constructible<_T1>::value
+              && is_default_constructible<_T2>::value
+              && !__enable_implicit_default<>();
+      }
+
+      template <int&...>
+      static constexpr bool __enable_implicit_default() {
+          return __is_implicitly_default_constructible<_T1>::value
+              && __is_implicitly_default_constructible<_T2>::value;
+      }
+
+      template <class _U1, class _U2>
+      static constexpr bool __enable_explicit() {
+          return is_constructible<first_type, _U1>::value
+              && is_constructible<second_type, _U2>::value
+              && (!is_convertible<_U1, first_type>::value
+                  || !is_convertible<_U2, second_type>::value);
+      }
+
+      template <class _U1, class _U2>
+      static constexpr bool __enable_implicit() {
+          return is_constructible<first_type, _U1>::value
+              && is_constructible<second_type, _U2>::value
+              && is_convertible<_U1, first_type>::value
+              && is_convertible<_U2, second_type>::value;
+      }
+    };
+
+    template <bool _MaybeEnable>
+    using _CheckArgsDep _LIBCPP_NODEBUG_TYPE = typename conditional<
+      _MaybeEnable, _CheckArgs, __check_tuple_constructor_fail>::type;
+
+    struct _CheckTupleLikeConstructor {
+        template <class _Tuple>
+        static constexpr bool __enable_implicit() {
+            return __tuple_convertible<_Tuple, pair>::value;
+        }
+
+        template <class _Tuple>
+        static constexpr bool __enable_explicit() {
+            return __tuple_constructible<_Tuple, pair>::value
+               && !__tuple_convertible<_Tuple, pair>::value;
+        }
+
+        template <class _Tuple>
+        static constexpr bool __enable_assign() {
+            return __tuple_assignable<_Tuple, pair>::value;
+        }
+    };
+
+    template <class _Tuple>
+    using _CheckTLC _LIBCPP_NODEBUG_TYPE = typename conditional<
+        __tuple_like_with_size<_Tuple, 2>::value
+            && !is_same<typename decay<_Tuple>::type, pair>::value,
+        _CheckTupleLikeConstructor,
+        __check_tuple_constructor_fail
+    >::type;
+
+    template<bool _Dummy = true, _EnableB<
+            _CheckArgsDep<_Dummy>::__enable_explicit_default()
+    > = false>
+    explicit _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+    pair() _NOEXCEPT_(is_nothrow_default_constructible<first_type>::value &&
+                      is_nothrow_default_constructible<second_type>::value)
+        : first(), second() {}
+
+    template<bool _Dummy = true, _EnableB<
+            _CheckArgsDep<_Dummy>::__enable_implicit_default()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+    pair() _NOEXCEPT_(is_nothrow_default_constructible<first_type>::value &&
+                      is_nothrow_default_constructible<second_type>::value)
+        : first(), second() {}
+
+    template <bool _Dummy = true, _EnableB<
+             _CheckArgsDep<_Dummy>::template __enable_explicit<_T1 const&, _T2 const&>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit pair(_T1 const& __t1, _T2 const& __t2)
+        _NOEXCEPT_(is_nothrow_copy_constructible<first_type>::value &&
+                   is_nothrow_copy_constructible<second_type>::value)
+        : first(__t1), second(__t2) {}
+
+    template<bool _Dummy = true, _EnableB<
+            _CheckArgsDep<_Dummy>::template __enable_implicit<_T1 const&, _T2 const&>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    pair(_T1 const& __t1, _T2 const& __t2)
+        _NOEXCEPT_(is_nothrow_copy_constructible<first_type>::value &&
+                   is_nothrow_copy_constructible<second_type>::value)
+        : first(__t1), second(__t2) {}
+
+    template<class _U1, class _U2, _EnableB<
+             _CheckArgs::template __enable_explicit<_U1, _U2>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit pair(_U1&& __u1, _U2&& __u2)
+        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1>::value &&
+                    is_nothrow_constructible<second_type, _U2>::value))
+        : first(_VSTD::forward<_U1>(__u1)), second(_VSTD::forward<_U2>(__u2)) {}
+
+    template<class _U1, class _U2, _EnableB<
+            _CheckArgs::template __enable_implicit<_U1, _U2>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    pair(_U1&& __u1, _U2&& __u2)
+        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1>::value &&
+                    is_nothrow_constructible<second_type, _U2>::value))
+        : first(_VSTD::forward<_U1>(__u1)), second(_VSTD::forward<_U2>(__u2)) {}
+
+    template<class _U1, class _U2, _EnableB<
+            _CheckArgs::template __enable_explicit<_U1 const&, _U2 const&>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit pair(pair<_U1, _U2> const& __p)
+        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1 const&>::value &&
+                    is_nothrow_constructible<second_type, _U2 const&>::value))
+        : first(__p.first), second(__p.second) {}
+
+    template<class _U1, class _U2, _EnableB<
+            _CheckArgs::template __enable_implicit<_U1 const&, _U2 const&>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    pair(pair<_U1, _U2> const& __p)
+        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1 const&>::value &&
+                    is_nothrow_constructible<second_type, _U2 const&>::value))
+        : first(__p.first), second(__p.second) {}
+
+    template<class _U1, class _U2, _EnableB<
+            _CheckArgs::template __enable_explicit<_U1, _U2>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit pair(pair<_U1, _U2>&&__p)
+        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1&&>::value &&
+                    is_nothrow_constructible<second_type, _U2&&>::value))
+        : first(_VSTD::forward<_U1>(__p.first)), second(_VSTD::forward<_U2>(__p.second)) {}
+
+    template<class _U1, class _U2, _EnableB<
+            _CheckArgs::template __enable_implicit<_U1, _U2>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    pair(pair<_U1, _U2>&& __p)
+        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1&&>::value &&
+                    is_nothrow_constructible<second_type, _U2&&>::value))
+        : first(_VSTD::forward<_U1>(__p.first)), second(_VSTD::forward<_U2>(__p.second)) {}
+
+    template<class _Tuple, _EnableB<
+            _CheckTLC<_Tuple>::template __enable_explicit<_Tuple>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit pair(_Tuple&& __p)
+        : first(_VSTD::get<0>(_VSTD::forward<_Tuple>(__p))),
+          second(_VSTD::get<1>(_VSTD::forward<_Tuple>(__p))) {}
+
+    template<class _Tuple, _EnableB<
+            _CheckTLC<_Tuple>::template __enable_implicit<_Tuple>()
+    > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    pair(_Tuple&& __p)
+        : first(_VSTD::get<0>(_VSTD::forward<_Tuple>(__p))),
+          second(_VSTD::get<1>(_VSTD::forward<_Tuple>(__p))) {}
+
+    template <class... _Args1, class... _Args2>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    pair(piecewise_construct_t __pc,
+         tuple<_Args1...> __first_args, tuple<_Args2...> __second_args)
+        _NOEXCEPT_((is_nothrow_constructible<first_type, _Args1...>::value &&
+                    is_nothrow_constructible<second_type, _Args2...>::value))
+        : pair(__pc, __first_args, __second_args,
+                typename __make_tuple_indices<sizeof...(_Args1)>::type(),
+                typename __make_tuple_indices<sizeof...(_Args2) >::type()) {}
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    pair& operator=(typename conditional<
+                        is_copy_assignable<first_type>::value &&
+                        is_copy_assignable<second_type>::value,
+                    pair, __nat>::type const& __p)
+        _NOEXCEPT_(is_nothrow_copy_assignable<first_type>::value &&
+                   is_nothrow_copy_assignable<second_type>::value)
+    {
+        first = __p.first;
+        second = __p.second;
+        return *this;
+    }
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    pair& operator=(typename conditional<
+                        is_move_assignable<first_type>::value &&
+                        is_move_assignable<second_type>::value,
+                    pair, __nat>::type&& __p)
+        _NOEXCEPT_(is_nothrow_move_assignable<first_type>::value &&
+                   is_nothrow_move_assignable<second_type>::value)
+    {
+        first = _VSTD::forward<first_type>(__p.first);
+        second = _VSTD::forward<second_type>(__p.second);
+        return *this;
+    }
+
+    template <class _Tuple, _EnableB<
+            _CheckTLC<_Tuple>::template __enable_assign<_Tuple>()
+     > = false>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    pair& operator=(_Tuple&& __p) {
+        first = _VSTD::get<0>(_VSTD::forward<_Tuple>(__p));
+        second = _VSTD::get<1>(_VSTD::forward<_Tuple>(__p));
+        return *this;
+    }
+#endif
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    void
+    swap(pair& __p) _NOEXCEPT_(__is_nothrow_swappable<first_type>::value &&
+                               __is_nothrow_swappable<second_type>::value)
+    {
+        using _VSTD::swap;
+        swap(first,  __p.first);
+        swap(second, __p.second);
+    }
+private:
+
+#ifndef _LIBCPP_CXX03_LANG
+    template <class... _Args1, class... _Args2, size_t... _I1, size_t... _I2>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    pair(piecewise_construct_t,
+         tuple<_Args1...>& __first_args, tuple<_Args2...>& __second_args,
+         __tuple_indices<_I1...>, __tuple_indices<_I2...>);
+#endif
+};
+
+#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
+template<class _T1, class _T2>
+pair(_T1, _T2) -> pair<_T1, _T2>;
+#endif // _LIBCPP_HAS_NO_DEDUCTION_GUIDES
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+bool
+operator==(const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
+{
+    return __x.first == __y.first && __x.second == __y.second;
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+bool
+operator!=(const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
+{
+    return !(__x == __y);
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+bool
+operator< (const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
+{
+    return __x.first < __y.first || (!(__y.first < __x.first) && __x.second < __y.second);
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+bool
+operator> (const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
+{
+    return __y < __x;
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+bool
+operator>=(const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
+{
+    return !(__x < __y);
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+bool
+operator<=(const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
+{
+    return !(__y < __x);
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+typename enable_if
+<
+    __is_swappable<_T1>::value &&
+    __is_swappable<_T2>::value,
+    void
+>::type
+swap(pair<_T1, _T2>& __x, pair<_T1, _T2>& __y)
+                     _NOEXCEPT_((__is_nothrow_swappable<_T1>::value &&
+                                 __is_nothrow_swappable<_T2>::value))
+{
+    __x.swap(__y);
+}
+
+#ifndef _LIBCPP_CXX03_LANG
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+pair<typename __unwrap_ref_decay<_T1>::type, typename __unwrap_ref_decay<_T2>::type>
+make_pair(_T1&& __t1, _T2&& __t2)
+{
+    return pair<typename __unwrap_ref_decay<_T1>::type, typename __unwrap_ref_decay<_T2>::type>
+               (_VSTD::forward<_T1>(__t1), _VSTD::forward<_T2>(__t2));
+}
+
+#else  // _LIBCPP_CXX03_LANG
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+pair<_T1,_T2>
+make_pair(_T1 __x, _T2 __y)
+{
+    return pair<_T1, _T2>(__x, __y);
+}
+
+#endif // _LIBCPP_CXX03_LANG
+
+template <class _T1, class _T2>
+  struct _LIBCPP_TEMPLATE_VIS tuple_size<pair<_T1, _T2> >
+    : public integral_constant<size_t, 2> {};
+
+template <size_t _Ip, class _T1, class _T2>
+struct _LIBCPP_TEMPLATE_VIS tuple_element<_Ip, pair<_T1, _T2> >
+{
+    static_assert(_Ip < 2, "Index out of bounds in std::tuple_element<std::pair<T1, T2>>");
+};
+
+template <class _T1, class _T2>
+struct _LIBCPP_TEMPLATE_VIS tuple_element<0, pair<_T1, _T2> >
+{
+    typedef _LIBCPP_NODEBUG_TYPE _T1 type;
+};
+
+template <class _T1, class _T2>
+struct _LIBCPP_TEMPLATE_VIS tuple_element<1, pair<_T1, _T2> >
+{
+    typedef _LIBCPP_NODEBUG_TYPE _T2 type;
+};
+
+template <size_t _Ip> struct __get_pair;
+
+template <>
+struct __get_pair<0>
+{
+    template <class _T1, class _T2>
+    static
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    _T1&
+    get(pair<_T1, _T2>& __p) _NOEXCEPT {return __p.first;}
+
+    template <class _T1, class _T2>
+    static
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    const _T1&
+    get(const pair<_T1, _T2>& __p) _NOEXCEPT {return __p.first;}
+
+#ifndef _LIBCPP_CXX03_LANG
+    template <class _T1, class _T2>
+    static
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    _T1&&
+    get(pair<_T1, _T2>&& __p) _NOEXCEPT {return _VSTD::forward<_T1>(__p.first);}
+
+    template <class _T1, class _T2>
+    static
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    const _T1&&
+    get(const pair<_T1, _T2>&& __p) _NOEXCEPT {return _VSTD::forward<const _T1>(__p.first);}
+#endif // _LIBCPP_CXX03_LANG
+};
+
+template <>
+struct __get_pair<1>
+{
+    template <class _T1, class _T2>
+    static
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    _T2&
+    get(pair<_T1, _T2>& __p) _NOEXCEPT {return __p.second;}
+
+    template <class _T1, class _T2>
+    static
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    const _T2&
+    get(const pair<_T1, _T2>& __p) _NOEXCEPT {return __p.second;}
+
+#ifndef _LIBCPP_CXX03_LANG
+    template <class _T1, class _T2>
+    static
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    _T2&&
+    get(pair<_T1, _T2>&& __p) _NOEXCEPT {return _VSTD::forward<_T2>(__p.second);}
+
+    template <class _T1, class _T2>
+    static
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    const _T2&&
+    get(const pair<_T1, _T2>&& __p) _NOEXCEPT {return _VSTD::forward<const _T2>(__p.second);}
+#endif // _LIBCPP_CXX03_LANG
+};
+
+template <size_t _Ip, class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+typename tuple_element<_Ip, pair<_T1, _T2> >::type&
+get(pair<_T1, _T2>& __p) _NOEXCEPT
+{
+    return __get_pair<_Ip>::get(__p);
+}
+
+template <size_t _Ip, class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+const typename tuple_element<_Ip, pair<_T1, _T2> >::type&
+get(const pair<_T1, _T2>& __p) _NOEXCEPT
+{
+    return __get_pair<_Ip>::get(__p);
+}
+
+#ifndef _LIBCPP_CXX03_LANG
+template <size_t _Ip, class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+typename tuple_element<_Ip, pair<_T1, _T2> >::type&&
+get(pair<_T1, _T2>&& __p) _NOEXCEPT
+{
+    return __get_pair<_Ip>::get(_VSTD::move(__p));
+}
+
+template <size_t _Ip, class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+const typename tuple_element<_Ip, pair<_T1, _T2> >::type&&
+get(const pair<_T1, _T2>&& __p) _NOEXCEPT
+{
+    return __get_pair<_Ip>::get(_VSTD::move(__p));
+}
+#endif // _LIBCPP_CXX03_LANG
+
+#if _LIBCPP_STD_VER > 11
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr _T1 & get(pair<_T1, _T2>& __p) _NOEXCEPT
+{
+    return __get_pair<0>::get(__p);
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr _T1 const & get(pair<_T1, _T2> const& __p) _NOEXCEPT
+{
+    return __get_pair<0>::get(__p);
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr _T1 && get(pair<_T1, _T2>&& __p) _NOEXCEPT
+{
+    return __get_pair<0>::get(_VSTD::move(__p));
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr _T1 const && get(pair<_T1, _T2> const&& __p) _NOEXCEPT
+{
+    return __get_pair<0>::get(_VSTD::move(__p));
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr _T1 & get(pair<_T2, _T1>& __p) _NOEXCEPT
+{
+    return __get_pair<1>::get(__p);
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr _T1 const & get(pair<_T2, _T1> const& __p) _NOEXCEPT
+{
+    return __get_pair<1>::get(__p);
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr _T1 && get(pair<_T2, _T1>&& __p) _NOEXCEPT
+{
+    return __get_pair<1>::get(_VSTD::move(__p));
+}
+
+template <class _T1, class _T2>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr _T1 const && get(pair<_T2, _T1> const&& __p) _NOEXCEPT
+{
+    return __get_pair<1>::get(_VSTD::move(__p));
+}
+
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_PAIR_H
lib/libcxx/include/__utility/piecewise_construct.h
@@ -0,0 +1,34 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_PIECEWISE_CONSTRUCT_H
+#define _LIBCPP___UTILITY_PIECEWISE_CONSTRUCT_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+struct _LIBCPP_TEMPLATE_VIS piecewise_construct_t { explicit piecewise_construct_t() = default; };
+#if defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
+extern _LIBCPP_EXPORTED_FROM_ABI const piecewise_construct_t piecewise_construct;// = piecewise_construct_t();
+#else
+/* _LIBCPP_INLINE_VAR */ constexpr piecewise_construct_t piecewise_construct = piecewise_construct_t();
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_PIECEWISE_CONSTRUCT_H
lib/libcxx/include/__utility/rel_ops.h
@@ -0,0 +1,67 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_REL_OPS_H
+#define _LIBCPP___UTILITY_REL_OPS_H
+
+#include <__config>
+#include <__utility/forward.h>
+#include <__utility/move.h>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+namespace rel_ops
+{
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator!=(const _Tp& __x, const _Tp& __y)
+{
+    return !(__x == __y);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator> (const _Tp& __x, const _Tp& __y)
+{
+    return __y < __x;
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator<=(const _Tp& __x, const _Tp& __y)
+{
+    return !(__y < __x);
+}
+
+template<class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+bool
+operator>=(const _Tp& __x, const _Tp& __y)
+{
+    return !(__x < __y);
+}
+
+}  // rel_ops
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_REL_OPS_H
lib/libcxx/include/__utility/swap.h
@@ -0,0 +1,55 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_SWAP_H
+#define _LIBCPP___UTILITY_SWAP_H
+
+#include <__config>
+#include <__utility/declval.h>
+#include <__utility/move.h>
+#include <type_traits>
+#include <cstddef>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#ifndef _LIBCPP_CXX03_LANG
+template <class _Tp>
+using __swap_result_t = typename enable_if<is_move_constructible<_Tp>::value && is_move_assignable<_Tp>::value>::type;
+#else
+template <class>
+using __swap_result_t = void;
+#endif
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY __swap_result_t<_Tp> _LIBCPP_CONSTEXPR_AFTER_CXX17 swap(_Tp& __x, _Tp& __y)
+    _NOEXCEPT_(is_nothrow_move_constructible<_Tp>::value&& is_nothrow_move_assignable<_Tp>::value) {
+  _Tp __t(_VSTD::move(__x));
+  __x = _VSTD::move(__y);
+  __y = _VSTD::move(__t);
+}
+
+template <class _Tp, size_t _Np>
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 typename enable_if<__is_swappable<_Tp>::value>::type
+swap(_Tp (&__a)[_Np], _Tp (&__b)[_Np]) _NOEXCEPT_(__is_nothrow_swappable<_Tp>::value) {
+  for (size_t __i = 0; __i != _Np; ++__i) {
+    swap(__a[__i], __b[__i]);
+  }
+}
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_SWAP_H
lib/libcxx/include/__utility/to_underlying.h
@@ -0,0 +1,45 @@
+// -*- C++ -*-
+//===----------------- __utility/to_underlying.h --------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___UTILITY_TO_UNDERLYING_H
+#define _LIBCPP___UTILITY_TO_UNDERLYING_H
+
+#include <__config>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#ifndef _LIBCPP_CXX03_LANG
+template <class _Tp>
+_LIBCPP_INLINE_VISIBILITY constexpr typename underlying_type<_Tp>::type
+__to_underlying(_Tp __val) noexcept {
+  return static_cast<typename underlying_type<_Tp>::type>(__val);
+}
+#endif // !_LIBCPP_CXX03_LANG
+
+#if _LIBCPP_STD_VER > 20
+template <class _Tp>
+_LIBCPP_NODISCARD_EXT _LIBCPP_INLINE_VISIBILITY constexpr underlying_type_t<_Tp>
+to_underlying(_Tp __val) noexcept {
+  return _VSTD::__to_underlying(__val);
+}
+#endif
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___UTILITY_TO_UNDERLYING_H
lib/libcxx/include/__variant/monostate.h
@@ -0,0 +1,65 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___VARIANT_MONOSTATE_H
+#define _LIBCPP___VARIANT_MONOSTATE_H
+
+#include <__config>
+#include <__functional/hash.h>
+#include <cstddef>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 14
+
+struct _LIBCPP_TEMPLATE_VIS monostate {};
+
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr bool operator<(monostate, monostate) noexcept { return false; }
+
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr bool operator>(monostate, monostate) noexcept { return false; }
+
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr bool operator<=(monostate, monostate) noexcept { return true; }
+
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr bool operator>=(monostate, monostate) noexcept { return true; }
+
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr bool operator==(monostate, monostate) noexcept { return true; }
+
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr bool operator!=(monostate, monostate) noexcept { return false; }
+
+template <>
+struct _LIBCPP_TEMPLATE_VIS hash<monostate> {
+  using argument_type = monostate;
+  using result_type = size_t;
+
+  inline _LIBCPP_INLINE_VISIBILITY
+  result_type operator()(const argument_type&) const _NOEXCEPT {
+    return 66740831; // return a fundamentally attractive random value.
+  }
+};
+
+#endif // _LIBCPP_STD_VER > 14
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___VARIANT_MONOSTATE_H
lib/libcxx/include/experimental/__config
@@ -32,10 +32,6 @@
 #define _LIBCPP_END_NAMESPACE_LFTS_PMR _LIBCPP_END_NAMESPACE_LFTS }
 #define _VSTD_LFTS_PMR _VSTD_LFTS::pmr
 
-#define _LIBCPP_BEGIN_NAMESPACE_CHRONO_LFTS _LIBCPP_BEGIN_NAMESPACE_STD        \
-  namespace chrono { namespace experimental { inline namespace fundamentals_v1 {
-#define _LIBCPP_END_NAMESPACE_CHRONO_LFTS _LIBCPP_END_NAMESPACE_STD } } }
-
 #if defined(_LIBCPP_NO_EXPERIMENTAL_DEPRECATION_WARNING_FILESYSTEM)
 #   define _LIBCPP_DEPRECATED_EXPERIMENTAL_FILESYSTEM /* nothing */
 #else
lib/libcxx/include/experimental/__memory
@@ -10,6 +10,8 @@
 #ifndef _LIBCPP_EXPERIMENTAL___MEMORY
 #define _LIBCPP_EXPERIMENTAL___MEMORY
 
+#include <__memory/allocator_arg_t.h>
+#include <__memory/uses_allocator.h>
 #include <experimental/__config>
 #include <experimental/utility> // for erased_type
 #include <__functional_base>
@@ -73,12 +75,35 @@ struct __lfts_uses_alloc_ctor
     >
 {};
 
+template <class _Tp, class _Allocator, class... _Args>
+inline _LIBCPP_INLINE_VISIBILITY
+void __user_alloc_construct_impl (integral_constant<int, 0>, _Tp *__storage, const _Allocator &, _Args &&... __args )
+{
+    new (__storage) _Tp (_VSTD::forward<_Args>(__args)...);
+}
+
+// FIXME: This should have a version which takes a non-const alloc.
+template <class _Tp, class _Allocator, class... _Args>
+inline _LIBCPP_INLINE_VISIBILITY
+void __user_alloc_construct_impl (integral_constant<int, 1>, _Tp *__storage, const _Allocator &__a, _Args &&... __args )
+{
+    new (__storage) _Tp (allocator_arg, __a, _VSTD::forward<_Args>(__args)...);
+}
+
+// FIXME: This should have a version which takes a non-const alloc.
+template <class _Tp, class _Allocator, class... _Args>
+inline _LIBCPP_INLINE_VISIBILITY
+void __user_alloc_construct_impl (integral_constant<int, 2>, _Tp *__storage, const _Allocator &__a, _Args &&... __args )
+{
+    new (__storage) _Tp (_VSTD::forward<_Args>(__args)..., __a);
+}
+
 template <class _Tp, class _Alloc, class ..._Args>
 inline _LIBCPP_INLINE_VISIBILITY
 void __lfts_user_alloc_construct(
     _Tp * __store, const _Alloc & __a, _Args &&... __args)
 {
-    _VSTD::__user_alloc_construct_impl(
+    ::std::experimental::fundamentals_v1::__user_alloc_construct_impl(
         typename __lfts_uses_alloc_ctor<_Tp, _Alloc, _Args...>::type()
        , __store, __a, _VSTD::forward<_Args>(__args)...
        );
lib/libcxx/include/experimental/functional
@@ -86,6 +86,7 @@ inline namespace fundamentals_v1 {
 
 */
 
+#include <__memory/uses_allocator.h>
 #include <experimental/__config>
 #include <functional>
 #include <algorithm>
@@ -109,7 +110,7 @@ _LIBCPP_BEGIN_NAMESPACE_LFTS
 #if _LIBCPP_STD_VER > 11
 // default searcher
 template<class _ForwardIterator, class _BinaryPredicate = equal_to<>>
-class _LIBCPP_TYPE_VIS default_searcher {
+class _LIBCPP_TEMPLATE_VIS default_searcher {
 public:
     _LIBCPP_INLINE_VISIBILITY
     default_searcher(_ForwardIterator __f, _ForwardIterator __l,
@@ -122,8 +123,8 @@ public:
     operator () (_ForwardIterator2 __f, _ForwardIterator2 __l) const
     {
         return _VSTD::__search(__f, __l, __first_, __last_, __pred_,
-            typename _VSTD::iterator_traits<_ForwardIterator>::iterator_category(),
-            typename _VSTD::iterator_traits<_ForwardIterator2>::iterator_category());
+            typename iterator_traits<_ForwardIterator>::iterator_category(),
+            typename iterator_traits<_ForwardIterator2>::iterator_category());
     }
 
 private:
@@ -154,7 +155,7 @@ public: // TODO private:
 
 public:
     _LIBCPP_INLINE_VISIBILITY
-    _BMSkipTable(std::size_t __sz, _Value __default, _Hash __hf, _BinaryPredicate __pred)
+    _BMSkipTable(size_t __sz, _Value __default, _Hash __hf, _BinaryPredicate __pred)
         : __default_value_(__default), __table(__sz, __hf, __pred) {}
 
     _LIBCPP_INLINE_VISIBILITY
@@ -179,13 +180,13 @@ private:
     typedef _Value value_type;
     typedef _Key   key_type;
 
-    typedef typename std::make_unsigned<key_type>::type unsigned_key_type;
-    typedef std::array<value_type, _VSTD::numeric_limits<unsigned_key_type>::max()> skip_map;
+    typedef typename make_unsigned<key_type>::type unsigned_key_type;
+    typedef std::array<value_type, numeric_limits<unsigned_key_type>::max()> skip_map;
     skip_map __table;
 
 public:
     _LIBCPP_INLINE_VISIBILITY
-    _BMSkipTable(std::size_t /*__sz*/, _Value __default, _Hash /*__hf*/, _BinaryPredicate /*__pred*/)
+    _BMSkipTable(size_t /*__sz*/, _Value __default, _Hash /*__hf*/, _BinaryPredicate /*__pred*/)
     {
         std::fill_n(__table.begin(), __table.size(), __default);
     }
@@ -207,12 +208,12 @@ public:
 template <class _RandomAccessIterator1,
           class _Hash = hash<typename iterator_traits<_RandomAccessIterator1>::value_type>,
           class _BinaryPredicate = equal_to<>>
-class _LIBCPP_TYPE_VIS boyer_moore_searcher {
+class _LIBCPP_TEMPLATE_VIS boyer_moore_searcher {
 private:
     typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type difference_type;
     typedef typename std::iterator_traits<_RandomAccessIterator1>::value_type      value_type;
     typedef _BMSkipTable<value_type, difference_type, _Hash, _BinaryPredicate,
-                    _VSTD::is_integral<value_type>::value && // what about enums?
+                    is_integral<value_type>::value && // what about enums?
                     sizeof(value_type) == 1 &&
                     is_same<_Hash, hash<value_type>>::value &&
                     is_same<_BinaryPredicate, equal_to<>>::value
@@ -247,7 +248,7 @@ public:
         if (__first_ == __last_) return make_pair(__f, __f); // empty pattern
 
     //  If the pattern is larger than the corpus, we can't find it!
-        if ( __pattern_length_ > _VSTD::distance (__f, __l))
+        if ( __pattern_length_ > _VSTD::distance(__f, __l))
             return make_pair(__l, __l);
 
     //  Do the search
@@ -299,11 +300,11 @@ public: // TODO private:
     template<typename _Iterator, typename _Container>
     void __compute_bm_prefix ( _Iterator __f, _Iterator __l, _BinaryPredicate __pred, _Container &__prefix )
     {
-        const std::size_t __count = _VSTD::distance(__f, __l);
+        const size_t __count = _VSTD::distance(__f, __l);
 
         __prefix[0] = 0;
-        std::size_t __k = 0;
-        for ( std::size_t __i = 1; __i < __count; ++__i )
+        size_t __k = 0;
+        for ( size_t __i = 1; __i < __count; ++__i )
         {
             while ( __k > 0 && !__pred ( __f[__k], __f[__i] ))
                 __k = __prefix [ __k - 1 ];
@@ -317,22 +318,22 @@ public: // TODO private:
     void __build_suffix_table(_RandomAccessIterator1 __f, _RandomAccessIterator1 __l,
                                                     _BinaryPredicate __pred)
     {
-        const std::size_t __count = _VSTD::distance(__f, __l);
+        const size_t __count = _VSTD::distance(__f, __l);
         vector<difference_type> & __suffix = *__suffix_.get();
         if (__count > 0)
         {
-            _VSTD::vector<value_type> __scratch(__count);
+            vector<value_type> __scratch(__count);
 
             __compute_bm_prefix(__f, __l, __pred, __scratch);
-            for ( std::size_t __i = 0; __i <= __count; __i++ )
+            for ( size_t __i = 0; __i <= __count; __i++ )
                 __suffix[__i] = __count - __scratch[__count-1];
 
-            typedef _VSTD::reverse_iterator<_RandomAccessIterator1> _RevIter;
+            typedef reverse_iterator<_RandomAccessIterator1> _RevIter;
             __compute_bm_prefix(_RevIter(__l), _RevIter(__f), __pred, __scratch);
 
-            for ( std::size_t __i = 0; __i < __count; __i++ )
+            for ( size_t __i = 0; __i < __count; __i++ )
             {
-                const std::size_t     __j = __count - __scratch[__i];
+                const size_t     __j = __count - __scratch[__i];
                 const difference_type __k = __i     - __scratch[__i] + 1;
 
                 if (__suffix[__j] > __k)
@@ -358,12 +359,12 @@ make_boyer_moore_searcher( _RandomAccessIterator __f, _RandomAccessIterator __l,
 template <class _RandomAccessIterator1,
           class _Hash = hash<typename iterator_traits<_RandomAccessIterator1>::value_type>,
           class _BinaryPredicate = equal_to<>>
-class _LIBCPP_TYPE_VIS boyer_moore_horspool_searcher {
+class _LIBCPP_TEMPLATE_VIS boyer_moore_horspool_searcher {
 private:
     typedef typename std::iterator_traits<_RandomAccessIterator1>::difference_type difference_type;
     typedef typename std::iterator_traits<_RandomAccessIterator1>::value_type      value_type;
     typedef _BMSkipTable<value_type, difference_type, _Hash, _BinaryPredicate,
-                    _VSTD::is_integral<value_type>::value && // what about enums?
+                    is_integral<value_type>::value && // what about enums?
                     sizeof(value_type) == 1 &&
                     is_same<_Hash, hash<value_type>>::value &&
                     is_same<_BinaryPredicate, equal_to<>>::value
@@ -399,7 +400,7 @@ public:
         if (__first_ == __last_) return make_pair(__f, __f); // empty pattern
 
     //  If the pattern is larger than the corpus, we can't find it!
-        if ( __pattern_length_ > _VSTD::distance (__f, __l))
+        if ( __pattern_length_ > _VSTD::distance(__f, __l))
             return make_pair(__l, __l);
 
     //  Do the search
lib/libcxx/include/experimental/iterator
@@ -56,6 +56,9 @@ namespace std {
 
 #if _LIBCPP_STD_VER > 11
 
+#include <__memory/addressof.h>
+#include <__utility/move.h>
+#include <__utility/forward.h>
 #include <iterator>
 
 _LIBCPP_BEGIN_NAMESPACE_LFTS
lib/libcxx/include/experimental/propagate_const
@@ -135,7 +135,7 @@ template <class _Tp>
 class propagate_const
 {
 public:
-  typedef remove_reference_t<decltype(*_VSTD::declval<_Tp&>())> element_type;
+  typedef remove_reference_t<decltype(*declval<_Tp&>())> element_type;
 
   static_assert(!is_array<_Tp>::value,
       "Instantiation of propagate_const with an array type is ill-formed.");
lib/libcxx/include/experimental/simd
@@ -725,12 +725,12 @@ constexpr size_t __ceil_pow_of_2(size_t __val) {
 
 template <class _Tp, size_t __bytes>
 struct __vec_ext_traits {
-#if !defined(_LIBCPP_COMPILER_CLANG)
+#if !defined(_LIBCPP_COMPILER_CLANG_BASED)
   typedef _Tp type __attribute__((vector_size(__ceil_pow_of_2(__bytes))));
 #endif
 };
 
-#if defined(_LIBCPP_COMPILER_CLANG)
+#if defined(_LIBCPP_COMPILER_CLANG_BASED)
 #define _LIBCPP_SPECIALIZE_VEC_EXT(_TYPE, _NUM_ELEMENT)                        \
   template <>                                                                  \
   struct __vec_ext_traits<_TYPE, sizeof(_TYPE) * _NUM_ELEMENT> {               \
lib/libcxx/include/experimental/type_traits
@@ -105,7 +105,7 @@ using raw_invocation_type_t = typename raw_invocation_type<_Tp>::type;
 // 3.3.4, Detection idiom
 template <class...> using void_t = void;
 
-struct nonesuch : private _VSTD::__nat { // make nonesuch "not an aggregate"
+struct nonesuch : private __nat { // make nonesuch "not an aggregate"
   ~nonesuch() = delete;
   nonesuch      (nonesuch const&) = delete;
   void operator=(nonesuch const&) = delete;
lib/libcxx/include/ext/__hash
@@ -12,6 +12,7 @@
 
 #pragma GCC system_header
 
+#include <__string>
 #include <string>
 #include <cstring>
 
@@ -130,4 +131,4 @@ template <> struct _LIBCPP_TEMPLATE_VIS hash<unsigned long>
 };
 }
 
-#endif  // _LIBCPP_EXT_HASH
+#endif // _LIBCPP_EXT_HASH
lib/libcxx/include/ext/hash_map
@@ -208,7 +208,7 @@ template <class Key, class T, class Hash, class Pred, class Alloc>
 #include <type_traits>
 #include <ext/__hash>
 
-#if __DEPRECATED
+#if defined(__DEPRECATED) && __DEPRECATED
 #if defined(_LIBCPP_WARNING)
     _LIBCPP_WARNING("Use of the header <ext/hash_map> is deprecated.  Migrate to <unordered_map>")
 #else
@@ -350,7 +350,7 @@ public:
         {
             const_cast<bool&>(__x.__value_constructed) = false;
         }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     void operator()(pointer __p)
@@ -981,4 +981,4 @@ operator!=(const hash_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x,
 
 } // __gnu_cxx
 
-#endif  // _LIBCPP_HASH_MAP
+#endif // _LIBCPP_HASH_MAP
lib/libcxx/include/ext/hash_set
@@ -197,7 +197,7 @@ template <class Value, class Hash, class Pred, class Alloc>
 #include <functional>
 #include <ext/__hash>
 
-#if __DEPRECATED
+#if defined(__DEPRECATED) && __DEPRECATED
 #if defined(_LIBCPP_WARNING)
     _LIBCPP_WARNING("Use of the header <ext/hash_set> is deprecated.  Migrate to <unordered_set>")
 #else
@@ -656,4 +656,4 @@ operator!=(const hash_multiset<_Value, _Hash, _Pred, _Alloc>& __x,
 
 } // __gnu_cxx
 
-#endif  // _LIBCPP_HASH_SET
+#endif // _LIBCPP_HASH_SET
lib/libcxx/include/__availability
@@ -43,6 +43,14 @@
 // as unavailable. When vendors decide to ship the feature as part of their
 // shared library, they can update the markup appropriately.
 //
+// Furthermore, many features in the standard library have corresponding
+// feature-test macros. When a feature is made unavailable on some deployment
+// target, a macro should be defined to signal that it is unavailable. That
+// macro can then be picked up when feature-test macros are generated (see
+// generate_feature_test_macro_components.py) to make sure that feature-test
+// macros don't announce a feature as being implemented if it has been marked
+// as unavailable.
+//
 // Note that this mechanism is disabled by default in the "upstream" libc++.
 // Availability annotations are only meaningful when shipping libc++ inside
 // a platform (i.e. as a system library), and so vendors that want them should
@@ -76,6 +84,8 @@
     // This controls the availability of std::shared_mutex and std::shared_timed_mutex,
     // which were added to the dylib later.
 #   define _LIBCPP_AVAILABILITY_SHARED_MUTEX
+// #   define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex
+// #   define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex
 
     // These macros control the availability of std::bad_optional_access and
     // other exception types. These were put in the shared library to prevent
@@ -114,6 +124,7 @@
 #   define _LIBCPP_AVAILABILITY_FILESYSTEM
 #   define _LIBCPP_AVAILABILITY_FILESYSTEM_PUSH
 #   define _LIBCPP_AVAILABILITY_FILESYSTEM_POP
+// #   define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_filesystem
 
     // This controls the availability of std::to_chars.
 #   define _LIBCPP_AVAILABILITY_TO_CHARS
@@ -122,6 +133,17 @@
     // which requires shared library support for various operations
     // (see libcxx/src/atomic.cpp).
 #   define _LIBCPP_AVAILABILITY_SYNC
+// #   define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_atomic_wait
+// #   define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_barrier
+// #   define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch
+// #   define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore
+
+    // This controls the availability of the C++20 format library.
+    // The library is in development and not ABI stable yet. Currently
+    // P2216 is aiming to be retroactively accepted in C++20. This paper
+    // contains ABI breaking changes.
+#   define _LIBCPP_AVAILABILITY_FORMAT
+// #   define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_format
 
 #elif defined(__APPLE__)
 
@@ -130,6 +152,14 @@
         __attribute__((availability(ios,strict,introduced=10.0)))               \
         __attribute__((availability(tvos,strict,introduced=10.0)))              \
         __attribute__((availability(watchos,strict,introduced=3.0)))
+#   if (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101200) ||    \
+        (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 100000) || \
+        (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 100000) ||         \
+        (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 30000)
+#       define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex
+#       define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex
+#   endif
+
 #   define _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS                             \
         __attribute__((availability(macosx,strict,introduced=10.13)))           \
         __attribute__((availability(ios,strict,introduced=11.0)))               \
@@ -139,27 +169,34 @@
         _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS
 #   define _LIBCPP_AVAILABILITY_BAD_ANY_CAST                                    \
         _LIBCPP_AVAILABILITY_BAD_OPTIONAL_ACCESS
+
 #   define _LIBCPP_AVAILABILITY_UNCAUGHT_EXCEPTIONS                             \
         __attribute__((availability(macosx,strict,introduced=10.12)))           \
         __attribute__((availability(ios,strict,introduced=10.0)))               \
         __attribute__((availability(tvos,strict,introduced=10.0)))              \
         __attribute__((availability(watchos,strict,introduced=3.0)))
+
 #   define _LIBCPP_AVAILABILITY_SIZED_NEW_DELETE                                \
         __attribute__((availability(macosx,strict,introduced=10.12)))           \
         __attribute__((availability(ios,strict,introduced=10.0)))               \
         __attribute__((availability(tvos,strict,introduced=10.0)))              \
         __attribute__((availability(watchos,strict,introduced=3.0)))
+
 #   define _LIBCPP_AVAILABILITY_FUTURE_ERROR                                    \
         __attribute__((availability(ios,strict,introduced=6.0)))
+
 #   define _LIBCPP_AVAILABILITY_TYPEINFO_VTABLE                                 \
         __attribute__((availability(macosx,strict,introduced=10.9)))            \
         __attribute__((availability(ios,strict,introduced=7.0)))
+
 #   define _LIBCPP_AVAILABILITY_LOCALE_CATEGORY                                 \
         __attribute__((availability(macosx,strict,introduced=10.9)))            \
         __attribute__((availability(ios,strict,introduced=7.0)))
+
 #   define _LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR                               \
         __attribute__((availability(macosx,strict,introduced=10.9)))            \
         __attribute__((availability(ios,strict,introduced=7.0)))
+
 #   define _LIBCPP_AVAILABILITY_FILESYSTEM                                      \
         __attribute__((availability(macosx,strict,introduced=10.15)))           \
         __attribute__((availability(ios,strict,introduced=13.0)))               \
@@ -175,11 +212,38 @@
         _Pragma("clang attribute pop")                                          \
         _Pragma("clang attribute pop")                                          \
         _Pragma("clang attribute pop")
+#   if (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101500) ||    \
+        (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 130000) || \
+        (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 130000) ||         \
+        (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 60000)
+#       define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_filesystem
+#   endif
+
 #   define _LIBCPP_AVAILABILITY_TO_CHARS                                        \
         _LIBCPP_AVAILABILITY_FILESYSTEM
+
 #   define _LIBCPP_AVAILABILITY_SYNC                                            \
-        __attribute__((unavailable))
+        __attribute__((availability(macosx,strict,introduced=11.0)))            \
+        __attribute__((availability(ios,strict,introduced=14.0)))               \
+        __attribute__((availability(tvos,strict,introduced=14.0)))              \
+        __attribute__((availability(watchos,strict,introduced=7.0)))
+#   if (defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 110000) ||    \
+        (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ < 140000) || \
+        (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ < 140000) ||         \
+        (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ < 70000)
+#       define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_atomic_wait
+#       define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_barrier
+#       define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch
+#       define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore
+#   endif
 
+    // This controls the availability of the C++20 format library.
+    // The library is in development and not ABI stable yet. Currently
+    // P2216 is aiming to be retroactively accepted in C++20. This paper
+    // contains ABI breaking changes.
+#   define _LIBCPP_AVAILABILITY_FORMAT                                          \
+        __attribute__((unavailable))
+#   define _LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_format
 #else
 
 // ...New vendors can add availability markup here...
@@ -203,4 +267,4 @@
 #   define _LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS  _LIBCPP_AVAILABILITY_BAD_VARIANT_ACCESS
 #endif
 
-#endif  // _LIBCPP___AVAILABILITY
+#endif // _LIBCPP___AVAILABILITY
lib/libcxx/include/__bit_reference
@@ -1114,28 +1114,26 @@ public:
 #endif
     {}
 
-    // avoid re-declaring a copy constructor for the non-const version.
-    using __type_for_copy_to_const =
-      _If<_IsConst, __bit_iterator<_Cp, false>, struct __private_nat>;
-
+    // When _IsConst=false, this is the copy constructor.
+    // It is non-trivial. Making it trivial would break ABI.
+    // When _IsConst=true, this is a converting constructor;
+    // the copy and move constructors are implicitly generated
+    // and trivial.
     _LIBCPP_INLINE_VISIBILITY
-    __bit_iterator(const __type_for_copy_to_const& __it) _NOEXCEPT
+    __bit_iterator(const __bit_iterator<_Cp, false>& __it) _NOEXCEPT
         : __seg_(__it.__seg_), __ctz_(__it.__ctz_) {}
 
-    // The non-const __bit_iterator has historically had a non-trivial
-    // copy constructor (as a quirk of its construction). We need to maintain
-    // this for ABI purposes.
-    using __type_for_abi_non_trivial_copy_ctor =
-      _If<!_IsConst, __bit_iterator, struct __private_nat>;
-
-    _LIBCPP_INLINE_VISIBILITY
-    __bit_iterator(__type_for_abi_non_trivial_copy_ctor const& __it) _NOEXCEPT
-      : __seg_(__it.__seg_), __ctz_(__it.__ctz_) {}
-
-    // Always declare the copy assignment operator since the implicit declaration
-    // is deprecated.
+    // When _IsConst=false, we have a user-provided copy constructor,
+    // so we must also provide a copy assignment operator because
+    // the implicit generation of a defaulted one is deprecated.
+    // When _IsConst=true, the assignment operators are
+    // implicitly generated and trivial.
     _LIBCPP_INLINE_VISIBILITY
-    __bit_iterator& operator=(__bit_iterator const&) = default;
+    __bit_iterator& operator=(const _If<_IsConst, struct __private_nat, __bit_iterator>& __it) {
+        __seg_ = __it.__seg_;
+        __ctz_ = __it.__ctz_;
+        return *this;
+    }
 
     _LIBCPP_INLINE_VISIBILITY reference operator*() const _NOEXCEPT
         {return reference(__seg_, __storage_type(1) << __ctz_);}
@@ -1302,4 +1300,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP___BIT_REFERENCE
+#endif // _LIBCPP___BIT_REFERENCE
lib/libcxx/include/__bits
@@ -76,7 +76,6 @@ inline _LIBCPP_INLINE_VISIBILITY
 int __libcpp_ctz(unsigned long long __x) {
     unsigned long __where;
 #if defined(_LIBCPP_HAS_BITSCAN64)
-    (defined(_M_AMD64) || defined(__x86_64__))
   if (_BitScanForward64(&__where, __x))
     return static_cast<int>(__where);
 #else
@@ -143,4 +142,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP__BITS
+#endif // _LIBCPP___BITS
lib/libcxx/include/__bsd_locale_fallbacks.h
@@ -13,9 +13,9 @@
 #ifndef _LIBCPP_BSD_LOCALE_FALLBACKS_DEFAULTS_H
 #define _LIBCPP_BSD_LOCALE_FALLBACKS_DEFAULTS_H
 
-#include <stdlib.h>
-#include <stdarg.h>
 #include <memory>
+#include <stdarg.h>
+#include <stdlib.h>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
lib/libcxx/include/__config
@@ -32,7 +32,7 @@
 #  define _GNUC_VER_NEW 0
 #endif
 
-#define _LIBCPP_VERSION 12000
+#define _LIBCPP_VERSION 13000
 
 #ifndef _LIBCPP_ABI_VERSION
 #  define _LIBCPP_ABI_VERSION 1
@@ -54,7 +54,7 @@
 #  else
 #    define _LIBCPP_STD_VER 21  // current year, or date of c++2b ratification
 #  endif
-#endif  // _LIBCPP_STD_VER
+#endif // _LIBCPP_STD_VER
 
 #if defined(__ELF__)
 #  define _LIBCPP_OBJECT_FORMAT_ELF   1
@@ -86,17 +86,18 @@
 // provided under the alternate keyword __nullptr, which changes the mangling
 // of nullptr_t. This option is ABI incompatible with GCC in C++03 mode.
 #  define _LIBCPP_ABI_ALWAYS_USE_CXX11_NULLPTR
-// Define the `pointer_safety` enum as a C++11 strongly typed enumeration
-// instead of as a class simulating an enum. If this option is enabled
-// `pointer_safety` and `get_pointer_safety()` will no longer be available
-// in C++03.
-#  define _LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE
 // Define a key function for `bad_function_call` in the library, to centralize
 // its vtable and typeinfo to libc++ rather than having all other libraries
 // using that class define their own copies.
 #  define _LIBCPP_ABI_BAD_FUNCTION_CALL_KEY_FUNCTION
 // Enable optimized version of __do_get_(un)signed which avoids redundant copies.
 #  define _LIBCPP_ABI_OPTIMIZED_LOCALE_NUM_GET
+// In C++20 and later, don't derive std::plus from std::binary_function,
+// nor std::negate from std::unary_function.
+#  define _LIBCPP_ABI_NO_BINDER_BASES
+// Give reverse_iterator<T> one data member of type T, not two.
+// Also, in C++17 and later, don't derive iterator types from std::iterator.
+#  define _LIBCPP_ABI_NO_ITERATOR_BASES
 // Use the smallest possible integer type to represent the index of the variant.
 // Previously libc++ used "unsigned int" exclusively.
 #  define _LIBCPP_ABI_VARIANT_INDEX_TYPE_OPTIMIZATION
@@ -104,6 +105,8 @@
 #  define _LIBCPP_ABI_OPTIMIZED_FUNCTION
 // All the regex constants must be distinct and nonzero.
 #  define _LIBCPP_ABI_REGEX_CONSTANTS_NONZERO
+// Use raw pointers, not wrapped ones, for std::span's iterator type.
+#  define _LIBCPP_ABI_SPAN_POINTER_ITERATORS
 // Re-worked external template instantiations for std::string with a focus on
 // performance and fast-path inlining.
 #  define _LIBCPP_ABI_STRING_OPTIMIZED_EXTERNAL_INSTANTIATION
@@ -181,11 +184,12 @@
 #define __has_include(...) 0
 #endif
 
-#if defined(__clang__)
-#  define _LIBCPP_COMPILER_CLANG
-#  ifndef __apple_build_version__
-#    define _LIBCPP_CLANG_VER (__clang_major__ * 100 + __clang_minor__)
-#  endif
+#if defined(__apple_build_version__)
+#  define _LIBCPP_COMPILER_CLANG_BASED
+#  define _LIBCPP_APPLE_CLANG_VER (__apple_build_version__ / 10000)
+#elif defined(__clang__)
+#  define _LIBCPP_COMPILER_CLANG_BASED
+#  define _LIBCPP_CLANG_VER (__clang_major__ * 100 + __clang_minor__)
 #elif defined(__GNUC__)
 #  define _LIBCPP_COMPILER_GCC
 #elif defined(_MSC_VER)
@@ -235,13 +239,13 @@
 #  if __LITTLE_ENDIAN__
 #    define _LIBCPP_LITTLE_ENDIAN
 #  endif  // __LITTLE_ENDIAN__
-#endif  // __LITTLE_ENDIAN__
+#endif // __LITTLE_ENDIAN__
 
 #ifdef __BIG_ENDIAN__
 #  if __BIG_ENDIAN__
 #    define _LIBCPP_BIG_ENDIAN
 #  endif  // __BIG_ENDIAN__
-#endif  // __BIG_ENDIAN__
+#endif // __BIG_ENDIAN__
 
 #ifdef __BYTE_ORDER__
 #  if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
@@ -262,7 +266,7 @@
 #  ifndef __LONG_LONG_SUPPORTED
 #    define _LIBCPP_HAS_NO_LONG_LONG
 #  endif  // __LONG_LONG_SUPPORTED
-#endif  // __FreeBSD__
+#endif // __FreeBSD__
 
 #if defined(__NetBSD__) || defined(__OpenBSD__)
 #  include <sys/endian.h>
@@ -271,7 +275,7 @@
 #  else  // _BYTE_ORDER == _LITTLE_ENDIAN
 #    define _LIBCPP_BIG_ENDIAN
 #  endif  // _BYTE_ORDER == _LITTLE_ENDIAN
-#endif  // defined(__NetBSD__) || defined(__OpenBSD__)
+#endif // defined(__NetBSD__) || defined(__OpenBSD__)
 
 #if defined(_WIN32)
 #  define _LIBCPP_WIN32API
@@ -340,7 +344,7 @@
 #  else  // __BYTE_ORDER == __BIG_ENDIAN
 #    error unable to determine endian
 #  endif
-#endif  // !defined(_LIBCPP_LITTLE_ENDIAN) && !defined(_LIBCPP_BIG_ENDIAN)
+#endif // !defined(_LIBCPP_LITTLE_ENDIAN) && !defined(_LIBCPP_BIG_ENDIAN)
 
 #if __has_attribute(__no_sanitize__) && !defined(_LIBCPP_COMPILER_GCC)
 #  define _LIBCPP_NO_CFI __attribute__((__no_sanitize__("cfi")))
@@ -348,7 +352,7 @@
 #  define _LIBCPP_NO_CFI
 #endif
 
-#if __ISO_C_VISIBLE >= 2011 || __cplusplus >= 201103L
+#if (defined(__ISO_C_VISIBLE) && (__ISO_C_VISIBLE >= 2011)) || __cplusplus >= 201103L
 #  if defined(__FreeBSD__)
 #    define _LIBCPP_HAS_ALIGNED_ALLOC
 #    define _LIBCPP_HAS_QUICK_EXIT
@@ -387,13 +391,16 @@
 #      define _LIBCPP_HAS_QUICK_EXIT
 #      define _LIBCPP_HAS_TIMESPEC_GET
 #    endif
+#  elif defined(_LIBCPP_MSVCRT)
+     // Using Microsoft's C Runtime library, not MinGW
+#    define _LIBCPP_HAS_TIMESPEC_GET
 #  elif defined(__APPLE__)
      // timespec_get and aligned_alloc were introduced in macOS 10.15 and
      // aligned releases
-#    if (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101500 || \
-         __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 130000 || \
-         __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ >= 130000 || \
-         __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ >= 60000)
+#    if ((defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101500) || \
+         (defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 130000) || \
+         (defined(__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__ >= 130000) || \
+         (defined(__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__ >= 60000))
 #      define _LIBCPP_HAS_ALIGNED_ALLOC
 #      define _LIBCPP_HAS_TIMESPEC_GET
 #    endif
@@ -402,7 +409,7 @@
 
 #ifndef _LIBCPP_CXX03_LANG
 # define _LIBCPP_ALIGNOF(_Tp) alignof(_Tp)
-#elif defined(_LIBCPP_COMPILER_CLANG)
+#elif defined(_LIBCPP_COMPILER_CLANG_BASED)
 # define _LIBCPP_ALIGNOF(_Tp) _Alignof(_Tp)
 #else
 # error "We don't know a correct way to implement alignof(T) in C++03 outside of Clang"
@@ -410,7 +417,7 @@
 
 #define _LIBCPP_PREFERRED_ALIGNOF(_Tp) __alignof(_Tp)
 
-#if defined(_LIBCPP_COMPILER_CLANG)
+#if defined(_LIBCPP_COMPILER_CLANG_BASED)
 
 #if defined(_LIBCPP_ALTERNATE_STRING_LAYOUT)
 #  error _LIBCPP_ALTERNATE_STRING_LAYOUT is deprecated, please use _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT instead
@@ -484,12 +491,12 @@ typedef __char32_t char32_t;
 #define _LIBCPP_HAS_NO_NOEXCEPT
 #endif
 
-#if !defined(_LIBCPP_HAS_NO_ASAN) && !__has_feature(address_sanitizer)
+#if !__has_feature(address_sanitizer)
 #define _LIBCPP_HAS_NO_ASAN
 #endif
 
 // Allow for build-time disabling of unsigned integer sanitization
-#if !defined(_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK) && __has_attribute(no_sanitize)
+#if __has_attribute(no_sanitize)
 #define _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK __attribute__((__no_sanitize__("unsigned-integer-overflow")))
 #endif
 
@@ -508,8 +515,8 @@ typedef __char32_t char32_t;
 #define _LIBCPP_ALWAYS_INLINE __attribute__ ((__always_inline__))
 
 // Literal operators ""d and ""y are supported starting with LLVM Clang 8 and AppleClang 10.0.1
-#if (defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER < 800) || \
-    (defined(__apple_build_version__) && __apple_build_version__ < 10010000)
+#if (defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER < 800) ||                 \
+    (defined(_LIBCPP_APPLE_CLANG_VER) && _LIBCPP_APPLE_CLANG_VER < 1001)
 #define _LIBCPP_HAS_NO_CXX20_CHRONO_LITERALS
 #endif
 
@@ -522,7 +529,7 @@ typedef __char32_t char32_t;
 
 #define _LIBCPP_NORETURN __attribute__((noreturn))
 
-#if !__EXCEPTIONS
+#if !defined(__EXCEPTIONS)
 #  define _LIBCPP_NO_EXCEPTIONS
 #endif
 
@@ -536,7 +543,7 @@ typedef __char32_t char32_t;
 #define _LIBCPP_HAS_NO_VARIABLE_TEMPLATES
 #endif
 
-#if !defined(_LIBCPP_HAS_NO_ASAN) && !defined(__SANITIZE_ADDRESS__)
+#if !defined(__SANITIZE_ADDRESS__)
 #define _LIBCPP_HAS_NO_ASAN
 #endif
 
@@ -640,6 +647,7 @@ typedef __char32_t char32_t;
 #define _LIBCPP_HIDDEN
 #define _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
 #define _LIBCPP_TEMPLATE_VIS
+#define _LIBCPP_TEMPLATE_DATA_VIS
 #define _LIBCPP_ENUM_VIS
 
 #endif // defined(_LIBCPP_OBJECT_FORMAT_COFF)
@@ -689,6 +697,14 @@ typedef __char32_t char32_t;
 #  endif
 #endif
 
+#ifndef _LIBCPP_TEMPLATE_DATA_VIS
+#  if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS)
+#    define _LIBCPP_TEMPLATE_DATA_VIS __attribute__ ((__visibility__("default")))
+#  else
+#    define _LIBCPP_TEMPLATE_DATA_VIS
+#  endif
+#endif
+
 #ifndef _LIBCPP_EXPORTED_FROM_ABI
 #  if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS)
 #    define _LIBCPP_EXPORTED_FROM_ABI __attribute__((__visibility__("default")))
@@ -792,10 +808,8 @@ _LIBCPP_BEGIN_NAMESPACE_STD _LIBCPP_END_NAMESPACE_STD
 
 #define _VSTD_FS _VSTD::__fs::filesystem
 
-#ifndef _LIBCPP_PREFERRED_OVERLOAD
-#  if __has_attribute(__enable_if__)
-#    define _LIBCPP_PREFERRED_OVERLOAD __attribute__ ((__enable_if__(true, "")))
-#  endif
+#if __has_attribute(__enable_if__)
+#   define _LIBCPP_PREFERRED_OVERLOAD __attribute__ ((__enable_if__(true, "")))
 #endif
 
 #ifndef _LIBCPP_HAS_NO_NOEXCEPT
@@ -809,7 +823,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD _LIBCPP_END_NAMESPACE_STD
 #ifdef _LIBCPP_HAS_NO_UNICODE_CHARS
 typedef unsigned short char16_t;
 typedef unsigned int   char32_t;
-#endif  // _LIBCPP_HAS_NO_UNICODE_CHARS
+#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
 
 #ifndef __SIZEOF_INT128__
 #define _LIBCPP_HAS_NO_INT128
@@ -818,7 +832,7 @@ typedef unsigned int   char32_t;
 #ifdef _LIBCPP_CXX03_LANG
 # define static_assert(...) _Static_assert(__VA_ARGS__)
 # define decltype(...) __decltype(__VA_ARGS__)
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 #ifdef _LIBCPP_CXX03_LANG
 #  define _LIBCPP_CONSTEXPR
@@ -832,6 +846,14 @@ typedef unsigned int   char32_t;
 #  define _LIBCPP_CONSTEVAL consteval
 #endif
 
+#if !defined(__cpp_concepts) || __cpp_concepts < 201907L
+#define _LIBCPP_HAS_NO_CONCEPTS
+#endif
+
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_HAS_NO_CONCEPTS)
+#define _LIBCPP_HAS_NO_RANGES
+#endif
+
 #ifdef _LIBCPP_CXX03_LANG
 #  define _LIBCPP_DEFAULT {}
 #else
@@ -850,11 +872,10 @@ typedef unsigned int   char32_t;
 #  define _LIBCPP_NOALIAS
 #endif
 
-#if __has_feature(cxx_explicit_conversions) || defined(__IBMCPP__) || \
-    (!defined(_LIBCPP_CXX03_LANG) && defined(__GNUC__)) // All supported GCC versions
-#  define _LIBCPP_EXPLICIT explicit
+#if __has_attribute(using_if_exists)
+# define _LIBCPP_USING_IF_EXISTS __attribute__((using_if_exists))
 #else
-#  define _LIBCPP_EXPLICIT
+# define _LIBCPP_USING_IF_EXISTS
 #endif
 
 #ifdef _LIBCPP_HAS_NO_STRONG_ENUMS
@@ -868,7 +889,7 @@ typedef unsigned int   char32_t;
 #else  // _LIBCPP_HAS_NO_STRONG_ENUMS
 #  define _LIBCPP_DECLARE_STRONG_ENUM(x) enum class _LIBCPP_ENUM_VIS x
 #  define _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(x)
-#endif  // _LIBCPP_HAS_NO_STRONG_ENUMS
+#endif // _LIBCPP_HAS_NO_STRONG_ENUMS
 
 // _LIBCPP_DEBUG potential values:
 //  - undefined: No assertions. This is the default.
@@ -884,33 +905,25 @@ typedef unsigned int   char32_t;
 # error Supported values for _LIBCPP_DEBUG are 0 and 1
 #endif
 
-// _LIBCPP_DEBUG_LEVEL is always defined to one of [0, 1, 2] at this point
-#if _LIBCPP_DEBUG_LEVEL >= 1 && !defined(_LIBCPP_DISABLE_EXTERN_TEMPLATE)
-# define _LIBCPP_EXTERN_TEMPLATE(...)
-#endif
-
-#ifdef _LIBCPP_DISABLE_EXTERN_TEMPLATE
-# define _LIBCPP_EXTERN_TEMPLATE(...)
-# define _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(...)
-#endif
-
-#ifndef _LIBCPP_EXTERN_TEMPLATE
-#define _LIBCPP_EXTERN_TEMPLATE(...) extern template __VA_ARGS__;
-#endif
-
-// When the Debug mode is enabled, we disable extern declarations because we
-// don't want to use the functions compiled in the library, which might not
-// have had the debug mode enabled when built. However, some extern declarations
-// need to be used, because code correctness depends on it (several instances
-// in the <locale>). Those special declarations are declared with
-// _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE, which is enabled even
-// when the debug mode is enabled.
-#ifndef _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE
-# define _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(...) extern template __VA_ARGS__;
-#endif
-
-#ifndef _LIBCPP_EXTERN_TEMPLATE_DEFINE
-#define _LIBCPP_EXTERN_TEMPLATE_DEFINE(...) template __VA_ARGS__;
+// Libc++ allows disabling extern template instantiation declarations by
+// means of users defining _LIBCPP_DISABLE_EXTERN_TEMPLATE.
+//
+// Furthermore, when the Debug mode is enabled, we disable extern declarations
+// when building user code because we don't want to use the functions compiled
+// in the library, which might not have had the debug mode enabled when built.
+// However, some extern declarations need to be used, because code correctness
+// depends on it (several instances in <locale>). Those special declarations
+// are declared with _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE, which is enabled
+// even when the debug mode is enabled.
+#if defined(_LIBCPP_DISABLE_EXTERN_TEMPLATE)
+#   define _LIBCPP_EXTERN_TEMPLATE(...) /* nothing */
+#   define _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(...) /* nothing */
+#elif _LIBCPP_DEBUG_LEVEL >= 1 && !defined(_LIBCPP_BUILDING_LIBRARY)
+#   define _LIBCPP_EXTERN_TEMPLATE(...) /* nothing */
+#   define _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(...) extern template __VA_ARGS__;
+#else
+#   define _LIBCPP_EXTERN_TEMPLATE(...) extern template __VA_ARGS__;
+#   define _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(...) extern template __VA_ARGS__;
 #endif
 
 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(_LIBCPP_MSVCRT_LIKE) || \
@@ -918,13 +931,6 @@ typedef unsigned int   char32_t;
 #define _LIBCPP_LOCALE__L_EXTENSIONS 1
 #endif
 
-#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
-// Most unix variants have catopen.  These are the specific ones that don't.
-#  if !defined(__BIONIC__) && !defined(_NEWLIB_VERSION)
-#    define _LIBCPP_HAS_CATOPEN 1
-#  endif
-#endif
-
 #ifdef __FreeBSD__
 #define _DECLARE_C99_LDBL_MATH 1
 #endif
@@ -948,9 +954,8 @@ typedef unsigned int   char32_t;
 #  endif
 #endif // defined(__APPLE__)
 
-#if !defined(_LIBCPP_HAS_NO_ALIGNED_ALLOCATION) && \
-    (defined(_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION) || \
-    (!defined(__cpp_aligned_new) || __cpp_aligned_new < 201606))
+#if defined(_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION) || \
+    (!defined(__cpp_aligned_new) || __cpp_aligned_new < 201606)
 #  define _LIBCPP_HAS_NO_ALIGNED_ALLOCATION
 #endif
 
@@ -963,7 +968,7 @@ typedef unsigned int   char32_t;
 #endif
 
 #if _LIBCPP_STD_VER <= 17 || !defined(__cpp_char8_t)
-#define _LIBCPP_NO_HAS_CHAR8_T
+#define _LIBCPP_HAS_NO_CHAR8_T
 #endif
 
 // Deprecation macros.
@@ -1006,24 +1011,23 @@ typedef unsigned int   char32_t;
 #  define _LIBCPP_DEPRECATED_IN_CXX20
 #endif
 
-#if !defined(_LIBCPP_NO_HAS_CHAR8_T)
+#if !defined(_LIBCPP_HAS_NO_CHAR8_T)
 #  define _LIBCPP_DEPRECATED_WITH_CHAR8_T _LIBCPP_DEPRECATED
 #else
 #  define _LIBCPP_DEPRECATED_WITH_CHAR8_T
 #endif
 
 // Macros to enter and leave a state where deprecation warnings are suppressed.
-#if !defined(_LIBCPP_SUPPRESS_DEPRECATED_PUSH) && \
-    (defined(_LIBCPP_COMPILER_CLANG) || defined(_LIBCPP_COMPILER_GCC))
-#  define _LIBCPP_SUPPRESS_DEPRECATED_PUSH \
-    _Pragma("GCC diagnostic push") \
-    _Pragma("GCC diagnostic ignored \"-Wdeprecated\"")
-#  define _LIBCPP_SUPPRESS_DEPRECATED_POP \
-    _Pragma("GCC diagnostic pop")
-#endif
-#if !defined(_LIBCPP_SUPPRESS_DEPRECATED_PUSH)
-#  define _LIBCPP_SUPPRESS_DEPRECATED_PUSH
-#  define _LIBCPP_SUPPRESS_DEPRECATED_POP
+#if defined(_LIBCPP_COMPILER_CLANG_BASED) || defined(_LIBCPP_COMPILER_GCC)
+#   define _LIBCPP_SUPPRESS_DEPRECATED_PUSH \
+        _Pragma("GCC diagnostic push") \
+        _Pragma("GCC diagnostic ignored \"-Wdeprecated\"") \
+        _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
+#   define _LIBCPP_SUPPRESS_DEPRECATED_POP \
+        _Pragma("GCC diagnostic pop")
+#else
+#   define _LIBCPP_SUPPRESS_DEPRECATED_PUSH
+#   define _LIBCPP_SUPPRESS_DEPRECATED_POP
 #endif
 
 #if _LIBCPP_STD_VER <= 11
@@ -1054,7 +1058,7 @@ typedef unsigned int   char32_t;
 // NODISCARD macros to the correct attribute.
 #if __has_cpp_attribute(nodiscard) || defined(_LIBCPP_COMPILER_MSVC)
 #  define _LIBCPP_NODISCARD_ATTRIBUTE [[nodiscard]]
-#elif defined(_LIBCPP_COMPILER_CLANG) && !defined(_LIBCPP_CXX03_LANG)
+#elif defined(_LIBCPP_COMPILER_CLANG_BASED) && !defined(_LIBCPP_CXX03_LANG)
 #  define _LIBCPP_NODISCARD_ATTRIBUTE [[clang::warn_unused_result]]
 #else
 // We can't use GCC's [[gnu::warn_unused_result]] and
@@ -1084,12 +1088,10 @@ typedef unsigned int   char32_t;
 #  define _LIBCPP_INLINE_VAR
 #endif
 
-#ifndef _LIBCPP_CONSTEXPR_IF_NODEBUG
 #if defined(_LIBCPP_DEBUG) || defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR)
-#define _LIBCPP_CONSTEXPR_IF_NODEBUG
+#   define _LIBCPP_CONSTEXPR_IF_NODEBUG
 #else
-#define _LIBCPP_CONSTEXPR_IF_NODEBUG constexpr
-#endif
+#   define _LIBCPP_CONSTEXPR_IF_NODEBUG constexpr
 #endif
 
 #if __has_attribute(no_destroy)
@@ -1104,7 +1106,7 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
 #endif
 
 // Try to find out if RTTI is disabled.
-#if defined(_LIBCPP_COMPILER_CLANG) && !__has_feature(cxx_rtti)
+#if defined(_LIBCPP_COMPILER_CLANG_BASED) && !__has_feature(cxx_rtti)
 #  define _LIBCPP_NO_RTTI
 #elif defined(__GNUC__) && !defined(__GXX_RTTI)
 #  define _LIBCPP_NO_RTTI
@@ -1132,6 +1134,7 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
       defined(__CloudABI__) || \
       defined(__sun__) || \
       defined(__MVS__) || \
+      defined(_AIX) || \
       (defined(__MINGW32__) && __has_include(<pthread.h>))
 #    define _LIBCPP_HAS_THREAD_API_PTHREAD
 #  elif defined(__Fuchsia__)
@@ -1218,12 +1221,10 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
 #endif
 
 // Some systems do not provide gets() in their C library, for security reasons.
-#ifndef _LIBCPP_C_HAS_NO_GETS
-#  if defined(_LIBCPP_MSVCRT) || \
-      (defined(__FreeBSD_version) && __FreeBSD_version >= 1300043) || \
-      defined(__OpenBSD__)
-#    define _LIBCPP_C_HAS_NO_GETS
-#  endif
+#if defined(_LIBCPP_MSVCRT) || \
+    (defined(__FreeBSD_version) && __FreeBSD_version >= 1300043) || \
+    defined(__OpenBSD__)
+#   define _LIBCPP_C_HAS_NO_GETS
 #endif
 
 #if defined(__BIONIC__) || defined(__CloudABI__) || defined(__NuttX__) ||      \
@@ -1273,13 +1274,11 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
 #  endif
 #endif
 
-#ifndef _LIBCPP_THREAD_SAFETY_ANNOTATION
-#  ifdef _LIBCPP_HAS_THREAD_SAFETY_ANNOTATIONS
-#    define _LIBCPP_THREAD_SAFETY_ANNOTATION(x) __attribute__((x))
-#  else
-#    define _LIBCPP_THREAD_SAFETY_ANNOTATION(x)
-#  endif
-#endif  // _LIBCPP_THREAD_SAFETY_ANNOTATION
+#ifdef _LIBCPP_HAS_THREAD_SAFETY_ANNOTATIONS
+#   define _LIBCPP_THREAD_SAFETY_ANNOTATION(x) __attribute__((x))
+#else
+#   define _LIBCPP_THREAD_SAFETY_ANNOTATION(x)
+#endif
 
 #if __has_attribute(require_constant_initialization)
 #  define _LIBCPP_SAFE_STATIC __attribute__((__require_constant_initialization__))
@@ -1295,12 +1294,6 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
 #define _LIBCPP_HAS_NO_BUILTIN_IS_CONSTANT_EVALUATED
 #endif
 
-#if !defined(_LIBCPP_HAS_NO_OFF_T_FUNCTIONS)
-#  if defined(_LIBCPP_MSVCRT) || defined(_NEWLIB_VERSION)
-#    define _LIBCPP_HAS_NO_OFF_T_FUNCTIONS
-#  endif
-#endif
-
 #if __has_attribute(diagnose_if) && !defined(_LIBCPP_DISABLE_ADDITIONAL_DIAGNOSTICS)
 #  define _LIBCPP_DIAGNOSE_WARNING(...) \
      __attribute__((diagnose_if(__VA_ARGS__, "warning")))
@@ -1328,14 +1321,17 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
 #define _LIBCPP_NODEBUG
 #endif
 
-#ifndef _LIBCPP_NODEBUG_TYPE
-#if __has_attribute(__nodebug__) && \
-    (defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER >= 900)
-#define _LIBCPP_NODEBUG_TYPE __attribute__((nodebug))
+#if __has_attribute(__nodebug__) && (defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER >= 900)
+#   define _LIBCPP_NODEBUG_TYPE __attribute__((nodebug))
 #else
-#define _LIBCPP_NODEBUG_TYPE
+#   define _LIBCPP_NODEBUG_TYPE
+#endif
+
+#if __has_attribute(__standalone_debug__)
+#define _LIBCPP_STANDALONE_DEBUG __attribute__((__standalone_debug__))
+#else
+#define _LIBCPP_STANDALONE_DEBUG
 #endif
-#endif // !defined(_LIBCPP_NODEBUG_TYPE)
 
 #if __has_attribute(__preferred_name__)
 #define _LIBCPP_PREFERRED_NAME(x) __attribute__((__preferred_name__(x)))
@@ -1352,11 +1348,19 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
 
 #if defined(_LIBCPP_ENABLE_CXX17_REMOVED_FEATURES)
 #define _LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR
-#define _LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS
-#define _LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE
 #define _LIBCPP_ENABLE_CXX17_REMOVED_BINDERS
+#define _LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE
+#define _LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS
 #endif // _LIBCPP_ENABLE_CXX17_REMOVED_FEATURES
 
+#if defined(_LIBCPP_ENABLE_CXX20_REMOVED_FEATURES)
+#define _LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS
+#define _LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS
+#define _LIBCPP_ENABLE_CXX20_REMOVED_NEGATORS
+#define _LIBCPP_ENABLE_CXX20_REMOVED_RAW_STORAGE_ITERATOR
+#define _LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS
+#endif // _LIBCPP_ENABLE_CXX20_REMOVED_FEATURES
+
 #if !defined(__cpp_deduction_guides) || __cpp_deduction_guides < 201611
 #define _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 #endif
@@ -1405,7 +1409,7 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
 
 #ifndef _LIBCPP_NO_AUTO_LINK
 #  if defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_BUILDING_LIBRARY)
-#    if defined(_DLL)
+#    if !defined(_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS)
 #      pragma comment(lib, "c++.lib")
 #    else
 #      pragma comment(lib, "libc++.lib")
@@ -1413,8 +1417,6 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
 #  endif // defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_BUILDING_LIBRARY)
 #endif // _LIBCPP_NO_AUTO_LINK
 
-#define _LIBCPP_UNUSED_VAR(x) ((void)(x))
-
 // Configures the fopen close-on-exec mode character, if any. This string will
 // be appended to any mode string used by fstream for fopen/fdopen.
 //
@@ -1445,6 +1447,13 @@ extern "C" _LIBCPP_FUNC_VIS void __sanitizer_annotate_contiguous_container(
 # define _LIBCPP_INIT_PRIORITY_MAX
 #endif
 
+#if defined(__GNUC__) || defined(__clang__)
+#define _LIBCPP_FORMAT_PRINTF(a, b)                                            \
+  __attribute__((__format__(__printf__, a, b)))
+#else
+#define _LIBCPP_FORMAT_PRINTF(a, b)
+#endif
+
 #endif // __cplusplus
 
 #endif // _LIBCPP_CONFIG
lib/libcxx/include/__config_site.in
@@ -1,40 +0,0 @@
-//===----------------------------------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _LIBCPP_CONFIG_SITE
-#define _LIBCPP_CONFIG_SITE
-
-#cmakedefine _LIBCPP_ABI_VERSION @_LIBCPP_ABI_VERSION@
-#cmakedefine _LIBCPP_ABI_UNSTABLE
-#cmakedefine _LIBCPP_ABI_FORCE_ITANIUM
-#cmakedefine _LIBCPP_ABI_FORCE_MICROSOFT
-#cmakedefine _LIBCPP_HIDE_FROM_ABI_PER_TU_BY_DEFAULT
-#cmakedefine _LIBCPP_HAS_NO_GLOBAL_FILESYSTEM_NAMESPACE
-#cmakedefine _LIBCPP_HAS_NO_STDIN
-#cmakedefine _LIBCPP_HAS_NO_STDOUT
-#cmakedefine _LIBCPP_HAS_NO_THREADS
-#cmakedefine _LIBCPP_HAS_NO_MONOTONIC_CLOCK
-#cmakedefine _LIBCPP_HAS_NO_THREAD_UNSAFE_C_FUNCTIONS
-#cmakedefine _LIBCPP_HAS_MUSL_LIBC
-#cmakedefine _LIBCPP_HAS_THREAD_API_PTHREAD
-#cmakedefine _LIBCPP_HAS_THREAD_API_EXTERNAL
-#cmakedefine _LIBCPP_HAS_THREAD_API_WIN32
-#cmakedefine _LIBCPP_HAS_THREAD_LIBRARY_EXTERNAL
-#cmakedefine _LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS
-#cmakedefine _LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS
-#cmakedefine _LIBCPP_NO_VCRUNTIME
-#cmakedefine _LIBCPP_TYPEINFO_COMPARISON_IMPLEMENTATION @_LIBCPP_TYPEINFO_COMPARISON_IMPLEMENTATION@
-#cmakedefine _LIBCPP_ABI_NAMESPACE @_LIBCPP_ABI_NAMESPACE@
-#cmakedefine _LIBCPP_HAS_NO_FILESYSTEM_LIBRARY
-#cmakedefine _LIBCPP_HAS_PARALLEL_ALGORITHMS
-#cmakedefine _LIBCPP_HAS_NO_RANDOM_DEVICE
-#cmakedefine _LIBCPP_HAS_NO_LOCALIZATION
-
-@_LIBCPP_ABI_DEFINES@
-
-#endif // _LIBCPP_CONFIG_SITE
lib/libcxx/include/__debug
@@ -270,4 +270,4 @@ _LIBCPP_FUNC_VIS const __libcpp_db* __get_const_db();
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_DEBUG_H
+#endif // _LIBCPP_DEBUG_H
lib/libcxx/include/__errc
@@ -214,4 +214,4 @@ _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(errc)
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP___ERRC
+#endif // _LIBCPP___ERRC
lib/libcxx/include/__function_like.h
@@ -0,0 +1,56 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP___ITERATOR_FUNCTION_LIKE_H
+#define _LIBCPP___ITERATOR_FUNCTION_LIKE_H
+
+#include <__config>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+// Per [range.iter.ops.general] and [algorithms.requirements], functions in namespace std::ranges
+// can't be found by ADL and inhibit ADL when found by unqualified lookup. The easiest way to
+// facilitate this is to use function objects.
+//
+// Since these are still standard library functions, we use `__function_like` to eliminate most of
+// the properties that function objects get by default (e.g. semiregularity, addressability), to
+// limit the surface area of the unintended public interface, so as to curb the effect of Hyrum's
+// law.
+struct __function_like {
+  __function_like() = delete;
+  __function_like(__function_like const&) = delete;
+  __function_like& operator=(__function_like const&) = delete;
+
+  void operator&() const = delete;
+
+  struct __tag { };
+
+protected:
+  constexpr explicit __function_like(__tag) noexcept {}
+  ~__function_like() = default;
+};
+} // namespace ranges
+
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___ITERATOR_FUNCTION_LIKE_H
lib/libcxx/include/__functional_base
@@ -11,645 +11,22 @@
 #define _LIBCPP_FUNCTIONAL_BASE
 
 #include <__config>
-#include <type_traits>
-#include <typeinfo>
+#include <__functional/binary_function.h>
+#include <__functional/invoke.h>
+#include <__functional/operations.h>
+#include <__functional/reference_wrapper.h>
+#include <__functional/unary_function.h>
+#include <__functional/weak_result_type.h>
+#include <__memory/allocator_arg_t.h>
+#include <__memory/uses_allocator.h>
 #include <exception>
 #include <new>
+#include <type_traits>
+#include <typeinfo>
 #include <utility>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
 
-_LIBCPP_BEGIN_NAMESPACE_STD
-
-template <class _Arg1, class _Arg2, class _Result>
-struct _LIBCPP_TEMPLATE_VIS binary_function
-{
-    typedef _Arg1   first_argument_type;
-    typedef _Arg2   second_argument_type;
-    typedef _Result result_type;
-};
-
-template <class _Tp>
-struct __has_result_type
-{
-private:
-    struct __two {char __lx; char __lxx;};
-    template <class _Up> static __two __test(...);
-    template <class _Up> static char __test(typename _Up::result_type* = 0);
-public:
-    static const bool value = sizeof(__test<_Tp>(0)) == 1;
-};
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS less : binary_function<_Tp, _Tp, bool>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x < __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS less<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) < _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-// __weak_result_type
-
-template <class _Tp>
-struct __derives_from_unary_function
-{
-private:
-    struct __two {char __lx; char __lxx;};
-    static __two __test(...);
-    template <class _Ap, class _Rp>
-        static unary_function<_Ap, _Rp>
-        __test(const volatile unary_function<_Ap, _Rp>*);
-public:
-    static const bool value = !is_same<decltype(__test((_Tp*)0)), __two>::value;
-    typedef decltype(__test((_Tp*)0)) type;
-};
-
-template <class _Tp>
-struct __derives_from_binary_function
-{
-private:
-    struct __two {char __lx; char __lxx;};
-    static __two __test(...);
-    template <class _A1, class _A2, class _Rp>
-        static binary_function<_A1, _A2, _Rp>
-        __test(const volatile binary_function<_A1, _A2, _Rp>*);
-public:
-    static const bool value = !is_same<decltype(__test((_Tp*)0)), __two>::value;
-    typedef decltype(__test((_Tp*)0)) type;
-};
-
-template <class _Tp, bool = __derives_from_unary_function<_Tp>::value>
-struct __maybe_derive_from_unary_function  // bool is true
-    : public __derives_from_unary_function<_Tp>::type
-{
-};
-
-template <class _Tp>
-struct __maybe_derive_from_unary_function<_Tp, false>
-{
-};
-
-template <class _Tp, bool = __derives_from_binary_function<_Tp>::value>
-struct __maybe_derive_from_binary_function  // bool is true
-    : public __derives_from_binary_function<_Tp>::type
-{
-};
-
-template <class _Tp>
-struct __maybe_derive_from_binary_function<_Tp, false>
-{
-};
-
-template <class _Tp, bool = __has_result_type<_Tp>::value>
-struct __weak_result_type_imp // bool is true
-    : public __maybe_derive_from_unary_function<_Tp>,
-      public __maybe_derive_from_binary_function<_Tp>
-{
-    typedef _LIBCPP_NODEBUG_TYPE typename _Tp::result_type result_type;
-};
-
-template <class _Tp>
-struct __weak_result_type_imp<_Tp, false>
-    : public __maybe_derive_from_unary_function<_Tp>,
-      public __maybe_derive_from_binary_function<_Tp>
-{
-};
-
-template <class _Tp>
-struct __weak_result_type
-    : public __weak_result_type_imp<_Tp>
-{
-};
-
-// 0 argument case
-
-template <class _Rp>
-struct __weak_result_type<_Rp ()>
-{
-    typedef _LIBCPP_NODEBUG_TYPE  _Rp result_type;
-};
-
-template <class _Rp>
-struct __weak_result_type<_Rp (&)()>
-{
-    typedef _LIBCPP_NODEBUG_TYPE  _Rp result_type;
-};
-
-template <class _Rp>
-struct __weak_result_type<_Rp (*)()>
-{
-    typedef _LIBCPP_NODEBUG_TYPE  _Rp result_type;
-};
-
-// 1 argument case
-
-template <class _Rp, class _A1>
-struct __weak_result_type<_Rp (_A1)>
-    : public unary_function<_A1, _Rp>
-{
-};
-
-template <class _Rp, class _A1>
-struct __weak_result_type<_Rp (&)(_A1)>
-    : public unary_function<_A1, _Rp>
-{
-};
-
-template <class _Rp, class _A1>
-struct __weak_result_type<_Rp (*)(_A1)>
-    : public unary_function<_A1, _Rp>
-{
-};
-
-template <class _Rp, class _Cp>
-struct __weak_result_type<_Rp (_Cp::*)()>
-    : public unary_function<_Cp*, _Rp>
-{
-};
-
-template <class _Rp, class _Cp>
-struct __weak_result_type<_Rp (_Cp::*)() const>
-    : public unary_function<const _Cp*, _Rp>
-{
-};
-
-template <class _Rp, class _Cp>
-struct __weak_result_type<_Rp (_Cp::*)() volatile>
-    : public unary_function<volatile _Cp*, _Rp>
-{
-};
-
-template <class _Rp, class _Cp>
-struct __weak_result_type<_Rp (_Cp::*)() const volatile>
-    : public unary_function<const volatile _Cp*, _Rp>
-{
-};
-
-// 2 argument case
-
-template <class _Rp, class _A1, class _A2>
-struct __weak_result_type<_Rp (_A1, _A2)>
-    : public binary_function<_A1, _A2, _Rp>
-{
-};
-
-template <class _Rp, class _A1, class _A2>
-struct __weak_result_type<_Rp (*)(_A1, _A2)>
-    : public binary_function<_A1, _A2, _Rp>
-{
-};
-
-template <class _Rp, class _A1, class _A2>
-struct __weak_result_type<_Rp (&)(_A1, _A2)>
-    : public binary_function<_A1, _A2, _Rp>
-{
-};
-
-template <class _Rp, class _Cp, class _A1>
-struct __weak_result_type<_Rp (_Cp::*)(_A1)>
-    : public binary_function<_Cp*, _A1, _Rp>
-{
-};
-
-template <class _Rp, class _Cp, class _A1>
-struct __weak_result_type<_Rp (_Cp::*)(_A1) const>
-    : public binary_function<const _Cp*, _A1, _Rp>
-{
-};
-
-template <class _Rp, class _Cp, class _A1>
-struct __weak_result_type<_Rp (_Cp::*)(_A1) volatile>
-    : public binary_function<volatile _Cp*, _A1, _Rp>
-{
-};
-
-template <class _Rp, class _Cp, class _A1>
-struct __weak_result_type<_Rp (_Cp::*)(_A1) const volatile>
-    : public binary_function<const volatile _Cp*, _A1, _Rp>
-{
-};
-
-
-#ifndef _LIBCPP_CXX03_LANG
-// 3 or more arguments
-
-template <class _Rp, class _A1, class _A2, class _A3, class ..._A4>
-struct __weak_result_type<_Rp (_A1, _A2, _A3, _A4...)>
-{
-    typedef _Rp result_type;
-};
-
-template <class _Rp, class _A1, class _A2, class _A3, class ..._A4>
-struct __weak_result_type<_Rp (&)(_A1, _A2, _A3, _A4...)>
-{
-    typedef _Rp result_type;
-};
-
-template <class _Rp, class _A1, class _A2, class _A3, class ..._A4>
-struct __weak_result_type<_Rp (*)(_A1, _A2, _A3, _A4...)>
-{
-    typedef _Rp result_type;
-};
-
-template <class _Rp, class _Cp, class _A1, class _A2, class ..._A3>
-struct __weak_result_type<_Rp (_Cp::*)(_A1, _A2, _A3...)>
-{
-    typedef _Rp result_type;
-};
-
-template <class _Rp, class _Cp, class _A1, class _A2, class ..._A3>
-struct __weak_result_type<_Rp (_Cp::*)(_A1, _A2, _A3...) const>
-{
-    typedef _Rp result_type;
-};
-
-template <class _Rp, class _Cp, class _A1, class _A2, class ..._A3>
-struct __weak_result_type<_Rp (_Cp::*)(_A1, _A2, _A3...) volatile>
-{
-    typedef _Rp result_type;
-};
-
-template <class _Rp, class _Cp, class _A1, class _A2, class ..._A3>
-struct __weak_result_type<_Rp (_Cp::*)(_A1, _A2, _A3...) const volatile>
-{
-    typedef _Rp result_type;
-};
-
-template <class _Tp, class ..._Args>
-struct __invoke_return
-{
-    typedef decltype(_VSTD::__invoke(declval<_Tp>(), declval<_Args>()...)) type;
-};
-
-#else // defined(_LIBCPP_CXX03_LANG)
-
-#include <__functional_base_03>
-
-#endif  // !defined(_LIBCPP_CXX03_LANG)
-
-
-template <class _Ret, bool = is_void<_Ret>::value>
-struct __invoke_void_return_wrapper
-{
-#ifndef _LIBCPP_CXX03_LANG
-    template <class ..._Args>
-    static _Ret __call(_Args&&... __args) {
-        return _VSTD::__invoke(_VSTD::forward<_Args>(__args)...);
-    }
-#else
-    template <class _Fn>
-    static _Ret __call(_Fn __f) {
-        return _VSTD::__invoke(__f);
-    }
-
-    template <class _Fn, class _A0>
-    static _Ret __call(_Fn __f, _A0& __a0) {
-        return _VSTD::__invoke(__f, __a0);
-    }
-
-    template <class _Fn, class _A0, class _A1>
-    static _Ret __call(_Fn __f, _A0& __a0, _A1& __a1) {
-        return _VSTD::__invoke(__f, __a0, __a1);
-    }
-
-    template <class _Fn, class _A0, class _A1, class _A2>
-    static _Ret __call(_Fn __f, _A0& __a0, _A1& __a1, _A2& __a2){
-        return _VSTD::__invoke(__f, __a0, __a1, __a2);
-    }
-#endif
-};
-
-template <class _Ret>
-struct __invoke_void_return_wrapper<_Ret, true>
-{
-#ifndef _LIBCPP_CXX03_LANG
-    template <class ..._Args>
-    static void __call(_Args&&... __args) {
-        _VSTD::__invoke(_VSTD::forward<_Args>(__args)...);
-    }
-#else
-    template <class _Fn>
-    static void __call(_Fn __f) {
-        _VSTD::__invoke(__f);
-    }
-
-    template <class _Fn, class _A0>
-    static void __call(_Fn __f, _A0& __a0) {
-        _VSTD::__invoke(__f, __a0);
-    }
-
-    template <class _Fn, class _A0, class _A1>
-    static void __call(_Fn __f, _A0& __a0, _A1& __a1) {
-        _VSTD::__invoke(__f, __a0, __a1);
-    }
-
-    template <class _Fn, class _A0, class _A1, class _A2>
-    static void __call(_Fn __f, _A0& __a0, _A1& __a1, _A2& __a2) {
-        _VSTD::__invoke(__f, __a0, __a1, __a2);
-    }
-#endif
-};
-
-template <class _Tp>
-class _LIBCPP_TEMPLATE_VIS reference_wrapper
-    : public __weak_result_type<_Tp>
-{
-public:
-    // types
-    typedef _Tp type;
-private:
-    type* __f_;
-
-public:
-    // construct/copy/destroy
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    reference_wrapper(type& __f) _NOEXCEPT
-        : __f_(_VSTD::addressof(__f)) {}
-#ifndef _LIBCPP_CXX03_LANG
-    private: reference_wrapper(type&&); public: // = delete; // do not bind to temps
-#endif
-
-    // access
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    operator type&() const _NOEXCEPT {return *__f_;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    type& get() const _NOEXCEPT {return *__f_;}
-
-#ifndef _LIBCPP_CXX03_LANG
-    // invoke
-    template <class... _ArgTypes>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    typename __invoke_of<type&, _ArgTypes...>::type
-    operator() (_ArgTypes&&... __args) const {
-        return _VSTD::__invoke(get(), _VSTD::forward<_ArgTypes>(__args)...);
-    }
-#else
-
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return<type>::type
-    operator() () const {
-        return _VSTD::__invoke(get());
-    }
-
-    template <class _A0>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return0<type, _A0>::type
-    operator() (_A0& __a0) const {
-        return _VSTD::__invoke(get(), __a0);
-    }
-
-    template <class _A0>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return0<type, _A0 const>::type
-    operator() (_A0 const& __a0) const {
-        return _VSTD::__invoke(get(), __a0);
-    }
-
-    template <class _A0, class _A1>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return1<type, _A0, _A1>::type
-    operator() (_A0& __a0, _A1& __a1) const {
-        return _VSTD::__invoke(get(), __a0, __a1);
-    }
-
-    template <class _A0, class _A1>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return1<type, _A0 const, _A1>::type
-    operator() (_A0 const& __a0, _A1& __a1) const {
-        return _VSTD::__invoke(get(), __a0, __a1);
-    }
-
-    template <class _A0, class _A1>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return1<type, _A0, _A1 const>::type
-    operator() (_A0& __a0, _A1 const& __a1) const {
-        return _VSTD::__invoke(get(), __a0, __a1);
-    }
-
-    template <class _A0, class _A1>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return1<type, _A0 const, _A1 const>::type
-    operator() (_A0 const& __a0, _A1 const& __a1) const {
-        return _VSTD::__invoke(get(), __a0, __a1);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0, _A1, _A2>::type
-    operator() (_A0& __a0, _A1& __a1, _A2& __a2) const {
-        return _VSTD::__invoke(get(), __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0 const, _A1, _A2>::type
-    operator() (_A0 const& __a0, _A1& __a1, _A2& __a2) const {
-        return _VSTD::__invoke(get(), __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0, _A1 const, _A2>::type
-    operator() (_A0& __a0, _A1 const& __a1, _A2& __a2) const {
-        return _VSTD::__invoke(get(), __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0, _A1, _A2 const>::type
-    operator() (_A0& __a0, _A1& __a1, _A2 const& __a2) const {
-        return _VSTD::__invoke(get(), __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0 const, _A1 const, _A2>::type
-    operator() (_A0 const& __a0, _A1 const& __a1, _A2& __a2) const {
-        return _VSTD::__invoke(get(), __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0 const, _A1, _A2 const>::type
-    operator() (_A0 const& __a0, _A1& __a1, _A2 const& __a2) const {
-        return _VSTD::__invoke(get(), __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0, _A1 const, _A2 const>::type
-    operator() (_A0& __a0, _A1 const& __a1, _A2 const& __a2) const {
-        return _VSTD::__invoke(get(), __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0 const, _A1 const, _A2 const>::type
-    operator() (_A0 const& __a0, _A1 const& __a1, _A2 const& __a2) const {
-        return _VSTD::__invoke(get(), __a0, __a1, __a2);
-    }
-#endif // _LIBCPP_CXX03_LANG
-};
-
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-reference_wrapper<_Tp>
-ref(_Tp& __t) _NOEXCEPT
-{
-    return reference_wrapper<_Tp>(__t);
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-reference_wrapper<_Tp>
-ref(reference_wrapper<_Tp> __t) _NOEXCEPT
-{
-    return _VSTD::ref(__t.get());
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-reference_wrapper<const _Tp>
-cref(const _Tp& __t) _NOEXCEPT
-{
-    return reference_wrapper<const _Tp>(__t);
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-reference_wrapper<const _Tp>
-cref(reference_wrapper<_Tp> __t) _NOEXCEPT
-{
-    return _VSTD::cref(__t.get());
-}
-
-#ifndef _LIBCPP_CXX03_LANG
-template <class _Tp> void ref(const _Tp&&) = delete;
-template <class _Tp> void cref(const _Tp&&) = delete;
-#endif
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp, class, class = void>
-struct __is_transparent : false_type {};
-
-template <class _Tp, class _Up>
-struct __is_transparent<_Tp, _Up,
-                        typename __void_t<typename _Tp::is_transparent>::type>
-   : true_type {};
-#endif
-
-// allocator_arg_t
-
-struct _LIBCPP_TEMPLATE_VIS allocator_arg_t { explicit allocator_arg_t() = default; };
-
-#if defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
-extern _LIBCPP_EXPORTED_FROM_ABI const allocator_arg_t allocator_arg;
-#else
-/* _LIBCPP_INLINE_VAR */ constexpr allocator_arg_t allocator_arg = allocator_arg_t();
-#endif
-
-// uses_allocator
-
-template <class _Tp>
-struct __has_allocator_type
-{
-private:
-    struct __two {char __lx; char __lxx;};
-    template <class _Up> static __two __test(...);
-    template <class _Up> static char __test(typename _Up::allocator_type* = 0);
-public:
-    static const bool value = sizeof(__test<_Tp>(0)) == 1;
-};
-
-template <class _Tp, class _Alloc, bool = __has_allocator_type<_Tp>::value>
-struct __uses_allocator
-    : public integral_constant<bool,
-        is_convertible<_Alloc, typename _Tp::allocator_type>::value>
-{
-};
-
-template <class _Tp, class _Alloc>
-struct __uses_allocator<_Tp, _Alloc, false>
-    : public false_type
-{
-};
-
-template <class _Tp, class _Alloc>
-struct _LIBCPP_TEMPLATE_VIS uses_allocator
-    : public __uses_allocator<_Tp, _Alloc>
-{
-};
-
-#if _LIBCPP_STD_VER > 14
-template <class _Tp, class _Alloc>
-_LIBCPP_INLINE_VAR constexpr size_t uses_allocator_v = uses_allocator<_Tp, _Alloc>::value;
-#endif
-
-#ifndef _LIBCPP_CXX03_LANG
-
-// allocator construction
-
-template <class _Tp, class _Alloc, class ..._Args>
-struct __uses_alloc_ctor_imp
-{
-    typedef _LIBCPP_NODEBUG_TYPE typename __uncvref<_Alloc>::type _RawAlloc;
-    static const bool __ua = uses_allocator<_Tp, _RawAlloc>::value;
-    static const bool __ic =
-        is_constructible<_Tp, allocator_arg_t, _Alloc, _Args...>::value;
-    static const int value = __ua ? 2 - __ic : 0;
-};
-
-template <class _Tp, class _Alloc, class ..._Args>
-struct __uses_alloc_ctor
-    : integral_constant<int, __uses_alloc_ctor_imp<_Tp, _Alloc, _Args...>::value>
-    {};
-
-template <class _Tp, class _Allocator, class... _Args>
-inline _LIBCPP_INLINE_VISIBILITY
-void __user_alloc_construct_impl (integral_constant<int, 0>, _Tp *__storage, const _Allocator &, _Args &&... __args )
-{
-    new (__storage) _Tp (_VSTD::forward<_Args>(__args)...);
-}
-
-// FIXME: This should have a version which takes a non-const alloc.
-template <class _Tp, class _Allocator, class... _Args>
-inline _LIBCPP_INLINE_VISIBILITY
-void __user_alloc_construct_impl (integral_constant<int, 1>, _Tp *__storage, const _Allocator &__a, _Args &&... __args )
-{
-    new (__storage) _Tp (allocator_arg, __a, _VSTD::forward<_Args>(__args)...);
-}
-
-// FIXME: This should have a version which takes a non-const alloc.
-template <class _Tp, class _Allocator, class... _Args>
-inline _LIBCPP_INLINE_VISIBILITY
-void __user_alloc_construct_impl (integral_constant<int, 2>, _Tp *__storage, const _Allocator &__a, _Args &&... __args )
-{
-    new (__storage) _Tp (_VSTD::forward<_Args>(__args)..., __a);
-}
-
-#endif  // _LIBCPP_CXX03_LANG
-
-_LIBCPP_END_NAMESPACE_STD
-
-#endif  // _LIBCPP_FUNCTIONAL_BASE
+#endif // _LIBCPP_FUNCTIONAL_BASE
lib/libcxx/include/__functional_base_03
@@ -1,223 +0,0 @@
-// -*- C++ -*-
-//===----------------------------------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef _LIBCPP_FUNCTIONAL_BASE_03
-#define _LIBCPP_FUNCTIONAL_BASE_03
-
-// manual variadic expansion for <functional>
-
-// __invoke
-
-template <class _Ret, class _T1, bool _IsFunc, bool _IsBase>
-struct __enable_invoke_imp;
-
-template <class _Ret, class _T1>
-struct __enable_invoke_imp<_Ret, _T1, true, true> {
-    typedef _Ret _Bullet1;
-    typedef _Bullet1 type;
-};
-
-template <class _Ret, class _T1>
-struct __enable_invoke_imp<_Ret, _T1, true, false>  {
-    typedef _Ret _Bullet2;
-    typedef _Bullet2 type;
-};
-
-template <class _Ret, class _T1>
-struct __enable_invoke_imp<_Ret, _T1, false, true>  {
-    typedef typename add_lvalue_reference<
-                typename __apply_cv<_T1, _Ret>::type
-            >::type _Bullet3;
-    typedef _Bullet3 type;
-};
-
-template <class _Ret, class _T1>
-struct __enable_invoke_imp<_Ret, _T1, false, false>  {
-    typedef typename add_lvalue_reference<
-                typename __apply_cv<decltype(*declval<_T1>()), _Ret>::type
-            >::type _Bullet4;
-    typedef _Bullet4 type;
-};
-
-template <class _Ret, class _T1>
-struct __enable_invoke_imp<_Ret, _T1*, false, false>  {
-    typedef typename add_lvalue_reference<
-                typename __apply_cv<_T1, _Ret>::type
-            >::type _Bullet4;
-    typedef _Bullet4  type;
-};
-
-template <class _Fn, class _T1,
-          class _Traits = __member_pointer_traits<_Fn>,
-          class _Ret = typename _Traits::_ReturnType,
-          class _Class = typename _Traits::_ClassType>
-struct __enable_invoke : __enable_invoke_imp<
-    _Ret, _T1,
-    is_member_function_pointer<_Fn>::value,
-    is_base_of<_Class, typename remove_reference<_T1>::type>::value>
-{
-};
-
-__nat __invoke(__any, ...);
-
-// first bullet
-
-template <class _Fn, class _T1>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet1
-__invoke(_Fn __f, _T1& __t1) {
-    return (__t1.*__f)();
-}
-
-template <class _Fn, class _T1, class _A0>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet1
-__invoke(_Fn __f, _T1& __t1, _A0& __a0) {
-    return (__t1.*__f)(__a0);
-}
-
-template <class _Fn, class _T1, class _A0, class _A1>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet1
-__invoke(_Fn __f, _T1& __t1, _A0& __a0, _A1& __a1) {
-    return (__t1.*__f)(__a0, __a1);
-}
-
-template <class _Fn, class _T1, class _A0, class _A1, class _A2>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet1
-__invoke(_Fn __f, _T1& __t1, _A0& __a0, _A1& __a1, _A2& __a2) {
-    return (__t1.*__f)(__a0, __a1, __a2);
-}
-
-template <class _Fn, class _T1>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet2
-__invoke(_Fn __f, _T1& __t1) {
-    return ((*__t1).*__f)();
-}
-
-template <class _Fn, class _T1, class _A0>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet2
-__invoke(_Fn __f, _T1& __t1, _A0& __a0) {
-    return ((*__t1).*__f)(__a0);
-}
-
-template <class _Fn, class _T1, class _A0, class _A1>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet2
-__invoke(_Fn __f, _T1& __t1, _A0& __a0, _A1& __a1) {
-    return ((*__t1).*__f)(__a0, __a1);
-}
-
-template <class _Fn, class _T1, class _A0, class _A1, class _A2>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet2
-__invoke(_Fn __f, _T1& __t1, _A0& __a0, _A1& __a1, _A2& __a2) {
-    return ((*__t1).*__f)(__a0, __a1, __a2);
-}
-
-template <class _Fn, class _T1>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet3
-__invoke(_Fn __f, _T1& __t1) {
-    return __t1.*__f;
-}
-
-template <class _Fn, class _T1>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __enable_invoke<_Fn, _T1>::_Bullet4
-__invoke(_Fn __f, _T1& __t1) {
-    return (*__t1).*__f;
-}
-
-// fifth bullet
-
-template <class _Fp>
-inline _LIBCPP_INLINE_VISIBILITY
-decltype(declval<_Fp&>()())
-__invoke(_Fp& __f)
-{
-    return __f();
-}
-
-template <class _Fp, class _A0>
-inline _LIBCPP_INLINE_VISIBILITY
-decltype(declval<_Fp&>()(declval<_A0&>()))
-__invoke(_Fp& __f, _A0& __a0)
-{
-    return __f(__a0);
-}
-
-template <class _Fp, class _A0, class _A1>
-inline _LIBCPP_INLINE_VISIBILITY
-decltype(declval<_Fp&>()(declval<_A0&>(), declval<_A1&>()))
-__invoke(_Fp& __f, _A0& __a0, _A1& __a1)
-{
-    return __f(__a0, __a1);
-}
-
-template <class _Fp, class _A0, class _A1, class _A2>
-inline _LIBCPP_INLINE_VISIBILITY
-decltype(declval<_Fp&>()(declval<_A0&>(), declval<_A1&>(), declval<_A2&>()))
-__invoke(_Fp& __f, _A0& __a0, _A1& __a1, _A2& __a2)
-{
-    return __f(__a0, __a1, __a2);
-}
-
-template <class _Fp, bool = __has_result_type<__weak_result_type<_Fp> >::value>
-struct __invoke_return
-{
-    typedef typename __weak_result_type<_Fp>::result_type type;
-};
-
-template <class _Fp>
-struct __invoke_return<_Fp, false>
-{
-    typedef decltype(_VSTD::__invoke(declval<_Fp&>())) type;
-};
-
-template <class _Tp, class _A0>
-struct __invoke_return0
-{
-    typedef decltype(_VSTD::__invoke(declval<_Tp&>(), declval<_A0&>())) type;
-};
-
-template <class _Rp, class _Tp, class _A0>
-struct __invoke_return0<_Rp _Tp::*, _A0>
-{
-    typedef typename __enable_invoke<_Rp _Tp::*, _A0>::type type;
-};
-
-template <class _Tp, class _A0, class _A1>
-struct __invoke_return1
-{
-    typedef decltype(_VSTD::__invoke(declval<_Tp&>(), declval<_A0&>(),
-                                                      declval<_A1&>())) type;
-};
-
-template <class _Rp, class _Class, class _A0, class _A1>
-struct __invoke_return1<_Rp _Class::*, _A0, _A1> {
-    typedef typename __enable_invoke<_Rp _Class::*, _A0>::type type;
-};
-
-template <class _Tp, class _A0, class _A1, class _A2>
-struct __invoke_return2
-{
-    typedef decltype(_VSTD::__invoke(declval<_Tp&>(), declval<_A0&>(),
-                                                      declval<_A1&>(),
-                                                      declval<_A2&>())) type;
-};
-
-template <class _Ret, class _Class, class _A0, class _A1, class _A2>
-struct __invoke_return2<_Ret _Class::*, _A0, _A1, _A2> {
-    typedef typename __enable_invoke<_Ret _Class::*, _A0>::type type;
-};
-#endif  // _LIBCPP_FUNCTIONAL_BASE_03
lib/libcxx/include/__hash_table
@@ -10,16 +10,16 @@
 #ifndef _LIBCPP__HASH_TABLE
 #define _LIBCPP__HASH_TABLE
 
+#include <__bits> // __libcpp_clz
 #include <__config>
-#include <initializer_list>
-#include <memory>
-#include <iterator>
+#include <__debug>
 #include <algorithm>
 #include <cmath>
-#include <utility>
+#include <initializer_list>
+#include <iterator>
+#include <memory>
 #include <type_traits>
-
-#include <__debug>
+#include <utility>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -89,7 +89,7 @@ struct __hash_node_base
 };
 
 template <class _Tp, class _VoidPtr>
-struct __hash_node
+struct _LIBCPP_STANDALONE_DEBUG __hash_node
     : public __hash_node_base
              <
                  typename __rebind_pointer<_VoidPtr, __hash_node<_Tp, _VoidPtr> >::type
@@ -317,7 +317,7 @@ public:
         }
         return *this;
     }
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
     _LIBCPP_INLINE_VISIBILITY
     reference operator*() const {
@@ -336,7 +336,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     __hash_iterator& operator++() {
         _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this),
-                       "Attempted to increment non-incrementable unordered container iterator");
+                       "Attempted to increment a non-incrementable unordered container iterator");
         __node_ = __node_->__next_;
         return *this;
     }
@@ -438,7 +438,7 @@ public:
         }
         return *this;
     }
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
     _LIBCPP_INLINE_VISIBILITY
     reference operator*() const {
@@ -456,7 +456,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     __hash_const_iterator& operator++() {
         _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this),
-                             "Attempted to increment non-incrementable unordered container const_iterator");
+                             "Attempted to increment a non-incrementable unordered container const_iterator");
         __node_ = __node_->__next_;
         return *this;
     }
@@ -550,7 +550,7 @@ public:
         }
         return *this;
     }
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
     _LIBCPP_INLINE_VISIBILITY
     reference operator*() const {
@@ -569,7 +569,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     __hash_local_iterator& operator++() {
         _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this),
-                       "Attempted to increment non-incrementable unordered container local_iterator");
+                       "Attempted to increment a non-incrementable unordered container local_iterator");
         __node_ = __node_->__next_;
         if (__node_ != nullptr && __constrain_hash(__node_->__hash(), __bucket_count_) != __bucket_)
             __node_ = nullptr;
@@ -695,7 +695,7 @@ public:
         }
         return *this;
     }
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
     _LIBCPP_INLINE_VISIBILITY
     reference operator*() const {
@@ -714,7 +714,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     __hash_const_local_iterator& operator++() {
         _LIBCPP_DEBUG_ASSERT(__get_const_db()->__dereferenceable(this),
-                       "Attempted to increment non-incrementable unordered container const_local_iterator");
+                       "Attempted to increment a non-incrementable unordered container const_local_iterator");
         __node_ = __node_->__next_;
         if (__node_ != nullptr && __constrain_hash(__node_->__hash(), __bucket_count_) != __bucket_)
             __node_ = nullptr;
@@ -741,9 +741,9 @@ public:
 private:
 #if _LIBCPP_DEBUG_LEVEL == 2
     _LIBCPP_INLINE_VISIBILITY
-    __hash_const_local_iterator(__next_pointer __node, size_t __bucket,
+    __hash_const_local_iterator(__next_pointer __node_ptr, size_t __bucket,
                                 size_t __bucket_count, const void* __c) _NOEXCEPT
-        : __node_(__node),
+        : __node_(__node_ptr),
           __bucket_(__bucket),
           __bucket_count_(__bucket_count)
         {
@@ -753,9 +753,9 @@ private:
         }
 #else
     _LIBCPP_INLINE_VISIBILITY
-    __hash_const_local_iterator(__next_pointer __node, size_t __bucket,
+    __hash_const_local_iterator(__next_pointer __node_ptr, size_t __bucket,
                                 size_t __bucket_count) _NOEXCEPT
-        : __node_(__node),
+        : __node_(__node_ptr),
           __bucket_(__bucket),
           __bucket_count_(__bucket_count)
         {
@@ -1337,7 +1337,7 @@ public:
     bool __addable(const const_iterator* __i, ptrdiff_t __n) const;
     bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const;
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 private:
     void __rehash(size_type __n);
@@ -1645,7 +1645,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__move_assign(
 #ifndef _LIBCPP_NO_EXCEPTIONS
             try
             {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
                 const_iterator __i = __u.begin();
                 while (__cache != nullptr && __u.size() != 0)
                 {
@@ -1662,7 +1662,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__move_assign(
                 __deallocate_node(__cache);
                 throw;
             }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             __deallocate_node(__cache);
         }
         const_iterator __i = __u.begin();
@@ -1707,7 +1707,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__assign_unique(_InputIterator __first
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (; __cache != nullptr && __first != __last; ++__first)
             {
                 __cache->__upcast()->__value_ = *__first;
@@ -1722,7 +1722,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__assign_unique(_InputIterator __first
             __deallocate_node(__cache);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __deallocate_node(__cache);
     }
     for (; __first != __last; ++__first)
@@ -1747,7 +1747,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__assign_multi(_InputIterator __first,
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (; __cache != nullptr && __first != __last; ++__first)
             {
                 __cache->__upcast()->__value_ = *__first;
@@ -1762,7 +1762,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__assign_multi(_InputIterator __first,
             __deallocate_node(__cache);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __deallocate_node(__cache);
     }
     for (; __first != __last; ++__first)
@@ -2299,7 +2299,7 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__node_handle_merge_multi(
         __node_insert_multi_perform(__src_ptr, __pn);
     }
 }
-#endif  // _LIBCPP_STD_VER > 14
+#endif // _LIBCPP_STD_VER > 14
 
 template <class _Tp, class _Hash, class _Equal, class _Alloc>
 void
@@ -2506,11 +2506,11 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::erase(const_iterator __first,
 {
 #if _LIBCPP_DEBUG_LEVEL == 2
     _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__first) == this,
-        "unodered container::erase(iterator, iterator) called with an iterator not"
-        " referring to this unodered container");
+        "unordered container::erase(iterator, iterator) called with an iterator not"
+        " referring to this container");
     _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__last) == this,
-        "unodered container::erase(iterator, iterator) called with an iterator not"
-        " referring to this unodered container");
+        "unordered container::erase(iterator, iterator) called with an iterator not"
+        " referring to this container");
 #endif
     for (const_iterator __p = __first; __first != __last; __p = __first)
     {
@@ -2804,10 +2804,10 @@ __hash_table<_Tp, _Hash, _Equal, _Alloc>::__subscriptable(const const_iterator*,
     return false;
 }
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP__HASH_TABLE
+#endif // _LIBCPP__HASH_TABLE
lib/libcxx/include/__libcpp_version
@@ -1,1 +1,1 @@
-12000
+13000
lib/libcxx/include/__locale
@@ -10,8 +10,8 @@
 #ifndef _LIBCPP___LOCALE
 #define _LIBCPP___LOCALE
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <string>
 #include <memory>
 #include <utility>
@@ -1161,7 +1161,7 @@ protected:
     virtual int do_max_length() const  _NOEXCEPT;
 };
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 
 // template <> class codecvt<char16_t, char8_t, mbstate_t> // C++20
 
@@ -1337,7 +1337,7 @@ protected:
     virtual int do_max_length() const  _NOEXCEPT;
 };
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 
 // template <> class codecvt<char32_t, char8_t, mbstate_t> // C++20
 
@@ -1455,7 +1455,7 @@ _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VI
 _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname<wchar_t, char, mbstate_t>)
 _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname<char16_t, char, mbstate_t>) // deprecated in C++20
 _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname<char32_t, char, mbstate_t>) // deprecated in C++20
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname<char16_t, char8_t, mbstate_t>) // C++20
 _LIBCPP_EXTERN_TEMPLATE_EVEN_IN_DEBUG_MODE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS codecvt_byname<char32_t, char8_t, mbstate_t>) // C++20
 #endif
@@ -1484,14 +1484,14 @@ struct __narrow_to_utf8<8>
 
 _LIBCPP_SUPPRESS_DEPRECATED_PUSH
 template <>
-struct _LIBCPP_TEMPLATE_VIS __narrow_to_utf8<16>
+struct _LIBCPP_TYPE_VIS __narrow_to_utf8<16>
     : public codecvt<char16_t, char, mbstate_t>
 {
     _LIBCPP_INLINE_VISIBILITY
     __narrow_to_utf8() : codecvt<char16_t, char, mbstate_t>(1) {}
 _LIBCPP_SUPPRESS_DEPRECATED_POP
 
-    _LIBCPP_EXPORTED_FROM_ABI ~__narrow_to_utf8();
+    ~__narrow_to_utf8();
 
     template <class _OutputIterator, class _CharT>
     _LIBCPP_INLINE_VISIBILITY
@@ -1520,14 +1520,14 @@ _LIBCPP_SUPPRESS_DEPRECATED_POP
 
 _LIBCPP_SUPPRESS_DEPRECATED_PUSH
 template <>
-struct _LIBCPP_TEMPLATE_VIS __narrow_to_utf8<32>
+struct _LIBCPP_TYPE_VIS __narrow_to_utf8<32>
     : public codecvt<char32_t, char, mbstate_t>
 {
     _LIBCPP_INLINE_VISIBILITY
     __narrow_to_utf8() : codecvt<char32_t, char, mbstate_t>(1) {}
 _LIBCPP_SUPPRESS_DEPRECATED_POP
 
-    _LIBCPP_EXPORTED_FROM_ABI ~__narrow_to_utf8();
+    ~__narrow_to_utf8();
 
     template <class _OutputIterator, class _CharT>
     _LIBCPP_INLINE_VISIBILITY
@@ -1578,14 +1578,14 @@ struct __widen_from_utf8<8>
 
 _LIBCPP_SUPPRESS_DEPRECATED_PUSH
 template <>
-struct _LIBCPP_TEMPLATE_VIS __widen_from_utf8<16>
+struct _LIBCPP_TYPE_VIS __widen_from_utf8<16>
     : public codecvt<char16_t, char, mbstate_t>
 {
     _LIBCPP_INLINE_VISIBILITY
     __widen_from_utf8() : codecvt<char16_t, char, mbstate_t>(1) {}
 _LIBCPP_SUPPRESS_DEPRECATED_POP
 
-    _LIBCPP_EXPORTED_FROM_ABI ~__widen_from_utf8();
+    ~__widen_from_utf8();
 
     template <class _OutputIterator>
     _LIBCPP_INLINE_VISIBILITY
@@ -1614,14 +1614,14 @@ _LIBCPP_SUPPRESS_DEPRECATED_POP
 
 _LIBCPP_SUPPRESS_DEPRECATED_PUSH
 template <>
-struct _LIBCPP_TEMPLATE_VIS __widen_from_utf8<32>
+struct _LIBCPP_TYPE_VIS __widen_from_utf8<32>
     : public codecvt<char32_t, char, mbstate_t>
 {
     _LIBCPP_INLINE_VISIBILITY
     __widen_from_utf8() : codecvt<char32_t, char, mbstate_t>(1) {}
 _LIBCPP_SUPPRESS_DEPRECATED_POP
 
-    _LIBCPP_EXPORTED_FROM_ABI ~__widen_from_utf8();
+    ~__widen_from_utf8();
 
     template <class _OutputIterator>
     _LIBCPP_INLINE_VISIBILITY
@@ -1756,4 +1756,4 @@ private:
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP___LOCALE
+#endif // _LIBCPP___LOCALE
lib/libcxx/include/__mutex_base
@@ -11,10 +11,9 @@
 #define _LIBCPP___MUTEX_BASE
 
 #include <__config>
+#include <__threading_support>
 #include <chrono>
 #include <system_error>
-#include <__threading_support>
-
 #include <time.h>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -190,8 +189,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     bool owns_lock() const _NOEXCEPT {return __owns_;}
     _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_EXPLICIT
-        operator bool () const _NOEXCEPT {return __owns_;}
+    explicit operator bool() const _NOEXCEPT {return __owns_;}
     _LIBCPP_INLINE_VISIBILITY
     mutex_type* mutex() const _NOEXCEPT {return __m_;}
 };
@@ -526,4 +524,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP___MUTEX_BASE
+#endif // _LIBCPP___MUTEX_BASE
lib/libcxx/include/__node_handle
@@ -11,6 +11,7 @@
 #define _LIBCPP___NODE_HANDLE
 
 #include <__config>
+#include <__debug>
 #include <memory>
 #include <optional>
 
@@ -205,4 +206,4 @@ struct _LIBCPP_TEMPLATE_VIS __insert_return_type
 _LIBCPP_END_NAMESPACE_STD
 _LIBCPP_POP_MACROS
 
-#endif
+#endif  // _LIBCPP___NODE_HANDLE
lib/libcxx/include/__nullptr
@@ -56,6 +56,6 @@ namespace std
     typedef decltype(nullptr) nullptr_t;
 }
 
-#endif  // _LIBCPP_HAS_NO_NULLPTR
+#endif // _LIBCPP_HAS_NO_NULLPTR
 
-#endif  // _LIBCPP_NULLPTR
+#endif // _LIBCPP_NULLPTR
lib/libcxx/include/__split_buffer
@@ -3,8 +3,9 @@
 #define _LIBCPP_SPLIT_BUFFER
 
 #include <__config>
-#include <type_traits>
+#include <__utility/forward.h>
 #include <algorithm>
+#include <type_traits>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -20,8 +21,8 @@ template <bool>
 class __split_buffer_common
 {
 protected:
-    void __throw_length_error() const;
-    void __throw_out_of_range() const;
+    _LIBCPP_NORETURN void __throw_length_error() const;
+    _LIBCPP_NORETURN void __throw_out_of_range() const;
 };
 
 template <class _Tp, class _Allocator = allocator<_Tp> >
@@ -444,7 +445,7 @@ __split_buffer<_Tp, _Allocator>::shrink_to_fit() _NOEXCEPT
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             __split_buffer<value_type, __alloc_rr&> __t(size(), 0, __alloc());
             __t.__construct_at_end(move_iterator<pointer>(__begin_),
                                    move_iterator<pointer>(__end_));
@@ -458,7 +459,7 @@ __split_buffer<_Tp, _Allocator>::shrink_to_fit() _NOEXCEPT
         catch (...)
         {
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -625,4 +626,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_SPLIT_BUFFER
+#endif // _LIBCPP_SPLIT_BUFFER
lib/libcxx/include/__std_stream
@@ -11,10 +11,10 @@
 #define _LIBCPP___STD_STREAM
 
 #include <__config>
-#include <ostream>
-#include <istream>
 #include <__locale>
 #include <cstdio>
+#include <istream>
+#include <ostream>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -358,4 +358,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP___STD_STREAM
+#endif // _LIBCPP___STD_STREAM
lib/libcxx/include/__string
@@ -10,55 +10,21 @@
 #ifndef _LIBCPP___STRING
 #define _LIBCPP___STRING
 
-/*
-    string synopsis
-
-namespace std
-{
-
-template <class charT>
-struct char_traits
-{
-    typedef charT     char_type;
-    typedef ...       int_type;
-    typedef streamoff off_type;
-    typedef streampos pos_type;
-    typedef mbstate_t state_type;
-
-    static constexpr void assign(char_type& c1, const char_type& c2) noexcept;
-    static constexpr bool eq(char_type c1, char_type c2) noexcept;
-    static constexpr bool lt(char_type c1, char_type c2) noexcept;
-
-    static constexpr int    compare(const char_type* s1, const char_type* s2, size_t n);
-    static constexpr size_t length(const char_type* s);
-    static constexpr const char_type*
-                            find(const char_type* s, size_t n, const char_type& a);
-
-    static constexpr char_type* move(char_type* s1, const char_type* s2, size_t n); // constexpr in C++20
-    static constexpr char_type* copy(char_type* s1, const char_type* s2, size_t n); // constexpr in C++20
-    static constexpr char_type* assign(char_type* s, size_t n, char_type a);        // constexpr in C++20
-
-    static constexpr int_type  not_eof(int_type c) noexcept;
-    static constexpr char_type to_char_type(int_type c) noexcept;
-    static constexpr int_type  to_int_type(char_type c) noexcept;
-    static constexpr bool      eq_int_type(int_type c1, int_type c2) noexcept;
-    static constexpr int_type  eof() noexcept;
-};
-
-template <> struct char_traits<char>;
-template <> struct char_traits<wchar_t>;
-template <> struct char_traits<char8_t>;  // c++20
-
-}  // std
-
-*/
-
 #include <__config>
-#include <algorithm>  // for search and min
-#include <cstdio>     // for EOF
-#include <cstring>    // for memcpy
-#include <cwchar>     // for wmemcpy
-#include <memory>     // for __murmur2_or_cityhash
+#include <__algorithm/copy.h>
+#include <__algorithm/copy_backward.h>
+#include <__algorithm/copy_n.h>
+#include <__algorithm/fill_n.h>
+#include <__algorithm/find_first_of.h>
+#include <__algorithm/find_end.h>
+#include <__algorithm/min.h>
+#include <__functional/hash.h>     // for __murmur2_or_cityhash
+#include <__iterator/iterator_traits.h>
+#include <cstdio>      // for EOF
+#include <cstdint>     // for uint_least16_t
+#include <cstring>     // for memcpy
+#include <cwchar>      // for wmemcpy
+#include <type_traits> // for __libcpp_is_constant_evaluated
 
 #include <__debug>
 
@@ -581,7 +547,7 @@ char_traits<wchar_t>::find(const char_type* __s, size_t __n, const char_type& __
 }
 
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 
 template <>
 struct _LIBCPP_TEMPLATE_VIS char_traits<char8_t>
@@ -688,7 +654,7 @@ char_traits<char8_t>::find(const char_type* __s, size_t __n, const char_type& __
     return nullptr;
 }
 
-#endif // #_LIBCPP_NO_HAS_CHAR8_T
+#endif // #_LIBCPP_HAS_NO_CHAR8_T
 
 #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
 
@@ -932,7 +898,7 @@ char_traits<char32_t>::assign(char_type* __s, size_t __n, char_type __a) _NOEXCE
     return __r;
 }
 
-#endif  // _LIBCPP_HAS_NO_UNICODE_CHARS
+#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
 
 // helper fns for basic_string and string_view
 
@@ -953,7 +919,7 @@ __str_find(const _CharT *__p, _SizeT __sz,
 template <class _CharT, class _Traits>
 inline _LIBCPP_CONSTEXPR_AFTER_CXX11 const _CharT *
 __search_substring(const _CharT *__first1, const _CharT *__last1,
-                   const _CharT *__first2, const _CharT *__last2) {
+                   const _CharT *__first2, const _CharT *__last2) _NOEXCEPT {
   // Take advantage of knowing source and pattern lengths.
   // Stop short when source is smaller than pattern.
   const ptrdiff_t __len2 = __last2 - __first2;
@@ -1177,4 +1143,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP___STRING
+#endif // _LIBCPP___STRING
lib/libcxx/include/__threading_support
@@ -10,11 +10,12 @@
 #ifndef _LIBCPP_THREADING_SUPPORT
 #define _LIBCPP_THREADING_SUPPORT
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <chrono>
-#include <iosfwd>
 #include <errno.h>
+#include <iosfwd>
+#include <limits>
 
 #ifdef __MVS__
 # include <__support/ibm/nanosleep.h>
@@ -28,14 +29,15 @@
 # include <__external_threading>
 #elif !defined(_LIBCPP_HAS_NO_THREADS)
 
+#if defined(__APPLE__) || defined(__MVS__)
+# define _LIBCPP_NO_NATIVE_SEMAPHORES
+#endif
+
 #if defined(_LIBCPP_HAS_THREAD_API_PTHREAD)
 # include <pthread.h>
 # include <sched.h>
-# if defined(__APPLE__) || defined(__MVS__)
-#  define _LIBCPP_NO_NATIVE_SEMAPHORES
-# endif
 # ifndef _LIBCPP_NO_NATIVE_SEMAPHORES
-# include <semaphore.h>
+#   include <semaphore.h>
 # endif
 #elif defined(_LIBCPP_HAS_THREAD_API_C11)
 # include <threads.h>
@@ -149,6 +151,9 @@ typedef void* __libcpp_condvar_t;
 
 // Semaphore
 typedef void* __libcpp_semaphore_t;
+#if defined(_LIBCPP_HAS_THREAD_API_WIN32)
+# define _LIBCPP_SEMAPHORE_MAX (::std::numeric_limits<long>::max())
+#endif
 
 // Execute Once
 typedef void* __libcpp_exec_once_flag;
@@ -390,7 +395,7 @@ bool __libcpp_recursive_mutex_trylock(__libcpp_recursive_mutex_t *__m)
   return pthread_mutex_trylock(__m) == 0;
 }
 
-int __libcpp_recursive_mutex_unlock(__libcpp_mutex_t *__m)
+int __libcpp_recursive_mutex_unlock(__libcpp_recursive_mutex_t *__m)
 {
   return pthread_mutex_unlock(__m);
 }
@@ -500,7 +505,7 @@ bool __libcpp_thread_id_less(__libcpp_thread_id t1, __libcpp_thread_id t2)
 
 // Thread
 bool __libcpp_thread_isnull(const __libcpp_thread_t *__t) {
-  return *__t == __libcpp_thread_t();
+  return __libcpp_thread_get_id(__t) == 0;
 }
 
 int __libcpp_thread_create(__libcpp_thread_t *__t, void *(*__func)(void *),
@@ -578,7 +583,7 @@ bool __libcpp_recursive_mutex_trylock(__libcpp_recursive_mutex_t *__m)
   return mtx_trylock(__m) == thrd_success;
 }
 
-int __libcpp_recursive_mutex_unlock(__libcpp_mutex_t *__m)
+int __libcpp_recursive_mutex_unlock(__libcpp_recursive_mutex_t *__m)
 {
   return mtx_unlock(__m) == thrd_success ? 0 : EINVAL;
 }
lib/libcxx/include/__tree
@@ -11,10 +11,12 @@
 #define _LIBCPP___TREE
 
 #include <__config>
+#include <__utility/forward.h>
+#include <algorithm>
 #include <iterator>
+#include <limits>
 #include <memory>
 #include <stdexcept>
-#include <algorithm>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -714,7 +716,7 @@ public:
 };
 
 template <class _VoidPtr>
-class __tree_node_base
+class _LIBCPP_STANDALONE_DEBUG __tree_node_base
     : public __tree_node_base_types<_VoidPtr>::__end_node_type
 {
     typedef __tree_node_base_types<_VoidPtr> _NodeBaseTypes;
@@ -742,7 +744,7 @@ private:
 };
 
 template <class _Tp, class _VoidPtr>
-class __tree_node
+class _LIBCPP_STANDALONE_DEBUG __tree_node
     : public __tree_node_base<_VoidPtr>
 {
 public:
@@ -2410,7 +2412,7 @@ __tree<_Tp, _Compare, _Allocator>::__node_handle_merge_multi(_Tree& __source)
     }
 }
 
-#endif  // _LIBCPP_STD_VER > 14
+#endif // _LIBCPP_STD_VER > 14
 
 template <class _Tp, class _Compare, class _Allocator>
 typename __tree<_Tp, _Compare, _Allocator>::iterator
@@ -2743,4 +2745,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP___TREE
+#endif // _LIBCPP___TREE
lib/libcxx/include/__tuple
@@ -134,7 +134,7 @@ template<> struct __parity<7> { template<size_t _Np> struct __pmake : __repeat<t
 
 } // namespace detail
 
-#endif  // !__has_builtin(__make_integer_seq) || defined(_LIBCPP_TESTING_FALLBACK_MAKE_INTEGER_SEQUENCE)
+#endif // !__has_builtin(__make_integer_seq) || defined(_LIBCPP_TESTING_FALLBACK_MAKE_INTEGER_SEQUENCE)
 
 #if __has_builtin(__make_integer_seq)
 template <size_t _Ep, size_t _Sp>
@@ -548,4 +548,4 @@ struct __sfinae_assign_base<false, true> {
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP___TUPLE
+#endif // _LIBCPP___TUPLE
lib/libcxx/include/algorithm
@@ -351,11 +351,11 @@ template <class ForwardIterator, class Compare>
     is_sorted_until(ForwardIterator first, ForwardIterator last, Compare comp);
 
 template <class RandomAccessIterator>
-    void
+    constexpr void               // constexpr in C++20
     sort(RandomAccessIterator first, RandomAccessIterator last);
 
 template <class RandomAccessIterator, class Compare>
-    void
+    constexpr void               // constexpr in C++20
     sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
 
 template <class RandomAccessIterator>
@@ -367,29 +367,29 @@ template <class RandomAccessIterator, class Compare>
     stable_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
 
 template <class RandomAccessIterator>
-    void
+    constexpr void                    // constexpr in C++20
     partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last);
 
 template <class RandomAccessIterator, class Compare>
-    void
+    constexpr void                    // constexpr in C++20
     partial_sort(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, Compare comp);
 
 template <class InputIterator, class RandomAccessIterator>
-    RandomAccessIterator
+    constexpr RandomAccessIterator    // constexpr in C++20
     partial_sort_copy(InputIterator first, InputIterator last,
                       RandomAccessIterator result_first, RandomAccessIterator result_last);
 
 template <class InputIterator, class RandomAccessIterator, class Compare>
-    RandomAccessIterator
+    constexpr RandomAccessIterator    // constexpr in C++20
     partial_sort_copy(InputIterator first, InputIterator last,
                       RandomAccessIterator result_first, RandomAccessIterator result_last, Compare comp);
 
 template <class RandomAccessIterator>
-    void
+    constexpr void                    // constexpr in C++20
     nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last);
 
 template <class RandomAccessIterator, class Compare>
-    void
+    constexpr void                    // constexpr in C++20
     nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare comp);
 
 template <class ForwardIterator, class T>
@@ -491,35 +491,35 @@ template <class InputIterator1, class InputIterator2, class OutputIterator, clas
                              InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp);
 
 template <class RandomAccessIterator>
-    void
+    constexpr void                                   // constexpr in C++20
     push_heap(RandomAccessIterator first, RandomAccessIterator last);
 
 template <class RandomAccessIterator, class Compare>
-    void
+    constexpr void                                   // constexpr in C++20
     push_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
 
 template <class RandomAccessIterator>
-    void
+    constexpr void                                   // constexpr in C++20
     pop_heap(RandomAccessIterator first, RandomAccessIterator last);
 
 template <class RandomAccessIterator, class Compare>
-    void
+    constexpr void                                   // constexpr in C++20
     pop_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
 
 template <class RandomAccessIterator>
-    void
+    constexpr void                                   // constexpr in C++20
     make_heap(RandomAccessIterator first, RandomAccessIterator last);
 
 template <class RandomAccessIterator, class Compare>
-    void
+    constexpr void                                   // constexpr in C++20
     make_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
 
 template <class RandomAccessIterator>
-    void
+    constexpr void                                   // constexpr in C++20
     sort_heap(RandomAccessIterator first, RandomAccessIterator last);
 
 template <class RandomAccessIterator, class Compare>
-    void
+    constexpr void                                   // constexpr in C++20
     sort_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
 
 template <class RandomAccessIterator>
@@ -646,18 +646,113 @@ template <class BidirectionalIterator, class Compare>
 */
 
 #include <__config>
-#include <initializer_list>
-#include <type_traits>
+#include <__debug>
+#include <__bits> // __libcpp_clz
+#include <cstddef>
 #include <cstring>
+#include <functional>
+#include <initializer_list>
 #include <utility> // needed to provide swap_ranges.
 #include <memory>
-#include <functional>
 #include <iterator>
-#include <cstddef>
-#include <bit>
+#include <memory>
+#include <type_traits>
+#include <utility> // swap_ranges
 #include <version>
 
-#include <__debug>
+#include <__algorithm/adjacent_find.h>
+#include <__algorithm/all_of.h>
+#include <__algorithm/any_of.h>
+#include <__algorithm/binary_search.h>
+#include <__algorithm/clamp.h>
+#include <__algorithm/comp.h>
+#include <__algorithm/comp_ref_type.h>
+#include <__algorithm/copy.h>
+#include <__algorithm/copy_backward.h>
+#include <__algorithm/copy_if.h>
+#include <__algorithm/copy_n.h>
+#include <__algorithm/count.h>
+#include <__algorithm/count_if.h>
+#include <__algorithm/equal.h>
+#include <__algorithm/equal_range.h>
+#include <__algorithm/fill_n.h>
+#include <__algorithm/fill.h>
+#include <__algorithm/find.h>
+#include <__algorithm/find_end.h>
+#include <__algorithm/find_first_of.h>
+#include <__algorithm/find_if.h>
+#include <__algorithm/find_if_not.h>
+#include <__algorithm/for_each.h>
+#include <__algorithm/for_each_n.h>
+#include <__algorithm/generate_n.h>
+#include <__algorithm/generate.h>
+#include <__algorithm/half_positive.h>
+#include <__algorithm/includes.h>
+#include <__algorithm/inplace_merge.h>
+#include <__algorithm/is_heap.h>
+#include <__algorithm/is_heap_until.h>
+#include <__algorithm/is_partitioned.h>
+#include <__algorithm/is_permutation.h>
+#include <__algorithm/is_sorted.h>
+#include <__algorithm/is_sorted_until.h>
+#include <__algorithm/iter_swap.h>
+#include <__algorithm/lexicographical_compare.h>
+#include <__algorithm/lower_bound.h>
+#include <__algorithm/make_heap.h>
+#include <__algorithm/max.h>
+#include <__algorithm/max_element.h>
+#include <__algorithm/merge.h>
+#include <__algorithm/min.h>
+#include <__algorithm/min_element.h>
+#include <__algorithm/minmax.h>
+#include <__algorithm/minmax_element.h>
+#include <__algorithm/mismatch.h>
+#include <__algorithm/move.h>
+#include <__algorithm/move_backward.h>
+#include <__algorithm/next_permutation.h>
+#include <__algorithm/none_of.h>
+#include <__algorithm/nth_element.h>
+#include <__algorithm/partial_sort.h>
+#include <__algorithm/partial_sort_copy.h>
+#include <__algorithm/partition.h>
+#include <__algorithm/partition_copy.h>
+#include <__algorithm/partition_point.h>
+#include <__algorithm/pop_heap.h>
+#include <__algorithm/prev_permutation.h>
+#include <__algorithm/push_heap.h>
+#include <__algorithm/remove.h>
+#include <__algorithm/remove_copy.h>
+#include <__algorithm/remove_copy_if.h>
+#include <__algorithm/remove_if.h>
+#include <__algorithm/replace.h>
+#include <__algorithm/replace_copy.h>
+#include <__algorithm/replace_copy_if.h>
+#include <__algorithm/replace_if.h>
+#include <__algorithm/reverse.h>
+#include <__algorithm/reverse_copy.h>
+#include <__algorithm/rotate.h>
+#include <__algorithm/rotate_copy.h>
+#include <__algorithm/sample.h>
+#include <__algorithm/search.h>
+#include <__algorithm/search_n.h>
+#include <__algorithm/set_difference.h>
+#include <__algorithm/set_intersection.h>
+#include <__algorithm/set_symmetric_difference.h>
+#include <__algorithm/set_union.h>
+#include <__algorithm/shift_left.h>
+#include <__algorithm/shift_right.h>
+#include <__algorithm/shuffle.h>
+#include <__algorithm/sift_down.h>
+#include <__algorithm/sort.h>
+#include <__algorithm/sort_heap.h>
+#include <__algorithm/stable_partition.h>
+#include <__algorithm/stable_sort.h>
+#include <__algorithm/swap_ranges.h>
+#include <__algorithm/transform.h>
+#include <__algorithm/unique_copy.h>
+#include <__algorithm/unique.h>
+#include <__algorithm/unwrap_iter.h>
+#include <__algorithm/upper_bound.h>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -666,5197 +761,10 @@ template <class BidirectionalIterator, class Compare>
 _LIBCPP_PUSH_MACROS
 #include <__undef_macros>
 
-
-_LIBCPP_BEGIN_NAMESPACE_STD
-
-// I'd like to replace these with _VSTD::equal_to<void>, but can't because:
-//   * That only works with C++14 and later, and
-//   * We haven't included <functional> here.
-template <class _T1, class _T2 = _T1>
-struct __equal_to
-{
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 bool operator()(const _T1& __x, const _T2& __y) const {return __x == __y;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 bool operator()(const _T2& __x, const _T1& __y) const {return __x == __y;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 bool operator()(const _T2& __x, const _T2& __y) const {return __x == __y;}
-};
-
-template <class _T1>
-struct __equal_to<_T1, _T1>
-{
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
-};
-
-template <class _T1>
-struct __equal_to<const _T1, _T1>
-{
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
-};
-
-template <class _T1>
-struct __equal_to<_T1, const _T1>
-{
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T1& __x, const _T1& __y) const {return __x == __y;}
-};
-
-template <class _T1, class _T2 = _T1>
-struct __less
-{
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T1& __x, const _T2& __y) const {return __x < __y;}
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T2& __x, const _T1& __y) const {return __x < __y;}
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T2& __x, const _T2& __y) const {return __x < __y;}
-};
-
-template <class _T1>
-struct __less<_T1, _T1>
-{
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
-};
-
-template <class _T1>
-struct __less<const _T1, _T1>
-{
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
-};
-
-template <class _T1>
-struct __less<_T1, const _T1>
-{
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}
-};
-
-template <class _Predicate>
-class __invert // invert the sense of a comparison
-{
-private:
-    _Predicate __p_;
-public:
-    _LIBCPP_INLINE_VISIBILITY __invert() {}
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __invert(_Predicate __p) : __p_(__p) {}
-
-    template <class _T1>
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _T1& __x) {return !__p_(__x);}
-
-    template <class _T1, class _T2>
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _T1& __x, const _T2& __y) {return __p_(__y, __x);}
-};
-
-// Perform division by two quickly for positive integers (llvm.org/PR39129)
-
-template <typename _Integral>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename enable_if
-<
-    is_integral<_Integral>::value,
-    _Integral
->::type
-__half_positive(_Integral __value)
-{
-    return static_cast<_Integral>(static_cast<typename make_unsigned<_Integral>::type>(__value) / 2);
-}
-
-template <typename _Tp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename enable_if
-<
-    !is_integral<_Tp>::value,
-    _Tp
->::type
-__half_positive(_Tp __value)
-{
-    return __value / 2;
-}
-
-#ifdef _LIBCPP_DEBUG
-
-template <class _Compare>
-struct __debug_less
-{
-    _Compare &__comp_;
-    _LIBCPP_CONSTEXPR_AFTER_CXX17
-    __debug_less(_Compare& __c) : __comp_(__c) {}
-
-    template <class _Tp, class _Up>
-    _LIBCPP_CONSTEXPR_AFTER_CXX17
-    bool operator()(const _Tp& __x,  const _Up& __y)
-    {
-        bool __r = __comp_(__x, __y);
-        if (__r)
-            __do_compare_assert(0, __y, __x);
-        return __r;
-    }
-
-    template <class _Tp, class _Up>
-    _LIBCPP_CONSTEXPR_AFTER_CXX17
-    bool operator()(_Tp& __x,  _Up& __y)
-    {
-        bool __r = __comp_(__x, __y);
-        if (__r)
-            __do_compare_assert(0, __y, __x);
-        return __r;
-    }
-
-    template <class _LHS, class _RHS>
-    _LIBCPP_CONSTEXPR_AFTER_CXX17
-    inline _LIBCPP_INLINE_VISIBILITY
-    decltype((void)_VSTD::declval<_Compare&>()(
-        _VSTD::declval<_LHS &>(), _VSTD::declval<_RHS &>()))
-    __do_compare_assert(int, _LHS & __l, _RHS & __r) {
-        _LIBCPP_ASSERT(!__comp_(__l, __r),
-            "Comparator does not induce a strict weak ordering");
-    }
-
-    template <class _LHS, class _RHS>
-    _LIBCPP_CONSTEXPR_AFTER_CXX17
-    inline _LIBCPP_INLINE_VISIBILITY
-    void __do_compare_assert(long, _LHS &, _RHS &) {}
-};
-
-#endif // _LIBCPP_DEBUG
-
-template <class _Comp>
-struct __comp_ref_type {
-  // Pass the comparator by lvalue reference. Or in debug mode, using a
-  // debugging wrapper that stores a reference.
-#ifndef _LIBCPP_DEBUG
-  typedef typename add_lvalue_reference<_Comp>::type type;
-#else
-  typedef __debug_less<_Comp> type;
-#endif
-};
-
-// all_of
-
-template <class _InputIterator, class _Predicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-all_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
-{
-    for (; __first != __last; ++__first)
-        if (!__pred(*__first))
-            return false;
-    return true;
-}
-
-// any_of
-
-template <class _InputIterator, class _Predicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-any_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
-{
-    for (; __first != __last; ++__first)
-        if (__pred(*__first))
-            return true;
-    return false;
-}
-
-// none_of
-
-template <class _InputIterator, class _Predicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-none_of(_InputIterator __first, _InputIterator __last, _Predicate __pred)
-{
-    for (; __first != __last; ++__first)
-        if (__pred(*__first))
-            return false;
-    return true;
-}
-
-// for_each
-
-template <class _InputIterator, class _Function>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_Function
-for_each(_InputIterator __first, _InputIterator __last, _Function __f)
-{
-    for (; __first != __last; ++__first)
-        __f(*__first);
-    return __f;
-}
-
-#if _LIBCPP_STD_VER > 14
-// for_each_n
-
-template <class _InputIterator, class _Size, class _Function>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_InputIterator
-for_each_n(_InputIterator __first, _Size __orig_n, _Function __f)
-{
-    typedef decltype(_VSTD::__convert_to_integral(__orig_n)) _IntegralSize;
-    _IntegralSize __n = __orig_n;
-    while (__n > 0)
-    {
-         __f(*__first);
-         ++__first;
-         --__n;
-    }
-    return __first;
-}
-#endif
-
-// find
-
-template <class _InputIterator, class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_InputIterator
-find(_InputIterator __first, _InputIterator __last, const _Tp& __value_)
-{
-    for (; __first != __last; ++__first)
-        if (*__first == __value_)
-            break;
-    return __first;
-}
-
-// find_if
-
-template <class _InputIterator, class _Predicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_InputIterator
-find_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
-{
-    for (; __first != __last; ++__first)
-        if (__pred(*__first))
-            break;
-    return __first;
-}
-
-// find_if_not
-
-template<class _InputIterator, class _Predicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_InputIterator
-find_if_not(_InputIterator __first, _InputIterator __last, _Predicate __pred)
-{
-    for (; __first != __last; ++__first)
-        if (!__pred(*__first))
-            break;
-    return __first;
-}
-
-// find_end
-
-template <class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator1
-__find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-           _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred,
-           forward_iterator_tag, forward_iterator_tag)
-{
-    // modeled after search algorithm
-    _ForwardIterator1 __r = __last1;  // __last1 is the "default" answer
-    if (__first2 == __last2)
-        return __r;
-    while (true)
-    {
-        while (true)
-        {
-            if (__first1 == __last1)         // if source exhausted return last correct answer
-                return __r;                  //    (or __last1 if never found)
-            if (__pred(*__first1, *__first2))
-                break;
-            ++__first1;
-        }
-        // *__first1 matches *__first2, now match elements after here
-        _ForwardIterator1 __m1 = __first1;
-        _ForwardIterator2 __m2 = __first2;
-        while (true)
-        {
-            if (++__m2 == __last2)
-            {                         // Pattern exhaused, record answer and search for another one
-                __r = __first1;
-                ++__first1;
-                break;
-            }
-            if (++__m1 == __last1)     // Source exhausted, return last answer
-                return __r;
-            if (!__pred(*__m1, *__m2))  // mismatch, restart with a new __first
-            {
-                ++__first1;
-                break;
-            }  // else there is a match, check next elements
-        }
-    }
-}
-
-template <class _BinaryPredicate, class _BidirectionalIterator1, class _BidirectionalIterator2>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _BidirectionalIterator1
-__find_end(_BidirectionalIterator1 __first1, _BidirectionalIterator1 __last1,
-           _BidirectionalIterator2 __first2, _BidirectionalIterator2 __last2, _BinaryPredicate __pred,
-           bidirectional_iterator_tag, bidirectional_iterator_tag)
-{
-    // modeled after search algorithm (in reverse)
-    if (__first2 == __last2)
-        return __last1;  // Everything matches an empty sequence
-    _BidirectionalIterator1 __l1 = __last1;
-    _BidirectionalIterator2 __l2 = __last2;
-    --__l2;
-    while (true)
-    {
-        // Find last element in sequence 1 that matchs *(__last2-1), with a mininum of loop checks
-        while (true)
-        {
-            if (__first1 == __l1)  // return __last1 if no element matches *__first2
-                return __last1;
-            if (__pred(*--__l1, *__l2))
-                break;
-        }
-        // *__l1 matches *__l2, now match elements before here
-        _BidirectionalIterator1 __m1 = __l1;
-        _BidirectionalIterator2 __m2 = __l2;
-        while (true)
-        {
-            if (__m2 == __first2)  // If pattern exhausted, __m1 is the answer (works for 1 element pattern)
-                return __m1;
-            if (__m1 == __first1)  // Otherwise if source exhaused, pattern not found
-                return __last1;
-            if (!__pred(*--__m1, *--__m2))  // if there is a mismatch, restart with a new __l1
-            {
-                break;
-            }  // else there is a match, check next elements
-        }
-    }
-}
-
-template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
-_LIBCPP_CONSTEXPR_AFTER_CXX11 _RandomAccessIterator1
-__find_end(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1,
-           _RandomAccessIterator2 __first2, _RandomAccessIterator2 __last2, _BinaryPredicate __pred,
-           random_access_iterator_tag, random_access_iterator_tag)
-{
-    // Take advantage of knowing source and pattern lengths.  Stop short when source is smaller than pattern
-    typename iterator_traits<_RandomAccessIterator2>::difference_type __len2 = __last2 - __first2;
-    if (__len2 == 0)
-        return __last1;
-    typename iterator_traits<_RandomAccessIterator1>::difference_type __len1 = __last1 - __first1;
-    if (__len1 < __len2)
-        return __last1;
-    const _RandomAccessIterator1 __s = __first1 + (__len2 - 1);  // End of pattern match can't go before here
-    _RandomAccessIterator1 __l1 = __last1;
-    _RandomAccessIterator2 __l2 = __last2;
-    --__l2;
-    while (true)
-    {
-        while (true)
-        {
-            if (__s == __l1)
-                return __last1;
-            if (__pred(*--__l1, *__l2))
-                break;
-        }
-        _RandomAccessIterator1 __m1 = __l1;
-        _RandomAccessIterator2 __m2 = __l2;
-        while (true)
-        {
-            if (__m2 == __first2)
-                return __m1;
-                                 // no need to check range on __m1 because __s guarantees we have enough source
-            if (!__pred(*--__m1, *--__m2))
-            {
-                break;
-            }
-        }
-    }
-}
-
-template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator1
-find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-         _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred)
-{
-    return _VSTD::__find_end<typename add_lvalue_reference<_BinaryPredicate>::type>
-                         (__first1, __last1, __first2, __last2, __pred,
-                          typename iterator_traits<_ForwardIterator1>::iterator_category(),
-                          typename iterator_traits<_ForwardIterator2>::iterator_category());
-}
-
-template <class _ForwardIterator1, class _ForwardIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator1
-find_end(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-         _ForwardIterator2 __first2, _ForwardIterator2 __last2)
-{
-    typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
-    typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
-    return _VSTD::find_end(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
-}
-
-// find_first_of
-
-template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
-_LIBCPP_CONSTEXPR_AFTER_CXX11 _ForwardIterator1
-__find_first_of_ce(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-              _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred)
-{
-    for (; __first1 != __last1; ++__first1)
-        for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
-            if (__pred(*__first1, *__j))
-                return __first1;
-    return __last1;
-}
-
-
-template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator1
-find_first_of(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-              _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred)
-{
-    return _VSTD::__find_first_of_ce(__first1, __last1, __first2, __last2, __pred);
-}
-
-template <class _ForwardIterator1, class _ForwardIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator1
-find_first_of(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-              _ForwardIterator2 __first2, _ForwardIterator2 __last2)
-{
-    typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
-    typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
-    return _VSTD::__find_first_of_ce(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
-}
-
-// adjacent_find
-
-template <class _ForwardIterator, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-adjacent_find(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __pred)
-{
-    if (__first != __last)
-    {
-        _ForwardIterator __i = __first;
-        while (++__i != __last)
-        {
-            if (__pred(*__first, *__i))
-                return __first;
-            __first = __i;
-        }
-    }
-    return __last;
-}
-
-template <class _ForwardIterator>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-adjacent_find(_ForwardIterator __first, _ForwardIterator __last)
-{
-    typedef typename iterator_traits<_ForwardIterator>::value_type __v;
-    return _VSTD::adjacent_find(__first, __last, __equal_to<__v>());
-}
-
-// count
-
-template <class _InputIterator, class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-typename iterator_traits<_InputIterator>::difference_type
-count(_InputIterator __first, _InputIterator __last, const _Tp& __value_)
-{
-    typename iterator_traits<_InputIterator>::difference_type __r(0);
-    for (; __first != __last; ++__first)
-        if (*__first == __value_)
-            ++__r;
-    return __r;
-}
-
-// count_if
-
-template <class _InputIterator, class _Predicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-typename iterator_traits<_InputIterator>::difference_type
-count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
-{
-    typename iterator_traits<_InputIterator>::difference_type __r(0);
-    for (; __first != __last; ++__first)
-        if (__pred(*__first))
-            ++__r;
-    return __r;
-}
-
-// mismatch
-
-template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-pair<_InputIterator1, _InputIterator2>
-mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
-         _InputIterator2 __first2, _BinaryPredicate __pred)
-{
-    for (; __first1 != __last1; ++__first1, (void) ++__first2)
-        if (!__pred(*__first1, *__first2))
-            break;
-    return pair<_InputIterator1, _InputIterator2>(__first1, __first2);
-}
-
-template <class _InputIterator1, class _InputIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-pair<_InputIterator1, _InputIterator2>
-mismatch(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2)
-{
-    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
-    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
-    return _VSTD::mismatch(__first1, __last1, __first2, __equal_to<__v1, __v2>());
-}
-
-#if _LIBCPP_STD_VER > 11
-template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-pair<_InputIterator1, _InputIterator2>
-mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
-         _InputIterator2 __first2, _InputIterator2 __last2,
-         _BinaryPredicate __pred)
-{
-    for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void) ++__first2)
-        if (!__pred(*__first1, *__first2))
-            break;
-    return pair<_InputIterator1, _InputIterator2>(__first1, __first2);
-}
-
-template <class _InputIterator1, class _InputIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-pair<_InputIterator1, _InputIterator2>
-mismatch(_InputIterator1 __first1, _InputIterator1 __last1,
-         _InputIterator2 __first2, _InputIterator2 __last2)
-{
-    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
-    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
-    return _VSTD::mismatch(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
-}
-#endif
-
-// equal
-
-template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _BinaryPredicate __pred)
-{
-    for (; __first1 != __last1; ++__first1, (void) ++__first2)
-        if (!__pred(*__first1, *__first2))
-            return false;
-    return true;
-}
-
-template <class _InputIterator1, class _InputIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2)
-{
-    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
-    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
-    return _VSTD::equal(__first1, __last1, __first2, __equal_to<__v1, __v2>());
-}
-
-#if _LIBCPP_STD_VER > 11
-template <class _BinaryPredicate, class _InputIterator1, class _InputIterator2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-__equal(_InputIterator1 __first1, _InputIterator1 __last1,
-        _InputIterator2 __first2, _InputIterator2 __last2, _BinaryPredicate __pred,
-        input_iterator_tag, input_iterator_tag )
-{
-    for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void) ++__first2)
-        if (!__pred(*__first1, *__first2))
-            return false;
-    return __first1 == __last1 && __first2 == __last2;
-}
-
-template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-__equal(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1,
-        _RandomAccessIterator2 __first2, _RandomAccessIterator2 __last2, _BinaryPredicate __pred,
-      random_access_iterator_tag, random_access_iterator_tag )
-{
-    if ( _VSTD::distance(__first1, __last1) != _VSTD::distance(__first2, __last2))
-        return false;
-    return _VSTD::equal<_RandomAccessIterator1, _RandomAccessIterator2,
-                        typename add_lvalue_reference<_BinaryPredicate>::type>
-                       (__first1, __last1, __first2, __pred );
-}
-
-template <class _InputIterator1, class _InputIterator2, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-equal(_InputIterator1 __first1, _InputIterator1 __last1,
-      _InputIterator2 __first2, _InputIterator2 __last2, _BinaryPredicate __pred )
-{
-    return _VSTD::__equal<typename add_lvalue_reference<_BinaryPredicate>::type>
-       (__first1, __last1, __first2, __last2, __pred,
-        typename iterator_traits<_InputIterator1>::iterator_category(),
-        typename iterator_traits<_InputIterator2>::iterator_category());
-}
-
-template <class _InputIterator1, class _InputIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-equal(_InputIterator1 __first1, _InputIterator1 __last1,
-      _InputIterator2 __first2, _InputIterator2 __last2)
-{
-    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
-    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
-    return _VSTD::__equal(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>(),
-        typename iterator_traits<_InputIterator1>::iterator_category(),
-        typename iterator_traits<_InputIterator2>::iterator_category());
-}
-#endif
-
-// is_permutation
-
-template<class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
-is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-               _ForwardIterator2 __first2, _BinaryPredicate __pred)
-{
-//  shorten sequences as much as possible by lopping of any equal prefix
-    for (; __first1 != __last1; ++__first1, (void) ++__first2)
-        if (!__pred(*__first1, *__first2))
-            break;
-    if (__first1 == __last1)
-        return true;
-
-//  __first1 != __last1 && *__first1 != *__first2
-    typedef typename iterator_traits<_ForwardIterator1>::difference_type _D1;
-    _D1 __l1 = _VSTD::distance(__first1, __last1);
-    if (__l1 == _D1(1))
-        return false;
-    _ForwardIterator2 __last2 = _VSTD::next(__first2, __l1);
-    // For each element in [f1, l1) see if there are the same number of
-    //    equal elements in [f2, l2)
-    for (_ForwardIterator1 __i = __first1; __i != __last1; ++__i)
-    {
-    //  Have we already counted the number of *__i in [f1, l1)?
-        _ForwardIterator1 __match = __first1;
-        for (; __match != __i; ++__match)
-            if (__pred(*__match, *__i))
-                break;
-        if (__match == __i) {
-            // Count number of *__i in [f2, l2)
-            _D1 __c2 = 0;
-            for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
-                if (__pred(*__i, *__j))
-                    ++__c2;
-            if (__c2 == 0)
-                return false;
-            // Count number of *__i in [__i, l1) (we can start with 1)
-            _D1 __c1 = 1;
-            for (_ForwardIterator1 __j = _VSTD::next(__i); __j != __last1; ++__j)
-                if (__pred(*__i, *__j))
-                    ++__c1;
-            if (__c1 != __c2)
-                return false;
-        }
-    }
-    return true;
-}
-
-template<class _ForwardIterator1, class _ForwardIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-               _ForwardIterator2 __first2)
-{
-    typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
-    typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
-    return _VSTD::is_permutation(__first1, __last1, __first2, __equal_to<__v1, __v2>());
-}
-
-#if _LIBCPP_STD_VER > 11
-template<class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
-__is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-                 _ForwardIterator2 __first2, _ForwardIterator2 __last2,
-                 _BinaryPredicate __pred,
-                 forward_iterator_tag, forward_iterator_tag )
-{
-//  shorten sequences as much as possible by lopping of any equal prefix
-    for (; __first1 != __last1 && __first2 != __last2; ++__first1, (void) ++__first2)
-        if (!__pred(*__first1, *__first2))
-            break;
-    if (__first1 == __last1)
-        return __first2 == __last2;
-    else if (__first2 == __last2)
-        return false;
-
-    typedef typename iterator_traits<_ForwardIterator1>::difference_type _D1;
-    _D1 __l1 = _VSTD::distance(__first1, __last1);
-
-    typedef typename iterator_traits<_ForwardIterator2>::difference_type _D2;
-    _D2 __l2 = _VSTD::distance(__first2, __last2);
-    if (__l1 != __l2)
-        return false;
-
-    // For each element in [f1, l1) see if there are the same number of
-    //    equal elements in [f2, l2)
-    for (_ForwardIterator1 __i = __first1; __i != __last1; ++__i)
-    {
-    //  Have we already counted the number of *__i in [f1, l1)?
-        _ForwardIterator1 __match = __first1;
-        for (; __match != __i; ++__match)
-            if (__pred(*__match, *__i))
-                break;
-        if (__match == __i) {
-            // Count number of *__i in [f2, l2)
-            _D1 __c2 = 0;
-            for (_ForwardIterator2 __j = __first2; __j != __last2; ++__j)
-                if (__pred(*__i, *__j))
-                    ++__c2;
-            if (__c2 == 0)
-                return false;
-            // Count number of *__i in [__i, l1) (we can start with 1)
-            _D1 __c1 = 1;
-            for (_ForwardIterator1 __j = _VSTD::next(__i); __j != __last1; ++__j)
-                if (__pred(*__i, *__j))
-                    ++__c1;
-            if (__c1 != __c2)
-                return false;
-        }
-    }
-    return true;
-}
-
-template<class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
-__is_permutation(_RandomAccessIterator1 __first1, _RandomAccessIterator2 __last1,
-               _RandomAccessIterator1 __first2, _RandomAccessIterator2 __last2,
-               _BinaryPredicate __pred,
-               random_access_iterator_tag, random_access_iterator_tag )
-{
-    if ( _VSTD::distance(__first1, __last1) != _VSTD::distance(__first2, __last2))
-        return false;
-    return _VSTD::is_permutation<_RandomAccessIterator1, _RandomAccessIterator2,
-                                 typename add_lvalue_reference<_BinaryPredicate>::type>
-                                (__first1, __last1, __first2, __pred );
-}
-
-template<class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-               _ForwardIterator2 __first2, _ForwardIterator2 __last2,
-               _BinaryPredicate __pred )
-{
-    return _VSTD::__is_permutation<typename add_lvalue_reference<_BinaryPredicate>::type>
-       (__first1, __last1, __first2, __last2, __pred,
-        typename iterator_traits<_ForwardIterator1>::iterator_category(),
-        typename iterator_traits<_ForwardIterator2>::iterator_category());
-}
-
-template<class _ForwardIterator1, class _ForwardIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-is_permutation(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-               _ForwardIterator2 __first2, _ForwardIterator2 __last2)
-{
-    typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
-    typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
-    return _VSTD::__is_permutation(__first1, __last1, __first2, __last2,
-        __equal_to<__v1, __v2>(),
-        typename iterator_traits<_ForwardIterator1>::iterator_category(),
-        typename iterator_traits<_ForwardIterator2>::iterator_category());
-}
-#endif
-
-// search
-// __search is in <functional>
-
-template <class _ForwardIterator1, class _ForwardIterator2, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator1
-search(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-       _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred)
-{
-    return _VSTD::__search<typename add_lvalue_reference<_BinaryPredicate>::type>
-                         (__first1, __last1, __first2, __last2, __pred,
-                          typename iterator_traits<_ForwardIterator1>::iterator_category(),
-                          typename iterator_traits<_ForwardIterator2>::iterator_category())
-            .first;
-}
-
-template <class _ForwardIterator1, class _ForwardIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator1
-search(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-       _ForwardIterator2 __first2, _ForwardIterator2 __last2)
-{
-    typedef typename iterator_traits<_ForwardIterator1>::value_type __v1;
-    typedef typename iterator_traits<_ForwardIterator2>::value_type __v2;
-    return _VSTD::search(__first1, __last1, __first2, __last2, __equal_to<__v1, __v2>());
-}
-
-
-#if _LIBCPP_STD_VER > 14
-template <class _ForwardIterator, class _Searcher>
-_LIBCPP_NODISCARD_EXT _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator search(_ForwardIterator __f, _ForwardIterator __l, const _Searcher &__s)
-{ return __s(__f, __l).first; }
-#endif
-
-// search_n
-
-template <class _BinaryPredicate, class _ForwardIterator, class _Size, class _Tp>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-__search_n(_ForwardIterator __first, _ForwardIterator __last,
-           _Size __count, const _Tp& __value_, _BinaryPredicate __pred, forward_iterator_tag)
-{
-    if (__count <= 0)
-        return __first;
-    while (true)
-    {
-        // Find first element in sequence that matchs __value_, with a mininum of loop checks
-        while (true)
-        {
-            if (__first == __last)  // return __last if no element matches __value_
-                return __last;
-            if (__pred(*__first, __value_))
-                break;
-            ++__first;
-        }
-        // *__first matches __value_, now match elements after here
-        _ForwardIterator __m = __first;
-        _Size __c(0);
-        while (true)
-        {
-            if (++__c == __count)  // If pattern exhausted, __first is the answer (works for 1 element pattern)
-                return __first;
-            if (++__m == __last)  // Otherwise if source exhaused, pattern not found
-                return __last;
-            if (!__pred(*__m, __value_))  // if there is a mismatch, restart with a new __first
-            {
-                __first = __m;
-                ++__first;
-                break;
-            }  // else there is a match, check next elements
-        }
-    }
-}
-
-template <class _BinaryPredicate, class _RandomAccessIterator, class _Size, class _Tp>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _RandomAccessIterator
-__search_n(_RandomAccessIterator __first, _RandomAccessIterator __last,
-           _Size __count, const _Tp& __value_, _BinaryPredicate __pred, random_access_iterator_tag)
-{
-    if (__count <= 0)
-        return __first;
-    _Size __len = static_cast<_Size>(__last - __first);
-    if (__len < __count)
-        return __last;
-    const _RandomAccessIterator __s = __last - (__count - 1);  // Start of pattern match can't go beyond here
-    while (true)
-    {
-        // Find first element in sequence that matchs __value_, with a mininum of loop checks
-        while (true)
-        {
-            if (__first >= __s)  // return __last if no element matches __value_
-                return __last;
-            if (__pred(*__first, __value_))
-                break;
-            ++__first;
-        }
-        // *__first matches __value_, now match elements after here
-        _RandomAccessIterator __m = __first;
-        _Size __c(0);
-        while (true)
-        {
-            if (++__c == __count)  // If pattern exhausted, __first is the answer (works for 1 element pattern)
-                return __first;
-             ++__m;          // no need to check range on __m because __s guarantees we have enough source
-            if (!__pred(*__m, __value_))  // if there is a mismatch, restart with a new __first
-            {
-                __first = __m;
-                ++__first;
-                break;
-            }  // else there is a match, check next elements
-        }
-    }
-}
-
-template <class _ForwardIterator, class _Size, class _Tp, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-search_n(_ForwardIterator __first, _ForwardIterator __last,
-         _Size __count, const _Tp& __value_, _BinaryPredicate __pred)
-{
-    return _VSTD::__search_n<typename add_lvalue_reference<_BinaryPredicate>::type>
-           (__first, __last, _VSTD::__convert_to_integral(__count), __value_, __pred,
-           typename iterator_traits<_ForwardIterator>::iterator_category());
-}
-
-template <class _ForwardIterator, class _Size, class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-search_n(_ForwardIterator __first, _ForwardIterator __last, _Size __count, const _Tp& __value_)
-{
-    typedef typename iterator_traits<_ForwardIterator>::value_type __v;
-    return _VSTD::search_n(__first, __last, _VSTD::__convert_to_integral(__count),
-                           __value_, __equal_to<__v, _Tp>());
-}
-
-// copy
-template <class _Iter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-_Iter
-__unwrap_iter(_Iter __i)
-{
-    return __i;
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename enable_if
-<
-    is_trivially_copy_assignable<_Tp>::value,
-    _Tp*
->::type
-__unwrap_iter(move_iterator<_Tp*> __i)
-{
-    return __i.base();
-}
-
-#if _LIBCPP_DEBUG_LEVEL < 2
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename enable_if
-<
-    is_trivially_copy_assignable<_Tp>::value,
-    _Tp*
->::type
-__unwrap_iter(__wrap_iter<_Tp*> __i)
-{
-    return __i.base();
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename enable_if
-<
-    is_trivially_copy_assignable<_Tp>::value,
-    const _Tp*
->::type
-__unwrap_iter(__wrap_iter<const _Tp*> __i)
-{
-    return __i.base();
-}
-
-#else
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename enable_if
-<
-    is_trivially_copy_assignable<_Tp>::value,
-    __wrap_iter<_Tp*>
->::type
-__unwrap_iter(__wrap_iter<_Tp*> __i)
-{
-    return __i;
-}
-
-#endif  // _LIBCPP_DEBUG_LEVEL < 2
-
-template <class _InputIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-__copy_constexpr(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
-{
-    for (; __first != __last; ++__first, (void) ++__result)
-        *__result = *__first;
-    return __result;
-}
-
-template <class _InputIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-_OutputIterator
-__copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
-{
-    return _VSTD::__copy_constexpr(__first, __last, __result);
-}
-
-template <class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-typename enable_if
-<
-    is_same<typename remove_const<_Tp>::type, _Up>::value &&
-    is_trivially_copy_assignable<_Up>::value,
-    _Up*
->::type
-__copy(_Tp* __first, _Tp* __last, _Up* __result)
-{
-    const size_t __n = static_cast<size_t>(__last - __first);
-    if (__n > 0)
-        _VSTD::memmove(__result, __first, __n * sizeof(_Up));
-    return __result + __n;
-}
-
-template <class _InputIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
-{
-    if (__libcpp_is_constant_evaluated()) {
-        return _VSTD::__copy_constexpr(
-            _VSTD::__unwrap_iter(__first), _VSTD::__unwrap_iter(__last), _VSTD::__unwrap_iter(__result));
-    } else {
-        return _VSTD::__copy(
-            _VSTD::__unwrap_iter(__first), _VSTD::__unwrap_iter(__last), _VSTD::__unwrap_iter(__result));
-    }
-}
-
-// copy_backward
-
-template <class _BidirectionalIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-__copy_backward_constexpr(_BidirectionalIterator __first, _BidirectionalIterator __last, _OutputIterator __result)
-{
-    while (__first != __last)
-        *--__result = *--__last;
-    return __result;
-}
-
-template <class _BidirectionalIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-_OutputIterator
-__copy_backward(_BidirectionalIterator __first, _BidirectionalIterator __last, _OutputIterator __result)
-{
-    return _VSTD::__copy_backward_constexpr(__first, __last, __result);
-}
-
-template <class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-typename enable_if
-<
-    is_same<typename remove_const<_Tp>::type, _Up>::value &&
-    is_trivially_copy_assignable<_Up>::value,
-    _Up*
->::type
-__copy_backward(_Tp* __first, _Tp* __last, _Up* __result)
-{
-    const size_t __n = static_cast<size_t>(__last - __first);
-    if (__n > 0)
-    {
-        __result -= __n;
-        _VSTD::memmove(__result, __first, __n * sizeof(_Up));
-    }
-    return __result;
-}
-
-template <class _BidirectionalIterator1, class _BidirectionalIterator2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_BidirectionalIterator2
-copy_backward(_BidirectionalIterator1 __first, _BidirectionalIterator1 __last,
-              _BidirectionalIterator2 __result)
-{
-    if (__libcpp_is_constant_evaluated()) {
-        return _VSTD::__copy_backward_constexpr(_VSTD::__unwrap_iter(__first),
-                                                _VSTD::__unwrap_iter(__last),
-                                                _VSTD::__unwrap_iter(__result));
-    } else {
-        return _VSTD::__copy_backward(_VSTD::__unwrap_iter(__first),
-                                      _VSTD::__unwrap_iter(__last),
-                                      _VSTD::__unwrap_iter(__result));
-    }
-}
-
-// copy_if
-
-template<class _InputIterator, class _OutputIterator, class _Predicate>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-copy_if(_InputIterator __first, _InputIterator __last,
-        _OutputIterator __result, _Predicate __pred)
-{
-    for (; __first != __last; ++__first)
-    {
-        if (__pred(*__first))
-        {
-            *__result = *__first;
-            ++__result;
-        }
-    }
-    return __result;
-}
-
-// copy_n
-
-template<class _InputIterator, class _Size, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-typename enable_if
-<
-    __is_cpp17_input_iterator<_InputIterator>::value &&
-   !__is_cpp17_random_access_iterator<_InputIterator>::value,
-    _OutputIterator
->::type
-copy_n(_InputIterator __first, _Size __orig_n, _OutputIterator __result)
-{
-    typedef decltype(_VSTD::__convert_to_integral(__orig_n)) _IntegralSize;
-    _IntegralSize __n = __orig_n;
-    if (__n > 0)
-    {
-        *__result = *__first;
-        ++__result;
-        for (--__n; __n > 0; --__n)
-        {
-            ++__first;
-            *__result = *__first;
-            ++__result;
-        }
-    }
-    return __result;
-}
-
-template<class _InputIterator, class _Size, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-typename enable_if
-<
-    __is_cpp17_random_access_iterator<_InputIterator>::value,
-    _OutputIterator
->::type
-copy_n(_InputIterator __first, _Size __orig_n, _OutputIterator __result)
-{
-    typedef decltype(_VSTD::__convert_to_integral(__orig_n)) _IntegralSize;
-    _IntegralSize __n = __orig_n;
-    return _VSTD::copy(__first, __first + __n, __result);
-}
-
-// move
-
-// __move_constexpr exists so that __move doesn't call itself when delegating to the constexpr
-// version of __move.
-template <class _InputIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-_OutputIterator
-__move_constexpr(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
-{
-    for (; __first != __last; ++__first, (void) ++__result)
-        *__result = _VSTD::move(*__first);
-    return __result;
-}
-
-template <class _InputIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-_OutputIterator
-__move(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
-{
-    return _VSTD::__move_constexpr(__first, __last, __result);
-}
-
-template <class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-typename enable_if
-<
-    is_same<typename remove_const<_Tp>::type, _Up>::value &&
-    is_trivially_copy_assignable<_Up>::value,
-    _Up*
->::type
-__move(_Tp* __first, _Tp* __last, _Up* __result)
-{
-    if (__libcpp_is_constant_evaluated())
-        return _VSTD::__move_constexpr(__first, __last, __result);
-    const size_t __n = static_cast<size_t>(__last - __first);
-    if (__n > 0)
-        _VSTD::memmove(__result, __first, __n * sizeof(_Up));
-    return __result + __n;
-}
-
-template <class _InputIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-move(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
-{
-    return _VSTD::__move(_VSTD::__unwrap_iter(__first), _VSTD::__unwrap_iter(__last), _VSTD::__unwrap_iter(__result));
-}
-
-// move_backward
-
-// __move_backward_constexpr exists so that __move_backward doesn't call itself when delegating to
-// the constexpr version of __move_backward.
-template <class _InputIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-_OutputIterator
-__move_backward_constexpr(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
-{
-    while (__first != __last)
-        *--__result = _VSTD::move(*--__last);
-    return __result;
-}
-
-template <class _InputIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-_OutputIterator
-__move_backward(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
-{
-    return _VSTD::__move_backward_constexpr(__first, __last, __result);
-}
-
-template <class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-typename enable_if
-<
-    is_same<typename remove_const<_Tp>::type, _Up>::value &&
-    is_trivially_copy_assignable<_Up>::value,
-    _Up*
->::type
-__move_backward(_Tp* __first, _Tp* __last, _Up* __result)
-{
-    if (__libcpp_is_constant_evaluated())
-        return _VSTD::__move_backward_constexpr(__first, __last, __result);
-    const size_t __n = static_cast<size_t>(__last - __first);
-    if (__n > 0)
-    {
-        __result -= __n;
-        _VSTD::memmove(__result, __first, __n * sizeof(_Up));
-    }
-    return __result;
-}
-
-template <class _BidirectionalIterator1, class _BidirectionalIterator2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_BidirectionalIterator2
-move_backward(_BidirectionalIterator1 __first, _BidirectionalIterator1 __last,
-              _BidirectionalIterator2 __result)
-{
-    return _VSTD::__move_backward(_VSTD::__unwrap_iter(__first), _VSTD::__unwrap_iter(__last), _VSTD::__unwrap_iter(__result));
-}
-
-// iter_swap
-
-// moved to <type_traits> for better swap / noexcept support
-
-// transform
-
-template <class _InputIterator, class _OutputIterator, class _UnaryOperation>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op)
-{
-    for (; __first != __last; ++__first, (void) ++__result)
-        *__result = __op(*__first);
-    return __result;
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _BinaryOperation>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-transform(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2,
-          _OutputIterator __result, _BinaryOperation __binary_op)
-{
-    for (; __first1 != __last1; ++__first1, (void) ++__first2, ++__result)
-        *__result = __binary_op(*__first1, *__first2);
-    return __result;
-}
-
-// replace
-
-template <class _ForwardIterator, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-replace(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __old_value, const _Tp& __new_value)
-{
-    for (; __first != __last; ++__first)
-        if (*__first == __old_value)
-            *__first = __new_value;
-}
-
-// replace_if
-
-template <class _ForwardIterator, class _Predicate, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-replace_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, const _Tp& __new_value)
-{
-    for (; __first != __last; ++__first)
-        if (__pred(*__first))
-            *__first = __new_value;
-}
-
-// replace_copy
-
-template <class _InputIterator, class _OutputIterator, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-replace_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
-             const _Tp& __old_value, const _Tp& __new_value)
-{
-    for (; __first != __last; ++__first, (void) ++__result)
-        if (*__first == __old_value)
-            *__result = __new_value;
-        else
-            *__result = *__first;
-    return __result;
-}
-
-// replace_copy_if
-
-template <class _InputIterator, class _OutputIterator, class _Predicate, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-replace_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
-                _Predicate __pred, const _Tp& __new_value)
-{
-    for (; __first != __last; ++__first, (void) ++__result)
-        if (__pred(*__first))
-            *__result = __new_value;
-        else
-            *__result = *__first;
-    return __result;
-}
-
-// fill_n
-
-template <class _OutputIterator, class _Size, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-__fill_n(_OutputIterator __first, _Size __n, const _Tp& __value_)
-{
-    for (; __n > 0; ++__first, (void) --__n)
-        *__first = __value_;
-    return __first;
-}
-
-template <class _OutputIterator, class _Size, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-fill_n(_OutputIterator __first, _Size __n, const _Tp& __value_)
-{
-   return _VSTD::__fill_n(__first, _VSTD::__convert_to_integral(__n), __value_);
-}
-
-// fill
-
-template <class _ForwardIterator, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-__fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, forward_iterator_tag)
-{
-    for (; __first != __last; ++__first)
-        *__first = __value_;
-}
-
-template <class _RandomAccessIterator, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-__fill(_RandomAccessIterator __first, _RandomAccessIterator __last, const _Tp& __value_, random_access_iterator_tag)
-{
-    _VSTD::fill_n(__first, __last - __first, __value_);
-}
-
-template <class _ForwardIterator, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
-{
-    _VSTD::__fill(__first, __last, __value_, typename iterator_traits<_ForwardIterator>::iterator_category());
-}
-
-// generate
-
-template <class _ForwardIterator, class _Generator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-generate(_ForwardIterator __first, _ForwardIterator __last, _Generator __gen)
-{
-    for (; __first != __last; ++__first)
-        *__first = __gen();
-}
-
-// generate_n
-
-template <class _OutputIterator, class _Size, class _Generator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-generate_n(_OutputIterator __first, _Size __orig_n, _Generator __gen)
-{
-    typedef decltype(_VSTD::__convert_to_integral(__orig_n)) _IntegralSize;
-    _IntegralSize __n = __orig_n;
-    for (; __n > 0; ++__first, (void) --__n)
-        *__first = __gen();
-    return __first;
-}
-
-// remove
-
-template <class _ForwardIterator, class _Tp>
-_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-remove(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
-{
-    __first = _VSTD::find(__first, __last, __value_);
-    if (__first != __last)
-    {
-        _ForwardIterator __i = __first;
-        while (++__i != __last)
-        {
-            if (!(*__i == __value_))
-            {
-                *__first = _VSTD::move(*__i);
-                ++__first;
-            }
-        }
-    }
-    return __first;
-}
-
-// remove_if
-
-template <class _ForwardIterator, class _Predicate>
-_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-remove_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
-{
-    __first = _VSTD::find_if<_ForwardIterator, typename add_lvalue_reference<_Predicate>::type>
-                           (__first, __last, __pred);
-    if (__first != __last)
-    {
-        _ForwardIterator __i = __first;
-        while (++__i != __last)
-        {
-            if (!__pred(*__i))
-            {
-                *__first = _VSTD::move(*__i);
-                ++__first;
-            }
-        }
-    }
-    return __first;
-}
-
-// remove_copy
-
-template <class _InputIterator, class _OutputIterator, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-remove_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, const _Tp& __value_)
-{
-    for (; __first != __last; ++__first)
-    {
-        if (!(*__first == __value_))
-        {
-            *__result = *__first;
-            ++__result;
-        }
-    }
-    return __result;
-}
-
-// remove_copy_if
-
-template <class _InputIterator, class _OutputIterator, class _Predicate>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-remove_copy_if(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _Predicate __pred)
-{
-    for (; __first != __last; ++__first)
-    {
-        if (!__pred(*__first))
-        {
-            *__result = *__first;
-            ++__result;
-        }
-    }
-    return __result;
-}
-
-// unique
-
-template <class _ForwardIterator, class _BinaryPredicate>
-_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-unique(_ForwardIterator __first, _ForwardIterator __last, _BinaryPredicate __pred)
-{
-    __first = _VSTD::adjacent_find<_ForwardIterator, typename add_lvalue_reference<_BinaryPredicate>::type>
-                                 (__first, __last, __pred);
-    if (__first != __last)
-    {
-        // ...  a  a  ?  ...
-        //      f     i
-        _ForwardIterator __i = __first;
-        for (++__i; ++__i != __last;)
-            if (!__pred(*__first, *__i))
-                *++__first = _VSTD::move(*__i);
-        ++__first;
-    }
-    return __first;
-}
-
-template <class _ForwardIterator>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-unique(_ForwardIterator __first, _ForwardIterator __last)
-{
-    typedef typename iterator_traits<_ForwardIterator>::value_type __v;
-    return _VSTD::unique(__first, __last, __equal_to<__v>());
-}
-
-// unique_copy
-
-template <class _BinaryPredicate, class _InputIterator, class _OutputIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
-__unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryPredicate __pred,
-              input_iterator_tag, output_iterator_tag)
-{
-    if (__first != __last)
-    {
-        typename iterator_traits<_InputIterator>::value_type __t(*__first);
-        *__result = __t;
-        ++__result;
-        while (++__first != __last)
-        {
-            if (!__pred(__t, *__first))
-            {
-                __t = *__first;
-                *__result = __t;
-                ++__result;
-            }
-        }
-    }
-    return __result;
-}
-
-template <class _BinaryPredicate, class _ForwardIterator, class _OutputIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
-__unique_copy(_ForwardIterator __first, _ForwardIterator __last, _OutputIterator __result, _BinaryPredicate __pred,
-              forward_iterator_tag, output_iterator_tag)
-{
-    if (__first != __last)
-    {
-        _ForwardIterator __i = __first;
-        *__result = *__i;
-        ++__result;
-        while (++__first != __last)
-        {
-            if (!__pred(*__i, *__first))
-            {
-                *__result = *__first;
-                ++__result;
-                __i = __first;
-            }
-        }
-    }
-    return __result;
-}
-
-template <class _BinaryPredicate, class _InputIterator, class _ForwardIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-__unique_copy(_InputIterator __first, _InputIterator __last, _ForwardIterator __result, _BinaryPredicate __pred,
-              input_iterator_tag, forward_iterator_tag)
-{
-    if (__first != __last)
-    {
-        *__result = *__first;
-        while (++__first != __last)
-            if (!__pred(*__result, *__first))
-                *++__result = *__first;
-        ++__result;
-    }
-    return __result;
-}
-
-template <class _InputIterator, class _OutputIterator, class _BinaryPredicate>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _BinaryPredicate __pred)
-{
-    return _VSTD::__unique_copy<typename add_lvalue_reference<_BinaryPredicate>::type>
-                              (__first, __last, __result, __pred,
-                               typename iterator_traits<_InputIterator>::iterator_category(),
-                               typename iterator_traits<_OutputIterator>::iterator_category());
-}
-
-template <class _InputIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-unique_copy(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
-{
-    typedef typename iterator_traits<_InputIterator>::value_type __v;
-    return _VSTD::unique_copy(__first, __last, __result, __equal_to<__v>());
-}
-
-// reverse
-
-template <class _BidirectionalIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-__reverse(_BidirectionalIterator __first, _BidirectionalIterator __last, bidirectional_iterator_tag)
-{
-    while (__first != __last)
-    {
-        if (__first == --__last)
-            break;
-        _VSTD::iter_swap(__first, __last);
-        ++__first;
-    }
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-__reverse(_RandomAccessIterator __first, _RandomAccessIterator __last, random_access_iterator_tag)
-{
-    if (__first != __last)
-        for (; __first < --__last; ++__first)
-            _VSTD::iter_swap(__first, __last);
-}
-
-template <class _BidirectionalIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-reverse(_BidirectionalIterator __first, _BidirectionalIterator __last)
-{
-    _VSTD::__reverse(__first, __last, typename iterator_traits<_BidirectionalIterator>::iterator_category());
-}
-
-// reverse_copy
-
-template <class _BidirectionalIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-reverse_copy(_BidirectionalIterator __first, _BidirectionalIterator __last, _OutputIterator __result)
-{
-    for (; __first != __last; ++__result)
-        *__result = *--__last;
-    return __result;
-}
-
-// rotate
-
-template <class _ForwardIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX11 _ForwardIterator
-__rotate_left(_ForwardIterator __first, _ForwardIterator __last)
-{
-    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
-    value_type __tmp = _VSTD::move(*__first);
-    _ForwardIterator __lm1 = _VSTD::move(_VSTD::next(__first), __last, __first);
-    *__lm1 = _VSTD::move(__tmp);
-    return __lm1;
-}
-
-template <class _BidirectionalIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX11 _BidirectionalIterator
-__rotate_right(_BidirectionalIterator __first, _BidirectionalIterator __last)
-{
-    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
-    _BidirectionalIterator __lm1 = _VSTD::prev(__last);
-    value_type __tmp = _VSTD::move(*__lm1);
-    _BidirectionalIterator __fp1 = _VSTD::move_backward(__first, __lm1, __last);
-    *__first = _VSTD::move(__tmp);
-    return __fp1;
-}
-
-template <class _ForwardIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX14 _ForwardIterator
-__rotate_forward(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last)
-{
-    _ForwardIterator __i = __middle;
-    while (true)
-    {
-        swap(*__first, *__i);
-        ++__first;
-        if (++__i == __last)
-            break;
-        if (__first == __middle)
-            __middle = __i;
-    }
-    _ForwardIterator __r = __first;
-    if (__first != __middle)
-    {
-        __i = __middle;
-        while (true)
-        {
-            swap(*__first, *__i);
-            ++__first;
-            if (++__i == __last)
-            {
-                if (__first == __middle)
-                    break;
-                __i = __middle;
-            }
-            else if (__first == __middle)
-                __middle = __i;
-        }
-    }
-    return __r;
-}
-
-template<typename _Integral>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_CONSTEXPR_AFTER_CXX14 _Integral
-__algo_gcd(_Integral __x, _Integral __y)
-{
-    do
-    {
-        _Integral __t = __x % __y;
-        __x = __y;
-        __y = __t;
-    } while (__y);
-    return __x;
-}
-
-template<typename _RandomAccessIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX14 _RandomAccessIterator
-__rotate_gcd(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-
-    const difference_type __m1 = __middle - __first;
-    const difference_type __m2 = __last - __middle;
-    if (__m1 == __m2)
-    {
-        _VSTD::swap_ranges(__first, __middle, __middle);
-        return __middle;
-    }
-    const difference_type __g = _VSTD::__algo_gcd(__m1, __m2);
-    for (_RandomAccessIterator __p = __first + __g; __p != __first;)
-    {
-        value_type __t(_VSTD::move(*--__p));
-        _RandomAccessIterator __p1 = __p;
-        _RandomAccessIterator __p2 = __p1 + __m1;
-        do
-        {
-            *__p1 = _VSTD::move(*__p2);
-            __p1 = __p2;
-            const difference_type __d = __last - __p2;
-            if (__m1 < __d)
-                __p2 += __m1;
-            else
-                __p2 = __first + (__m1 - __d);
-        } while (__p2 != __p);
-        *__p1 = _VSTD::move(__t);
-    }
-    return __first + __m2;
-}
-
-template <class _ForwardIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_CONSTEXPR_AFTER_CXX11 _ForwardIterator
-__rotate(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last,
-         _VSTD::forward_iterator_tag)
-{
-    typedef typename _VSTD::iterator_traits<_ForwardIterator>::value_type value_type;
-    if (_VSTD::is_trivially_move_assignable<value_type>::value)
-    {
-        if (_VSTD::next(__first) == __middle)
-            return _VSTD::__rotate_left(__first, __last);
-    }
-    return _VSTD::__rotate_forward(__first, __middle, __last);
-}
-
-template <class _BidirectionalIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_CONSTEXPR_AFTER_CXX11 _BidirectionalIterator
-__rotate(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
-         _VSTD::bidirectional_iterator_tag)
-{
-    typedef typename _VSTD::iterator_traits<_BidirectionalIterator>::value_type value_type;
-    if (_VSTD::is_trivially_move_assignable<value_type>::value)
-    {
-        if (_VSTD::next(__first) == __middle)
-            return _VSTD::__rotate_left(__first, __last);
-        if (_VSTD::next(__middle) == __last)
-            return _VSTD::__rotate_right(__first, __last);
-    }
-    return _VSTD::__rotate_forward(__first, __middle, __last);
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_CONSTEXPR_AFTER_CXX11 _RandomAccessIterator
-__rotate(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
-         _VSTD::random_access_iterator_tag)
-{
-    typedef typename _VSTD::iterator_traits<_RandomAccessIterator>::value_type value_type;
-    if (_VSTD::is_trivially_move_assignable<value_type>::value)
-    {
-        if (_VSTD::next(__first) == __middle)
-            return _VSTD::__rotate_left(__first, __last);
-        if (_VSTD::next(__middle) == __last)
-            return _VSTD::__rotate_right(__first, __last);
-        return _VSTD::__rotate_gcd(__first, __middle, __last);
-    }
-    return _VSTD::__rotate_forward(__first, __middle, __last);
-}
-
-template <class _ForwardIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-rotate(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last)
-{
-    if (__first == __middle)
-        return __last;
-    if (__middle == __last)
-        return __first;
-    return _VSTD::__rotate(__first, __middle, __last,
-                           typename _VSTD::iterator_traits<_ForwardIterator>::iterator_category());
-}
-
-// rotate_copy
-
-template <class _ForwardIterator, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-rotate_copy(_ForwardIterator __first, _ForwardIterator __middle, _ForwardIterator __last, _OutputIterator __result)
-{
-    return _VSTD::copy(__first, __middle, _VSTD::copy(__middle, __last, __result));
-}
-
-// min_element
-
-template <class _ForwardIterator, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_ForwardIterator
-min_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
-{
-    static_assert(__is_cpp17_forward_iterator<_ForwardIterator>::value,
-        "std::min_element requires a ForwardIterator");
-    if (__first != __last)
-    {
-        _ForwardIterator __i = __first;
-        while (++__i != __last)
-            if (__comp(*__i, *__first))
-                __first = __i;
-    }
-    return __first;
-}
-
-template <class _ForwardIterator>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_ForwardIterator
-min_element(_ForwardIterator __first, _ForwardIterator __last)
-{
-    return _VSTD::min_element(__first, __last,
-              __less<typename iterator_traits<_ForwardIterator>::value_type>());
-}
-
-// min
-
-template <class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-const _Tp&
-min(const _Tp& __a, const _Tp& __b, _Compare __comp)
-{
-    return __comp(__b, __a) ? __b : __a;
-}
-
-template <class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-const _Tp&
-min(const _Tp& __a, const _Tp& __b)
-{
-    return _VSTD::min(__a, __b, __less<_Tp>());
-}
-
-#ifndef _LIBCPP_CXX03_LANG
-
-template<class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_Tp
-min(initializer_list<_Tp> __t, _Compare __comp)
-{
-    return *_VSTD::min_element(__t.begin(), __t.end(), __comp);
-}
-
-template<class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_Tp
-min(initializer_list<_Tp> __t)
-{
-    return *_VSTD::min_element(__t.begin(), __t.end(), __less<_Tp>());
-}
-
-#endif  // _LIBCPP_CXX03_LANG
-
-// max_element
-
-template <class _ForwardIterator, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_ForwardIterator
-max_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
-{
-    static_assert(__is_cpp17_forward_iterator<_ForwardIterator>::value,
-        "std::max_element requires a ForwardIterator");
-    if (__first != __last)
-    {
-        _ForwardIterator __i = __first;
-        while (++__i != __last)
-            if (__comp(*__first, *__i))
-                __first = __i;
-    }
-    return __first;
-}
-
-
-template <class _ForwardIterator>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_ForwardIterator
-max_element(_ForwardIterator __first, _ForwardIterator __last)
-{
-    return _VSTD::max_element(__first, __last,
-              __less<typename iterator_traits<_ForwardIterator>::value_type>());
-}
-
-// max
-
-template <class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-const _Tp&
-max(const _Tp& __a, const _Tp& __b, _Compare __comp)
-{
-    return __comp(__a, __b) ? __b : __a;
-}
-
-template <class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-const _Tp&
-max(const _Tp& __a, const _Tp& __b)
-{
-    return _VSTD::max(__a, __b, __less<_Tp>());
-}
-
-#ifndef _LIBCPP_CXX03_LANG
-
-template<class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_Tp
-max(initializer_list<_Tp> __t, _Compare __comp)
-{
-    return *_VSTD::max_element(__t.begin(), __t.end(), __comp);
-}
-
-template<class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_Tp
-max(initializer_list<_Tp> __t)
-{
-    return *_VSTD::max_element(__t.begin(), __t.end(), __less<_Tp>());
-}
-
-#endif  // _LIBCPP_CXX03_LANG
-
-#if _LIBCPP_STD_VER > 14
-// clamp
-template<class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-const _Tp&
-clamp(const _Tp& __v, const _Tp& __lo, const _Tp& __hi, _Compare __comp)
-{
-    _LIBCPP_ASSERT(!__comp(__hi, __lo), "Bad bounds passed to std::clamp");
-    return __comp(__v, __lo) ? __lo : __comp(__hi, __v) ? __hi : __v;
-
-}
-
-template<class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-const _Tp&
-clamp(const _Tp& __v, const _Tp& __lo, const _Tp& __hi)
-{
-    return _VSTD::clamp(__v, __lo, __hi, __less<_Tp>());
-}
-#endif
-
-// minmax_element
-
-template <class _ForwardIterator, class _Compare>
-_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX11
-pair<_ForwardIterator, _ForwardIterator>
-minmax_element(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
-{
-  static_assert(__is_cpp17_forward_iterator<_ForwardIterator>::value,
-        "std::minmax_element requires a ForwardIterator");
-  pair<_ForwardIterator, _ForwardIterator> __result(__first, __first);
-  if (__first != __last)
-  {
-      if (++__first != __last)
-      {
-          if (__comp(*__first, *__result.first))
-              __result.first = __first;
-          else
-              __result.second = __first;
-          while (++__first != __last)
-          {
-              _ForwardIterator __i = __first;
-              if (++__first == __last)
-              {
-                  if (__comp(*__i, *__result.first))
-                      __result.first = __i;
-                  else if (!__comp(*__i, *__result.second))
-                      __result.second = __i;
-                  break;
-              }
-              else
-              {
-                  if (__comp(*__first, *__i))
-                  {
-                      if (__comp(*__first, *__result.first))
-                          __result.first = __first;
-                      if (!__comp(*__i, *__result.second))
-                          __result.second = __i;
-                  }
-                  else
-                  {
-                      if (__comp(*__i, *__result.first))
-                          __result.first = __i;
-                      if (!__comp(*__first, *__result.second))
-                          __result.second = __first;
-                  }
-              }
-          }
-      }
-  }
-  return __result;
-}
-
-template <class _ForwardIterator>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-pair<_ForwardIterator, _ForwardIterator>
-minmax_element(_ForwardIterator __first, _ForwardIterator __last)
-{
-    return _VSTD::minmax_element(__first, __last,
-              __less<typename iterator_traits<_ForwardIterator>::value_type>());
-}
-
-// minmax
-
-template<class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-pair<const _Tp&, const _Tp&>
-minmax(const _Tp& __a, const _Tp& __b, _Compare __comp)
-{
-    return __comp(__b, __a) ? pair<const _Tp&, const _Tp&>(__b, __a) :
-                              pair<const _Tp&, const _Tp&>(__a, __b);
-}
-
-template<class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-pair<const _Tp&, const _Tp&>
-minmax(const _Tp& __a, const _Tp& __b)
-{
-    return _VSTD::minmax(__a, __b, __less<_Tp>());
-}
-
-#ifndef _LIBCPP_CXX03_LANG
-
-template<class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-pair<_Tp, _Tp>
-minmax(initializer_list<_Tp> __t, _Compare __comp)
-{
-    typedef typename initializer_list<_Tp>::const_iterator _Iter;
-    _Iter __first = __t.begin();
-    _Iter __last  = __t.end();
-    pair<_Tp, _Tp> __result(*__first, *__first);
-
-    ++__first;
-    if (__t.size() % 2 == 0)
-    {
-        if (__comp(*__first,  __result.first))
-            __result.first  = *__first;
-        else
-            __result.second = *__first;
-        ++__first;
-    }
-
-    while (__first != __last)
-    {
-        _Tp __prev = *__first++;
-        if (__comp(*__first, __prev)) {
-            if ( __comp(*__first, __result.first)) __result.first  = *__first;
-            if (!__comp(__prev, __result.second))  __result.second = __prev;
-            }
-        else {
-            if ( __comp(__prev, __result.first))    __result.first  = __prev;
-            if (!__comp(*__first, __result.second)) __result.second = *__first;
-            }
-
-        __first++;
-    }
-    return __result;
-}
-
-template<class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-pair<_Tp, _Tp>
-minmax(initializer_list<_Tp> __t)
-{
-    return _VSTD::minmax(__t, __less<_Tp>());
-}
-
-#endif  // _LIBCPP_CXX03_LANG
-
-// random_shuffle
-
-// __independent_bits_engine
-
-template <unsigned long long _Xp, size_t _Rp>
-struct __log2_imp
-{
-    static const size_t value = _Xp & ((unsigned long long)(1) << _Rp) ? _Rp
-                                           : __log2_imp<_Xp, _Rp - 1>::value;
-};
-
-template <unsigned long long _Xp>
-struct __log2_imp<_Xp, 0>
-{
-    static const size_t value = 0;
-};
-
-template <size_t _Rp>
-struct __log2_imp<0, _Rp>
-{
-    static const size_t value = _Rp + 1;
-};
-
-template <class _UIntType, _UIntType _Xp>
-struct __log2
-{
-    static const size_t value = __log2_imp<_Xp,
-                                         sizeof(_UIntType) * __CHAR_BIT__ - 1>::value;
-};
-
-template<class _Engine, class _UIntType>
-class __independent_bits_engine
-{
-public:
-    // types
-    typedef _UIntType result_type;
-
-private:
-    typedef typename _Engine::result_type _Engine_result_type;
-    typedef typename conditional
-        <
-            sizeof(_Engine_result_type) <= sizeof(result_type),
-                result_type,
-                _Engine_result_type
-        >::type _Working_result_type;
-
-    _Engine& __e_;
-    size_t __w_;
-    size_t __w0_;
-    size_t __n_;
-    size_t __n0_;
-    _Working_result_type __y0_;
-    _Working_result_type __y1_;
-    _Engine_result_type __mask0_;
-    _Engine_result_type __mask1_;
-
-#ifdef _LIBCPP_CXX03_LANG
-    static const _Working_result_type _Rp = _Engine::_Max - _Engine::_Min
-                                          + _Working_result_type(1);
-#else
-    static _LIBCPP_CONSTEXPR const _Working_result_type _Rp = _Engine::max() - _Engine::min()
-                                                      + _Working_result_type(1);
-#endif
-    static _LIBCPP_CONSTEXPR const size_t __m = __log2<_Working_result_type, _Rp>::value;
-    static _LIBCPP_CONSTEXPR const size_t _WDt = numeric_limits<_Working_result_type>::digits;
-    static _LIBCPP_CONSTEXPR const size_t _EDt = numeric_limits<_Engine_result_type>::digits;
-
-public:
-    // constructors and seeding functions
-    __independent_bits_engine(_Engine& __e, size_t __w);
-
-    // generating functions
-    result_type operator()() {return __eval(integral_constant<bool, _Rp != 0>());}
-
-private:
-    result_type __eval(false_type);
-    result_type __eval(true_type);
-};
-
-template<class _Engine, class _UIntType>
-__independent_bits_engine<_Engine, _UIntType>
-    ::__independent_bits_engine(_Engine& __e, size_t __w)
-        : __e_(__e),
-          __w_(__w)
-{
-    __n_ = __w_ / __m + (__w_ % __m != 0);
-    __w0_ = __w_ / __n_;
-    if (_Rp == 0)
-        __y0_ = _Rp;
-    else if (__w0_ < _WDt)
-        __y0_ = (_Rp >> __w0_) << __w0_;
-    else
-        __y0_ = 0;
-    if (_Rp - __y0_ > __y0_ / __n_)
-    {
-        ++__n_;
-        __w0_ = __w_ / __n_;
-        if (__w0_ < _WDt)
-            __y0_ = (_Rp >> __w0_) << __w0_;
-        else
-            __y0_ = 0;
-    }
-    __n0_ = __n_ - __w_ % __n_;
-    if (__w0_ < _WDt - 1)
-        __y1_ = (_Rp >> (__w0_ + 1)) << (__w0_ + 1);
-    else
-        __y1_ = 0;
-    __mask0_ = __w0_ > 0 ? _Engine_result_type(~0) >> (_EDt - __w0_) :
-                          _Engine_result_type(0);
-    __mask1_ = __w0_ < _EDt - 1 ?
-                               _Engine_result_type(~0) >> (_EDt - (__w0_ + 1)) :
-                               _Engine_result_type(~0);
-}
-
-template<class _Engine, class _UIntType>
-inline
-_UIntType
-__independent_bits_engine<_Engine, _UIntType>::__eval(false_type)
-{
-    return static_cast<result_type>(__e_() & __mask0_);
-}
-
-template<class _Engine, class _UIntType>
-_UIntType
-__independent_bits_engine<_Engine, _UIntType>::__eval(true_type)
-{
-    const size_t _WRt = numeric_limits<result_type>::digits;
-    result_type _Sp = 0;
-    for (size_t __k = 0; __k < __n0_; ++__k)
-    {
-        _Engine_result_type __u;
-        do
-        {
-            __u = __e_() - _Engine::min();
-        } while (__u >= __y0_);
-        if (__w0_ < _WRt)
-            _Sp <<= __w0_;
-        else
-            _Sp = 0;
-        _Sp += __u & __mask0_;
-    }
-    for (size_t __k = __n0_; __k < __n_; ++__k)
-    {
-        _Engine_result_type __u;
-        do
-        {
-            __u = __e_() - _Engine::min();
-        } while (__u >= __y1_);
-        if (__w0_ < _WRt - 1)
-            _Sp <<= __w0_ + 1;
-        else
-            _Sp = 0;
-        _Sp += __u & __mask1_;
-    }
-    return _Sp;
-}
-
-// uniform_int_distribution
-
-template<class _IntType = int>
-class uniform_int_distribution
-{
-public:
-    // types
-    typedef _IntType result_type;
-
-    class param_type
-    {
-        result_type __a_;
-        result_type __b_;
-    public:
-        typedef uniform_int_distribution distribution_type;
-
-        explicit param_type(result_type __a = 0,
-                            result_type __b = numeric_limits<result_type>::max())
-            : __a_(__a), __b_(__b) {}
-
-        result_type a() const {return __a_;}
-        result_type b() const {return __b_;}
-
-        friend bool operator==(const param_type& __x, const param_type& __y)
-            {return __x.__a_ == __y.__a_ && __x.__b_ == __y.__b_;}
-        friend bool operator!=(const param_type& __x, const param_type& __y)
-            {return !(__x == __y);}
-    };
-
-private:
-    param_type __p_;
-
-public:
-    // constructors and reset functions
-#ifndef _LIBCPP_CXX03_LANG
-    uniform_int_distribution() : uniform_int_distribution(0) {}
-    explicit uniform_int_distribution(
-        result_type __a, result_type __b = numeric_limits<result_type>::max())
-        : __p_(param_type(__a, __b)) {}
-#else
-    explicit uniform_int_distribution(
-        result_type __a = 0,
-        result_type __b = numeric_limits<result_type>::max())
-        : __p_(param_type(__a, __b)) {}
-#endif
-    explicit uniform_int_distribution(const param_type& __p) : __p_(__p) {}
-    void reset() {}
-
-    // generating functions
-    template<class _URNG> result_type operator()(_URNG& __g)
-        {return (*this)(__g, __p_);}
-    template<class _URNG> result_type operator()(_URNG& __g, const param_type& __p);
-
-    // property functions
-    result_type a() const {return __p_.a();}
-    result_type b() const {return __p_.b();}
-
-    param_type param() const {return __p_;}
-    void param(const param_type& __p) {__p_ = __p;}
-
-    result_type min() const {return a();}
-    result_type max() const {return b();}
-
-    friend bool operator==(const uniform_int_distribution& __x,
-                           const uniform_int_distribution& __y)
-        {return __x.__p_ == __y.__p_;}
-    friend bool operator!=(const uniform_int_distribution& __x,
-                           const uniform_int_distribution& __y)
-            {return !(__x == __y);}
-};
-
-template<class _IntType>
-template<class _URNG>
-typename uniform_int_distribution<_IntType>::result_type
-uniform_int_distribution<_IntType>::operator()(_URNG& __g, const param_type& __p)
-_LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
-{
-    typedef typename conditional<sizeof(result_type) <= sizeof(uint32_t),
-                                            uint32_t, uint64_t>::type _UIntType;
-    const _UIntType _Rp = _UIntType(__p.b()) - _UIntType(__p.a()) + _UIntType(1);
-    if (_Rp == 1)
-        return __p.a();
-    const size_t _Dt = numeric_limits<_UIntType>::digits;
-    typedef __independent_bits_engine<_URNG, _UIntType> _Eng;
-    if (_Rp == 0)
-        return static_cast<result_type>(_Eng(__g, _Dt)());
-    size_t __w = _Dt - __libcpp_clz(_Rp) - 1;
-    if ((_Rp & (numeric_limits<_UIntType>::max() >> (_Dt - __w))) != 0)
-        ++__w;
-    _Eng __e(__g, __w);
-    _UIntType __u;
-    do
-    {
-        __u = __e();
-    } while (__u >= _Rp);
-    return static_cast<result_type>(__u + __p.a());
-}
-
-#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_RANDOM_SHUFFLE) \
-  || defined(_LIBCPP_BUILDING_LIBRARY)
-class _LIBCPP_TYPE_VIS __rs_default;
-
-_LIBCPP_FUNC_VIS __rs_default __rs_get();
-
-class _LIBCPP_TYPE_VIS __rs_default
-{
-    static unsigned __c_;
-
-    __rs_default();
-public:
-    typedef uint_fast32_t result_type;
-
-    static const result_type _Min = 0;
-    static const result_type _Max = 0xFFFFFFFF;
-
-    __rs_default(const __rs_default&);
-    ~__rs_default();
-
-    result_type operator()();
-
-    static _LIBCPP_CONSTEXPR result_type min() {return _Min;}
-    static _LIBCPP_CONSTEXPR result_type max() {return _Max;}
-
-    friend _LIBCPP_FUNC_VIS __rs_default __rs_get();
-};
-
-_LIBCPP_FUNC_VIS __rs_default __rs_get();
-
-template <class _RandomAccessIterator>
-_LIBCPP_DEPRECATED_IN_CXX14 void
-random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    typedef uniform_int_distribution<ptrdiff_t> _Dp;
-    typedef typename _Dp::param_type _Pp;
-    difference_type __d = __last - __first;
-    if (__d > 1)
-    {
-        _Dp __uid;
-        __rs_default __g = __rs_get();
-        for (--__last, (void) --__d; __first < __last; ++__first, (void) --__d)
-        {
-            difference_type __i = __uid(__g, _Pp(0, __d));
-            if (__i != difference_type(0))
-                swap(*__first, *(__first + __i));
-        }
-    }
-}
-
-template <class _RandomAccessIterator, class _RandomNumberGenerator>
-_LIBCPP_DEPRECATED_IN_CXX14 void
-random_shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last,
-#ifndef _LIBCPP_CXX03_LANG
-               _RandomNumberGenerator&& __rand)
-#else
-               _RandomNumberGenerator& __rand)
-#endif
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    difference_type __d = __last - __first;
-    if (__d > 1)
-    {
-        for (--__last; __first < __last; ++__first, (void) --__d)
-        {
-            difference_type __i = __rand(__d);
-            if (__i != difference_type(0))
-              swap(*__first, *(__first + __i));
-        }
-    }
-}
-#endif
-
-template <class _PopulationIterator, class _SampleIterator, class _Distance,
-          class _UniformRandomNumberGenerator>
-_LIBCPP_INLINE_VISIBILITY
-_SampleIterator __sample(_PopulationIterator __first,
-                         _PopulationIterator __last, _SampleIterator __output_iter,
-                         _Distance __n,
-                         _UniformRandomNumberGenerator & __g,
-                         input_iterator_tag) {
-
-  _Distance __k = 0;
-  for (; __first != __last && __k < __n; ++__first, (void) ++__k)
-    __output_iter[__k] = *__first;
-  _Distance __sz = __k;
-  for (; __first != __last; ++__first, (void) ++__k) {
-    _Distance __r = _VSTD::uniform_int_distribution<_Distance>(0, __k)(__g);
-    if (__r < __sz)
-      __output_iter[__r] = *__first;
-  }
-  return __output_iter + _VSTD::min(__n, __k);
-}
-
-template <class _PopulationIterator, class _SampleIterator, class _Distance,
-          class _UniformRandomNumberGenerator>
-_LIBCPP_INLINE_VISIBILITY
-_SampleIterator __sample(_PopulationIterator __first,
-                         _PopulationIterator __last, _SampleIterator __output_iter,
-                         _Distance __n,
-                         _UniformRandomNumberGenerator& __g,
-                         forward_iterator_tag) {
-  _Distance __unsampled_sz = _VSTD::distance(__first, __last);
-  for (__n = _VSTD::min(__n, __unsampled_sz); __n != 0; ++__first) {
-    _Distance __r =
-        _VSTD::uniform_int_distribution<_Distance>(0, --__unsampled_sz)(__g);
-    if (__r < __n) {
-      *__output_iter++ = *__first;
-      --__n;
-    }
-  }
-  return __output_iter;
-}
-
-template <class _PopulationIterator, class _SampleIterator, class _Distance,
-          class _UniformRandomNumberGenerator>
-_LIBCPP_INLINE_VISIBILITY
-_SampleIterator __sample(_PopulationIterator __first,
-                         _PopulationIterator __last, _SampleIterator __output_iter,
-                         _Distance __n, _UniformRandomNumberGenerator& __g) {
-  typedef typename iterator_traits<_PopulationIterator>::iterator_category
-        _PopCategory;
-  typedef typename iterator_traits<_PopulationIterator>::difference_type
-        _Difference;
-  static_assert(__is_cpp17_forward_iterator<_PopulationIterator>::value ||
-                __is_cpp17_random_access_iterator<_SampleIterator>::value,
-                "SampleIterator must meet the requirements of RandomAccessIterator");
-  typedef typename common_type<_Distance, _Difference>::type _CommonType;
-  _LIBCPP_ASSERT(__n >= 0, "N must be a positive number.");
-  return _VSTD::__sample(
-      __first, __last, __output_iter, _CommonType(__n),
-      __g, _PopCategory());
-}
-
-#if _LIBCPP_STD_VER > 14
-template <class _PopulationIterator, class _SampleIterator, class _Distance,
-          class _UniformRandomNumberGenerator>
-inline _LIBCPP_INLINE_VISIBILITY
-_SampleIterator sample(_PopulationIterator __first,
-                       _PopulationIterator __last, _SampleIterator __output_iter,
-                       _Distance __n, _UniformRandomNumberGenerator&& __g) {
-    return _VSTD::__sample(__first, __last, __output_iter, __n, __g);
-}
-#endif // _LIBCPP_STD_VER > 14
-
-template<class _RandomAccessIterator, class _UniformRandomNumberGenerator>
-    void shuffle(_RandomAccessIterator __first, _RandomAccessIterator __last,
-                 _UniformRandomNumberGenerator&& __g)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    typedef uniform_int_distribution<ptrdiff_t> _Dp;
-    typedef typename _Dp::param_type _Pp;
-    difference_type __d = __last - __first;
-    if (__d > 1)
-    {
-        _Dp __uid;
-        for (--__last, (void) --__d; __first < __last; ++__first, (void) --__d)
-        {
-            difference_type __i = __uid(__g, _Pp(0, __d));
-            if (__i != difference_type(0))
-                swap(*__first, *(__first + __i));
-        }
-    }
-}
-
-#if _LIBCPP_STD_VER > 17
-
-// shift_left, shift_right
-
-template <class _ForwardIterator>
-inline _LIBCPP_INLINE_VISIBILITY constexpr
-_ForwardIterator
-shift_left(_ForwardIterator __first, _ForwardIterator __last,
-           typename iterator_traits<_ForwardIterator>::difference_type __n)
-{
-    if (__n == 0) {
-        return __last;
-    }
-
-    _ForwardIterator __m = __first;
-    if constexpr (__is_cpp17_random_access_iterator<_ForwardIterator>::value) {
-        if (__n >= __last - __first) {
-            return __first;
-        }
-        __m += __n;
-    } else {
-        for (; __n > 0; --__n) {
-            if (__m == __last) {
-                return __first;
-            }
-            ++__m;
-        }
-    }
-    return _VSTD::move(__m, __last, __first);
-}
-
-template <class _ForwardIterator>
-inline _LIBCPP_INLINE_VISIBILITY constexpr
-_ForwardIterator
-shift_right(_ForwardIterator __first, _ForwardIterator __last,
-            typename iterator_traits<_ForwardIterator>::difference_type __n)
-{
-    if (__n == 0) {
-        return __first;
-    }
-
-    if constexpr (__is_cpp17_random_access_iterator<_ForwardIterator>::value) {
-        decltype(__n) __d = __last - __first;
-        if (__n >= __d) {
-            return __last;
-        }
-        _ForwardIterator __m = __first + (__d - __n);
-        return _VSTD::move_backward(__first, __m, __last);
-    } else if constexpr (__is_cpp17_bidirectional_iterator<_ForwardIterator>::value) {
-        _ForwardIterator __m = __last;
-        for (; __n > 0; --__n) {
-            if (__m == __first) {
-                return __last;
-            }
-            --__m;
-        }
-        return _VSTD::move_backward(__first, __m, __last);
-    } else {
-        _ForwardIterator __ret = __first;
-        for (; __n > 0; --__n) {
-            if (__ret == __last) {
-                return __last;
-            }
-            ++__ret;
-        }
-
-        // We have an __n-element scratch space from __first to __ret.
-        // Slide an __n-element window [__trail, __lead) from left to right.
-        // We're essentially doing swap_ranges(__first, __ret, __trail, __lead)
-        // over and over; but once __lead reaches __last we needn't bother
-        // to save the values of elements [__trail, __last).
-
-        auto __trail = __first;
-        auto __lead = __ret;
-        while (__trail != __ret) {
-            if (__lead == __last) {
-                _VSTD::move(__first, __trail, __ret);
-                return __ret;
-            }
-            ++__trail;
-            ++__lead;
-        }
-
-        _ForwardIterator __mid = __first;
-        while (true) {
-            if (__lead == __last) {
-                __trail = _VSTD::move(__mid, __ret, __trail);
-                _VSTD::move(__first, __mid, __trail);
-                return __ret;
-            }
-            swap(*__mid, *__trail);
-            ++__mid;
-            ++__trail;
-            ++__lead;
-            if (__mid == __ret) {
-                __mid = __first;
-            }
-        }
-    }
-}
-
-#endif // _LIBCPP_STD_VER > 17
-
-// is_partitioned
-
-template <class _InputIterator, class _Predicate>
-_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 bool
-is_partitioned(_InputIterator __first, _InputIterator __last, _Predicate __pred)
-{
-    for (; __first != __last; ++__first)
-        if (!__pred(*__first))
-            break;
-    if ( __first == __last )
-        return true;
-    ++__first;
-    for (; __first != __last; ++__first)
-        if (__pred(*__first))
-            return false;
-    return true;
-}
-
-// partition
-
-template <class _Predicate, class _ForwardIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-__partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred, forward_iterator_tag)
-{
-    while (true)
-    {
-        if (__first == __last)
-            return __first;
-        if (!__pred(*__first))
-            break;
-        ++__first;
-    }
-    for (_ForwardIterator __p = __first; ++__p != __last;)
-    {
-        if (__pred(*__p))
-        {
-            swap(*__first, *__p);
-            ++__first;
-        }
-    }
-    return __first;
-}
-
-template <class _Predicate, class _BidirectionalIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _BidirectionalIterator
-__partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
-            bidirectional_iterator_tag)
-{
-    while (true)
-    {
-        while (true)
-        {
-            if (__first == __last)
-                return __first;
-            if (!__pred(*__first))
-                break;
-            ++__first;
-        }
-        do
-        {
-            if (__first == --__last)
-                return __first;
-        } while (!__pred(*__last));
-        swap(*__first, *__last);
-        ++__first;
-    }
-}
-
-template <class _ForwardIterator, class _Predicate>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
-{
-    return _VSTD::__partition<typename add_lvalue_reference<_Predicate>::type>
-                            (__first, __last, __pred, typename iterator_traits<_ForwardIterator>::iterator_category());
-}
-
-// partition_copy
-
-template <class _InputIterator, class _OutputIterator1,
-          class _OutputIterator2, class _Predicate>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_OutputIterator1, _OutputIterator2>
-partition_copy(_InputIterator __first, _InputIterator __last,
-               _OutputIterator1 __out_true, _OutputIterator2 __out_false,
-               _Predicate __pred)
-{
-    for (; __first != __last; ++__first)
-    {
-        if (__pred(*__first))
-        {
-            *__out_true = *__first;
-            ++__out_true;
-        }
-        else
-        {
-            *__out_false = *__first;
-            ++__out_false;
-        }
-    }
-    return pair<_OutputIterator1, _OutputIterator2>(__out_true, __out_false);
-}
-
-// partition_point
-
-template<class _ForwardIterator, class _Predicate>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-partition_point(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
-{
-    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
-    difference_type __len = _VSTD::distance(__first, __last);
-    while (__len != 0)
-    {
-        difference_type __l2 = _VSTD::__half_positive(__len);
-        _ForwardIterator __m = __first;
-        _VSTD::advance(__m, __l2);
-        if (__pred(*__m))
-        {
-            __first = ++__m;
-            __len -= __l2 + 1;
-        }
-        else
-            __len = __l2;
-    }
-    return __first;
-}
-
-// stable_partition
-
-template <class _Predicate, class _ForwardIterator, class _Distance, class _Pair>
-_ForwardIterator
-__stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred,
-                   _Distance __len, _Pair __p, forward_iterator_tag __fit)
-{
-    // *__first is known to be false
-    // __len >= 1
-    if (__len == 1)
-        return __first;
-    if (__len == 2)
-    {
-        _ForwardIterator __m = __first;
-        if (__pred(*++__m))
-        {
-            swap(*__first, *__m);
-            return __m;
-        }
-        return __first;
-    }
-    if (__len <= __p.second)
-    {   // The buffer is big enough to use
-        typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
-        __destruct_n __d(0);
-        unique_ptr<value_type, __destruct_n&> __h(__p.first, __d);
-        // Move the falses into the temporary buffer, and the trues to the front of the line
-        // Update __first to always point to the end of the trues
-        value_type* __t = __p.first;
-        ::new ((void*)__t) value_type(_VSTD::move(*__first));
-        __d.template __incr<value_type>();
-        ++__t;
-        _ForwardIterator __i = __first;
-        while (++__i != __last)
-        {
-            if (__pred(*__i))
-            {
-                *__first = _VSTD::move(*__i);
-                ++__first;
-            }
-            else
-            {
-                ::new ((void*)__t) value_type(_VSTD::move(*__i));
-                __d.template __incr<value_type>();
-                ++__t;
-            }
-        }
-        // All trues now at start of range, all falses in buffer
-        // Move falses back into range, but don't mess up __first which points to first false
-        __i = __first;
-        for (value_type* __t2 = __p.first; __t2 < __t; ++__t2, (void) ++__i)
-            *__i = _VSTD::move(*__t2);
-        // __h destructs moved-from values out of the temp buffer, but doesn't deallocate buffer
-        return __first;
-    }
-    // Else not enough buffer, do in place
-    // __len >= 3
-    _ForwardIterator __m = __first;
-    _Distance __len2 = __len / 2;  // __len2 >= 2
-    _VSTD::advance(__m, __len2);
-    // recurse on [__first, __m), *__first know to be false
-    // F?????????????????
-    // f       m         l
-    typedef typename add_lvalue_reference<_Predicate>::type _PredRef;
-    _ForwardIterator __first_false = _VSTD::__stable_partition<_PredRef>(__first, __m, __pred, __len2, __p, __fit);
-    // TTTFFFFF??????????
-    // f  ff   m         l
-    // recurse on [__m, __last], except increase __m until *(__m) is false, *__last know to be true
-    _ForwardIterator __m1 = __m;
-    _ForwardIterator __second_false = __last;
-    _Distance __len_half = __len - __len2;
-    while (__pred(*__m1))
-    {
-        if (++__m1 == __last)
-            goto __second_half_done;
-        --__len_half;
-    }
-    // TTTFFFFFTTTF??????
-    // f  ff   m  m1     l
-    __second_false = _VSTD::__stable_partition<_PredRef>(__m1, __last, __pred, __len_half, __p, __fit);
-__second_half_done:
-    // TTTFFFFFTTTTTFFFFF
-    // f  ff   m    sf   l
-    return _VSTD::rotate(__first_false, __m, __second_false);
-    // TTTTTTTTFFFFFFFFFF
-    //         |
-}
-
-struct __return_temporary_buffer
-{
-    template <class _Tp>
-    _LIBCPP_INLINE_VISIBILITY void operator()(_Tp* __p) const {_VSTD::return_temporary_buffer(__p);}
-};
-
-template <class _Predicate, class _ForwardIterator>
-_ForwardIterator
-__stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred,
-                   forward_iterator_tag)
-{
-    const unsigned __alloc_limit = 3;  // might want to make this a function of trivial assignment
-    // Either prove all true and return __first or point to first false
-    while (true)
-    {
-        if (__first == __last)
-            return __first;
-        if (!__pred(*__first))
-            break;
-        ++__first;
-    }
-    // We now have a reduced range [__first, __last)
-    // *__first is known to be false
-    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
-    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
-    difference_type __len = _VSTD::distance(__first, __last);
-    pair<value_type*, ptrdiff_t> __p(0, 0);
-    unique_ptr<value_type, __return_temporary_buffer> __h;
-    if (__len >= __alloc_limit)
-    {
-        __p = _VSTD::get_temporary_buffer<value_type>(__len);
-        __h.reset(__p.first);
-    }
-    return _VSTD::__stable_partition<typename add_lvalue_reference<_Predicate>::type>
-                             (__first, __last, __pred, __len, __p, forward_iterator_tag());
-}
-
-template <class _Predicate, class _BidirectionalIterator, class _Distance, class _Pair>
-_BidirectionalIterator
-__stable_partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
-                   _Distance __len, _Pair __p, bidirectional_iterator_tag __bit)
-{
-    // *__first is known to be false
-    // *__last is known to be true
-    // __len >= 2
-    if (__len == 2)
-    {
-        swap(*__first, *__last);
-        return __last;
-    }
-    if (__len == 3)
-    {
-        _BidirectionalIterator __m = __first;
-        if (__pred(*++__m))
-        {
-            swap(*__first, *__m);
-            swap(*__m, *__last);
-            return __last;
-        }
-        swap(*__m, *__last);
-        swap(*__first, *__m);
-        return __m;
-    }
-    if (__len <= __p.second)
-    {   // The buffer is big enough to use
-        typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
-        __destruct_n __d(0);
-        unique_ptr<value_type, __destruct_n&> __h(__p.first, __d);
-        // Move the falses into the temporary buffer, and the trues to the front of the line
-        // Update __first to always point to the end of the trues
-        value_type* __t = __p.first;
-        ::new ((void*)__t) value_type(_VSTD::move(*__first));
-        __d.template __incr<value_type>();
-        ++__t;
-        _BidirectionalIterator __i = __first;
-        while (++__i != __last)
-        {
-            if (__pred(*__i))
-            {
-                *__first = _VSTD::move(*__i);
-                ++__first;
-            }
-            else
-            {
-                ::new ((void*)__t) value_type(_VSTD::move(*__i));
-                __d.template __incr<value_type>();
-                ++__t;
-            }
-        }
-        // move *__last, known to be true
-        *__first = _VSTD::move(*__i);
-        __i = ++__first;
-        // All trues now at start of range, all falses in buffer
-        // Move falses back into range, but don't mess up __first which points to first false
-        for (value_type* __t2 = __p.first; __t2 < __t; ++__t2, (void) ++__i)
-            *__i = _VSTD::move(*__t2);
-        // __h destructs moved-from values out of the temp buffer, but doesn't deallocate buffer
-        return __first;
-    }
-    // Else not enough buffer, do in place
-    // __len >= 4
-    _BidirectionalIterator __m = __first;
-    _Distance __len2 = __len / 2;  // __len2 >= 2
-    _VSTD::advance(__m, __len2);
-    // recurse on [__first, __m-1], except reduce __m-1 until *(__m-1) is true, *__first know to be false
-    // F????????????????T
-    // f       m        l
-    _BidirectionalIterator __m1 = __m;
-    _BidirectionalIterator __first_false = __first;
-    _Distance __len_half = __len2;
-    while (!__pred(*--__m1))
-    {
-        if (__m1 == __first)
-            goto __first_half_done;
-        --__len_half;
-    }
-    // F???TFFF?????????T
-    // f   m1  m        l
-    typedef typename add_lvalue_reference<_Predicate>::type _PredRef;
-    __first_false = _VSTD::__stable_partition<_PredRef>(__first, __m1, __pred, __len_half, __p, __bit);
-__first_half_done:
-    // TTTFFFFF?????????T
-    // f  ff   m        l
-    // recurse on [__m, __last], except increase __m until *(__m) is false, *__last know to be true
-    __m1 = __m;
-    _BidirectionalIterator __second_false = __last;
-    ++__second_false;
-    __len_half = __len - __len2;
-    while (__pred(*__m1))
-    {
-        if (++__m1 == __last)
-            goto __second_half_done;
-        --__len_half;
-    }
-    // TTTFFFFFTTTF?????T
-    // f  ff   m  m1    l
-    __second_false = _VSTD::__stable_partition<_PredRef>(__m1, __last, __pred, __len_half, __p, __bit);
-__second_half_done:
-    // TTTFFFFFTTTTTFFFFF
-    // f  ff   m    sf  l
-    return _VSTD::rotate(__first_false, __m, __second_false);
-    // TTTTTTTTFFFFFFFFFF
-    //         |
-}
-
-template <class _Predicate, class _BidirectionalIterator>
-_BidirectionalIterator
-__stable_partition(_BidirectionalIterator __first, _BidirectionalIterator __last, _Predicate __pred,
-                   bidirectional_iterator_tag)
-{
-    typedef typename iterator_traits<_BidirectionalIterator>::difference_type difference_type;
-    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
-    const difference_type __alloc_limit = 4;  // might want to make this a function of trivial assignment
-    // Either prove all true and return __first or point to first false
-    while (true)
-    {
-        if (__first == __last)
-            return __first;
-        if (!__pred(*__first))
-            break;
-        ++__first;
-    }
-    // __first points to first false, everything prior to __first is already set.
-    // Either prove [__first, __last) is all false and return __first, or point __last to last true
-    do
-    {
-        if (__first == --__last)
-            return __first;
-    } while (!__pred(*__last));
-    // We now have a reduced range [__first, __last]
-    // *__first is known to be false
-    // *__last is known to be true
-    // __len >= 2
-    difference_type __len = _VSTD::distance(__first, __last) + 1;
-    pair<value_type*, ptrdiff_t> __p(0, 0);
-    unique_ptr<value_type, __return_temporary_buffer> __h;
-    if (__len >= __alloc_limit)
-    {
-        __p = _VSTD::get_temporary_buffer<value_type>(__len);
-        __h.reset(__p.first);
-    }
-    return _VSTD::__stable_partition<typename add_lvalue_reference<_Predicate>::type>
-                             (__first, __last, __pred, __len, __p, bidirectional_iterator_tag());
-}
-
-template <class _ForwardIterator, class _Predicate>
-inline _LIBCPP_INLINE_VISIBILITY
-_ForwardIterator
-stable_partition(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred)
-{
-    return _VSTD::__stable_partition<typename add_lvalue_reference<_Predicate>::type>
-                             (__first, __last, __pred, typename iterator_traits<_ForwardIterator>::iterator_category());
-}
-
-// is_sorted_until
-
-template <class _ForwardIterator, class _Compare>
-_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-is_sorted_until(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
-{
-    if (__first != __last)
-    {
-        _ForwardIterator __i = __first;
-        while (++__i != __last)
-        {
-            if (__comp(*__i, *__first))
-                return __i;
-            __first = __i;
-        }
-    }
-    return __last;
-}
-
-template<class _ForwardIterator>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-is_sorted_until(_ForwardIterator __first, _ForwardIterator __last)
-{
-    return _VSTD::is_sorted_until(__first, __last, __less<typename iterator_traits<_ForwardIterator>::value_type>());
-}
-
-// is_sorted
-
-template <class _ForwardIterator, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-is_sorted(_ForwardIterator __first, _ForwardIterator __last, _Compare __comp)
-{
-    return _VSTD::is_sorted_until(__first, __last, __comp) == __last;
-}
-
-template<class _ForwardIterator>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-is_sorted(_ForwardIterator __first, _ForwardIterator __last)
-{
-    return _VSTD::is_sorted(__first, __last, __less<typename iterator_traits<_ForwardIterator>::value_type>());
-}
-
-// sort
-
-// stable, 2-3 compares, 0-2 swaps
-
-template <class _Compare, class _ForwardIterator>
-unsigned
-__sort3(_ForwardIterator __x, _ForwardIterator __y, _ForwardIterator __z, _Compare __c)
-{
-    unsigned __r = 0;
-    if (!__c(*__y, *__x))          // if x <= y
-    {
-        if (!__c(*__z, *__y))      // if y <= z
-            return __r;            // x <= y && y <= z
-                                   // x <= y && y > z
-        swap(*__y, *__z);          // x <= z && y < z
-        __r = 1;
-        if (__c(*__y, *__x))       // if x > y
-        {
-            swap(*__x, *__y);      // x < y && y <= z
-            __r = 2;
-        }
-        return __r;                // x <= y && y < z
-    }
-    if (__c(*__z, *__y))           // x > y, if y > z
-    {
-        swap(*__x, *__z);          // x < y && y < z
-        __r = 1;
-        return __r;
-    }
-    swap(*__x, *__y);              // x > y && y <= z
-    __r = 1;                       // x < y && x <= z
-    if (__c(*__z, *__y))           // if y > z
-    {
-        swap(*__y, *__z);          // x <= y && y < z
-        __r = 2;
-    }
-    return __r;
-}                                  // x <= y && y <= z
-
-// stable, 3-6 compares, 0-5 swaps
-
-template <class _Compare, class _ForwardIterator>
-unsigned
-__sort4(_ForwardIterator __x1, _ForwardIterator __x2, _ForwardIterator __x3,
-            _ForwardIterator __x4, _Compare __c)
-{
-    unsigned __r = _VSTD::__sort3<_Compare>(__x1, __x2, __x3, __c);
-    if (__c(*__x4, *__x3))
-    {
-        swap(*__x3, *__x4);
-        ++__r;
-        if (__c(*__x3, *__x2))
-        {
-            swap(*__x2, *__x3);
-            ++__r;
-            if (__c(*__x2, *__x1))
-            {
-                swap(*__x1, *__x2);
-                ++__r;
-            }
-        }
-    }
-    return __r;
-}
-
-// stable, 4-10 compares, 0-9 swaps
-
-template <class _Compare, class _ForwardIterator>
-_LIBCPP_HIDDEN
-unsigned
-__sort5(_ForwardIterator __x1, _ForwardIterator __x2, _ForwardIterator __x3,
-            _ForwardIterator __x4, _ForwardIterator __x5, _Compare __c)
-{
-    unsigned __r = _VSTD::__sort4<_Compare>(__x1, __x2, __x3, __x4, __c);
-    if (__c(*__x5, *__x4))
-    {
-        swap(*__x4, *__x5);
-        ++__r;
-        if (__c(*__x4, *__x3))
-        {
-            swap(*__x3, *__x4);
-            ++__r;
-            if (__c(*__x3, *__x2))
-            {
-                swap(*__x2, *__x3);
-                ++__r;
-                if (__c(*__x2, *__x1))
-                {
-                    swap(*__x1, *__x2);
-                    ++__r;
-                }
-            }
-        }
-    }
-    return __r;
-}
-
-// Assumes size > 0
-template <class _Compare, class _BidirectionalIterator>
-void
-__selection_sort(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
-{
-    _BidirectionalIterator __lm1 = __last;
-    for (--__lm1; __first != __lm1; ++__first)
-    {
-        _BidirectionalIterator __i = _VSTD::min_element<_BidirectionalIterator,
-                                                        typename add_lvalue_reference<_Compare>::type>
-                                                       (__first, __last, __comp);
-        if (__i != __first)
-            swap(*__first, *__i);
-    }
-}
-
-template <class _Compare, class _BidirectionalIterator>
-void
-__insertion_sort(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
-{
-    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
-    if (__first != __last)
-    {
-        _BidirectionalIterator __i = __first;
-        for (++__i; __i != __last; ++__i)
-        {
-            _BidirectionalIterator __j = __i;
-            value_type __t(_VSTD::move(*__j));
-            for (_BidirectionalIterator __k = __i; __k != __first && __comp(__t,  *--__k); --__j)
-                *__j = _VSTD::move(*__k);
-            *__j = _VSTD::move(__t);
-        }
-    }
-}
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__insertion_sort_3(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-    _RandomAccessIterator __j = __first+2;
-    _VSTD::__sort3<_Compare>(__first, __first+1, __j, __comp);
-    for (_RandomAccessIterator __i = __j+1; __i != __last; ++__i)
-    {
-        if (__comp(*__i, *__j))
-        {
-            value_type __t(_VSTD::move(*__i));
-            _RandomAccessIterator __k = __j;
-            __j = __i;
-            do
-            {
-                *__j = _VSTD::move(*__k);
-                __j = __k;
-            } while (__j != __first && __comp(__t, *--__k));
-            *__j = _VSTD::move(__t);
-        }
-        __j = __i;
-    }
-}
-
-template <class _Compare, class _RandomAccessIterator>
-bool
-__insertion_sort_incomplete(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    switch (__last - __first)
-    {
-    case 0:
-    case 1:
-        return true;
-    case 2:
-        if (__comp(*--__last, *__first))
-            swap(*__first, *__last);
-        return true;
-    case 3:
-        _VSTD::__sort3<_Compare>(__first, __first+1, --__last, __comp);
-        return true;
-    case 4:
-        _VSTD::__sort4<_Compare>(__first, __first+1, __first+2, --__last, __comp);
-        return true;
-    case 5:
-        _VSTD::__sort5<_Compare>(__first, __first+1, __first+2, __first+3, --__last, __comp);
-        return true;
-    }
-    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-    _RandomAccessIterator __j = __first+2;
-    _VSTD::__sort3<_Compare>(__first, __first+1, __j, __comp);
-    const unsigned __limit = 8;
-    unsigned __count = 0;
-    for (_RandomAccessIterator __i = __j+1; __i != __last; ++__i)
-    {
-        if (__comp(*__i, *__j))
-        {
-            value_type __t(_VSTD::move(*__i));
-            _RandomAccessIterator __k = __j;
-            __j = __i;
-            do
-            {
-                *__j = _VSTD::move(*__k);
-                __j = __k;
-            } while (__j != __first && __comp(__t, *--__k));
-            *__j = _VSTD::move(__t);
-            if (++__count == __limit)
-                return ++__i == __last;
-        }
-        __j = __i;
-    }
-    return true;
-}
-
-template <class _Compare, class _BidirectionalIterator>
-void
-__insertion_sort_move(_BidirectionalIterator __first1, _BidirectionalIterator __last1,
-                      typename iterator_traits<_BidirectionalIterator>::value_type* __first2, _Compare __comp)
-{
-    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
-    if (__first1 != __last1)
-    {
-        __destruct_n __d(0);
-        unique_ptr<value_type, __destruct_n&> __h(__first2, __d);
-        value_type* __last2 = __first2;
-        ::new ((void*)__last2) value_type(_VSTD::move(*__first1));
-        __d.template __incr<value_type>();
-        for (++__last2; ++__first1 != __last1; ++__last2)
-        {
-            value_type* __j2 = __last2;
-            value_type* __i2 = __j2;
-            if (__comp(*__first1, *--__i2))
-            {
-                ::new ((void*)__j2) value_type(_VSTD::move(*__i2));
-                __d.template __incr<value_type>();
-                for (--__j2; __i2 != __first2 && __comp(*__first1,  *--__i2); --__j2)
-                    *__j2 = _VSTD::move(*__i2);
-                *__j2 = _VSTD::move(*__first1);
-            }
-            else
-            {
-                ::new ((void*)__j2) value_type(_VSTD::move(*__first1));
-                __d.template __incr<value_type>();
-            }
-        }
-        __h.release();
-    }
-}
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    // _Compare is known to be a reference type
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-    const difference_type __limit = is_trivially_copy_constructible<value_type>::value &&
-                                    is_trivially_copy_assignable<value_type>::value ? 30 : 6;
-    while (true)
-    {
-    __restart:
-        difference_type __len = __last - __first;
-        switch (__len)
-        {
-        case 0:
-        case 1:
-            return;
-        case 2:
-            if (__comp(*--__last, *__first))
-                swap(*__first, *__last);
-            return;
-        case 3:
-            _VSTD::__sort3<_Compare>(__first, __first+1, --__last, __comp);
-            return;
-        case 4:
-            _VSTD::__sort4<_Compare>(__first, __first+1, __first+2, --__last, __comp);
-            return;
-        case 5:
-            _VSTD::__sort5<_Compare>(__first, __first+1, __first+2, __first+3, --__last, __comp);
-            return;
-        }
-        if (__len <= __limit)
-        {
-            _VSTD::__insertion_sort_3<_Compare>(__first, __last, __comp);
-            return;
-        }
-        // __len > 5
-        _RandomAccessIterator __m = __first;
-        _RandomAccessIterator __lm1 = __last;
-        --__lm1;
-        unsigned __n_swaps;
-        {
-        difference_type __delta;
-        if (__len >= 1000)
-        {
-            __delta = __len/2;
-            __m += __delta;
-            __delta /= 2;
-            __n_swaps = _VSTD::__sort5<_Compare>(__first, __first + __delta, __m, __m+__delta, __lm1, __comp);
-        }
-        else
-        {
-            __delta = __len/2;
-            __m += __delta;
-            __n_swaps = _VSTD::__sort3<_Compare>(__first, __m, __lm1, __comp);
-        }
-        }
-        // *__m is median
-        // partition [__first, __m) < *__m and *__m <= [__m, __last)
-        // (this inhibits tossing elements equivalent to __m around unnecessarily)
-        _RandomAccessIterator __i = __first;
-        _RandomAccessIterator __j = __lm1;
-        // j points beyond range to be tested, *__m is known to be <= *__lm1
-        // The search going up is known to be guarded but the search coming down isn't.
-        // Prime the downward search with a guard.
-        if (!__comp(*__i, *__m))  // if *__first == *__m
-        {
-            // *__first == *__m, *__first doesn't go in first part
-            // manually guard downward moving __j against __i
-            while (true)
-            {
-                if (__i == --__j)
-                {
-                    // *__first == *__m, *__m <= all other elements
-                    // Parition instead into [__first, __i) == *__first and *__first < [__i, __last)
-                    ++__i;  // __first + 1
-                    __j = __last;
-                    if (!__comp(*__first, *--__j))  // we need a guard if *__first == *(__last-1)
-                    {
-                        while (true)
-                        {
-                            if (__i == __j)
-                                return;  // [__first, __last) all equivalent elements
-                            if (__comp(*__first, *__i))
-                            {
-                                swap(*__i, *__j);
-                                ++__n_swaps;
-                                ++__i;
-                                break;
-                            }
-                            ++__i;
-                        }
-                    }
-                    // [__first, __i) == *__first and *__first < [__j, __last) and __j == __last - 1
-                    if (__i == __j)
-                        return;
-                    while (true)
-                    {
-                        while (!__comp(*__first, *__i))
-                            ++__i;
-                        while (__comp(*__first, *--__j))
-                            ;
-                        if (__i >= __j)
-                            break;
-                        swap(*__i, *__j);
-                        ++__n_swaps;
-                        ++__i;
-                    }
-                    // [__first, __i) == *__first and *__first < [__i, __last)
-                    // The first part is sorted, sort the second part
-                    // _VSTD::__sort<_Compare>(__i, __last, __comp);
-                    __first = __i;
-                    goto __restart;
-                }
-                if (__comp(*__j, *__m))
-                {
-                    swap(*__i, *__j);
-                    ++__n_swaps;
-                    break;  // found guard for downward moving __j, now use unguarded partition
-                }
-            }
-        }
-        // It is known that *__i < *__m
-        ++__i;
-        // j points beyond range to be tested, *__m is known to be <= *__lm1
-        // if not yet partitioned...
-        if (__i < __j)
-        {
-            // known that *(__i - 1) < *__m
-            // known that __i <= __m
-            while (true)
-            {
-                // __m still guards upward moving __i
-                while (__comp(*__i, *__m))
-                    ++__i;
-                // It is now known that a guard exists for downward moving __j
-                while (!__comp(*--__j, *__m))
-                    ;
-                if (__i > __j)
-                    break;
-                swap(*__i, *__j);
-                ++__n_swaps;
-                // It is known that __m != __j
-                // If __m just moved, follow it
-                if (__m == __i)
-                    __m = __j;
-                ++__i;
-            }
-        }
-        // [__first, __i) < *__m and *__m <= [__i, __last)
-        if (__i != __m && __comp(*__m, *__i))
-        {
-            swap(*__i, *__m);
-            ++__n_swaps;
-        }
-        // [__first, __i) < *__i and *__i <= [__i+1, __last)
-        // If we were given a perfect partition, see if insertion sort is quick...
-        if (__n_swaps == 0)
-        {
-            bool __fs = _VSTD::__insertion_sort_incomplete<_Compare>(__first, __i, __comp);
-            if (_VSTD::__insertion_sort_incomplete<_Compare>(__i+1, __last, __comp))
-            {
-                if (__fs)
-                    return;
-                __last = __i;
-                continue;
-            }
-            else
-            {
-                if (__fs)
-                {
-                    __first = ++__i;
-                    continue;
-                }
-            }
-        }
-        // sort smaller range with recursive call and larger with tail recursion elimination
-        if (__i - __first < __last - __i)
-        {
-            _VSTD::__sort<_Compare>(__first, __i, __comp);
-            // _VSTD::__sort<_Compare>(__i+1, __last, __comp);
-            __first = ++__i;
-        }
-        else
-        {
-            _VSTD::__sort<_Compare>(__i+1, __last, __comp);
-            // _VSTD::__sort<_Compare>(__first, __i, __comp);
-            __last = __i;
-        }
-    }
-}
-
-// This forwarder keeps the top call and the recursive calls using the same instantiation, forcing a reference _Compare
-template <class _RandomAccessIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    _VSTD::__sort<_Comp_ref>(__first, __last, _Comp_ref(__comp));
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
-{
-    _VSTD::sort(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-sort(_Tp** __first, _Tp** __last)
-{
-    _VSTD::sort((uintptr_t*)__first, (uintptr_t*)__last, __less<uintptr_t>());
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-sort(__wrap_iter<_Tp*> __first, __wrap_iter<_Tp*> __last)
-{
-    _VSTD::sort(__first.base(), __last.base());
-}
-
-template <class _Tp, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-sort(__wrap_iter<_Tp*> __first, __wrap_iter<_Tp*> __last, _Compare __comp)
-{
-    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
-    _VSTD::sort<_Tp*, _Comp_ref>(__first.base(), __last.base(), __comp);
-}
-
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<char>&, char*>(char*, char*, __less<char>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<short>&, short*>(short*, short*, __less<short>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<int>&, int*>(int*, int*, __less<int>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long>&, long*>(long*, long*, __less<long>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long long>&, long long*>(long long*, long long*, __less<long long>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<float>&, float*>(float*, float*, __less<float>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<double>&, double*>(double*, double*, __less<double>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long double>&, long double*>(long double*, long double*, __less<long double>&))
-
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<char>&, char*>(char*, char*, __less<char>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<short>&, short*>(short*, short*, __less<short>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<int>&, int*>(int*, int*, __less<int>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long>&, long*>(long*, long*, __less<long>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long long>&, long long*>(long long*, long long*, __less<long long>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<float>&, float*>(float*, float*, __less<float>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<double>&, double*>(double*, double*, __less<double>&))
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long double>&, long double*>(long double*, long double*, __less<long double>&))
-
-_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS unsigned __sort5<__less<long double>&, long double*>(long double*, long double*, long double*, long double*, long double*, __less<long double>&))
-
-// lower_bound
-
-template <class _Compare, class _ForwardIterator, class _Tp>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-__lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
-{
-    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
-    difference_type __len = _VSTD::distance(__first, __last);
-    while (__len != 0)
-    {
-        difference_type __l2 = _VSTD::__half_positive(__len);
-        _ForwardIterator __m = __first;
-        _VSTD::advance(__m, __l2);
-        if (__comp(*__m, __value_))
-        {
-            __first = ++__m;
-            __len -= __l2 + 1;
-        }
-        else
-            __len = __l2;
-    }
-    return __first;
-}
-
-template <class _ForwardIterator, class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
-{
-    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
-    return _VSTD::__lower_bound<_Comp_ref>(__first, __last, __value_, __comp);
-}
-
-template <class _ForwardIterator, class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-lower_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
-{
-    return _VSTD::lower_bound(__first, __last, __value_,
-                             __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
-}
-
-// upper_bound
-
-template <class _Compare, class _ForwardIterator, class _Tp>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _ForwardIterator
-__upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
-{
-    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
-    difference_type __len = _VSTD::distance(__first, __last);
-    while (__len != 0)
-    {
-        difference_type __l2 = _VSTD::__half_positive(__len);
-        _ForwardIterator __m = __first;
-        _VSTD::advance(__m, __l2);
-        if (__comp(__value_, *__m))
-            __len = __l2;
-        else
-        {
-            __first = ++__m;
-            __len -= __l2 + 1;
-        }
-    }
-    return __first;
-}
-
-template <class _ForwardIterator, class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
-{
-    typedef typename add_lvalue_reference<_Compare>::type _Comp_ref;
-    return _VSTD::__upper_bound<_Comp_ref>(__first, __last, __value_, __comp);
-}
-
-template <class _ForwardIterator, class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator
-upper_bound(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
-{
-    return _VSTD::upper_bound(__first, __last, __value_,
-                             __less<_Tp, typename iterator_traits<_ForwardIterator>::value_type>());
-}
-
-// equal_range
-
-template <class _Compare, class _ForwardIterator, class _Tp>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 pair<_ForwardIterator, _ForwardIterator>
-__equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
-{
-    typedef typename iterator_traits<_ForwardIterator>::difference_type difference_type;
-    difference_type __len = _VSTD::distance(__first, __last);
-    while (__len != 0)
-    {
-        difference_type __l2 = _VSTD::__half_positive(__len);
-        _ForwardIterator __m = __first;
-        _VSTD::advance(__m, __l2);
-        if (__comp(*__m, __value_))
-        {
-            __first = ++__m;
-            __len -= __l2 + 1;
-        }
-        else if (__comp(__value_, *__m))
-        {
-            __last = __m;
-            __len = __l2;
-        }
-        else
-        {
-            _ForwardIterator __mp1 = __m;
-            return pair<_ForwardIterator, _ForwardIterator>
-                   (
-                      _VSTD::__lower_bound<_Compare>(__first, __m, __value_, __comp),
-                      _VSTD::__upper_bound<_Compare>(++__mp1, __last, __value_, __comp)
-                   );
-        }
-    }
-    return pair<_ForwardIterator, _ForwardIterator>(__first, __first);
-}
-
-template <class _ForwardIterator, class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-pair<_ForwardIterator, _ForwardIterator>
-equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__equal_range<_Comp_ref>(__first, __last, __value_, __comp);
-}
-
-template <class _ForwardIterator, class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-pair<_ForwardIterator, _ForwardIterator>
-equal_range(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
-{
-    return _VSTD::equal_range(__first, __last, __value_,
-                             __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
-}
-
-// binary_search
-
-template <class _Compare, class _ForwardIterator, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-__binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
-{
-    __first = _VSTD::__lower_bound<_Compare>(__first, __last, __value_, __comp);
-    return __first != __last && !__comp(__value_, *__first);
-}
-
-template <class _ForwardIterator, class _Tp, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__binary_search<_Comp_ref>(__first, __last, __value_, __comp);
-}
-
-template <class _ForwardIterator, class _Tp>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-binary_search(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value_)
-{
-    return _VSTD::binary_search(__first, __last, __value_,
-                             __less<typename iterator_traits<_ForwardIterator>::value_type, _Tp>());
-}
-
-// merge
-
-template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-__merge(_InputIterator1 __first1, _InputIterator1 __last1,
-        _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    for (; __first1 != __last1; ++__result)
-    {
-        if (__first2 == __last2)
-            return _VSTD::copy(__first1, __last1, __result);
-        if (__comp(*__first2, *__first1))
-        {
-            *__result = *__first2;
-            ++__first2;
-        }
-        else
-        {
-            *__result = *__first1;
-            ++__first1;
-        }
-    }
-    return _VSTD::copy(__first2, __last2, __result);
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-merge(_InputIterator1 __first1, _InputIterator1 __last1,
-      _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__merge<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-merge(_InputIterator1 __first1, _InputIterator1 __last1,
-      _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
-{
-    typedef typename iterator_traits<_InputIterator1>::value_type __v1;
-    typedef typename iterator_traits<_InputIterator2>::value_type __v2;
-    return _VSTD::merge(__first1, __last1, __first2, __last2, __result, __less<__v1, __v2>());
-}
-
-// inplace_merge
-
-template <class _Compare, class _InputIterator1, class _InputIterator2,
-          class _OutputIterator>
-void __half_inplace_merge(_InputIterator1 __first1, _InputIterator1 __last1,
-                          _InputIterator2 __first2, _InputIterator2 __last2,
-                          _OutputIterator __result, _Compare __comp)
-{
-    for (; __first1 != __last1; ++__result)
-    {
-        if (__first2 == __last2)
-        {
-            _VSTD::move(__first1, __last1, __result);
-            return;
-        }
-
-        if (__comp(*__first2, *__first1))
-        {
-            *__result = _VSTD::move(*__first2);
-            ++__first2;
-        }
-        else
-        {
-            *__result = _VSTD::move(*__first1);
-            ++__first1;
-        }
-    }
-    // __first2 through __last2 are already in the right spot.
-}
-
-template <class _Compare, class _BidirectionalIterator>
-void
-__buffered_inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
-                _Compare __comp, typename iterator_traits<_BidirectionalIterator>::difference_type __len1,
-                                 typename iterator_traits<_BidirectionalIterator>::difference_type __len2,
-                typename iterator_traits<_BidirectionalIterator>::value_type* __buff)
-{
-    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
-    __destruct_n __d(0);
-    unique_ptr<value_type, __destruct_n&> __h2(__buff, __d);
-    if (__len1 <= __len2)
-    {
-        value_type* __p = __buff;
-        for (_BidirectionalIterator __i = __first; __i != __middle; __d.template __incr<value_type>(), (void) ++__i, (void) ++__p)
-            ::new ((void*)__p) value_type(_VSTD::move(*__i));
-        _VSTD::__half_inplace_merge<_Compare>(__buff, __p, __middle, __last, __first, __comp);
-    }
-    else
-    {
-        value_type* __p = __buff;
-        for (_BidirectionalIterator __i = __middle; __i != __last; __d.template __incr<value_type>(), (void) ++__i, (void) ++__p)
-            ::new ((void*)__p) value_type(_VSTD::move(*__i));
-        typedef reverse_iterator<_BidirectionalIterator> _RBi;
-        typedef reverse_iterator<value_type*> _Rv;
-        typedef __invert<_Compare> _Inverted;
-        _VSTD::__half_inplace_merge<_Inverted>(_Rv(__p), _Rv(__buff),
-                                    _RBi(__middle), _RBi(__first),
-                                    _RBi(__last), _Inverted(__comp));
-    }
-}
-
-template <class _Compare, class _BidirectionalIterator>
-void
-__inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
-                _Compare __comp, typename iterator_traits<_BidirectionalIterator>::difference_type __len1,
-                                 typename iterator_traits<_BidirectionalIterator>::difference_type __len2,
-                typename iterator_traits<_BidirectionalIterator>::value_type* __buff, ptrdiff_t __buff_size)
-{
-    typedef typename iterator_traits<_BidirectionalIterator>::difference_type difference_type;
-    while (true)
-    {
-        // if __middle == __last, we're done
-        if (__len2 == 0)
-            return;
-        if (__len1 <= __buff_size || __len2 <= __buff_size)
-            return _VSTD::__buffered_inplace_merge<_Compare>
-                   (__first, __middle, __last, __comp, __len1, __len2, __buff);
-        // shrink [__first, __middle) as much as possible (with no moves), returning if it shrinks to 0
-        for (; true; ++__first, (void) --__len1)
-        {
-            if (__len1 == 0)
-                return;
-            if (__comp(*__middle, *__first))
-                break;
-        }
-        // __first < __middle < __last
-        // *__first > *__middle
-        // partition [__first, __m1) [__m1, __middle) [__middle, __m2) [__m2, __last) such that
-        //     all elements in:
-        //         [__first, __m1)  <= [__middle, __m2)
-        //         [__middle, __m2) <  [__m1, __middle)
-        //         [__m1, __middle) <= [__m2, __last)
-        //     and __m1 or __m2 is in the middle of its range
-        _BidirectionalIterator __m1;  // "median" of [__first, __middle)
-        _BidirectionalIterator __m2;  // "median" of [__middle, __last)
-        difference_type __len11;      // distance(__first, __m1)
-        difference_type __len21;      // distance(__middle, __m2)
-        // binary search smaller range
-        if (__len1 < __len2)
-        {   // __len >= 1, __len2 >= 2
-            __len21 = __len2 / 2;
-            __m2 = __middle;
-            _VSTD::advance(__m2, __len21);
-            __m1 = _VSTD::__upper_bound<_Compare>(__first, __middle, *__m2, __comp);
-            __len11 = _VSTD::distance(__first, __m1);
-        }
-        else
-        {
-            if (__len1 == 1)
-            {   // __len1 >= __len2 && __len2 > 0, therefore __len2 == 1
-                // It is known *__first > *__middle
-                swap(*__first, *__middle);
-                return;
-            }
-            // __len1 >= 2, __len2 >= 1
-            __len11 = __len1 / 2;
-            __m1 = __first;
-            _VSTD::advance(__m1, __len11);
-            __m2 = _VSTD::__lower_bound<_Compare>(__middle, __last, *__m1, __comp);
-            __len21 = _VSTD::distance(__middle, __m2);
-        }
-        difference_type __len12 = __len1 - __len11;  // distance(__m1, __middle)
-        difference_type __len22 = __len2 - __len21;  // distance(__m2, __last)
-        // [__first, __m1) [__m1, __middle) [__middle, __m2) [__m2, __last)
-        // swap middle two partitions
-        __middle = _VSTD::rotate(__m1, __middle, __m2);
-        // __len12 and __len21 now have swapped meanings
-        // merge smaller range with recursive call and larger with tail recursion elimination
-        if (__len11 + __len21 < __len12 + __len22)
-        {
-            _VSTD::__inplace_merge<_Compare>(__first, __m1, __middle, __comp, __len11, __len21, __buff, __buff_size);
-//          _VSTD::__inplace_merge<_Compare>(__middle, __m2, __last, __comp, __len12, __len22, __buff, __buff_size);
-            __first = __middle;
-            __middle = __m2;
-            __len1 = __len12;
-            __len2 = __len22;
-        }
-        else
-        {
-            _VSTD::__inplace_merge<_Compare>(__middle, __m2, __last, __comp, __len12, __len22, __buff, __buff_size);
-//          _VSTD::__inplace_merge<_Compare>(__first, __m1, __middle, __comp, __len11, __len21, __buff, __buff_size);
-            __last = __middle;
-            __middle = __m1;
-            __len1 = __len11;
-            __len2 = __len21;
-        }
-    }
-}
-
-template <class _BidirectionalIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last,
-              _Compare __comp)
-{
-    typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
-    typedef typename iterator_traits<_BidirectionalIterator>::difference_type difference_type;
-    difference_type __len1 = _VSTD::distance(__first, __middle);
-    difference_type __len2 = _VSTD::distance(__middle, __last);
-    difference_type __buf_size = _VSTD::min(__len1, __len2);
-    pair<value_type*, ptrdiff_t> __buf = _VSTD::get_temporary_buffer<value_type>(__buf_size);
-    unique_ptr<value_type, __return_temporary_buffer> __h(__buf.first);
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__inplace_merge<_Comp_ref>(__first, __middle, __last, __comp, __len1, __len2,
-                                            __buf.first, __buf.second);
-}
-
-template <class _BidirectionalIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-inplace_merge(_BidirectionalIterator __first, _BidirectionalIterator __middle, _BidirectionalIterator __last)
-{
-    _VSTD::inplace_merge(__first, __middle, __last,
-                        __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
-}
-
-// stable_sort
-
-template <class _Compare, class _InputIterator1, class _InputIterator2>
-void
-__merge_move_construct(_InputIterator1 __first1, _InputIterator1 __last1,
-        _InputIterator2 __first2, _InputIterator2 __last2,
-        typename iterator_traits<_InputIterator1>::value_type* __result, _Compare __comp)
-{
-    typedef typename iterator_traits<_InputIterator1>::value_type value_type;
-    __destruct_n __d(0);
-    unique_ptr<value_type, __destruct_n&> __h(__result, __d);
-    for (; true; ++__result)
-    {
-        if (__first1 == __last1)
-        {
-            for (; __first2 != __last2; ++__first2, ++__result, (void)__d.template __incr<value_type>())
-                ::new ((void*)__result) value_type(_VSTD::move(*__first2));
-            __h.release();
-            return;
-        }
-        if (__first2 == __last2)
-        {
-            for (; __first1 != __last1; ++__first1, ++__result, (void)__d.template __incr<value_type>())
-                ::new ((void*)__result) value_type(_VSTD::move(*__first1));
-            __h.release();
-            return;
-        }
-        if (__comp(*__first2, *__first1))
-        {
-            ::new ((void*)__result) value_type(_VSTD::move(*__first2));
-            __d.template __incr<value_type>();
-            ++__first2;
-        }
-        else
-        {
-            ::new ((void*)__result) value_type(_VSTD::move(*__first1));
-            __d.template __incr<value_type>();
-            ++__first1;
-        }
-    }
-}
-
-template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
-void
-__merge_move_assign(_InputIterator1 __first1, _InputIterator1 __last1,
-        _InputIterator2 __first2, _InputIterator2 __last2,
-        _OutputIterator __result, _Compare __comp)
-{
-    for (; __first1 != __last1; ++__result)
-    {
-        if (__first2 == __last2)
-        {
-            for (; __first1 != __last1; ++__first1, (void) ++__result)
-                *__result = _VSTD::move(*__first1);
-            return;
-        }
-        if (__comp(*__first2, *__first1))
-        {
-            *__result = _VSTD::move(*__first2);
-            ++__first2;
-        }
-        else
-        {
-            *__result = _VSTD::move(*__first1);
-            ++__first1;
-        }
-    }
-    for (; __first2 != __last2; ++__first2, (void) ++__result)
-        *__result = _VSTD::move(*__first2);
-}
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
-              typename iterator_traits<_RandomAccessIterator>::difference_type __len,
-              typename iterator_traits<_RandomAccessIterator>::value_type* __buff, ptrdiff_t __buff_size);
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__stable_sort_move(_RandomAccessIterator __first1, _RandomAccessIterator __last1, _Compare __comp,
-                   typename iterator_traits<_RandomAccessIterator>::difference_type __len,
-                   typename iterator_traits<_RandomAccessIterator>::value_type* __first2)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-    switch (__len)
-    {
-    case 0:
-        return;
-    case 1:
-        ::new ((void*)__first2) value_type(_VSTD::move(*__first1));
-        return;
-    case 2:
-        __destruct_n __d(0);
-        unique_ptr<value_type, __destruct_n&> __h2(__first2, __d);
-        if (__comp(*--__last1, *__first1))
-        {
-            ::new ((void*)__first2) value_type(_VSTD::move(*__last1));
-            __d.template __incr<value_type>();
-            ++__first2;
-            ::new ((void*)__first2) value_type(_VSTD::move(*__first1));
-        }
-        else
-        {
-            ::new ((void*)__first2) value_type(_VSTD::move(*__first1));
-            __d.template __incr<value_type>();
-            ++__first2;
-            ::new ((void*)__first2) value_type(_VSTD::move(*__last1));
-        }
-        __h2.release();
-        return;
-    }
-    if (__len <= 8)
-    {
-        _VSTD::__insertion_sort_move<_Compare>(__first1, __last1, __first2, __comp);
-        return;
-    }
-    typename iterator_traits<_RandomAccessIterator>::difference_type __l2 = __len / 2;
-    _RandomAccessIterator __m = __first1 + __l2;
-    _VSTD::__stable_sort<_Compare>(__first1, __m, __comp, __l2, __first2, __l2);
-    _VSTD::__stable_sort<_Compare>(__m, __last1, __comp, __len - __l2, __first2 + __l2, __len - __l2);
-    _VSTD::__merge_move_construct<_Compare>(__first1, __m, __m, __last1, __first2, __comp);
-}
-
-template <class _Tp>
-struct __stable_sort_switch
-{
-    static const unsigned value = 128*is_trivially_copy_assignable<_Tp>::value;
-};
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
-              typename iterator_traits<_RandomAccessIterator>::difference_type __len,
-              typename iterator_traits<_RandomAccessIterator>::value_type* __buff, ptrdiff_t __buff_size)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    switch (__len)
-    {
-    case 0:
-    case 1:
-        return;
-    case 2:
-        if (__comp(*--__last, *__first))
-            swap(*__first, *__last);
-        return;
-    }
-    if (__len <= static_cast<difference_type>(__stable_sort_switch<value_type>::value))
-    {
-        _VSTD::__insertion_sort<_Compare>(__first, __last, __comp);
-        return;
-    }
-    typename iterator_traits<_RandomAccessIterator>::difference_type __l2 = __len / 2;
-    _RandomAccessIterator __m = __first + __l2;
-    if (__len <= __buff_size)
-    {
-        __destruct_n __d(0);
-        unique_ptr<value_type, __destruct_n&> __h2(__buff, __d);
-        _VSTD::__stable_sort_move<_Compare>(__first, __m, __comp, __l2, __buff);
-        __d.__set(__l2, (value_type*)nullptr);
-        _VSTD::__stable_sort_move<_Compare>(__m, __last, __comp, __len - __l2, __buff + __l2);
-        __d.__set(__len, (value_type*)nullptr);
-        _VSTD::__merge_move_assign<_Compare>(__buff, __buff + __l2, __buff + __l2, __buff + __len, __first, __comp);
-//         _VSTD::__merge<_Compare>(move_iterator<value_type*>(__buff),
-//                                  move_iterator<value_type*>(__buff + __l2),
-//                                  move_iterator<_RandomAccessIterator>(__buff + __l2),
-//                                  move_iterator<_RandomAccessIterator>(__buff + __len),
-//                                  __first, __comp);
-        return;
-    }
-    _VSTD::__stable_sort<_Compare>(__first, __m, __comp, __l2, __buff, __buff_size);
-    _VSTD::__stable_sort<_Compare>(__m, __last, __comp, __len - __l2, __buff, __buff_size);
-    _VSTD::__inplace_merge<_Compare>(__first, __m, __last, __comp, __l2, __len - __l2, __buff, __buff_size);
-}
-
-template <class _RandomAccessIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    difference_type __len = __last - __first;
-    pair<value_type*, ptrdiff_t> __buf(0, 0);
-    unique_ptr<value_type, __return_temporary_buffer> __h;
-    if (__len > static_cast<difference_type>(__stable_sort_switch<value_type>::value))
-    {
-        __buf = _VSTD::get_temporary_buffer<value_type>(__len);
-        __h.reset(__buf.first);
-    }
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    _VSTD::__stable_sort<_Comp_ref>(__first, __last, __comp, __len, __buf.first, __buf.second);
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
-{
-    _VSTD::stable_sort(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// is_heap_until
-
-template <class _RandomAccessIterator, class _Compare>
-_LIBCPP_NODISCARD_EXT _LIBCPP_CONSTEXPR_AFTER_CXX17 _RandomAccessIterator
-is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename _VSTD::iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    difference_type __len = __last - __first;
-    difference_type __p = 0;
-    difference_type __c = 1;
-    _RandomAccessIterator __pp = __first;
-    while (__c < __len)
-    {
-        _RandomAccessIterator __cp = __first + __c;
-        if (__comp(*__pp, *__cp))
-            return __cp;
-        ++__c;
-        ++__cp;
-        if (__c == __len)
-            return __last;
-        if (__comp(*__pp, *__cp))
-            return __cp;
-        ++__p;
-        ++__pp;
-        __c = 2 * __p + 1;
-    }
-    return __last;
-}
-
-template<class _RandomAccessIterator>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_RandomAccessIterator
-is_heap_until(_RandomAccessIterator __first, _RandomAccessIterator __last)
-{
-    return _VSTD::is_heap_until(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// is_heap
-
-template <class _RandomAccessIterator, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    return _VSTD::is_heap_until(__first, __last, __comp) == __last;
-}
-
-template<class _RandomAccessIterator>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-is_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
-{
-    return _VSTD::is_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// push_heap
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__sift_up(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
-          typename iterator_traits<_RandomAccessIterator>::difference_type __len)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-    if (__len > 1)
-    {
-        __len = (__len - 2) / 2;
-        _RandomAccessIterator __ptr = __first + __len;
-        if (__comp(*__ptr, *--__last))
-        {
-            value_type __t(_VSTD::move(*__last));
-            do
-            {
-                *__last = _VSTD::move(*__ptr);
-                __last = __ptr;
-                if (__len == 0)
-                    break;
-                __len = (__len - 1) / 2;
-                __ptr = __first + __len;
-            } while (__comp(*__ptr, __t));
-            *__last = _VSTD::move(__t);
-        }
-    }
-}
-
-template <class _RandomAccessIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    _VSTD::__sift_up<_Comp_ref>(__first, __last, __comp, __last - __first);
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-push_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
-{
-    _VSTD::push_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// pop_heap
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__sift_down(_RandomAccessIterator __first, _RandomAccessIterator /*__last*/,
-            _Compare __comp,
-            typename iterator_traits<_RandomAccessIterator>::difference_type __len,
-            _RandomAccessIterator __start)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
-    // left-child of __start is at 2 * __start + 1
-    // right-child of __start is at 2 * __start + 2
-    difference_type __child = __start - __first;
-
-    if (__len < 2 || (__len - 2) / 2 < __child)
-        return;
-
-    __child = 2 * __child + 1;
-    _RandomAccessIterator __child_i = __first + __child;
-
-    if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + 1))) {
-        // right-child exists and is greater than left-child
-        ++__child_i;
-        ++__child;
-    }
-
-    // check if we are in heap-order
-    if (__comp(*__child_i, *__start))
-        // we are, __start is larger than it's largest child
-        return;
-
-    value_type __top(_VSTD::move(*__start));
-    do
-    {
-        // we are not in heap-order, swap the parent with it's largest child
-        *__start = _VSTD::move(*__child_i);
-        __start = __child_i;
-
-        if ((__len - 2) / 2 < __child)
-            break;
-
-        // recompute the child based off of the updated parent
-        __child = 2 * __child + 1;
-        __child_i = __first + __child;
-
-        if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + 1))) {
-            // right-child exists and is greater than left-child
-            ++__child_i;
-            ++__child;
-        }
-
-        // check if we are in heap-order
-    } while (!__comp(*__child_i, __top));
-    *__start = _VSTD::move(__top);
-}
-
-template <class _Compare, class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-__pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
-           typename iterator_traits<_RandomAccessIterator>::difference_type __len)
-{
-    if (__len > 1)
-    {
-        swap(*__first, *--__last);
-        _VSTD::__sift_down<_Compare>(__first, __last, __comp, __len - 1, __first);
-    }
-}
-
-template <class _RandomAccessIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    _VSTD::__pop_heap<_Comp_ref>(__first, __last, __comp, __last - __first);
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-pop_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
-{
-    _VSTD::pop_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// make_heap
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    difference_type __n = __last - __first;
-    if (__n > 1)
-    {
-        // start from the first parent, there is no need to consider children
-        for (difference_type __start = (__n - 2) / 2; __start >= 0; --__start)
-        {
-            _VSTD::__sift_down<_Compare>(__first, __last, __comp, __n, __first + __start);
-        }
-    }
-}
-
-template <class _RandomAccessIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    _VSTD::__make_heap<_Comp_ref>(__first, __last, __comp);
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-make_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
-{
-    _VSTD::make_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// sort_heap
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    for (difference_type __n = __last - __first; __n > 1; --__last, (void) --__n)
-        _VSTD::__pop_heap<_Compare>(__first, __last, __comp, __n);
-}
-
-template <class _RandomAccessIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    _VSTD::__sort_heap<_Comp_ref>(__first, __last, __comp);
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-sort_heap(_RandomAccessIterator __first, _RandomAccessIterator __last)
-{
-    _VSTD::sort_heap(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// partial_sort
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
-             _Compare __comp)
-{
-    _VSTD::__make_heap<_Compare>(__first, __middle, __comp);
-    typename iterator_traits<_RandomAccessIterator>::difference_type __len = __middle - __first;
-    for (_RandomAccessIterator __i = __middle; __i != __last; ++__i)
-    {
-        if (__comp(*__i, *__first))
-        {
-            swap(*__i, *__first);
-            _VSTD::__sift_down<_Compare>(__first, __middle, __comp, __len, __first);
-        }
-    }
-    _VSTD::__sort_heap<_Compare>(__first, __middle, __comp);
-}
-
-template <class _RandomAccessIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
-             _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    _VSTD::__partial_sort<_Comp_ref>(__first, __middle, __last, __comp);
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last)
-{
-    _VSTD::partial_sort(__first, __middle, __last,
-                       __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// partial_sort_copy
-
-template <class _Compare, class _InputIterator, class _RandomAccessIterator>
-_RandomAccessIterator
-__partial_sort_copy(_InputIterator __first, _InputIterator __last,
-                    _RandomAccessIterator __result_first, _RandomAccessIterator __result_last, _Compare __comp)
-{
-    _RandomAccessIterator __r = __result_first;
-    if (__r != __result_last)
-    {
-        for (; __first != __last && __r != __result_last; ++__first, (void) ++__r)
-            *__r = *__first;
-        _VSTD::__make_heap<_Compare>(__result_first, __r, __comp);
-        typename iterator_traits<_RandomAccessIterator>::difference_type __len = __r - __result_first;
-        for (; __first != __last; ++__first)
-            if (__comp(*__first, *__result_first))
-            {
-                *__result_first = *__first;
-                _VSTD::__sift_down<_Compare>(__result_first, __r, __comp, __len, __result_first);
-            }
-        _VSTD::__sort_heap<_Compare>(__result_first, __r, __comp);
-    }
-    return __r;
-}
-
-template <class _InputIterator, class _RandomAccessIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-_RandomAccessIterator
-partial_sort_copy(_InputIterator __first, _InputIterator __last,
-                  _RandomAccessIterator __result_first, _RandomAccessIterator __result_last, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__partial_sort_copy<_Comp_ref>(__first, __last, __result_first, __result_last, __comp);
-}
-
-template <class _InputIterator, class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-_RandomAccessIterator
-partial_sort_copy(_InputIterator __first, _InputIterator __last,
-                  _RandomAccessIterator __result_first, _RandomAccessIterator __result_last)
-{
-    return _VSTD::partial_sort_copy(__first, __last, __result_first, __result_last,
-                                   __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// nth_element
-
-template <class _Compare, class _RandomAccessIterator>
-void
-__nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp)
-{
-    // _Compare is known to be a reference type
-    typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
-    const difference_type __limit = 7;
-    while (true)
-    {
-    __restart:
-        if (__nth == __last)
-            return;
-        difference_type __len = __last - __first;
-        switch (__len)
-        {
-        case 0:
-        case 1:
-            return;
-        case 2:
-            if (__comp(*--__last, *__first))
-                swap(*__first, *__last);
-            return;
-        case 3:
-            {
-            _RandomAccessIterator __m = __first;
-            _VSTD::__sort3<_Compare>(__first, ++__m, --__last, __comp);
-            return;
-            }
-        }
-        if (__len <= __limit)
-        {
-            _VSTD::__selection_sort<_Compare>(__first, __last, __comp);
-            return;
-        }
-        // __len > __limit >= 3
-        _RandomAccessIterator __m = __first + __len/2;
-        _RandomAccessIterator __lm1 = __last;
-        unsigned __n_swaps = _VSTD::__sort3<_Compare>(__first, __m, --__lm1, __comp);
-        // *__m is median
-        // partition [__first, __m) < *__m and *__m <= [__m, __last)
-        // (this inhibits tossing elements equivalent to __m around unnecessarily)
-        _RandomAccessIterator __i = __first;
-        _RandomAccessIterator __j = __lm1;
-        // j points beyond range to be tested, *__lm1 is known to be <= *__m
-        // The search going up is known to be guarded but the search coming down isn't.
-        // Prime the downward search with a guard.
-        if (!__comp(*__i, *__m))  // if *__first == *__m
-        {
-            // *__first == *__m, *__first doesn't go in first part
-            // manually guard downward moving __j against __i
-            while (true)
-            {
-                if (__i == --__j)
-                {
-                    // *__first == *__m, *__m <= all other elements
-                    // Partition instead into [__first, __i) == *__first and *__first < [__i, __last)
-                    ++__i;  // __first + 1
-                    __j = __last;
-                    if (!__comp(*__first, *--__j))  // we need a guard if *__first == *(__last-1)
-                    {
-                        while (true)
-                        {
-                            if (__i == __j)
-                                return;  // [__first, __last) all equivalent elements
-                            if (__comp(*__first, *__i))
-                            {
-                                swap(*__i, *__j);
-                                ++__n_swaps;
-                                ++__i;
-                                break;
-                            }
-                            ++__i;
-                        }
-                    }
-                    // [__first, __i) == *__first and *__first < [__j, __last) and __j == __last - 1
-                    if (__i == __j)
-                        return;
-                    while (true)
-                    {
-                        while (!__comp(*__first, *__i))
-                            ++__i;
-                        while (__comp(*__first, *--__j))
-                            ;
-                        if (__i >= __j)
-                            break;
-                        swap(*__i, *__j);
-                        ++__n_swaps;
-                        ++__i;
-                    }
-                    // [__first, __i) == *__first and *__first < [__i, __last)
-                    // The first part is sorted,
-                    if (__nth < __i)
-                        return;
-                    // __nth_element the second part
-                    // _VSTD::__nth_element<_Compare>(__i, __nth, __last, __comp);
-                    __first = __i;
-                    goto __restart;
-                }
-                if (__comp(*__j, *__m))
-                {
-                    swap(*__i, *__j);
-                    ++__n_swaps;
-                    break;  // found guard for downward moving __j, now use unguarded partition
-                }
-            }
-        }
-        ++__i;
-        // j points beyond range to be tested, *__lm1 is known to be <= *__m
-        // if not yet partitioned...
-        if (__i < __j)
-        {
-            // known that *(__i - 1) < *__m
-            while (true)
-            {
-                // __m still guards upward moving __i
-                while (__comp(*__i, *__m))
-                    ++__i;
-                // It is now known that a guard exists for downward moving __j
-                while (!__comp(*--__j, *__m))
-                    ;
-                if (__i >= __j)
-                    break;
-                swap(*__i, *__j);
-                ++__n_swaps;
-                // It is known that __m != __j
-                // If __m just moved, follow it
-                if (__m == __i)
-                    __m = __j;
-                ++__i;
-            }
-        }
-        // [__first, __i) < *__m and *__m <= [__i, __last)
-        if (__i != __m && __comp(*__m, *__i))
-        {
-            swap(*__i, *__m);
-            ++__n_swaps;
-        }
-        // [__first, __i) < *__i and *__i <= [__i+1, __last)
-        if (__nth == __i)
-            return;
-        if (__n_swaps == 0)
-        {
-            // We were given a perfectly partitioned sequence.  Coincidence?
-            if (__nth < __i)
-            {
-                // Check for [__first, __i) already sorted
-                __j = __m = __first;
-                while (++__j != __i)
-                {
-                    if (__comp(*__j, *__m))
-                        // not yet sorted, so sort
-                        goto not_sorted;
-                    __m = __j;
-                }
-                // [__first, __i) sorted
-                return;
-            }
-            else
-            {
-                // Check for [__i, __last) already sorted
-                __j = __m = __i;
-                while (++__j != __last)
-                {
-                    if (__comp(*__j, *__m))
-                        // not yet sorted, so sort
-                        goto not_sorted;
-                    __m = __j;
-                }
-                // [__i, __last) sorted
-                return;
-            }
-        }
-not_sorted:
-        // __nth_element on range containing __nth
-        if (__nth < __i)
-        {
-            // _VSTD::__nth_element<_Compare>(__first, __nth, __i, __comp);
-            __last = __i;
-        }
-        else
-        {
-            // _VSTD::__nth_element<_Compare>(__i+1, __nth, __last, __comp);
-            __first = ++__i;
-        }
-    }
-}
-
-template <class _RandomAccessIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    _VSTD::__nth_element<_Comp_ref>(__first, __nth, __last, __comp);
-}
-
-template <class _RandomAccessIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last)
-{
-    _VSTD::nth_element(__first, __nth, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
-}
-
-// includes
-
-template <class _Compare, class _InputIterator1, class _InputIterator2>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
-__includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2,
-           _Compare __comp)
-{
-    for (; __first2 != __last2; ++__first1)
-    {
-        if (__first1 == __last1 || __comp(*__first2, *__first1))
-            return false;
-        if (!__comp(*__first1, *__first2))
-            ++__first2;
-    }
-    return true;
-}
-
-template <class _InputIterator1, class _InputIterator2, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2,
-         _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__includes<_Comp_ref>(__first1, __last1, __first2, __last2, __comp);
-}
-
-template <class _InputIterator1, class _InputIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2)
-{
-    return _VSTD::includes(__first1, __last1, __first2, __last2,
-                          __less<typename iterator_traits<_InputIterator1>::value_type,
-                                 typename iterator_traits<_InputIterator2>::value_type>());
-}
-
-// set_union
-
-template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
-__set_union(_InputIterator1 __first1, _InputIterator1 __last1,
-            _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    for (; __first1 != __last1; ++__result)
-    {
-        if (__first2 == __last2)
-            return _VSTD::copy(__first1, __last1, __result);
-        if (__comp(*__first2, *__first1))
-        {
-            *__result = *__first2;
-            ++__first2;
-        }
-        else
-        {
-            if (!__comp(*__first1, *__first2))
-                ++__first2;
-            *__result = *__first1;
-            ++__first1;
-        }
-    }
-    return _VSTD::copy(__first2, __last2, __result);
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-set_union(_InputIterator1 __first1, _InputIterator1 __last1,
-          _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__set_union<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-set_union(_InputIterator1 __first1, _InputIterator1 __last1,
-          _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
-{
-    return _VSTD::set_union(__first1, __last1, __first2, __last2, __result,
-                          __less<typename iterator_traits<_InputIterator1>::value_type,
-                                 typename iterator_traits<_InputIterator2>::value_type>());
-}
-
-// set_intersection
-
-template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
-__set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
-                   _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    while (__first1 != __last1 && __first2 != __last2)
-    {
-        if (__comp(*__first1, *__first2))
-            ++__first1;
-        else
-        {
-            if (!__comp(*__first2, *__first1))
-            {
-                *__result = *__first1;
-                ++__result;
-                ++__first1;
-            }
-            ++__first2;
-        }
-    }
-    return __result;
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
-                 _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__set_intersection<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
-                 _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
-{
-    return _VSTD::set_intersection(__first1, __last1, __first2, __last2, __result,
-                                  __less<typename iterator_traits<_InputIterator1>::value_type,
-                                         typename iterator_traits<_InputIterator2>::value_type>());
-}
-
-// set_difference
-
-template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
-__set_difference(_InputIterator1 __first1, _InputIterator1 __last1,
-                 _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    while (__first1 != __last1)
-    {
-        if (__first2 == __last2)
-            return _VSTD::copy(__first1, __last1, __result);
-        if (__comp(*__first1, *__first2))
-        {
-            *__result = *__first1;
-            ++__result;
-            ++__first1;
-        }
-        else
-        {
-            if (!__comp(*__first2, *__first1))
-                ++__first1;
-            ++__first2;
-        }
-    }
-    return __result;
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-set_difference(_InputIterator1 __first1, _InputIterator1 __last1,
-               _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__set_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-set_difference(_InputIterator1 __first1, _InputIterator1 __last1,
-               _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
-{
-    return _VSTD::set_difference(__first1, __last1, __first2, __last2, __result,
-                                __less<typename iterator_traits<_InputIterator1>::value_type,
-                                       typename iterator_traits<_InputIterator2>::value_type>());
-}
-
-// set_symmetric_difference
-
-template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 _OutputIterator
-__set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1,
-                           _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    while (__first1 != __last1)
-    {
-        if (__first2 == __last2)
-            return _VSTD::copy(__first1, __last1, __result);
-        if (__comp(*__first1, *__first2))
-        {
-            *__result = *__first1;
-            ++__result;
-            ++__first1;
-        }
-        else
-        {
-            if (__comp(*__first2, *__first1))
-            {
-                *__result = *__first2;
-                ++__result;
-            }
-            else
-                ++__first1;
-            ++__first2;
-        }
-    }
-    return _VSTD::copy(__first2, __last2, __result);
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1,
-                         _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__set_symmetric_difference<_Comp_ref>(__first1, __last1, __first2, __last2, __result, __comp);
-}
-
-template <class _InputIterator1, class _InputIterator2, class _OutputIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_OutputIterator
-set_symmetric_difference(_InputIterator1 __first1, _InputIterator1 __last1,
-                         _InputIterator2 __first2, _InputIterator2 __last2, _OutputIterator __result)
-{
-    return _VSTD::set_symmetric_difference(__first1, __last1, __first2, __last2, __result,
-                                          __less<typename iterator_traits<_InputIterator1>::value_type,
-                                                 typename iterator_traits<_InputIterator2>::value_type>());
-}
-
-// lexicographical_compare
-
-template <class _Compare, class _InputIterator1, class _InputIterator2>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
-__lexicographical_compare(_InputIterator1 __first1, _InputIterator1 __last1,
-                          _InputIterator2 __first2, _InputIterator2 __last2, _Compare __comp)
-{
-    for (; __first2 != __last2; ++__first1, (void) ++__first2)
-    {
-        if (__first1 == __last1 || __comp(*__first1, *__first2))
-            return true;
-        if (__comp(*__first2, *__first1))
-            return false;
-    }
-    return false;
-}
-
-template <class _InputIterator1, class _InputIterator2, class _Compare>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-lexicographical_compare(_InputIterator1 __first1, _InputIterator1 __last1,
-                        _InputIterator2 __first2, _InputIterator2 __last2, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__lexicographical_compare<_Comp_ref>(__first1, __last1, __first2, __last2, __comp);
-}
-
-template <class _InputIterator1, class _InputIterator2>
-_LIBCPP_NODISCARD_EXT inline
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-lexicographical_compare(_InputIterator1 __first1, _InputIterator1 __last1,
-                        _InputIterator2 __first2, _InputIterator2 __last2)
-{
-    return _VSTD::lexicographical_compare(__first1, __last1, __first2, __last2,
-                                         __less<typename iterator_traits<_InputIterator1>::value_type,
-                                                typename iterator_traits<_InputIterator2>::value_type>());
-}
-
-// next_permutation
-
-template <class _Compare, class _BidirectionalIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
-__next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
-{
-    _BidirectionalIterator __i = __last;
-    if (__first == __last || __first == --__i)
-        return false;
-    while (true)
-    {
-        _BidirectionalIterator __ip1 = __i;
-        if (__comp(*--__i, *__ip1))
-        {
-            _BidirectionalIterator __j = __last;
-            while (!__comp(*__i, *--__j))
-                ;
-            swap(*__i, *__j);
-            _VSTD::reverse(__ip1, __last);
-            return true;
-        }
-        if (__i == __first)
-        {
-            _VSTD::reverse(__first, __last);
-            return false;
-        }
-    }
-}
-
-template <class _BidirectionalIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__next_permutation<_Comp_ref>(__first, __last, __comp);
-}
-
-template <class _BidirectionalIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-next_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last)
-{
-    return _VSTD::next_permutation(__first, __last,
-                                  __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
-}
-
-// prev_permutation
-
-template <class _Compare, class _BidirectionalIterator>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 bool
-__prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
-{
-    _BidirectionalIterator __i = __last;
-    if (__first == __last || __first == --__i)
-        return false;
-    while (true)
-    {
-        _BidirectionalIterator __ip1 = __i;
-        if (__comp(*__ip1, *--__i))
-        {
-            _BidirectionalIterator __j = __last;
-            while (!__comp(*--__j, *__i))
-                ;
-            swap(*__i, *__j);
-            _VSTD::reverse(__ip1, __last);
-            return true;
-        }
-        if (__i == __first)
-        {
-            _VSTD::reverse(__first, __last);
-            return false;
-        }
-    }
-}
-
-template <class _BidirectionalIterator, class _Compare>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
-{
-    typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
-    return _VSTD::__prev_permutation<_Comp_ref>(__first, __last, __comp);
-}
-
-template <class _BidirectionalIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool
-prev_permutation(_BidirectionalIterator __first, _BidirectionalIterator __last)
-{
-    return _VSTD::prev_permutation(__first, __last,
-                                  __less<typename iterator_traits<_BidirectionalIterator>::value_type>());
-}
-
-_LIBCPP_END_NAMESPACE_STD
-
 _LIBCPP_POP_MACROS
 
 #if defined(_LIBCPP_HAS_PARALLEL_ALGORITHMS) && _LIBCPP_STD_VER >= 17
 #   include <__pstl_algorithm>
 #endif
 
-#endif  // _LIBCPP_ALGORITHM
+#endif // _LIBCPP_ALGORITHM
lib/libcxx/include/any
@@ -80,12 +80,13 @@ namespace std {
 
 */
 
-#include <experimental/__config>
 #include <__availability>
+#include <__config>
+#include <__utility/forward.h>
+#include <cstdlib>
 #include <memory>
-#include <typeinfo>
 #include <type_traits>
-#include <cstdlib>
+#include <typeinfo>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
lib/libcxx/include/array
@@ -109,25 +109,22 @@ template <size_t I, class T, size_t N> const T&& get(const array<T, N>&&) noexce
 */
 
 #include <__config>
+#include <__debug>
 #include <__tuple>
-#include <type_traits>
-#include <utility>
-#include <iterator>
 #include <algorithm>
-#include <stdexcept>
 #include <cstdlib> // for _LIBCPP_UNREACHABLE
+#include <iterator>
+#include <stdexcept>
+#include <type_traits>
+#include <utility>
 #include <version>
-#include <__debug>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
 
-
-
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-
 template <class _Tp, size_t _Size>
 struct _LIBCPP_TEMPLATE_VIS array
 {
@@ -520,4 +517,4 @@ to_array(_Tp(&&__arr)[_Size]) noexcept(is_nothrow_move_constructible_v<_Tp>) {
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_ARRAY
+#endif // _LIBCPP_ARRAY
lib/libcxx/include/atomic
@@ -67,7 +67,8 @@ struct atomic
     bool is_lock_free() const volatile noexcept;
     bool is_lock_free() const noexcept;
 
-    atomic() noexcept = default;
+    atomic() noexcept = default; // until C++20
+    constexpr atomic() noexcept(is_nothrow_default_constructible_v<T>); // since C++20
     constexpr atomic(T desr) noexcept;
     atomic(const atomic&) = delete;
     atomic& operator=(const atomic&) = delete;
@@ -201,7 +202,8 @@ struct atomic<T*>
     bool is_lock_free() const volatile noexcept;
     bool is_lock_free() const noexcept;
 
-    atomic() noexcept = default;
+    atomic() noexcept = default; // until C++20
+    constexpr atomic() noexcept; // since C++20
     constexpr atomic(T* desr) noexcept;
     atomic(const atomic&) = delete;
     atomic& operator=(const atomic&) = delete;
@@ -509,7 +511,8 @@ typedef atomic<uintmax_t> atomic_uintmax_t;
 
 typedef struct atomic_flag
 {
-    atomic_flag() noexcept = default;
+    atomic_flag() noexcept = default; // until C++20
+    constexpr atomic_flag() noexcept; // since C++20
     atomic_flag(const atomic_flag&) = delete;
     atomic_flag& operator=(const atomic_flag&) = delete;
     atomic_flag& operator=(const atomic_flag&) volatile = delete;
@@ -574,8 +577,8 @@ template <class T>
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <__threading_support>
 #include <cstddef>
 #include <cstdint>
@@ -669,7 +672,7 @@ static_assert((is_same<underlying_type<memory_order>::type, __memory_order_under
   "unexpected underlying type for std::memory_order");
 
 #if defined(_LIBCPP_HAS_GCC_ATOMIC_IMP) || \
-	defined(_LIBCPP_ATOMIC_ONLY_USE_BUILTINS)
+    defined(_LIBCPP_ATOMIC_ONLY_USE_BUILTINS)
 
 // [atomics.types.generic]p1 guarantees _Tp is trivially copyable. Because
 // the default operator= in an object is not volatile, a byte-by-byte copy
@@ -1017,26 +1020,33 @@ _Tp __cxx_atomic_exchange(__cxx_atomic_base_impl<_Tp> * __a, _Tp __value, memory
     return __c11_atomic_exchange(&__a->__a_value, __value, static_cast<__memory_order_underlying_t>(__order));
 }
 
+_LIBCPP_INLINE_VISIBILITY inline _LIBCPP_CONSTEXPR memory_order __to_failure_order(memory_order __order) {
+  // Avoid switch statement to make this a constexpr.
+  return __order == memory_order_release ? memory_order_relaxed:
+         (__order == memory_order_acq_rel ? memory_order_acquire:
+             __order);
+}
+
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY
 bool __cxx_atomic_compare_exchange_strong(__cxx_atomic_base_impl<_Tp> volatile* __a, _Tp* __expected, _Tp __value, memory_order __success, memory_order __failure) _NOEXCEPT {
-    return __c11_atomic_compare_exchange_strong(&__a->__a_value, __expected, __value, static_cast<__memory_order_underlying_t>(__success), static_cast<__memory_order_underlying_t>(__failure));
+    return __c11_atomic_compare_exchange_strong(&__a->__a_value, __expected, __value, static_cast<__memory_order_underlying_t>(__success), static_cast<__memory_order_underlying_t>(__to_failure_order(__failure)));
 }
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY
 bool __cxx_atomic_compare_exchange_strong(__cxx_atomic_base_impl<_Tp> * __a, _Tp* __expected, _Tp __value, memory_order __success, memory_order __failure) _NOEXCEPT {
-    return __c11_atomic_compare_exchange_strong(&__a->__a_value, __expected, __value, static_cast<__memory_order_underlying_t>(__success), static_cast<__memory_order_underlying_t>(__failure));
+    return __c11_atomic_compare_exchange_strong(&__a->__a_value, __expected, __value, static_cast<__memory_order_underlying_t>(__success), static_cast<__memory_order_underlying_t>(__to_failure_order(__failure)));
 }
 
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY
 bool __cxx_atomic_compare_exchange_weak(__cxx_atomic_base_impl<_Tp> volatile* __a, _Tp* __expected, _Tp __value, memory_order __success, memory_order __failure) _NOEXCEPT {
-    return __c11_atomic_compare_exchange_weak(&__a->__a_value, __expected, __value, static_cast<__memory_order_underlying_t>(__success), static_cast<__memory_order_underlying_t>(__failure));
+    return __c11_atomic_compare_exchange_weak(&__a->__a_value, __expected, __value, static_cast<__memory_order_underlying_t>(__success), static_cast<__memory_order_underlying_t>(__to_failure_order(__failure)));
 }
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY
 bool __cxx_atomic_compare_exchange_weak(__cxx_atomic_base_impl<_Tp> * __a, _Tp* __expected, _Tp __value, memory_order __success, memory_order __failure) _NOEXCEPT {
-    return __c11_atomic_compare_exchange_weak(&__a->__a_value, __expected, __value,  static_cast<__memory_order_underlying_t>(__success), static_cast<__memory_order_underlying_t>(__failure));
+    return __c11_atomic_compare_exchange_weak(&__a->__a_value, __expected, __value,  static_cast<__memory_order_underlying_t>(__success), static_cast<__memory_order_underlying_t>(__to_failure_order(__failure)));
 }
 
 template<class _Tp>
@@ -1127,7 +1137,7 @@ _Tp kill_dependency(_Tp __y) _NOEXCEPT
 #if defined(__CLANG_ATOMIC_BOOL_LOCK_FREE)
 # define ATOMIC_BOOL_LOCK_FREE      __CLANG_ATOMIC_BOOL_LOCK_FREE
 # define ATOMIC_CHAR_LOCK_FREE      __CLANG_ATOMIC_CHAR_LOCK_FREE
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 # define ATOMIC_CHAR8_T_LOCK_FREE   __CLANG_ATOMIC_CHAR8_T_LOCK_FREE
 #endif
 # define ATOMIC_CHAR16_T_LOCK_FREE  __CLANG_ATOMIC_CHAR16_T_LOCK_FREE
@@ -1141,7 +1151,7 @@ _Tp kill_dependency(_Tp __y) _NOEXCEPT
 #elif defined(__GCC_ATOMIC_BOOL_LOCK_FREE)
 # define ATOMIC_BOOL_LOCK_FREE      __GCC_ATOMIC_BOOL_LOCK_FREE
 # define ATOMIC_CHAR_LOCK_FREE      __GCC_ATOMIC_CHAR_LOCK_FREE
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 # define ATOMIC_CHAR8_T_LOCK_FREE   __GCC_ATOMIC_CHAR8_T_LOCK_FREE
 #endif
 # define ATOMIC_CHAR16_T_LOCK_FREE  __GCC_ATOMIC_CHAR16_T_LOCK_FREE
@@ -1458,7 +1468,7 @@ template<> struct __cxx_is_always_lock_free<bool> { enum { __value = 2 == ATOMIC
 template<> struct __cxx_is_always_lock_free<char> { enum { __value = 2 == ATOMIC_CHAR_LOCK_FREE }; };
 template<> struct __cxx_is_always_lock_free<signed char> { enum { __value = 2 == ATOMIC_CHAR_LOCK_FREE }; };
 template<> struct __cxx_is_always_lock_free<unsigned char> { enum { __value = 2 == ATOMIC_CHAR_LOCK_FREE }; };
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 template<> struct __cxx_is_always_lock_free<char8_t> { enum { __value = 2 == ATOMIC_CHAR8_T_LOCK_FREE }; };
 #endif
 template<> struct __cxx_is_always_lock_free<char16_t> { enum { __value = 2 == ATOMIC_CHAR16_T_LOCK_FREE }; };
@@ -1673,24 +1683,23 @@ struct __atomic_base  // false
     _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY void notify_all() _NOEXCEPT
         {__cxx_atomic_notify_all(&__a_);}
 
+#if _LIBCPP_STD_VER > 17
+    _LIBCPP_INLINE_VISIBILITY constexpr
+    __atomic_base() noexcept(is_nothrow_default_constructible_v<_Tp>) : __a_(_Tp()) {}
+#else
     _LIBCPP_INLINE_VISIBILITY
     __atomic_base() _NOEXCEPT _LIBCPP_DEFAULT
+#endif
 
     _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
     __atomic_base(_Tp __d) _NOEXCEPT : __a_(__d) {}
 
 #ifndef _LIBCPP_CXX03_LANG
     __atomic_base(const __atomic_base&) = delete;
-    __atomic_base& operator=(const __atomic_base&) = delete;
-    __atomic_base& operator=(const __atomic_base&) volatile = delete;
 #else
 private:
     _LIBCPP_INLINE_VISIBILITY
     __atomic_base(const __atomic_base&);
-    _LIBCPP_INLINE_VISIBILITY
-    __atomic_base& operator=(const __atomic_base&);
-    _LIBCPP_INLINE_VISIBILITY
-    __atomic_base& operator=(const __atomic_base&) volatile;
 #endif
 };
 
@@ -1706,8 +1715,10 @@ struct __atomic_base<_Tp, true>
     : public __atomic_base<_Tp, false>
 {
     typedef __atomic_base<_Tp, false> __base;
-    _LIBCPP_INLINE_VISIBILITY
+
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
     __atomic_base() _NOEXCEPT _LIBCPP_DEFAULT
+
     _LIBCPP_INLINE_VISIBILITY
     _LIBCPP_CONSTEXPR __atomic_base(_Tp __d) _NOEXCEPT : __base(__d) {}
 
@@ -1789,8 +1800,15 @@ struct atomic
     typedef __atomic_base<_Tp> __base;
     typedef _Tp value_type;
     typedef value_type difference_type;
+
+#if _LIBCPP_STD_VER > 17
+    _LIBCPP_INLINE_VISIBILITY
+    atomic() = default;
+#else
     _LIBCPP_INLINE_VISIBILITY
     atomic() _NOEXCEPT _LIBCPP_DEFAULT
+#endif
+
     _LIBCPP_INLINE_VISIBILITY
     _LIBCPP_CONSTEXPR atomic(_Tp __d) _NOEXCEPT : __base(__d) {}
 
@@ -1800,6 +1818,9 @@ struct atomic
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator=(_Tp __d) _NOEXCEPT
         {__base::store(__d); return __d;}
+
+    atomic& operator=(const atomic&) = delete;
+    atomic& operator=(const atomic&) volatile = delete;
 };
 
 // atomic<T*>
@@ -1811,8 +1832,10 @@ struct atomic<_Tp*>
     typedef __atomic_base<_Tp*> __base;
     typedef _Tp* value_type;
     typedef ptrdiff_t difference_type;
+
     _LIBCPP_INLINE_VISIBILITY
     atomic() _NOEXCEPT _LIBCPP_DEFAULT
+
     _LIBCPP_INLINE_VISIBILITY
     _LIBCPP_CONSTEXPR atomic(_Tp* __d) _NOEXCEPT : __base(__d) {}
 
@@ -1862,6 +1885,9 @@ struct atomic<_Tp*>
     _Tp* operator-=(ptrdiff_t __op) volatile _NOEXCEPT {return fetch_sub(__op) - __op;}
     _LIBCPP_INLINE_VISIBILITY
     _Tp* operator-=(ptrdiff_t __op) _NOEXCEPT          {return fetch_sub(__op) - __op;}
+
+    atomic& operator=(const atomic&) = delete;
+    atomic& operator=(const atomic&) volatile = delete;
 };
 
 // atomic_is_lock_free
@@ -1885,7 +1911,7 @@ atomic_is_lock_free(const atomic<_Tp>* __o) _NOEXCEPT
 // atomic_init
 
 template <class _Tp>
-_LIBCPP_INLINE_VISIBILITY
+_LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_INLINE_VISIBILITY
 void
 atomic_init(volatile atomic<_Tp>* __o, typename atomic<_Tp>::value_type __d) _NOEXCEPT
 {
@@ -1893,7 +1919,7 @@ atomic_init(volatile atomic<_Tp>* __o, typename atomic<_Tp>::value_type __d) _NO
 }
 
 template <class _Tp>
-_LIBCPP_INLINE_VISIBILITY
+_LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_INLINE_VISIBILITY
 void
 atomic_init(atomic<_Tp>* __o, typename atomic<_Tp>::value_type __d) _NOEXCEPT
 {
@@ -2534,8 +2560,13 @@ typedef struct atomic_flag
     void notify_all() _NOEXCEPT
         {__cxx_atomic_notify_all(&__a_);}
 
+#if _LIBCPP_STD_VER > 17
+    _LIBCPP_INLINE_VISIBILITY constexpr
+    atomic_flag() _NOEXCEPT : __a_(false) {}
+#else
     _LIBCPP_INLINE_VISIBILITY
     atomic_flag() _NOEXCEPT _LIBCPP_DEFAULT
+#endif
 
     _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
     atomic_flag(bool __b) _NOEXCEPT : __a_(__b) {} // EXTENSION
@@ -2728,7 +2759,7 @@ typedef atomic<long>               atomic_long;
 typedef atomic<unsigned long>      atomic_ulong;
 typedef atomic<long long>          atomic_llong;
 typedef atomic<unsigned long long> atomic_ullong;
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 typedef atomic<char8_t>            atomic_char8_t;
 #endif
 typedef atomic<char16_t>           atomic_char16_t;
@@ -2801,4 +2832,4 @@ typedef atomic<__libcpp_unsigned_lock_free> atomic_unsigned_lock_free;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_ATOMIC
+#endif // _LIBCPP_ATOMIC
lib/libcxx/include/barrier
@@ -45,8 +45,8 @@ namespace std
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <atomic>
 #ifndef _LIBCPP_HAS_NO_TREE_BARRIER
 # include <memory>
@@ -107,7 +107,6 @@ void __destroy_barrier_algorithm_base(__barrier_algorithm_base* __barrier);
 
 template<class _CompletionF>
 class __barrier_base {
-
     ptrdiff_t                                               __expected;
     unique_ptr<__barrier_algorithm_base,
                void (*)(__barrier_algorithm_base*)>         __base;
@@ -146,7 +145,7 @@ public:
     _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
     void wait(arrival_token&& __old_phase) const
     {
-        auto const __test_fn = [=]() -> bool {
+        auto const __test_fn = [this, __old_phase]() -> bool {
             return __phase.load(memory_order_acquire) != __old_phase;
         };
         __libcpp_thread_poll_with_backoff(__test_fn, __libcpp_timed_backoff_policy());
@@ -309,11 +308,11 @@ public:
     {
         __b.wait(_VSTD::move(__phase));
     }
-	_LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
     void arrive_and_wait()
     {
         wait(arrive());
-	}
+    }
     _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
     void arrive_and_drop()
     {
lib/libcxx/include/bit
@@ -55,11 +55,11 @@ namespace std {
 */
 
 #include <__config>
-#include <__bits>
+#include <__bits> // __libcpp_clz
+#include <__debug>
 #include <limits>
 #include <type_traits>
 #include <version>
-#include <__debug>
 
 #if defined(__IBMCPP__)
 #include "__support/ibm/support.h"
@@ -77,49 +77,33 @@ _LIBCPP_PUSH_MACROS
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-
-template <class _Tp>
-using __bitop_unsigned_integer _LIBCPP_NODEBUG_TYPE = integral_constant<bool,
-         is_integral<_Tp>::value &&
-         is_unsigned<_Tp>::value &&
-        _IsNotSame<typename remove_cv<_Tp>::type, bool>::value &&
-        _IsNotSame<typename remove_cv<_Tp>::type, signed char>::value &&
-        _IsNotSame<typename remove_cv<_Tp>::type, wchar_t>::value &&
-        _IsNotSame<typename remove_cv<_Tp>::type, char16_t>::value &&
-        _IsNotSame<typename remove_cv<_Tp>::type, char32_t>::value
-    >;
-
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 _Tp __rotl(_Tp __t, unsigned int __cnt) _NOEXCEPT
 {
-    static_assert(__bitop_unsigned_integer<_Tp>::value, "__rotl requires unsigned");
+    static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__rotl requires an unsigned integer type");
     const unsigned int __dig = numeric_limits<_Tp>::digits;
     if ((__cnt % __dig) == 0)
         return __t;
     return (__t << (__cnt % __dig)) | (__t >> (__dig - (__cnt % __dig)));
 }
 
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 _Tp __rotr(_Tp __t, unsigned int __cnt) _NOEXCEPT
 {
-    static_assert(__bitop_unsigned_integer<_Tp>::value, "__rotr requires unsigned");
+    static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__rotr requires an unsigned integer type");
     const unsigned int __dig = numeric_limits<_Tp>::digits;
     if ((__cnt % __dig) == 0)
         return __t;
     return (__t >> (__cnt % __dig)) | (__t << (__dig - (__cnt % __dig)));
 }
 
-
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 int __countr_zero(_Tp __t) _NOEXCEPT
 {
-    static_assert(__bitop_unsigned_integer<_Tp>::value, "__countr_zero requires unsigned");
+    static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__countr_zero requires an unsigned integer type");
     if (__t == 0)
         return numeric_limits<_Tp>::digits;
 
@@ -132,14 +116,13 @@ int __countr_zero(_Tp __t) _NOEXCEPT
     else
     {
         int __ret = 0;
-        int __iter = 0;
         const unsigned int __ulldigits = numeric_limits<unsigned long long>::digits;
-        while ((__iter = __libcpp_ctz(static_cast<unsigned long long>(__t))) == __ulldigits)
+        while (static_cast<unsigned long long>(__t) == 0uLL)
         {
-            __ret += __iter;
+            __ret += __ulldigits;
             __t >>= __ulldigits;
         }
-        return __ret + __iter;
+        return __ret + __libcpp_ctz(static_cast<unsigned long long>(__t));
     }
 }
 
@@ -147,7 +130,7 @@ template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 int __countl_zero(_Tp __t) _NOEXCEPT
 {
-    static_assert(__bitop_unsigned_integer<_Tp>::value, "__countl_zero requires unsigned");
+    static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__countl_zero requires an unsigned integer type");
     if (__t == 0)
         return numeric_limits<_Tp>::digits;
 
@@ -179,30 +162,27 @@ template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 int __countl_one(_Tp __t) _NOEXCEPT
 {
-    static_assert(__bitop_unsigned_integer<_Tp>::value, "__countl_one requires unsigned");
+    static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__countl_one requires an unsigned integer type");
     return __t != numeric_limits<_Tp>::max()
         ? __countl_zero(static_cast<_Tp>(~__t))
         : numeric_limits<_Tp>::digits;
 }
 
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 int __countr_one(_Tp __t) _NOEXCEPT
 {
-    static_assert(__bitop_unsigned_integer<_Tp>::value, "__countr_one requires unsigned");
+    static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__countr_one requires an unsigned integer type");
     return __t != numeric_limits<_Tp>::max()
         ? __countr_zero(static_cast<_Tp>(~__t))
         : numeric_limits<_Tp>::digits;
 }
 
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-int
-__popcount(_Tp __t) _NOEXCEPT
+int __popcount(_Tp __t) _NOEXCEPT
 {
-    static_assert(__bitop_unsigned_integer<_Tp>::value, "__libcpp_popcount requires unsigned");
+    static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__popcount requires an unsigned integer type");
     if      (sizeof(_Tp) <= sizeof(unsigned int))
         return __libcpp_popcount(static_cast<unsigned int>(__t));
     else if (sizeof(_Tp) <= sizeof(unsigned long))
@@ -221,13 +201,12 @@ __popcount(_Tp __t) _NOEXCEPT
     }
 }
 
-
 // integral log base 2
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 unsigned __bit_log2(_Tp __t) _NOEXCEPT
 {
-    static_assert(__bitop_unsigned_integer<_Tp>::value, "__bit_log2 requires unsigned");
+    static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__bit_log2 requires an unsigned integer type");
     return numeric_limits<_Tp>::digits - 1 - __countl_zero(__t);
 }
 
@@ -235,80 +214,71 @@ template <class _Tp>
 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
 bool __has_single_bit(_Tp __t) _NOEXCEPT
 {
-    static_assert(__bitop_unsigned_integer<_Tp>::value, "__has_single_bit requires unsigned");
+    static_assert(__libcpp_is_unsigned_integer<_Tp>::value, "__has_single_bit requires an unsigned integer type");
     return __t != 0 && (((__t & (__t - 1)) == 0));
 }
 
-
 #if _LIBCPP_STD_VER > 17
 
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, _Tp>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, _Tp>
 rotl(_Tp __t, unsigned int __cnt) noexcept
 {
     return __rotl(__t, __cnt);
 }
 
-
-// rotr
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, _Tp>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, _Tp>
 rotr(_Tp __t, unsigned int __cnt) noexcept
 {
     return __rotr(__t, __cnt);
 }
 
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, int>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, int>
 countl_zero(_Tp __t) noexcept
 {
     return __countl_zero(__t);
 }
 
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, int>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, int>
 countl_one(_Tp __t) noexcept
 {
     return __countl_one(__t);
 }
 
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, int>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, int>
 countr_zero(_Tp __t) noexcept
 {
     return __countr_zero(__t);
 }
 
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, int>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, int>
 countr_one(_Tp __t) noexcept
 {
     return __countr_one(__t);
 }
 
-
 template<class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, int>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, int>
 popcount(_Tp __t) noexcept
 {
     return __popcount(__t);
 }
 
-
 template <class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, bool>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, bool>
 has_single_bit(_Tp __t) noexcept
 {
     return __has_single_bit(__t);
@@ -316,7 +286,7 @@ has_single_bit(_Tp __t) noexcept
 
 template <class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, _Tp>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, _Tp>
 bit_floor(_Tp __t) noexcept
 {
     return __t == 0 ? 0 : _Tp{1} << __bit_log2(__t);
@@ -324,7 +294,7 @@ bit_floor(_Tp __t) noexcept
 
 template <class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, _Tp>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, _Tp>
 bit_ceil(_Tp __t) noexcept
 {
     if (__t < 2) return 1;
@@ -343,7 +313,7 @@ bit_ceil(_Tp __t) noexcept
 
 template <class _Tp>
 _LIBCPP_INLINE_VISIBILITY constexpr
-enable_if_t<__bitop_unsigned_integer<_Tp>::value, _Tp>
+_EnableIf<__libcpp_is_unsigned_integer<_Tp>::value, _Tp>
 bit_width(_Tp __t) noexcept
 {
     return __t == 0 ? 0 : __bit_log2(__t) + 1;
lib/libcxx/include/bitset
@@ -114,12 +114,12 @@ template <size_t N> struct hash<std::bitset<N>>;
 
 #include <__config>
 #include <__bit_reference>
-#include <cstddef>
+#include <__functional_base>
 #include <climits>
-#include <string>
-#include <stdexcept>
+#include <cstddef>
 #include <iosfwd>
-#include <__functional_base>
+#include <stdexcept>
+#include <string>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -202,7 +202,7 @@ private:
     void __init(unsigned long long __v, false_type) _NOEXCEPT;
     _LIBCPP_INLINE_VISIBILITY
     void __init(unsigned long long __v, true_type) _NOEXCEPT;
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     unsigned long to_ulong(false_type) const;
     _LIBCPP_INLINE_VISIBILITY
     unsigned long to_ulong(true_type) const;
@@ -258,7 +258,7 @@ __bitset<_N_words, _Size>::__init(unsigned long long __v, true_type) _NOEXCEPT
     _VSTD::fill(__first_ + 1, __first_ + sizeof(__first_)/sizeof(__first_[0]), __storage_type(0));
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <size_t _N_words, size_t _Size>
 inline
@@ -775,10 +775,7 @@ bitset<_Size>::bitset(const _CharT* __str,
     for (; __i < _Mp; ++__i)
     {
         _CharT __c = __str[_Mp - 1 - __i];
-        if (__c == __zero)
-            (*this)[__i] = false;
-        else
-            (*this)[__i] = true;
+        (*this)[__i] = (__c == __one);
     }
     _VSTD::fill(base::__make_iter(__i), base::__make_iter(_Size), false);
 }
@@ -803,10 +800,7 @@ bitset<_Size>::bitset(const basic_string<_CharT,_Traits,_Allocator>& __str,
     for (; __i < _Mp; ++__i)
     {
         _CharT __c = __str[__pos + _Mp - 1 - __i];
-        if (_Traits::eq(__c, __zero))
-            (*this)[__i] = false;
-        else
-            (*this)[__i] = true;
+        (*this)[__i] = _Traits::eq(__c, __one);
     }
     _VSTD::fill(base::__make_iter(__i), base::__make_iter(_Size), false);
 }
@@ -1106,4 +1100,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_BITSET
+#endif // _LIBCPP_BITSET
lib/libcxx/include/ccomplex
@@ -25,4 +25,4 @@
 
 // hh 080623 Created
 
-#endif  // _LIBCPP_CCOMPLEX
+#endif // _LIBCPP_CCOMPLEX
lib/libcxx/include/cctype
@@ -100,21 +100,21 @@ _LIBCPP_BEGIN_NAMESPACE_STD
 #endif
 
 
-using ::isalnum;
-using ::isalpha;
-using ::isblank;
-using ::iscntrl;
-using ::isdigit;
-using ::isgraph;
-using ::islower;
-using ::isprint;
-using ::ispunct;
-using ::isspace;
-using ::isupper;
-using ::isxdigit;
-using ::tolower;
-using ::toupper;
+using ::isalnum _LIBCPP_USING_IF_EXISTS;
+using ::isalpha _LIBCPP_USING_IF_EXISTS;
+using ::isblank _LIBCPP_USING_IF_EXISTS;
+using ::iscntrl _LIBCPP_USING_IF_EXISTS;
+using ::isdigit _LIBCPP_USING_IF_EXISTS;
+using ::isgraph _LIBCPP_USING_IF_EXISTS;
+using ::islower _LIBCPP_USING_IF_EXISTS;
+using ::isprint _LIBCPP_USING_IF_EXISTS;
+using ::ispunct _LIBCPP_USING_IF_EXISTS;
+using ::isspace _LIBCPP_USING_IF_EXISTS;
+using ::isupper _LIBCPP_USING_IF_EXISTS;
+using ::isxdigit _LIBCPP_USING_IF_EXISTS;
+using ::tolower _LIBCPP_USING_IF_EXISTS;
+using ::toupper _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CCTYPE
+#endif // _LIBCPP_CCTYPE
lib/libcxx/include/cerrno
@@ -29,4 +29,4 @@ Macros:
 #pragma GCC system_header
 #endif
 
-#endif  // _LIBCPP_CERRNO
+#endif // _LIBCPP_CERRNO
lib/libcxx/include/cfenv
@@ -61,21 +61,21 @@ int feupdateenv(const fenv_t* envp);
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::fenv_t;
-using ::fexcept_t;
-
-using ::feclearexcept;
-using ::fegetexceptflag;
-using ::feraiseexcept;
-using ::fesetexceptflag;
-using ::fetestexcept;
-using ::fegetround;
-using ::fesetround;
-using ::fegetenv;
-using ::feholdexcept;
-using ::fesetenv;
-using ::feupdateenv;
+using ::fenv_t _LIBCPP_USING_IF_EXISTS;
+using ::fexcept_t _LIBCPP_USING_IF_EXISTS;
+
+using ::feclearexcept _LIBCPP_USING_IF_EXISTS;
+using ::fegetexceptflag _LIBCPP_USING_IF_EXISTS;
+using ::feraiseexcept _LIBCPP_USING_IF_EXISTS;
+using ::fesetexceptflag _LIBCPP_USING_IF_EXISTS;
+using ::fetestexcept _LIBCPP_USING_IF_EXISTS;
+using ::fegetround _LIBCPP_USING_IF_EXISTS;
+using ::fesetround _LIBCPP_USING_IF_EXISTS;
+using ::fegetenv _LIBCPP_USING_IF_EXISTS;
+using ::feholdexcept _LIBCPP_USING_IF_EXISTS;
+using ::fesetenv _LIBCPP_USING_IF_EXISTS;
+using ::feupdateenv _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CFENV
+#endif // _LIBCPP_CFENV
lib/libcxx/include/cfloat
@@ -76,4 +76,4 @@ Macros:
 #pragma GCC system_header
 #endif
 
-#endif  // _LIBCPP_CFLOAT
+#endif // _LIBCPP_CFLOAT
lib/libcxx/include/charconv
@@ -73,11 +73,13 @@ namespace std {
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <__errc>
+#include <__utility/to_underlying.h>
 #include <cmath> // for log2f
 #include <cstdint>
+#include <cstdlib> // for _LIBCPP_UNREACHABLE
 #include <cstring>
 #include <limits>
 #include <type_traits>
@@ -108,6 +110,47 @@ enum class _LIBCPP_ENUM_VIS chars_format
     general = fixed | scientific
 };
 
+inline _LIBCPP_INLINE_VISIBILITY constexpr chars_format
+operator~(chars_format __x) {
+  return chars_format(~_VSTD::__to_underlying(__x));
+}
+
+inline _LIBCPP_INLINE_VISIBILITY constexpr chars_format
+operator&(chars_format __x, chars_format __y) {
+  return chars_format(_VSTD::__to_underlying(__x) &
+                      _VSTD::__to_underlying(__y));
+}
+
+inline _LIBCPP_INLINE_VISIBILITY constexpr chars_format
+operator|(chars_format __x, chars_format __y) {
+  return chars_format(_VSTD::__to_underlying(__x) |
+                      _VSTD::__to_underlying(__y));
+}
+
+inline _LIBCPP_INLINE_VISIBILITY constexpr chars_format
+operator^(chars_format __x, chars_format __y) {
+  return chars_format(_VSTD::__to_underlying(__x) ^
+                      _VSTD::__to_underlying(__y));
+}
+
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 chars_format&
+operator&=(chars_format& __x, chars_format __y) {
+  __x = __x & __y;
+  return __x;
+}
+
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 chars_format&
+operator|=(chars_format& __x, chars_format __y) {
+  __x = __x | __y;
+  return __x;
+}
+
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11 chars_format&
+operator^=(chars_format& __x, chars_format __y) {
+  __x = __x ^ __y;
+  return __x;
+}
+
 struct _LIBCPP_TYPE_VIS to_chars_result
 {
     char* ptr;
@@ -288,19 +331,12 @@ __complement(_Tp __x)
     return _Tp(~__x + 1);
 }
 
-template <typename _Tp>
-inline _LIBCPP_INLINE_VISIBILITY typename make_unsigned<_Tp>::type
-__to_unsigned(_Tp __x)
-{
-    return static_cast<typename make_unsigned<_Tp>::type>(__x);
-}
-
 template <typename _Tp>
 _LIBCPP_AVAILABILITY_TO_CHARS
 inline _LIBCPP_INLINE_VISIBILITY to_chars_result
 __to_chars_itoa(char* __first, char* __last, _Tp __value, true_type)
 {
-    auto __x = __to_unsigned(__value);
+    auto __x = __to_unsigned_like(__value);
     if (__value < 0 && __first != __last)
     {
         *__first++ = '-';
@@ -348,7 +384,7 @@ inline _LIBCPP_INLINE_VISIBILITY to_chars_result
 __to_chars_integral(char* __first, char* __last, _Tp __value, int __base,
                     true_type)
 {
-    auto __x = __to_unsigned(__value);
+    auto __x = __to_unsigned_like(__value);
     if (__value < 0 && __first != __last)
     {
         *__first++ = '-';
@@ -358,33 +394,54 @@ __to_chars_integral(char* __first, char* __last, _Tp __value, int __base,
     return __to_chars_integral(__first, __last, __x, __base, false_type());
 }
 
+template <typename _Tp>
+_LIBCPP_AVAILABILITY_TO_CHARS _LIBCPP_INLINE_VISIBILITY int __to_chars_integral_width(_Tp __value, unsigned __base) {
+  _LIBCPP_ASSERT(__value >= 0, "The function requires a non-negative value.");
+
+  unsigned __base_2 = __base * __base;
+  unsigned __base_3 = __base_2 * __base;
+  unsigned __base_4 = __base_2 * __base_2;
+
+  int __r = 0;
+  while (true) {
+    if (__value < __base)
+      return __r + 1;
+    if (__value < __base_2)
+      return __r + 2;
+    if (__value < __base_3)
+      return __r + 3;
+    if (__value < __base_4)
+      return __r + 4;
+
+    __value /= __base_4;
+    __r += 4;
+  }
+
+  _LIBCPP_UNREACHABLE();
+}
+
 template <typename _Tp>
 _LIBCPP_AVAILABILITY_TO_CHARS
 inline _LIBCPP_INLINE_VISIBILITY to_chars_result
 __to_chars_integral(char* __first, char* __last, _Tp __value, int __base,
                     false_type)
 {
-    if (__base == 10)
-        return __to_chars_itoa(__first, __last, __value, false_type());
-
-    auto __p = __last;
-    while (__p != __first)
-    {
-        auto __c = __value % __base;
-        __value /= __base;
-        *--__p = "0123456789abcdefghijklmnopqrstuvwxyz"[__c];
-        if (__value == 0)
-            break;
-    }
-
-    auto __len = __last - __p;
-    if (__value != 0 || !__len)
-        return {__last, errc::value_too_large};
-    else
-    {
-        _VSTD::memmove(__first, __p, __len);
-        return {__first + __len, {}};
-    }
+  if (__base == 10)
+    return __to_chars_itoa(__first, __last, __value, false_type());
+
+  ptrdiff_t __cap = __last - __first;
+  int __n = __to_chars_integral_width(__value, __base);
+  if (__n > __cap)
+    return {__last, errc::value_too_large};
+
+  __last = __first + __n;
+  char* __p = __last;
+  do {
+    unsigned __c = __value % __base;
+    __value /= __base;
+    *--__p = "0123456789abcdefghijklmnopqrstuvwxyz"[__c];
+  } while (__value != 0);
+  return {__last, errc(0)};
 }
 
 template <typename _Tp, typename enable_if<is_integral<_Tp>::value, int>::type = 0>
@@ -410,7 +467,7 @@ inline _LIBCPP_INLINE_VISIBILITY from_chars_result
 __sign_combinator(_It __first, _It __last, _Tp& __value, _Fn __f, _Ts... __args)
 {
     using __tl = numeric_limits<_Tp>;
-    decltype(__to_unsigned(__value)) __x;
+    decltype(__to_unsigned_like(__value)) __x;
 
     bool __neg = (__first != __last && *__first == '-');
     auto __r = __f(__neg ? __first + 1 : __first, __last, __x, __args...);
@@ -426,7 +483,7 @@ __sign_combinator(_It __first, _It __last, _Tp& __value, _Fn __f, _Ts... __args)
 
     if (__neg)
     {
-        if (__x <= __complement(__to_unsigned(__tl::min())))
+        if (__x <= __complement(__to_unsigned_like(__tl::min())))
         {
             __x = __complement(__x);
             _VSTD::memcpy(&__value, &__x, sizeof(__x));
@@ -541,7 +598,7 @@ template <typename _Tp, typename enable_if<is_signed<_Tp>::value, int>::type = 0
 inline _LIBCPP_INLINE_VISIBILITY from_chars_result
 __from_chars_atoi(const char* __first, const char* __last, _Tp& __value)
 {
-    using __t = decltype(__to_unsigned(__value));
+    using __t = decltype(__to_unsigned_like(__value));
     return __sign_combinator(__first, __last, __value, __from_chars_atoi<__t>);
 }
 
@@ -555,13 +612,13 @@ __from_chars_integral(const char* __first, const char* __last, _Tp& __value,
 
     return __subject_seq_combinator(
         __first, __last, __value,
-        [](const char* __p, const char* __last, _Tp& __value,
+        [](const char* __p, const char* __lastx, _Tp& __value,
            int __base) -> from_chars_result {
             using __tl = numeric_limits<_Tp>;
             auto __digits = __tl::digits / log2f(float(__base));
             _Tp __a = __in_pattern(*__p++, __base).__val, __b = 0;
 
-            for (int __i = 1; __p != __last; ++__i, ++__p)
+            for (int __i = 1; __p != __lastx; ++__i, ++__p)
             {
                 if (auto __c = __in_pattern(*__p, __base))
                 {
@@ -579,7 +636,7 @@ __from_chars_integral(const char* __first, const char* __last, _Tp& __value,
                     break;
             }
 
-            if (__p == __last || !__in_pattern(*__p, __base))
+            if (__p == __lastx || !__in_pattern(*__p, __base))
             {
                 if (__tl::max() - __a >= __b)
                 {
@@ -597,7 +654,7 @@ inline _LIBCPP_INLINE_VISIBILITY from_chars_result
 __from_chars_integral(const char* __first, const char* __last, _Tp& __value,
                       int __base)
 {
-    using __t = decltype(__to_unsigned(__value));
+    using __t = decltype(__to_unsigned_like(__value));
     return __sign_combinator(__first, __last, __value,
                              __from_chars_integral<__t>, __base);
 }
@@ -617,10 +674,10 @@ from_chars(const char* __first, const char* __last, _Tp& __value, int __base)
     return __from_chars_integral(__first, __last, __value, __base);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_CHARCONV
+#endif // _LIBCPP_CHARCONV
lib/libcxx/include/chrono
@@ -823,12 +823,13 @@ constexpr chrono::year                                  operator ""y(unsigned lo
 }  // std
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
+#include <compare>
 #include <ctime>
-#include <type_traits>
-#include <ratio>
 #include <limits>
+#include <ratio>
+#include <type_traits>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -1091,7 +1092,7 @@ public:
                 (__no_overflow<_Period2, period>::type::den == 1 &&
                  !treat_as_floating_point<_Rep2>::value))
             >::type* = nullptr)
-                : __rep_(_VSTD::chrono::duration_cast<duration>(__d).count()) {}
+                : __rep_(chrono::duration_cast<duration>(__d).count()) {}
 
     // observer
 
@@ -1410,7 +1411,7 @@ inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 time_point<_Clock, _ToDuration>
 time_point_cast(const time_point<_Clock, _Duration>& __t)
 {
-    return time_point<_Clock, _ToDuration>(_VSTD::chrono::duration_cast<_ToDuration>(__t.time_since_epoch()));
+    return time_point<_Clock, _ToDuration>(chrono::duration_cast<_ToDuration>(__t.time_since_epoch()));
 }
 
 #if _LIBCPP_STD_VER > 14
@@ -1926,13 +1927,13 @@ inline constexpr weekday& weekday::operator-=(const days& __dd) noexcept
 
 class weekday_indexed {
 private:
-    _VSTD::chrono::weekday __wd;
+    chrono::weekday __wd;
     unsigned char          __idx;
 public:
     weekday_indexed() = default;
-    inline constexpr weekday_indexed(const _VSTD::chrono::weekday& __wdval, unsigned __idxval) noexcept
+    inline constexpr weekday_indexed(const chrono::weekday& __wdval, unsigned __idxval) noexcept
         : __wd{__wdval}, __idx(__idxval) {}
-    inline constexpr _VSTD::chrono::weekday weekday() const noexcept { return __wd; }
+    inline constexpr chrono::weekday weekday() const noexcept { return __wd; }
     inline constexpr unsigned                 index() const noexcept { return __idx; }
     inline constexpr bool ok() const noexcept { return __wd.ok() && __idx >= 1 && __idx <= 5; }
 };
@@ -1948,11 +1949,11 @@ bool operator!=(const weekday_indexed& __lhs, const weekday_indexed& __rhs) noex
 
 class weekday_last {
 private:
-    _VSTD::chrono::weekday __wd;
+    chrono::weekday __wd;
 public:
-    explicit constexpr weekday_last(const _VSTD::chrono::weekday& __val) noexcept
+    explicit constexpr weekday_last(const chrono::weekday& __val) noexcept
         : __wd{__val} {}
-    constexpr _VSTD::chrono::weekday weekday() const noexcept { return __wd; }
+    constexpr chrono::weekday weekday() const noexcept { return __wd; }
     constexpr bool ok() const noexcept { return __wd.ok(); }
 };
 
@@ -2308,8 +2309,8 @@ inline constexpr
 year_month_day
 year_month_day::__from_days(days __d) noexcept
 {
-    static_assert(std::numeric_limits<unsigned>::digits >= 18, "");
-    static_assert(std::numeric_limits<int>::digits >= 20     , "");
+    static_assert(numeric_limits<unsigned>::digits >= 18, "");
+    static_assert(numeric_limits<int>::digits >= 20     , "");
     const int      __z = __d.count() + 719468;
     const int      __era = (__z >= 0 ? __z : __z - 146096) / 146097;
     const unsigned __doe = static_cast<unsigned>(__z - __era * 146097);              // [0, 146096]
@@ -2325,8 +2326,8 @@ year_month_day::__from_days(days __d) noexcept
 // https://howardhinnant.github.io/date_algorithms.html#days_from_civil
 inline constexpr days year_month_day::__to_days() const noexcept
 {
-    static_assert(std::numeric_limits<unsigned>::digits >= 18, "");
-    static_assert(std::numeric_limits<int>::digits >= 20     , "");
+    static_assert(numeric_limits<unsigned>::digits >= 18, "");
+    static_assert(numeric_limits<int>::digits >= 20     , "");
 
     const int      __yr  = static_cast<int>(__y) - (__m <= February);
     const unsigned __mth = static_cast<unsigned>(__m);
@@ -2964,4 +2965,4 @@ _LIBCPP_END_NAMESPACE_FILESYSTEM
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_CHRONO
+#endif // _LIBCPP_CHRONO
lib/libcxx/include/cinttypes
@@ -244,14 +244,14 @@ uintmax_t wcstoumax(const wchar_t* restrict nptr, wchar_t** restrict endptr, int
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using::imaxdiv_t;
-using::imaxabs;
-using::imaxdiv;
-using::strtoimax;
-using::strtoumax;
-using::wcstoimax;
-using::wcstoumax;
+using ::imaxdiv_t _LIBCPP_USING_IF_EXISTS;
+using ::imaxabs _LIBCPP_USING_IF_EXISTS;
+using ::imaxdiv _LIBCPP_USING_IF_EXISTS;
+using ::strtoimax _LIBCPP_USING_IF_EXISTS;
+using ::strtoumax _LIBCPP_USING_IF_EXISTS;
+using ::wcstoimax _LIBCPP_USING_IF_EXISTS;
+using ::wcstoumax _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CINTTYPES
+#endif // _LIBCPP_CINTTYPES
lib/libcxx/include/ciso646
@@ -21,4 +21,4 @@
 #pragma GCC system_header
 #endif
 
-#endif  // _LIBCPP_CISO646
+#endif // _LIBCPP_CISO646
lib/libcxx/include/climits
@@ -44,4 +44,4 @@ Macros:
 #pragma GCC system_header
 #endif
 
-#endif  // _LIBCPP_CLIMITS
+#endif // _LIBCPP_CLIMITS
lib/libcxx/include/clocale
@@ -43,12 +43,12 @@ lconv* localeconv();
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::lconv;
+using ::lconv _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_THREAD_UNSAFE_C_FUNCTIONS
-using ::setlocale;
+using ::setlocale _LIBCPP_USING_IF_EXISTS;
 #endif
-using ::localeconv;
+using ::localeconv _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CLOCALE
+#endif // _LIBCPP_CLOCALE
lib/libcxx/include/cmath
@@ -318,217 +318,215 @@ _LIBCPP_PUSH_MACROS
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::signbit;
-using ::fpclassify;
-using ::isfinite;
-using ::isinf;
-using ::isnan;
-using ::isnormal;
-using ::isgreater;
-using ::isgreaterequal;
-using ::isless;
-using ::islessequal;
-using ::islessgreater;
-using ::isunordered;
-using ::isunordered;
-
-using ::float_t;
-using ::double_t;
-
-#ifndef _AIX
-using ::abs;
-#endif
-
-using ::acos;
-using ::acosf;
-using ::asin;
-using ::asinf;
-using ::atan;
-using ::atanf;
-using ::atan2;
-using ::atan2f;
-using ::ceil;
-using ::ceilf;
-using ::cos;
-using ::cosf;
-using ::cosh;
-using ::coshf;
-
-using ::exp;
-using ::expf;
-
-using ::fabs;
-using ::fabsf;
-using ::floor;
-using ::floorf;
-
-using ::fmod;
-using ::fmodf;
-
-using ::frexp;
-using ::frexpf;
-using ::ldexp;
-using ::ldexpf;
-
-using ::log;
-using ::logf;
-
-using ::log10;
-using ::log10f;
-using ::modf;
-using ::modff;
-
-using ::pow;
-using ::powf;
-
-using ::sin;
-using ::sinf;
-using ::sinh;
-using ::sinhf;
-
-using ::sqrt;
-using ::sqrtf;
-using ::tan;
-using ::tanf;
-
-using ::tanh;
-using ::tanhf;
-
-using ::acosh;
-using ::acoshf;
-using ::asinh;
-using ::asinhf;
-using ::atanh;
-using ::atanhf;
-using ::cbrt;
-using ::cbrtf;
-
-using ::copysign;
-using ::copysignf;
-
-using ::erf;
-using ::erff;
-using ::erfc;
-using ::erfcf;
-using ::exp2;
-using ::exp2f;
-using ::expm1;
-using ::expm1f;
-using ::fdim;
-using ::fdimf;
-using ::fmaf;
-using ::fma;
-using ::fmax;
-using ::fmaxf;
-using ::fmin;
-using ::fminf;
-using ::hypot;
-using ::hypotf;
-using ::ilogb;
-using ::ilogbf;
-using ::lgamma;
-using ::lgammaf;
-using ::llrint;
-using ::llrintf;
-using ::llround;
-using ::llroundf;
-using ::log1p;
-using ::log1pf;
-using ::log2;
-using ::log2f;
-using ::logb;
-using ::logbf;
-using ::lrint;
-using ::lrintf;
-using ::lround;
-using ::lroundf;
-
-using ::nan;
-using ::nanf;
-
-using ::nearbyint;
-using ::nearbyintf;
-using ::nextafter;
-using ::nextafterf;
-using ::nexttoward;
-using ::nexttowardf;
-using ::remainder;
-using ::remainderf;
-using ::remquo;
-using ::remquof;
-using ::rint;
-using ::rintf;
-using ::round;
-using ::roundf;
-using ::scalbln;
-using ::scalblnf;
-using ::scalbn;
-using ::scalbnf;
-using ::tgamma;
-using ::tgammaf;
-using ::trunc;
-using ::truncf;
-
-using ::acosl;
-using ::asinl;
-using ::atanl;
-using ::atan2l;
-using ::ceill;
-using ::cosl;
-using ::coshl;
-using ::expl;
-using ::fabsl;
-using ::floorl;
-using ::fmodl;
-using ::frexpl;
-using ::ldexpl;
-using ::logl;
-using ::log10l;
-using ::modfl;
-using ::powl;
-using ::sinl;
-using ::sinhl;
-using ::sqrtl;
-using ::tanl;
-
-using ::tanhl;
-using ::acoshl;
-using ::asinhl;
-using ::atanhl;
-using ::cbrtl;
-
-using ::copysignl;
-
-using ::erfl;
-using ::erfcl;
-using ::exp2l;
-using ::expm1l;
-using ::fdiml;
-using ::fmal;
-using ::fmaxl;
-using ::fminl;
-using ::hypotl;
-using ::ilogbl;
-using ::lgammal;
-using ::llrintl;
-using ::llroundl;
-using ::log1pl;
-using ::log2l;
-using ::logbl;
-using ::lrintl;
-using ::lroundl;
-using ::nanl;
-using ::nearbyintl;
-using ::nextafterl;
-using ::nexttowardl;
-using ::remainderl;
-using ::remquol;
-using ::rintl;
-using ::roundl;
-using ::scalblnl;
-using ::scalbnl;
-using ::tgammal;
-using ::truncl;
+using ::signbit _LIBCPP_USING_IF_EXISTS;
+using ::fpclassify _LIBCPP_USING_IF_EXISTS;
+using ::isfinite _LIBCPP_USING_IF_EXISTS;
+using ::isinf _LIBCPP_USING_IF_EXISTS;
+using ::isnan _LIBCPP_USING_IF_EXISTS;
+using ::isnormal _LIBCPP_USING_IF_EXISTS;
+using ::isgreater _LIBCPP_USING_IF_EXISTS;
+using ::isgreaterequal _LIBCPP_USING_IF_EXISTS;
+using ::isless _LIBCPP_USING_IF_EXISTS;
+using ::islessequal _LIBCPP_USING_IF_EXISTS;
+using ::islessgreater _LIBCPP_USING_IF_EXISTS;
+using ::isunordered _LIBCPP_USING_IF_EXISTS;
+using ::isunordered _LIBCPP_USING_IF_EXISTS;
+
+using ::float_t _LIBCPP_USING_IF_EXISTS;
+using ::double_t _LIBCPP_USING_IF_EXISTS;
+
+using ::abs _LIBCPP_USING_IF_EXISTS;
+
+using ::acos _LIBCPP_USING_IF_EXISTS;
+using ::acosf _LIBCPP_USING_IF_EXISTS;
+using ::asin _LIBCPP_USING_IF_EXISTS;
+using ::asinf _LIBCPP_USING_IF_EXISTS;
+using ::atan _LIBCPP_USING_IF_EXISTS;
+using ::atanf _LIBCPP_USING_IF_EXISTS;
+using ::atan2 _LIBCPP_USING_IF_EXISTS;
+using ::atan2f _LIBCPP_USING_IF_EXISTS;
+using ::ceil _LIBCPP_USING_IF_EXISTS;
+using ::ceilf _LIBCPP_USING_IF_EXISTS;
+using ::cos _LIBCPP_USING_IF_EXISTS;
+using ::cosf _LIBCPP_USING_IF_EXISTS;
+using ::cosh _LIBCPP_USING_IF_EXISTS;
+using ::coshf _LIBCPP_USING_IF_EXISTS;
+
+using ::exp _LIBCPP_USING_IF_EXISTS;
+using ::expf _LIBCPP_USING_IF_EXISTS;
+
+using ::fabs _LIBCPP_USING_IF_EXISTS;
+using ::fabsf _LIBCPP_USING_IF_EXISTS;
+using ::floor _LIBCPP_USING_IF_EXISTS;
+using ::floorf _LIBCPP_USING_IF_EXISTS;
+
+using ::fmod _LIBCPP_USING_IF_EXISTS;
+using ::fmodf _LIBCPP_USING_IF_EXISTS;
+
+using ::frexp _LIBCPP_USING_IF_EXISTS;
+using ::frexpf _LIBCPP_USING_IF_EXISTS;
+using ::ldexp _LIBCPP_USING_IF_EXISTS;
+using ::ldexpf _LIBCPP_USING_IF_EXISTS;
+
+using ::log _LIBCPP_USING_IF_EXISTS;
+using ::logf _LIBCPP_USING_IF_EXISTS;
+
+using ::log10 _LIBCPP_USING_IF_EXISTS;
+using ::log10f _LIBCPP_USING_IF_EXISTS;
+using ::modf _LIBCPP_USING_IF_EXISTS;
+using ::modff _LIBCPP_USING_IF_EXISTS;
+
+using ::pow _LIBCPP_USING_IF_EXISTS;
+using ::powf _LIBCPP_USING_IF_EXISTS;
+
+using ::sin _LIBCPP_USING_IF_EXISTS;
+using ::sinf _LIBCPP_USING_IF_EXISTS;
+using ::sinh _LIBCPP_USING_IF_EXISTS;
+using ::sinhf _LIBCPP_USING_IF_EXISTS;
+
+using ::sqrt _LIBCPP_USING_IF_EXISTS;
+using ::sqrtf _LIBCPP_USING_IF_EXISTS;
+using ::tan _LIBCPP_USING_IF_EXISTS;
+using ::tanf _LIBCPP_USING_IF_EXISTS;
+
+using ::tanh _LIBCPP_USING_IF_EXISTS;
+using ::tanhf _LIBCPP_USING_IF_EXISTS;
+
+using ::acosh _LIBCPP_USING_IF_EXISTS;
+using ::acoshf _LIBCPP_USING_IF_EXISTS;
+using ::asinh _LIBCPP_USING_IF_EXISTS;
+using ::asinhf _LIBCPP_USING_IF_EXISTS;
+using ::atanh _LIBCPP_USING_IF_EXISTS;
+using ::atanhf _LIBCPP_USING_IF_EXISTS;
+using ::cbrt _LIBCPP_USING_IF_EXISTS;
+using ::cbrtf _LIBCPP_USING_IF_EXISTS;
+
+using ::copysign _LIBCPP_USING_IF_EXISTS;
+using ::copysignf _LIBCPP_USING_IF_EXISTS;
+
+using ::erf _LIBCPP_USING_IF_EXISTS;
+using ::erff _LIBCPP_USING_IF_EXISTS;
+using ::erfc _LIBCPP_USING_IF_EXISTS;
+using ::erfcf _LIBCPP_USING_IF_EXISTS;
+using ::exp2 _LIBCPP_USING_IF_EXISTS;
+using ::exp2f _LIBCPP_USING_IF_EXISTS;
+using ::expm1 _LIBCPP_USING_IF_EXISTS;
+using ::expm1f _LIBCPP_USING_IF_EXISTS;
+using ::fdim _LIBCPP_USING_IF_EXISTS;
+using ::fdimf _LIBCPP_USING_IF_EXISTS;
+using ::fmaf _LIBCPP_USING_IF_EXISTS;
+using ::fma _LIBCPP_USING_IF_EXISTS;
+using ::fmax _LIBCPP_USING_IF_EXISTS;
+using ::fmaxf _LIBCPP_USING_IF_EXISTS;
+using ::fmin _LIBCPP_USING_IF_EXISTS;
+using ::fminf _LIBCPP_USING_IF_EXISTS;
+using ::hypot _LIBCPP_USING_IF_EXISTS;
+using ::hypotf _LIBCPP_USING_IF_EXISTS;
+using ::ilogb _LIBCPP_USING_IF_EXISTS;
+using ::ilogbf _LIBCPP_USING_IF_EXISTS;
+using ::lgamma _LIBCPP_USING_IF_EXISTS;
+using ::lgammaf _LIBCPP_USING_IF_EXISTS;
+using ::llrint _LIBCPP_USING_IF_EXISTS;
+using ::llrintf _LIBCPP_USING_IF_EXISTS;
+using ::llround _LIBCPP_USING_IF_EXISTS;
+using ::llroundf _LIBCPP_USING_IF_EXISTS;
+using ::log1p _LIBCPP_USING_IF_EXISTS;
+using ::log1pf _LIBCPP_USING_IF_EXISTS;
+using ::log2 _LIBCPP_USING_IF_EXISTS;
+using ::log2f _LIBCPP_USING_IF_EXISTS;
+using ::logb _LIBCPP_USING_IF_EXISTS;
+using ::logbf _LIBCPP_USING_IF_EXISTS;
+using ::lrint _LIBCPP_USING_IF_EXISTS;
+using ::lrintf _LIBCPP_USING_IF_EXISTS;
+using ::lround _LIBCPP_USING_IF_EXISTS;
+using ::lroundf _LIBCPP_USING_IF_EXISTS;
+
+using ::nan _LIBCPP_USING_IF_EXISTS;
+using ::nanf _LIBCPP_USING_IF_EXISTS;
+
+using ::nearbyint _LIBCPP_USING_IF_EXISTS;
+using ::nearbyintf _LIBCPP_USING_IF_EXISTS;
+using ::nextafter _LIBCPP_USING_IF_EXISTS;
+using ::nextafterf _LIBCPP_USING_IF_EXISTS;
+using ::nexttoward _LIBCPP_USING_IF_EXISTS;
+using ::nexttowardf _LIBCPP_USING_IF_EXISTS;
+using ::remainder _LIBCPP_USING_IF_EXISTS;
+using ::remainderf _LIBCPP_USING_IF_EXISTS;
+using ::remquo _LIBCPP_USING_IF_EXISTS;
+using ::remquof _LIBCPP_USING_IF_EXISTS;
+using ::rint _LIBCPP_USING_IF_EXISTS;
+using ::rintf _LIBCPP_USING_IF_EXISTS;
+using ::round _LIBCPP_USING_IF_EXISTS;
+using ::roundf _LIBCPP_USING_IF_EXISTS;
+using ::scalbln _LIBCPP_USING_IF_EXISTS;
+using ::scalblnf _LIBCPP_USING_IF_EXISTS;
+using ::scalbn _LIBCPP_USING_IF_EXISTS;
+using ::scalbnf _LIBCPP_USING_IF_EXISTS;
+using ::tgamma _LIBCPP_USING_IF_EXISTS;
+using ::tgammaf _LIBCPP_USING_IF_EXISTS;
+using ::trunc _LIBCPP_USING_IF_EXISTS;
+using ::truncf _LIBCPP_USING_IF_EXISTS;
+
+using ::acosl _LIBCPP_USING_IF_EXISTS;
+using ::asinl _LIBCPP_USING_IF_EXISTS;
+using ::atanl _LIBCPP_USING_IF_EXISTS;
+using ::atan2l _LIBCPP_USING_IF_EXISTS;
+using ::ceill _LIBCPP_USING_IF_EXISTS;
+using ::cosl _LIBCPP_USING_IF_EXISTS;
+using ::coshl _LIBCPP_USING_IF_EXISTS;
+using ::expl _LIBCPP_USING_IF_EXISTS;
+using ::fabsl _LIBCPP_USING_IF_EXISTS;
+using ::floorl _LIBCPP_USING_IF_EXISTS;
+using ::fmodl _LIBCPP_USING_IF_EXISTS;
+using ::frexpl _LIBCPP_USING_IF_EXISTS;
+using ::ldexpl _LIBCPP_USING_IF_EXISTS;
+using ::logl _LIBCPP_USING_IF_EXISTS;
+using ::log10l _LIBCPP_USING_IF_EXISTS;
+using ::modfl _LIBCPP_USING_IF_EXISTS;
+using ::powl _LIBCPP_USING_IF_EXISTS;
+using ::sinl _LIBCPP_USING_IF_EXISTS;
+using ::sinhl _LIBCPP_USING_IF_EXISTS;
+using ::sqrtl _LIBCPP_USING_IF_EXISTS;
+using ::tanl _LIBCPP_USING_IF_EXISTS;
+
+using ::tanhl _LIBCPP_USING_IF_EXISTS;
+using ::acoshl _LIBCPP_USING_IF_EXISTS;
+using ::asinhl _LIBCPP_USING_IF_EXISTS;
+using ::atanhl _LIBCPP_USING_IF_EXISTS;
+using ::cbrtl _LIBCPP_USING_IF_EXISTS;
+
+using ::copysignl _LIBCPP_USING_IF_EXISTS;
+
+using ::erfl _LIBCPP_USING_IF_EXISTS;
+using ::erfcl _LIBCPP_USING_IF_EXISTS;
+using ::exp2l _LIBCPP_USING_IF_EXISTS;
+using ::expm1l _LIBCPP_USING_IF_EXISTS;
+using ::fdiml _LIBCPP_USING_IF_EXISTS;
+using ::fmal _LIBCPP_USING_IF_EXISTS;
+using ::fmaxl _LIBCPP_USING_IF_EXISTS;
+using ::fminl _LIBCPP_USING_IF_EXISTS;
+using ::hypotl _LIBCPP_USING_IF_EXISTS;
+using ::ilogbl _LIBCPP_USING_IF_EXISTS;
+using ::lgammal _LIBCPP_USING_IF_EXISTS;
+using ::llrintl _LIBCPP_USING_IF_EXISTS;
+using ::llroundl _LIBCPP_USING_IF_EXISTS;
+using ::log1pl _LIBCPP_USING_IF_EXISTS;
+using ::log2l _LIBCPP_USING_IF_EXISTS;
+using ::logbl _LIBCPP_USING_IF_EXISTS;
+using ::lrintl _LIBCPP_USING_IF_EXISTS;
+using ::lroundl _LIBCPP_USING_IF_EXISTS;
+using ::nanl _LIBCPP_USING_IF_EXISTS;
+using ::nearbyintl _LIBCPP_USING_IF_EXISTS;
+using ::nextafterl _LIBCPP_USING_IF_EXISTS;
+using ::nexttowardl _LIBCPP_USING_IF_EXISTS;
+using ::remainderl _LIBCPP_USING_IF_EXISTS;
+using ::remquol _LIBCPP_USING_IF_EXISTS;
+using ::rintl _LIBCPP_USING_IF_EXISTS;
+using ::roundl _LIBCPP_USING_IF_EXISTS;
+using ::scalblnl _LIBCPP_USING_IF_EXISTS;
+using ::scalbnl _LIBCPP_USING_IF_EXISTS;
+using ::tgammal _LIBCPP_USING_IF_EXISTS;
+using ::truncl _LIBCPP_USING_IF_EXISTS;
 
 #if _LIBCPP_STD_VER > 14
 inline _LIBCPP_INLINE_VISIBILITY float       hypot(       float x,       float y,       float z ) { return sqrt(x*x + y*y + z*z); }
@@ -623,10 +621,10 @@ _Fp __lerp(_Fp __a, _Fp __b, _Fp __t) noexcept {
 
     if (__t == 1) return __b;
     const _Fp __x = __a + __t * (__b - __a);
-    if (__t > 1 == __b > __a)
-    	return __b < __x ? __x : __b;
+    if ((__t > 1) == (__b > __a))
+        return __b < __x ? __x : __b;
     else
-    	return __x < __b ? __x : __b;
+        return __x < __b ? __x : __b;
 }
 
 constexpr float
@@ -674,4 +672,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_CMATH
+#endif // _LIBCPP_CMATH
lib/libcxx/include/codecvt
@@ -570,4 +570,4 @@ public:
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CODECVT
+#endif // _LIBCPP_CODECVT
lib/libcxx/include/compare
@@ -15,15 +15,13 @@
 
 namespace std {
   // [cmp.categories], comparison category types
-  class weak_equality;
-  class strong_equality;
   class partial_ordering;
   class weak_ordering;
   class strong_ordering;
 
   // named comparison functions
-  constexpr bool is_eq  (weak_equality cmp) noexcept    { return cmp == 0; }
-  constexpr bool is_neq (weak_equality cmp) noexcept    { return cmp != 0; }
+  constexpr bool is_eq  (partial_ordering cmp) noexcept    { return cmp == 0; }
+  constexpr bool is_neq (partial_ordering cmp) noexcept    { return cmp != 0; }
   constexpr bool is_lt  (partial_ordering cmp) noexcept { return cmp < 0; }
   constexpr bool is_lteq(partial_ordering cmp) noexcept { return cmp <= 0; }
   constexpr bool is_gt  (partial_ordering cmp) noexcept { return cmp > 0; }
@@ -41,8 +39,6 @@ namespace std {
   template<class T> constexpr strong_ordering strong_order(const T& a, const T& b);
   template<class T> constexpr weak_ordering weak_order(const T& a, const T& b);
   template<class T> constexpr partial_ordering partial_order(const T& a, const T& b);
-  template<class T> constexpr strong_equality strong_equal(const T& a, const T& b);
-  template<class T> constexpr weak_equality weak_equal(const T& a, const T& b);
 
   // [cmp.partialord], Class partial_ordering
   class partial_ordering {
@@ -126,7 +122,6 @@ namespace std {
 
 #include <__config>
 #include <type_traits>
-#include <array>
 
 #ifndef _LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER
 #pragma GCC system_header
@@ -134,8 +129,7 @@ namespace std {
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-#if _LIBCPP_STD_VER > 17
-
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_SPACESHIP_OPERATOR)
 // exposition only
 enum class _LIBCPP_ENUM_VIS _EqResult : unsigned char {
   __zero = 0,
@@ -154,138 +148,21 @@ enum class _LIBCPP_ENUM_VIS _NCmpResult : signed char {
   __unordered = -127
 };
 
+class partial_ordering;
+class weak_ordering;
+class strong_ordering;
+
+template<class _Tp, class... _Args>
+inline constexpr bool __one_of_v = (is_same_v<_Tp, _Args> || ...);
+
 struct _CmpUnspecifiedParam {
   _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEVAL
   _CmpUnspecifiedParam(int _CmpUnspecifiedParam::*) noexcept {}
 
-  template<typename _Tp, typename = _VSTD::enable_if_t<!_VSTD::is_same_v<_Tp, int>>>
+  template<class _Tp, class = enable_if_t<!__one_of_v<_Tp, int, partial_ordering, weak_ordering, strong_ordering>>>
   _CmpUnspecifiedParam(_Tp) = delete;
 };
 
-class  weak_equality {
-  _LIBCPP_INLINE_VISIBILITY
-  constexpr explicit weak_equality(_EqResult __val) noexcept : __value_(__val) {}
-
-public:
-  static const weak_equality equivalent;
-  static const weak_equality nonequivalent;
-
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(weak_equality __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, weak_equality __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(weak_equality __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, weak_equality __v) noexcept;
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-  _LIBCPP_INLINE_VISIBILITY friend constexpr weak_equality operator<=>(weak_equality __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr weak_equality operator<=>(_CmpUnspecifiedParam, weak_equality __v) noexcept;
-#endif
-
-private:
-  _EqResult __value_;
-};
-
-_LIBCPP_INLINE_VAR constexpr weak_equality weak_equality::equivalent(_EqResult::__equiv);
-_LIBCPP_INLINE_VAR constexpr weak_equality weak_equality::nonequivalent(_EqResult::__nonequiv);
-
-_LIBCPP_INLINE_VISIBILITY
-inline constexpr bool operator==(weak_equality __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ == _EqResult::__zero;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-inline constexpr bool operator==(_CmpUnspecifiedParam, weak_equality __v) noexcept {
-  return __v.__value_ == _EqResult::__zero;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-inline constexpr bool operator!=(weak_equality __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ != _EqResult::__zero;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-inline constexpr bool operator!=(_CmpUnspecifiedParam, weak_equality __v) noexcept {
-  return __v.__value_ != _EqResult::__zero;
-}
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-_LIBCPP_INLINE_VISIBILITY
-inline constexpr weak_equality operator<=>(weak_equality __v, _CmpUnspecifiedParam) noexcept {
-  return __v;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-inline constexpr weak_equality operator<=>(_CmpUnspecifiedParam, weak_equality __v) noexcept {
-  return __v;
-}
-#endif
-
-class strong_equality {
-  _LIBCPP_INLINE_VISIBILITY
-  explicit constexpr strong_equality(_EqResult __val) noexcept : __value_(__val) {}
-
-public:
-  static const strong_equality equal;
-  static const strong_equality nonequal;
-  static const strong_equality equivalent;
-  static const strong_equality nonequivalent;
-
-  // conversion
-  _LIBCPP_INLINE_VISIBILITY constexpr operator weak_equality() const noexcept {
-    return __value_ == _EqResult::__zero ? weak_equality::equivalent
-          : weak_equality::nonequivalent;
-  }
-
-  // comparisons
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(strong_equality __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(strong_equality __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, strong_equality __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, strong_equality __v) noexcept;
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-  _LIBCPP_INLINE_VISIBILITY friend constexpr strong_equality operator<=>(strong_equality __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr strong_equality operator<=>(_CmpUnspecifiedParam, strong_equality __v) noexcept;
-#endif
-private:
-  _EqResult __value_;
-};
-
-_LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::equal(_EqResult::__equal);
-_LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::nonequal(_EqResult::__nonequal);
-_LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::equivalent(_EqResult::__equiv);
-_LIBCPP_INLINE_VAR constexpr strong_equality strong_equality::nonequivalent(_EqResult::__nonequiv);
-
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator==(strong_equality __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ == _EqResult::__zero;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator==(_CmpUnspecifiedParam, strong_equality __v) noexcept {
-  return __v.__value_ == _EqResult::__zero;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator!=(strong_equality __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ != _EqResult::__zero;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator!=(_CmpUnspecifiedParam, strong_equality __v) noexcept {
-  return __v.__value_ != _EqResult::__zero;
-}
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-_LIBCPP_INLINE_VISIBILITY
-constexpr strong_equality operator<=>(strong_equality __v, _CmpUnspecifiedParam) noexcept {
-  return __v;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-constexpr strong_equality operator<=>(_CmpUnspecifiedParam, strong_equality __v) noexcept {
-  return __v;
-}
-#endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-
 class partial_ordering {
   using _ValueT = signed char;
 
@@ -311,32 +188,52 @@ public:
   static const partial_ordering greater;
   static const partial_ordering unordered;
 
-  // conversion
-  constexpr operator weak_equality() const noexcept {
-    return __value_ == 0 ? weak_equality::equivalent : weak_equality::nonequivalent;
-  }
-
   // comparisons
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(partial_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(partial_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (partial_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(partial_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (partial_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(partial_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, partial_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, partial_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, partial_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, partial_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, partial_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, partial_ordering __v) noexcept;
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
   _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(partial_ordering, partial_ordering) noexcept = default;
 
-  _LIBCPP_INLINE_VISIBILITY friend constexpr partial_ordering operator<=>(partial_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr partial_ordering operator<=>(_CmpUnspecifiedParam, partial_ordering __v) noexcept;
-#endif
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(partial_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__is_ordered() && __v.__value_ == 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (partial_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__is_ordered() && __v.__value_ < 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(partial_ordering __v, _CmpUnspecifiedParam) noexcept  {
+    return __v.__is_ordered() && __v.__value_ <= 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (partial_ordering __v, _CmpUnspecifiedParam) noexcept  {
+    return __v.__is_ordered() && __v.__value_ > 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(partial_ordering __v, _CmpUnspecifiedParam) noexcept  {
+    return __v.__is_ordered() && __v.__value_ >= 0;
+  }
 
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, partial_ordering __v) noexcept  {
+    return __v.__is_ordered() && 0 < __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, partial_ordering __v) noexcept  {
+    return __v.__is_ordered() && 0 <= __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, partial_ordering __v) noexcept  {
+    return __v.__is_ordered() && 0 > __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, partial_ordering __v) noexcept  {
+    return __v.__is_ordered() && 0 >= __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr partial_ordering operator<=>(partial_ordering __v, _CmpUnspecifiedParam) noexcept  {
+    return __v;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr partial_ordering operator<=>(_CmpUnspecifiedParam, partial_ordering __v) noexcept  {
+    return __v < 0 ? partial_ordering::greater : (__v > 0 ? partial_ordering::less : __v);
+  }
 private:
   _ValueT __value_;
 };
@@ -346,68 +243,6 @@ _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::equivalent(_EqRe
 _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::greater(_OrdResult::__greater);
 _LIBCPP_INLINE_VAR constexpr partial_ordering partial_ordering::unordered(_NCmpResult ::__unordered);
 
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator==(partial_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__is_ordered() && __v.__value_ == 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator< (partial_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__is_ordered() && __v.__value_ < 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator<=(partial_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__is_ordered() && __v.__value_ <= 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator> (partial_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__is_ordered() && __v.__value_ > 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator>=(partial_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__is_ordered() && __v.__value_ >= 0;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator==(_CmpUnspecifiedParam, partial_ordering __v) noexcept {
-  return __v.__is_ordered() && 0 == __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator< (_CmpUnspecifiedParam, partial_ordering __v) noexcept {
-  return __v.__is_ordered() && 0 < __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator<=(_CmpUnspecifiedParam, partial_ordering __v) noexcept {
-  return __v.__is_ordered() && 0 <= __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator> (_CmpUnspecifiedParam, partial_ordering __v) noexcept {
-  return __v.__is_ordered() && 0 > __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator>=(_CmpUnspecifiedParam, partial_ordering __v) noexcept {
-  return __v.__is_ordered() && 0 >= __v.__value_;
-}
-
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator!=(partial_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return !__v.__is_ordered() || __v.__value_ != 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator!=(_CmpUnspecifiedParam, partial_ordering __v) noexcept {
-  return !__v.__is_ordered() || __v.__value_ != 0;
-}
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-_LIBCPP_INLINE_VISIBILITY
-constexpr partial_ordering operator<=>(partial_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr partial_ordering operator<=>(_CmpUnspecifiedParam, partial_ordering __v) noexcept {
-  return __v < 0 ? partial_ordering::greater : (__v > 0 ? partial_ordering::less : __v);
-}
-#endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-
 class weak_ordering {
   using _ValueT = signed char;
 
@@ -421,13 +256,6 @@ public:
   static const weak_ordering equivalent;
   static const weak_ordering greater;
 
-  // conversions
-  _LIBCPP_INLINE_VISIBILITY
-  constexpr operator weak_equality() const noexcept {
-    return __value_ == 0 ? weak_equality::equivalent
-                         : weak_equality::nonequivalent;
-  }
-
   _LIBCPP_INLINE_VISIBILITY
   constexpr operator partial_ordering() const noexcept {
     return __value_ == 0 ? partial_ordering::equivalent
@@ -435,25 +263,51 @@ public:
   }
 
   // comparisons
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(weak_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(weak_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (weak_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(weak_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (weak_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(weak_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, weak_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, weak_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, weak_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, weak_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, weak_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, weak_ordering __v) noexcept;
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
   _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(weak_ordering, weak_ordering) noexcept = default;
 
-  _LIBCPP_INLINE_VISIBILITY friend constexpr weak_ordering operator<=>(weak_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr weak_ordering operator<=>(_CmpUnspecifiedParam, weak_ordering __v) noexcept;
-#endif
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(weak_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ == 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (weak_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ < 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(weak_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ <= 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (weak_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ > 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(weak_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ >= 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, weak_ordering __v) noexcept {
+    return 0 < __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, weak_ordering __v) noexcept {
+    return 0 <= __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, weak_ordering __v) noexcept {
+    return 0 > __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, weak_ordering __v) noexcept {
+    return 0 >= __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr weak_ordering operator<=>(weak_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr weak_ordering operator<=>(_CmpUnspecifiedParam, weak_ordering __v) noexcept {
+    return __v < 0 ? weak_ordering::greater : (__v > 0 ? weak_ordering::less : __v);
+  }
 
 private:
   _ValueT __value_;
@@ -462,67 +316,6 @@ private:
 _LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::less(_OrdResult::__less);
 _LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::equivalent(_EqResult::__equiv);
 _LIBCPP_INLINE_VAR constexpr weak_ordering weak_ordering::greater(_OrdResult::__greater);
-
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator==(weak_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ == 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator!=(weak_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ != 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator< (weak_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ < 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator<=(weak_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ <= 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator> (weak_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ > 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator>=(weak_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ >= 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator==(_CmpUnspecifiedParam, weak_ordering __v) noexcept {
-  return 0 == __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator!=(_CmpUnspecifiedParam, weak_ordering __v) noexcept {
-  return 0 != __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator< (_CmpUnspecifiedParam, weak_ordering __v) noexcept {
-  return 0 < __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator<=(_CmpUnspecifiedParam, weak_ordering __v) noexcept {
-  return 0 <= __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator> (_CmpUnspecifiedParam, weak_ordering __v) noexcept {
-  return 0 > __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator>=(_CmpUnspecifiedParam, weak_ordering __v) noexcept {
-  return 0 >= __v.__value_;
-}
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-_LIBCPP_INLINE_VISIBILITY
-constexpr weak_ordering operator<=>(weak_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr weak_ordering operator<=>(_CmpUnspecifiedParam, weak_ordering __v) noexcept {
-  return __v < 0 ? weak_ordering::greater : (__v > 0 ? weak_ordering::less : __v);
-}
-#endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-
 class strong_ordering {
   using _ValueT = signed char;
 
@@ -538,18 +331,6 @@ public:
   static const strong_ordering greater;
 
   // conversions
-  _LIBCPP_INLINE_VISIBILITY
-  constexpr operator weak_equality() const noexcept {
-    return __value_ == 0 ? weak_equality::equivalent
-                         : weak_equality::nonequivalent;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  constexpr operator strong_equality() const noexcept {
-    return __value_ == 0 ? strong_equality::equal
-                         : strong_equality::nonequal;
-  }
-
   _LIBCPP_INLINE_VISIBILITY
   constexpr operator partial_ordering() const noexcept {
     return __value_ == 0 ? partial_ordering::equivalent
@@ -563,25 +344,51 @@ public:
   }
 
   // comparisons
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(strong_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(strong_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (strong_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(strong_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (strong_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(strong_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(_CmpUnspecifiedParam, strong_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator!=(_CmpUnspecifiedParam, strong_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, strong_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, strong_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, strong_ordering __v) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, strong_ordering __v) noexcept;
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
   _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(strong_ordering, strong_ordering) noexcept = default;
 
-  _LIBCPP_INLINE_VISIBILITY friend constexpr strong_ordering operator<=>(strong_ordering __v, _CmpUnspecifiedParam) noexcept;
-  _LIBCPP_INLINE_VISIBILITY friend constexpr strong_ordering operator<=>(_CmpUnspecifiedParam, strong_ordering __v) noexcept;
-#endif
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator==(strong_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ == 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (strong_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ < 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(strong_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ <= 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (strong_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ > 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(strong_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v.__value_ >= 0;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator< (_CmpUnspecifiedParam, strong_ordering __v) noexcept {
+    return 0 < __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator<=(_CmpUnspecifiedParam, strong_ordering __v) noexcept {
+    return 0 <= __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator> (_CmpUnspecifiedParam, strong_ordering __v) noexcept {
+    return 0 > __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr bool operator>=(_CmpUnspecifiedParam, strong_ordering __v) noexcept {
+    return 0 >= __v.__value_;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr strong_ordering operator<=>(strong_ordering __v, _CmpUnspecifiedParam) noexcept {
+    return __v;
+  }
+
+  _LIBCPP_INLINE_VISIBILITY friend constexpr strong_ordering operator<=>(_CmpUnspecifiedParam, strong_ordering __v) noexcept {
+    return __v < 0 ? strong_ordering::greater : (__v > 0 ? strong_ordering::less : __v);
+  }
 
 private:
   _ValueT __value_;
@@ -592,73 +399,7 @@ _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::equal(_EqResult::_
 _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::equivalent(_EqResult::__equiv);
 _LIBCPP_INLINE_VAR constexpr strong_ordering strong_ordering::greater(_OrdResult::__greater);
 
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator==(strong_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ == 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator!=(strong_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ != 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator< (strong_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ < 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator<=(strong_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ <= 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator> (strong_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ > 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator>=(strong_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v.__value_ >= 0;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator==(_CmpUnspecifiedParam, strong_ordering __v) noexcept {
-  return 0 == __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator!=(_CmpUnspecifiedParam, strong_ordering __v) noexcept {
-  return 0 != __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator< (_CmpUnspecifiedParam, strong_ordering __v) noexcept {
-  return 0 < __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator<=(_CmpUnspecifiedParam, strong_ordering __v) noexcept {
-  return 0 <= __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator> (_CmpUnspecifiedParam, strong_ordering __v) noexcept {
-  return 0 > __v.__value_;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool operator>=(_CmpUnspecifiedParam, strong_ordering __v) noexcept {
-  return 0 >= __v.__value_;
-}
-
-#ifndef _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-_LIBCPP_INLINE_VISIBILITY
-constexpr strong_ordering operator<=>(strong_ordering __v, _CmpUnspecifiedParam) noexcept {
-  return __v;
-}
-_LIBCPP_INLINE_VISIBILITY
-constexpr strong_ordering operator<=>(_CmpUnspecifiedParam, strong_ordering __v) noexcept {
-  return __v < 0 ? strong_ordering::greater : (__v > 0 ? strong_ordering::less : __v);
-}
-#endif // _LIBCPP_HAS_NO_SPACESHIP_OPERATOR
-
 // named comparison functions
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool is_eq(weak_equality __cmp) noexcept    { return __cmp == 0; }
-
-_LIBCPP_INLINE_VISIBILITY
-constexpr bool is_neq(weak_equality __cmp) noexcept    { return __cmp != 0; }
-
 _LIBCPP_INLINE_VISIBILITY
 constexpr bool is_lt(partial_ordering __cmp) noexcept { return __cmp < 0; }
 
@@ -675,8 +416,6 @@ namespace __comp_detail {
 
 enum _ClassifyCompCategory : unsigned{
   _None,
-  _WeakEq,
-  _StrongEq,
   _PartialOrd,
   _WeakOrd,
   _StrongOrd,
@@ -686,10 +425,6 @@ enum _ClassifyCompCategory : unsigned{
 template <class _Tp>
 _LIBCPP_INLINE_VISIBILITY
 constexpr _ClassifyCompCategory __type_to_enum() noexcept {
-  if (is_same_v<_Tp, weak_equality>)
-    return _WeakEq;
-  if (is_same_v<_Tp, strong_equality>)
-    return _StrongEq;
   if (is_same_v<_Tp, partial_ordering>)
     return _PartialOrd;
   if (is_same_v<_Tp, weak_ordering>)
@@ -701,18 +436,12 @@ constexpr _ClassifyCompCategory __type_to_enum() noexcept {
 
 template <size_t _Size>
 constexpr _ClassifyCompCategory
-__compute_comp_type(array<_ClassifyCompCategory, _Size> __types) {
-  array<int, _CCC_Size> __seen = {};
+__compute_comp_type(const _ClassifyCompCategory (&__types)[_Size]) {
+  int __seen[_CCC_Size] = {};
   for (auto __type : __types)
     ++__seen[__type];
   if (__seen[_None])
     return _None;
-  if (__seen[_WeakEq])
-    return _WeakEq;
-  if (__seen[_StrongEq] && (__seen[_PartialOrd] || __seen[_WeakOrd]))
-    return _WeakEq;
-  if (__seen[_StrongEq])
-    return _StrongEq;
   if (__seen[_PartialOrd])
     return _PartialOrd;
   if (__seen[_WeakOrd])
@@ -720,18 +449,13 @@ __compute_comp_type(array<_ClassifyCompCategory, _Size> __types) {
   return _StrongOrd;
 }
 
-template <class ..._Ts>
+template <class ..._Ts, bool _False = false>
 constexpr auto __get_comp_type() {
   using _CCC = _ClassifyCompCategory;
-  constexpr array<_CCC, sizeof...(_Ts)> __type_kinds{{__comp_detail::__type_to_enum<_Ts>()...}};
-  constexpr _CCC _Cat = sizeof...(_Ts) == 0 ? _StrongOrd
-      : __compute_comp_type(__type_kinds);
+  constexpr _CCC __type_kinds[] = {_StrongOrd, __type_to_enum<_Ts>()...};
+  constexpr _CCC _Cat = __compute_comp_type(__type_kinds);
   if constexpr (_Cat == _None)
     return void();
-  else if constexpr (_Cat == _WeakEq)
-    return weak_equality::equivalent;
-  else if constexpr (_Cat == _StrongEq)
-    return strong_equality::equivalent;
   else if constexpr (_Cat == _PartialOrd)
     return partial_ordering::equivalent;
   else if constexpr (_Cat == _WeakOrd)
@@ -739,7 +463,7 @@ constexpr auto __get_comp_type() {
   else if constexpr (_Cat == _StrongOrd)
     return strong_ordering::equivalent;
   else
-    static_assert(_Cat != _Cat, "unhandled case");
+    static_assert(_False, "unhandled case");
 }
 } // namespace __comp_detail
 
@@ -757,10 +481,8 @@ using common_comparison_category_t = typename common_comparison_category<_Ts...>
 template<class _Tp> constexpr strong_ordering strong_order(const _Tp& __lhs, const _Tp& __rhs);
 template<class _Tp> constexpr weak_ordering weak_order(const _Tp& __lhs, const _Tp& __rhs);
 template<class _Tp> constexpr partial_ordering partial_order(const _Tp& __lhs, const _Tp& __rhs);
-template<class _Tp> constexpr strong_equality strong_equal(const _Tp& __lhs, const _Tp& __rhs);
-template<class _Tp> constexpr weak_equality weak_equal(const _Tp& __lhs, const _Tp& __rhs);
 
-#endif // _LIBCPP_STD_VER > 17
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_SPACESHIP_OPERATOR)
 
 _LIBCPP_END_NAMESPACE_STD
 
lib/libcxx/include/complex
@@ -232,10 +232,10 @@ template<class T> complex<T> tanh (const complex<T>&);
 */
 
 #include <__config>
-#include <type_traits>
-#include <stdexcept>
 #include <cmath>
 #include <iosfwd>
+#include <stdexcept>
+#include <type_traits>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_LOCALIZATION)
@@ -1490,4 +1490,4 @@ inline namespace literals
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_COMPLEX
+#endif // _LIBCPP_COMPLEX
lib/libcxx/include/complex.h
@@ -31,6 +31,6 @@
 
 #include_next <complex.h>
 
-#endif  // __cplusplus
+#endif // __cplusplus
 
-#endif  // _LIBCPP_COMPLEX_H
+#endif // _LIBCPP_COMPLEX_H
lib/libcxx/include/concepts
@@ -67,9 +67,9 @@ namespace std {
   template<class T, class... Args>
     concept constructible_from = see below;
 
-  // [concept.defaultconstructible], concept default_constructible
+  // [concept.default.init], concept default_initializable
   template<class T>
-    concept default_constructible = see below;
+    concept default_initializable = see below;
 
   // [concept.moveconstructible], concept move_constructible
   template<class T>
@@ -79,11 +79,6 @@ namespace std {
   template<class T>
     concept copy_constructible = see below;
 
-  // [concepts.compare], comparison concepts
-  // [concept.boolean], concept boolean
-  template<class B>
-    concept boolean = see below;
-
   // [concept.equalitycomparable], concept equality_comparable
   template<class T>
     concept equality_comparable = see below;
@@ -135,7 +130,10 @@ namespace std {
 */
 
 #include <__config>
+#include <__functional/invoke.h>
+#include <__functional_base>
 #include <type_traits>
+#include <utility>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -147,7 +145,7 @@ _LIBCPP_PUSH_MACROS
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-#if _LIBCPP_STD_VER > 17 && defined(__cpp_concepts) && __cpp_concepts >= 201811L
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CONCEPTS)
 
 // [concept.same]
 
@@ -157,12 +155,298 @@ concept __same_as_impl = _VSTD::_IsSame<_Tp, _Up>::value;
 template<class _Tp, class _Up>
 concept same_as = __same_as_impl<_Tp, _Up> && __same_as_impl<_Up, _Tp>;
 
+// [concept.derived]
+template<class _Dp, class _Bp>
+concept derived_from =
+  is_base_of_v<_Bp, _Dp> &&
+  is_convertible_v<const volatile _Dp*, const volatile _Bp*>;
+
+// [concept.convertible]
+template<class _From, class _To>
+concept convertible_to =
+  is_convertible_v<_From, _To> &&
+  requires(add_rvalue_reference_t<_From> (&__f)()) {
+    static_cast<_To>(__f());
+  };
+
+// [concept.commonref]
+template<class _Tp, class _Up>
+concept common_reference_with =
+  same_as<common_reference_t<_Tp, _Up>, common_reference_t<_Up, _Tp>> &&
+  convertible_to<_Tp, common_reference_t<_Tp, _Up>> &&
+  convertible_to<_Up, common_reference_t<_Tp, _Up>>;
+
+// [concept.common]
+template<class _Tp, class _Up>
+concept common_with =
+  same_as<common_type_t<_Tp, _Up>, common_type_t<_Up, _Tp>> &&
+  requires {
+    static_cast<common_type_t<_Tp, _Up>>(declval<_Tp>());
+    static_cast<common_type_t<_Tp, _Up>>(declval<_Up>());
+  } &&
+  common_reference_with<
+    add_lvalue_reference_t<const _Tp>,
+    add_lvalue_reference_t<const _Up>> &&
+  common_reference_with<
+    add_lvalue_reference_t<common_type_t<_Tp, _Up>>,
+    common_reference_t<
+      add_lvalue_reference_t<const _Tp>,
+      add_lvalue_reference_t<const _Up>>>;
+
+// [concepts.arithmetic], arithmetic concepts
+template<class _Tp>
+concept integral = is_integral_v<_Tp>;
+
+template<class _Tp>
+concept signed_integral = integral<_Tp> && is_signed_v<_Tp>;
+
+template<class _Tp>
+concept unsigned_integral = integral<_Tp> && !signed_integral<_Tp>;
+
+template<class _Tp>
+concept floating_point = is_floating_point_v<_Tp>;
+
+// [concept.assignable]
+template<class _Lhs, class _Rhs>
+concept assignable_from =
+  is_lvalue_reference_v<_Lhs> &&
+  common_reference_with<__make_const_lvalue_ref<_Lhs>, __make_const_lvalue_ref<_Rhs>> &&
+  requires (_Lhs __lhs, _Rhs&& __rhs) {
+    { __lhs = _VSTD::forward<_Rhs>(__rhs) } -> same_as<_Lhs>;
+  };
+
 // [concept.destructible]
 
 template<class _Tp>
-concept destructible = _VSTD::is_nothrow_destructible_v<_Tp>;
+concept destructible = is_nothrow_destructible_v<_Tp>;
+
+// [concept.constructible]
+template<class _Tp, class... _Args>
+concept constructible_from =
+    destructible<_Tp> && is_constructible_v<_Tp, _Args...>;
+
+// [concept.default.init]
+
+template<class _Tp>
+concept __default_initializable = requires { ::new _Tp; };
+
+template<class _Tp>
+concept default_initializable = constructible_from<_Tp> &&
+    requires { _Tp{}; } && __default_initializable<_Tp>;
+
+// [concept.moveconstructible]
+template<class _Tp>
+concept move_constructible =
+  constructible_from<_Tp, _Tp> && convertible_to<_Tp, _Tp>;
+
+// [concept.copyconstructible]
+template<class _Tp>
+concept copy_constructible =
+  move_constructible<_Tp> &&
+  constructible_from<_Tp, _Tp&> && convertible_to<_Tp&, _Tp> &&
+  constructible_from<_Tp, const _Tp&> && convertible_to<const _Tp&, _Tp> &&
+  constructible_from<_Tp, const _Tp> && convertible_to<const _Tp, _Tp>;
+
+// Whether a type is a class type or enumeration type according to the Core wording.
+template<class _Tp>
+concept __class_or_enum = is_class_v<_Tp> || is_union_v<_Tp> || is_enum_v<_Tp>;
+
+// [concept.swappable]
+namespace ranges::__swap {
+  // Deleted to inhibit ADL
+  template<class _Tp>
+  void swap(_Tp&, _Tp&) = delete;
+
+
+  // [1]
+  template<class _Tp, class _Up>
+  concept __unqualified_swappable_with =
+    (__class_or_enum<remove_cvref_t<_Tp>> || __class_or_enum<remove_cvref_t<_Up>>) &&
+    requires(_Tp&& __t, _Up&& __u) {
+      swap(_VSTD::forward<_Tp>(__t), _VSTD::forward<_Up>(__u));
+    };
+
+  struct __fn;
+
+  template<class _Tp, class _Up, size_t _Size>
+  concept __swappable_arrays =
+    !__unqualified_swappable_with<_Tp(&)[_Size], _Up(&)[_Size]> &&
+    extent_v<_Tp> == extent_v<_Up> &&
+    requires(_Tp(& __t)[_Size], _Up(& __u)[_Size], const __fn& __swap) {
+      __swap(__t[0], __u[0]);
+    };
+
+  template<class _Tp>
+  concept __exchangeable =
+    !__unqualified_swappable_with<_Tp&, _Tp&> &&
+    move_constructible<_Tp> &&
+    assignable_from<_Tp&, _Tp>;
+
+  struct __fn {
+    // 2.1   `S` is `(void)swap(E1, E2)`* if `E1` or `E2` has class or enumeration type and...
+    // *The name `swap` is used here unqualified.
+    template<class _Tp, class _Up>
+    requires __unqualified_swappable_with<_Tp, _Up>
+    constexpr void operator()(_Tp&& __t, _Up&& __u) const
+    noexcept(noexcept(swap(_VSTD::forward<_Tp>(__t), _VSTD::forward<_Up>(__u))))
+    {
+      swap(_VSTD::forward<_Tp>(__t), _VSTD::forward<_Up>(__u));
+    }
+
+    // 2.2   Otherwise, if `E1` and `E2` are lvalues of array types with equal extent and...
+    template<class _Tp, class _Up, size_t _Size>
+    requires __swappable_arrays<_Tp, _Up, _Size>
+    constexpr void operator()(_Tp(& __t)[_Size], _Up(& __u)[_Size]) const
+    noexcept(noexcept((*this)(*__t, *__u)))
+    {
+      // TODO(cjdb): replace with `ranges::swap_ranges`.
+      for (size_t __i = 0; __i < _Size; ++__i) {
+        (*this)(__t[__i], __u[__i]);
+      }
+    }
+
+    // 2.3   Otherwise, if `E1` and `E2` are lvalues of the same type `T` that models...
+    template<__exchangeable _Tp>
+    constexpr void operator()(_Tp& __x, _Tp& __y) const
+    noexcept(is_nothrow_move_constructible_v<_Tp> && is_nothrow_move_assignable_v<_Tp>)
+    {
+      __y = _VSTD::exchange(__x, _VSTD::move(__y));
+    }
+  };
+} // namespace ranges::__swap
+
+namespace ranges::inline __cpo {
+  inline constexpr auto swap = __swap::__fn{};
+} // namespace ranges::__cpo
+
+template<class _Tp>
+concept swappable = requires(_Tp& __a, _Tp& __b) { ranges::swap(__a, __b); };
+
+template<class _Tp, class _Up>
+concept swappable_with =
+  common_reference_with<_Tp, _Up> &&
+  requires(_Tp&& __t, _Up&& __u) {
+    ranges::swap(_VSTD::forward<_Tp>(__t), _VSTD::forward<_Tp>(__t));
+    ranges::swap(_VSTD::forward<_Up>(__u), _VSTD::forward<_Up>(__u));
+    ranges::swap(_VSTD::forward<_Tp>(__t), _VSTD::forward<_Up>(__u));
+    ranges::swap(_VSTD::forward<_Up>(__u), _VSTD::forward<_Tp>(__t));
+  };
+
+// [concept.booleantestable]
+template<class _Tp>
+concept __boolean_testable_impl = convertible_to<_Tp, bool>;
+
+template<class _Tp>
+concept __boolean_testable = __boolean_testable_impl<_Tp> && requires(_Tp&& __t) {
+  { !std::forward<_Tp>(__t) } -> __boolean_testable_impl;
+};
+
+// [concept.equalitycomparable]
+template<class _Tp, class _Up>
+concept __weakly_equality_comparable_with =
+  requires(__make_const_lvalue_ref<_Tp> __t, __make_const_lvalue_ref<_Up> __u) {
+    { __t == __u } -> __boolean_testable;
+    { __t != __u } -> __boolean_testable;
+    { __u == __t } -> __boolean_testable;
+    { __u != __t } -> __boolean_testable;
+  };
+
+template<class _Tp>
+concept equality_comparable = __weakly_equality_comparable_with<_Tp, _Tp>;
+
+template<class _Tp, class _Up>
+concept equality_comparable_with =
+  equality_comparable<_Tp> && equality_comparable<_Up> &&
+  common_reference_with<__make_const_lvalue_ref<_Tp>, __make_const_lvalue_ref<_Up>> &&
+  equality_comparable<
+    common_reference_t<
+      __make_const_lvalue_ref<_Tp>,
+      __make_const_lvalue_ref<_Up>>> &&
+  __weakly_equality_comparable_with<_Tp, _Up>;
+
+// [concept.totallyordered]
+
+template<class _Tp, class _Up>
+concept __partially_ordered_with =
+  requires(__make_const_lvalue_ref<_Tp> __t, __make_const_lvalue_ref<_Up> __u) {
+    { __t <  __u } -> __boolean_testable;
+    { __t >  __u } -> __boolean_testable;
+    { __t <= __u } -> __boolean_testable;
+    { __t >= __u } -> __boolean_testable;
+    { __u <  __t } -> __boolean_testable;
+    { __u >  __t } -> __boolean_testable;
+    { __u <= __t } -> __boolean_testable;
+    { __u >= __t } -> __boolean_testable;
+  };
+
+template<class _Tp>
+concept totally_ordered = equality_comparable<_Tp> && __partially_ordered_with<_Tp, _Tp>;
+
+template<class _Tp, class _Up>
+concept totally_ordered_with =
+  totally_ordered<_Tp> && totally_ordered<_Up> &&
+  equality_comparable_with<_Tp, _Up> &&
+  totally_ordered<
+    common_reference_t<
+      __make_const_lvalue_ref<_Tp>,
+      __make_const_lvalue_ref<_Up>>> &&
+  __partially_ordered_with<_Tp, _Up>;
+
+// [concepts.object]
+template<class _Tp>
+concept movable =
+  is_object_v<_Tp> &&
+  move_constructible<_Tp> &&
+  assignable_from<_Tp&, _Tp> &&
+  swappable<_Tp>;
+
+template<class _Tp>
+concept copyable =
+  copy_constructible<_Tp> &&
+  movable<_Tp> &&
+  assignable_from<_Tp&, _Tp&> &&
+  assignable_from<_Tp&, const _Tp&> &&
+  assignable_from<_Tp&, const _Tp>;
+
+template<class _Tp>
+concept semiregular = copyable<_Tp> && default_initializable<_Tp>;
+
+template<class _Tp>
+concept regular = semiregular<_Tp> && equality_comparable<_Tp>;
+
+// [concept.invocable]
+template<class _Fn, class... _Args>
+concept invocable = requires(_Fn&& __fn, _Args&&... __args) {
+  _VSTD::invoke(_VSTD::forward<_Fn>(__fn), _VSTD::forward<_Args>(__args)...); // not required to be equality preserving
+};
+
+// [concept.regular.invocable]
+template<class _Fn, class... _Args>
+concept regular_invocable = invocable<_Fn, _Args...>;
+
+// [concept.predicate]
+template<class _Fn, class... _Args>
+concept predicate =
+  regular_invocable<_Fn, _Args...> && __boolean_testable<invoke_result_t<_Fn, _Args...>>;
+
+// [concept.relation]
+template<class _Rp, class _Tp, class _Up>
+concept relation =
+  predicate<_Rp, _Tp, _Tp> && predicate<_Rp, _Up, _Up> &&
+  predicate<_Rp, _Tp, _Up> && predicate<_Rp, _Up, _Tp>;
+
+// [concept.equiv]
+template<class _Rp, class _Tp, class _Up>
+concept equivalence_relation = relation<_Rp, _Tp, _Up>;
+
+// [concept.strictweakorder]
+template<class _Rp, class _Tp, class _Up>
+concept strict_weak_order = relation<_Rp, _Tp, _Up>;
+
+template<class _Tp, class _Up>
+concept __different_from = !same_as<remove_cvref_t<_Tp>, remove_cvref_t<_Up>>;
 
-#endif //_LIBCPP_STD_VER > 17 && defined(__cpp_concepts) && __cpp_concepts >= 201811L
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CONCEPTS)
 
 _LIBCPP_END_NAMESPACE_STD
 
lib/libcxx/include/condition_variable
@@ -265,4 +265,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 #endif // !_LIBCPP_HAS_NO_THREADS
 
-#endif  // _LIBCPP_CONDITION_VARIABLE
+#endif // _LIBCPP_CONDITION_VARIABLE
lib/libcxx/include/csetjmp
@@ -39,9 +39,9 @@ void longjmp(jmp_buf env, int val);
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::jmp_buf;
-using ::longjmp;
+using ::jmp_buf _LIBCPP_USING_IF_EXISTS;
+using ::longjmp _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CSETJMP
+#endif // _LIBCPP_CSETJMP
lib/libcxx/include/csignal
@@ -48,10 +48,10 @@ int raise(int sig);
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::sig_atomic_t;
-using ::signal;
-using ::raise;
+using ::sig_atomic_t _LIBCPP_USING_IF_EXISTS;
+using ::signal _LIBCPP_USING_IF_EXISTS;
+using ::raise _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CSIGNAL
+#endif // _LIBCPP_CSIGNAL
lib/libcxx/include/cstdarg
@@ -40,8 +40,8 @@ Types:
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::va_list;
+using ::va_list _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CSTDARG
+#endif // _LIBCPP_CSTDARG
lib/libcxx/include/cstdbool
@@ -28,4 +28,4 @@ Macros:
 #undef __bool_true_false_are_defined
 #define __bool_true_false_are_defined 1
 
-#endif  // _LIBCPP_CSTDBOOL
+#endif // _LIBCPP_CSTDBOOL
lib/libcxx/include/cstddef
@@ -46,11 +46,11 @@ Types:
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::ptrdiff_t;
-using ::size_t;
+using ::ptrdiff_t _LIBCPP_USING_IF_EXISTS;
+using ::size_t _LIBCPP_USING_IF_EXISTS;
 
 #if !defined(_LIBCPP_CXX03_LANG)
-using ::max_align_t;
+using ::max_align_t _LIBCPP_USING_IF_EXISTS;
 #endif
 
 template <class _Tp> struct __libcpp_is_integral                     { enum { value = 0 }; };
@@ -59,13 +59,13 @@ template <>          struct __libcpp_is_integral<char>               { enum { va
 template <>          struct __libcpp_is_integral<signed char>        { enum { value = 1 }; };
 template <>          struct __libcpp_is_integral<unsigned char>      { enum { value = 1 }; };
 template <>          struct __libcpp_is_integral<wchar_t>            { enum { value = 1 }; };
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 template <>          struct __libcpp_is_integral<char8_t>            { enum { value = 1 }; };
 #endif
 #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
 template <>          struct __libcpp_is_integral<char16_t>           { enum { value = 1 }; };
 template <>          struct __libcpp_is_integral<char32_t>           { enum { value = 1 }; };
-#endif  // _LIBCPP_HAS_NO_UNICODE_CHARS
+#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
 template <>          struct __libcpp_is_integral<short>              { enum { value = 1 }; };
 template <>          struct __libcpp_is_integral<unsigned short>     { enum { value = 1 }; };
 template <>          struct __libcpp_is_integral<int>                { enum { value = 1 }; };
@@ -152,10 +152,10 @@ template <class _Integer>
   { return static_cast<byte>(static_cast<unsigned char>(static_cast<unsigned int>(__lhs) >> __shift)); }
 
 template <class _Integer, class = _EnableByteOverload<_Integer> >
-  constexpr _Integer
+  _LIBCPP_NODISCARD_EXT constexpr _Integer
   to_integer(byte __b) noexcept { return static_cast<_Integer>(__b); }
 }
 
 #endif
 
-#endif  // _LIBCPP_CSTDDEF
+#endif // _LIBCPP_CSTDDEF
lib/libcxx/include/cstdint
@@ -149,42 +149,42 @@ Types:
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using::int8_t;
-using::int16_t;
-using::int32_t;
-using::int64_t;
-
-using::uint8_t;
-using::uint16_t;
-using::uint32_t;
-using::uint64_t;
-
-using::int_least8_t;
-using::int_least16_t;
-using::int_least32_t;
-using::int_least64_t;
-
-using::uint_least8_t;
-using::uint_least16_t;
-using::uint_least32_t;
-using::uint_least64_t;
-
-using::int_fast8_t;
-using::int_fast16_t;
-using::int_fast32_t;
-using::int_fast64_t;
-
-using::uint_fast8_t;
-using::uint_fast16_t;
-using::uint_fast32_t;
-using::uint_fast64_t;
-
-using::intptr_t;
-using::uintptr_t;
-
-using::intmax_t;
-using::uintmax_t;
+using ::int8_t _LIBCPP_USING_IF_EXISTS;
+using ::int16_t _LIBCPP_USING_IF_EXISTS;
+using ::int32_t _LIBCPP_USING_IF_EXISTS;
+using ::int64_t _LIBCPP_USING_IF_EXISTS;
+
+using ::uint8_t _LIBCPP_USING_IF_EXISTS;
+using ::uint16_t _LIBCPP_USING_IF_EXISTS;
+using ::uint32_t _LIBCPP_USING_IF_EXISTS;
+using ::uint64_t _LIBCPP_USING_IF_EXISTS;
+
+using ::int_least8_t _LIBCPP_USING_IF_EXISTS;
+using ::int_least16_t _LIBCPP_USING_IF_EXISTS;
+using ::int_least32_t _LIBCPP_USING_IF_EXISTS;
+using ::int_least64_t _LIBCPP_USING_IF_EXISTS;
+
+using ::uint_least8_t _LIBCPP_USING_IF_EXISTS;
+using ::uint_least16_t _LIBCPP_USING_IF_EXISTS;
+using ::uint_least32_t _LIBCPP_USING_IF_EXISTS;
+using ::uint_least64_t _LIBCPP_USING_IF_EXISTS;
+
+using ::int_fast8_t _LIBCPP_USING_IF_EXISTS;
+using ::int_fast16_t _LIBCPP_USING_IF_EXISTS;
+using ::int_fast32_t _LIBCPP_USING_IF_EXISTS;
+using ::int_fast64_t _LIBCPP_USING_IF_EXISTS;
+
+using ::uint_fast8_t _LIBCPP_USING_IF_EXISTS;
+using ::uint_fast16_t _LIBCPP_USING_IF_EXISTS;
+using ::uint_fast32_t _LIBCPP_USING_IF_EXISTS;
+using ::uint_fast64_t _LIBCPP_USING_IF_EXISTS;
+
+using ::intptr_t _LIBCPP_USING_IF_EXISTS;
+using ::uintptr_t _LIBCPP_USING_IF_EXISTS;
+
+using ::intmax_t _LIBCPP_USING_IF_EXISTS;
+using ::uintmax_t _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CSTDINT
+#endif // _LIBCPP_CSTDINT
lib/libcxx/include/cstdio
@@ -104,72 +104,72 @@ void perror(const char* s);
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::FILE;
-using ::fpos_t;
-using ::size_t;
-
-using ::fclose;
-using ::fflush;
-using ::setbuf;
-using ::setvbuf;
-using ::fprintf;
-using ::fscanf;
-using ::snprintf;
-using ::sprintf;
-using ::sscanf;
-using ::vfprintf;
-using ::vfscanf;
-using ::vsscanf;
-using ::vsnprintf;
-using ::vsprintf;
-using ::fgetc;
-using ::fgets;
-using ::fputc;
-using ::fputs;
-using ::getc;
-using ::putc;
-using ::ungetc;
-using ::fread;
-using ::fwrite;
+using ::FILE _LIBCPP_USING_IF_EXISTS;
+using ::fpos_t _LIBCPP_USING_IF_EXISTS;
+using ::size_t _LIBCPP_USING_IF_EXISTS;
+
+using ::fclose _LIBCPP_USING_IF_EXISTS;
+using ::fflush _LIBCPP_USING_IF_EXISTS;
+using ::setbuf _LIBCPP_USING_IF_EXISTS;
+using ::setvbuf _LIBCPP_USING_IF_EXISTS;
+using ::fprintf _LIBCPP_USING_IF_EXISTS;
+using ::fscanf _LIBCPP_USING_IF_EXISTS;
+using ::snprintf _LIBCPP_USING_IF_EXISTS;
+using ::sprintf _LIBCPP_USING_IF_EXISTS;
+using ::sscanf _LIBCPP_USING_IF_EXISTS;
+using ::vfprintf _LIBCPP_USING_IF_EXISTS;
+using ::vfscanf _LIBCPP_USING_IF_EXISTS;
+using ::vsscanf _LIBCPP_USING_IF_EXISTS;
+using ::vsnprintf _LIBCPP_USING_IF_EXISTS;
+using ::vsprintf _LIBCPP_USING_IF_EXISTS;
+using ::fgetc _LIBCPP_USING_IF_EXISTS;
+using ::fgets _LIBCPP_USING_IF_EXISTS;
+using ::fputc _LIBCPP_USING_IF_EXISTS;
+using ::fputs _LIBCPP_USING_IF_EXISTS;
+using ::getc _LIBCPP_USING_IF_EXISTS;
+using ::putc _LIBCPP_USING_IF_EXISTS;
+using ::ungetc _LIBCPP_USING_IF_EXISTS;
+using ::fread _LIBCPP_USING_IF_EXISTS;
+using ::fwrite _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_FGETPOS_FSETPOS
-using ::fgetpos;
+using ::fgetpos _LIBCPP_USING_IF_EXISTS;
 #endif
-using ::fseek;
+using ::fseek _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_FGETPOS_FSETPOS
-using ::fsetpos;
+using ::fsetpos _LIBCPP_USING_IF_EXISTS;
 #endif
-using ::ftell;
-using ::rewind;
-using ::clearerr;
-using ::feof;
-using ::ferror;
-using ::perror;
+using ::ftell _LIBCPP_USING_IF_EXISTS;
+using ::rewind _LIBCPP_USING_IF_EXISTS;
+using ::clearerr _LIBCPP_USING_IF_EXISTS;
+using ::feof _LIBCPP_USING_IF_EXISTS;
+using ::ferror _LIBCPP_USING_IF_EXISTS;
+using ::perror _LIBCPP_USING_IF_EXISTS;
 
 #ifndef _LIBCPP_HAS_NO_GLOBAL_FILESYSTEM_NAMESPACE
-using ::fopen;
-using ::freopen;
-using ::remove;
-using ::rename;
-using ::tmpfile;
-using ::tmpnam;
+using ::fopen _LIBCPP_USING_IF_EXISTS;
+using ::freopen _LIBCPP_USING_IF_EXISTS;
+using ::remove _LIBCPP_USING_IF_EXISTS;
+using ::rename _LIBCPP_USING_IF_EXISTS;
+using ::tmpfile _LIBCPP_USING_IF_EXISTS;
+using ::tmpnam _LIBCPP_USING_IF_EXISTS;
 #endif
 
 #ifndef _LIBCPP_HAS_NO_STDIN
-using ::getchar;
+using ::getchar _LIBCPP_USING_IF_EXISTS;
 #if _LIBCPP_STD_VER <= 11 && !defined(_LIBCPP_C_HAS_NO_GETS)
-using ::gets;
+using ::gets _LIBCPP_USING_IF_EXISTS;
 #endif
-using ::scanf;
-using ::vscanf;
+using ::scanf _LIBCPP_USING_IF_EXISTS;
+using ::vscanf _LIBCPP_USING_IF_EXISTS;
 #endif
 
 #ifndef _LIBCPP_HAS_NO_STDOUT
-using ::printf;
-using ::putchar;
-using ::puts;
-using ::vprintf;
+using ::printf _LIBCPP_USING_IF_EXISTS;
+using ::putchar _LIBCPP_USING_IF_EXISTS;
+using ::puts _LIBCPP_USING_IF_EXISTS;
+using ::vprintf _LIBCPP_USING_IF_EXISTS;
 #endif
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CSTDIO
+#endif // _LIBCPP_CSTDIO
lib/libcxx/include/cstdlib
@@ -96,68 +96,68 @@ void *aligned_alloc(size_t alignment, size_t size);                       // C11
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::size_t;
-using ::div_t;
-using ::ldiv_t;
+using ::size_t _LIBCPP_USING_IF_EXISTS;
+using ::div_t _LIBCPP_USING_IF_EXISTS;
+using ::ldiv_t _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_LONG_LONG
-using ::lldiv_t;
+using ::lldiv_t _LIBCPP_USING_IF_EXISTS;
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-using ::atof;
-using ::atoi;
-using ::atol;
+using ::atof _LIBCPP_USING_IF_EXISTS;
+using ::atoi _LIBCPP_USING_IF_EXISTS;
+using ::atol _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_LONG_LONG
-using ::atoll;
+using ::atoll _LIBCPP_USING_IF_EXISTS;
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-using ::strtod;
-using ::strtof;
-using ::strtold;
-using ::strtol;
+using ::strtod _LIBCPP_USING_IF_EXISTS;
+using ::strtof _LIBCPP_USING_IF_EXISTS;
+using ::strtold _LIBCPP_USING_IF_EXISTS;
+using ::strtol _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_LONG_LONG
-using ::strtoll;
+using ::strtoll _LIBCPP_USING_IF_EXISTS;
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-using ::strtoul;
+using ::strtoul _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_LONG_LONG
-using ::strtoull;
+using ::strtoull _LIBCPP_USING_IF_EXISTS;
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-using ::rand;
-using ::srand;
-using ::calloc;
-using ::free;
-using ::malloc;
-using ::realloc;
-using ::abort;
-using ::atexit;
-using ::exit;
-using ::_Exit;
+using ::rand _LIBCPP_USING_IF_EXISTS;
+using ::srand _LIBCPP_USING_IF_EXISTS;
+using ::calloc _LIBCPP_USING_IF_EXISTS;
+using ::free _LIBCPP_USING_IF_EXISTS;
+using ::malloc _LIBCPP_USING_IF_EXISTS;
+using ::realloc _LIBCPP_USING_IF_EXISTS;
+using ::abort _LIBCPP_USING_IF_EXISTS;
+using ::atexit _LIBCPP_USING_IF_EXISTS;
+using ::exit _LIBCPP_USING_IF_EXISTS;
+using ::_Exit _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_WINDOWS_STORE_APP
-using ::getenv;
-using ::system;
+using ::getenv _LIBCPP_USING_IF_EXISTS;
+using ::system _LIBCPP_USING_IF_EXISTS;
 #endif
-using ::bsearch;
-using ::qsort;
-using ::abs;
-using ::labs;
+using ::bsearch _LIBCPP_USING_IF_EXISTS;
+using ::qsort _LIBCPP_USING_IF_EXISTS;
+using ::abs _LIBCPP_USING_IF_EXISTS;
+using ::labs _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_LONG_LONG
-using ::llabs;
+using ::llabs _LIBCPP_USING_IF_EXISTS;
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-using ::div;
-using ::ldiv;
+using ::div _LIBCPP_USING_IF_EXISTS;
+using ::ldiv _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_LONG_LONG
-using ::lldiv;
+using ::lldiv _LIBCPP_USING_IF_EXISTS;
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-using ::mblen;
-using ::mbtowc;
-using ::wctomb;
-using ::mbstowcs;
-using ::wcstombs;
+using ::mblen _LIBCPP_USING_IF_EXISTS;
+using ::mbtowc _LIBCPP_USING_IF_EXISTS;
+using ::wctomb _LIBCPP_USING_IF_EXISTS;
+using ::mbstowcs _LIBCPP_USING_IF_EXISTS;
+using ::wcstombs _LIBCPP_USING_IF_EXISTS;
 #if !defined(_LIBCPP_CXX03_LANG) && defined(_LIBCPP_HAS_QUICK_EXIT)
-using ::at_quick_exit;
-using ::quick_exit;
+using ::at_quick_exit _LIBCPP_USING_IF_EXISTS;
+using ::quick_exit _LIBCPP_USING_IF_EXISTS;
 #endif
 #if _LIBCPP_STD_VER > 14 && defined(_LIBCPP_HAS_ALIGNED_ALLOC)
-using ::aligned_alloc;
+using ::aligned_alloc _LIBCPP_USING_IF_EXISTS;
 #endif
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CSTDLIB
+#endif // _LIBCPP_CSTDLIB
lib/libcxx/include/cstring
@@ -65,32 +65,32 @@ size_t strlen(const char* s);
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::size_t;
-using ::memcpy;
-using ::memmove;
-using ::strcpy;
-using ::strncpy;
-using ::strcat;
-using ::strncat;
-using ::memcmp;
-using ::strcmp;
-using ::strncmp;
-using ::strcoll;
-using ::strxfrm;
-using ::memchr;
-using ::strchr;
-using ::strcspn;
-using ::strpbrk;
-using ::strrchr;
-using ::strspn;
-using ::strstr;
+using ::size_t _LIBCPP_USING_IF_EXISTS;
+using ::memcpy _LIBCPP_USING_IF_EXISTS;
+using ::memmove _LIBCPP_USING_IF_EXISTS;
+using ::strcpy _LIBCPP_USING_IF_EXISTS;
+using ::strncpy _LIBCPP_USING_IF_EXISTS;
+using ::strcat _LIBCPP_USING_IF_EXISTS;
+using ::strncat _LIBCPP_USING_IF_EXISTS;
+using ::memcmp _LIBCPP_USING_IF_EXISTS;
+using ::strcmp _LIBCPP_USING_IF_EXISTS;
+using ::strncmp _LIBCPP_USING_IF_EXISTS;
+using ::strcoll _LIBCPP_USING_IF_EXISTS;
+using ::strxfrm _LIBCPP_USING_IF_EXISTS;
+using ::memchr _LIBCPP_USING_IF_EXISTS;
+using ::strchr _LIBCPP_USING_IF_EXISTS;
+using ::strcspn _LIBCPP_USING_IF_EXISTS;
+using ::strpbrk _LIBCPP_USING_IF_EXISTS;
+using ::strrchr _LIBCPP_USING_IF_EXISTS;
+using ::strspn _LIBCPP_USING_IF_EXISTS;
+using ::strstr _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_THREAD_UNSAFE_C_FUNCTIONS
-using ::strtok;
+using ::strtok _LIBCPP_USING_IF_EXISTS;
 #endif
-using ::memset;
-using ::strerror;
-using ::strlen;
+using ::memset _LIBCPP_USING_IF_EXISTS;
+using ::strerror _LIBCPP_USING_IF_EXISTS;
+using ::strlen _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CSTRING
+#endif // _LIBCPP_CSTRING
lib/libcxx/include/ctgmath
@@ -25,4 +25,4 @@
 #pragma GCC system_header
 #endif
 
-#endif  // _LIBCPP_CTGMATH
+#endif // _LIBCPP_CTGMATH
lib/libcxx/include/ctime
@@ -68,28 +68,28 @@ int timespec_get( struct timespec *ts, int base); // C++17
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::clock_t;
-using ::size_t;
-using ::time_t;
-using ::tm;
+using ::clock_t _LIBCPP_USING_IF_EXISTS;
+using ::size_t _LIBCPP_USING_IF_EXISTS;
+using ::time_t _LIBCPP_USING_IF_EXISTS;
+using ::tm _LIBCPP_USING_IF_EXISTS;
 #if _LIBCPP_STD_VER > 14 && defined(_LIBCPP_HAS_TIMESPEC_GET)
-using ::timespec;
+using ::timespec _LIBCPP_USING_IF_EXISTS;
 #endif
-using ::clock;
-using ::difftime;
-using ::mktime;
-using ::time;
+using ::clock _LIBCPP_USING_IF_EXISTS;
+using ::difftime _LIBCPP_USING_IF_EXISTS;
+using ::mktime _LIBCPP_USING_IF_EXISTS;
+using ::time _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_THREAD_UNSAFE_C_FUNCTIONS
-using ::asctime;
-using ::ctime;
-using ::gmtime;
-using ::localtime;
+using ::asctime _LIBCPP_USING_IF_EXISTS;
+using ::ctime _LIBCPP_USING_IF_EXISTS;
+using ::gmtime _LIBCPP_USING_IF_EXISTS;
+using ::localtime _LIBCPP_USING_IF_EXISTS;
 #endif
-using ::strftime;
+using ::strftime _LIBCPP_USING_IF_EXISTS;
 #if _LIBCPP_STD_VER > 14 && defined(_LIBCPP_HAS_TIMESPEC_GET) && !defined(_LIBCPP_HAS_TIMESPEC_GET_NOT_ACTUALLY_PROVIDED)
-using ::timespec_get;
+using ::timespec_get _LIBCPP_USING_IF_EXISTS;
 #endif
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CTIME
+#endif // _LIBCPP_CTIME
lib/libcxx/include/ctype.h
@@ -56,4 +56,4 @@ int toupper(int c);
 
 #endif
 
-#endif  // _LIBCPP_CTYPE_H
+#endif // _LIBCPP_CTYPE_H
lib/libcxx/include/cwchar
@@ -112,81 +112,81 @@ size_t wcsrtombs(char* restrict dst, const wchar_t** restrict src, size_t len,
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::mbstate_t;
-using ::size_t;
-using ::tm;
-using ::wint_t;
-using ::FILE;
-using ::fwprintf;
-using ::fwscanf;
-using ::swprintf;
-using ::vfwprintf;
-using ::vswprintf;
-using ::swscanf;
-using ::vfwscanf;
-using ::vswscanf;
-using ::fgetwc;
-using ::fgetws;
-using ::fputwc;
-using ::fputws;
-using ::fwide;
-using ::getwc;
-using ::putwc;
-using ::ungetwc;
-using ::wcstod;
-using ::wcstof;
-using ::wcstold;
-using ::wcstol;
+using ::mbstate_t _LIBCPP_USING_IF_EXISTS;
+using ::size_t _LIBCPP_USING_IF_EXISTS;
+using ::tm _LIBCPP_USING_IF_EXISTS;
+using ::wint_t _LIBCPP_USING_IF_EXISTS;
+using ::FILE _LIBCPP_USING_IF_EXISTS;
+using ::fwprintf _LIBCPP_USING_IF_EXISTS;
+using ::fwscanf _LIBCPP_USING_IF_EXISTS;
+using ::swprintf _LIBCPP_USING_IF_EXISTS;
+using ::vfwprintf _LIBCPP_USING_IF_EXISTS;
+using ::vswprintf _LIBCPP_USING_IF_EXISTS;
+using ::swscanf _LIBCPP_USING_IF_EXISTS;
+using ::vfwscanf _LIBCPP_USING_IF_EXISTS;
+using ::vswscanf _LIBCPP_USING_IF_EXISTS;
+using ::fgetwc _LIBCPP_USING_IF_EXISTS;
+using ::fgetws _LIBCPP_USING_IF_EXISTS;
+using ::fputwc _LIBCPP_USING_IF_EXISTS;
+using ::fputws _LIBCPP_USING_IF_EXISTS;
+using ::fwide _LIBCPP_USING_IF_EXISTS;
+using ::getwc _LIBCPP_USING_IF_EXISTS;
+using ::putwc _LIBCPP_USING_IF_EXISTS;
+using ::ungetwc _LIBCPP_USING_IF_EXISTS;
+using ::wcstod _LIBCPP_USING_IF_EXISTS;
+using ::wcstof _LIBCPP_USING_IF_EXISTS;
+using ::wcstold _LIBCPP_USING_IF_EXISTS;
+using ::wcstol _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_LONG_LONG
-using ::wcstoll;
+using ::wcstoll _LIBCPP_USING_IF_EXISTS;
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-using ::wcstoul;
+using ::wcstoul _LIBCPP_USING_IF_EXISTS;
 #ifndef _LIBCPP_HAS_NO_LONG_LONG
-using ::wcstoull;
+using ::wcstoull _LIBCPP_USING_IF_EXISTS;
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-using ::wcscpy;
-using ::wcsncpy;
-using ::wcscat;
-using ::wcsncat;
-using ::wcscmp;
-using ::wcscoll;
-using ::wcsncmp;
-using ::wcsxfrm;
-using ::wcschr;
-using ::wcspbrk;
-using ::wcsrchr;
-using ::wcsstr;
-using ::wmemchr;
-using ::wcscspn;
-using ::wcslen;
-using ::wcsspn;
-using ::wcstok;
-using ::wmemcmp;
-using ::wmemcpy;
-using ::wmemmove;
-using ::wmemset;
-using ::wcsftime;
-using ::btowc;
-using ::wctob;
-using ::mbsinit;
-using ::mbrlen;
-using ::mbrtowc;
-using ::wcrtomb;
-using ::mbsrtowcs;
-using ::wcsrtombs;
+using ::wcscpy _LIBCPP_USING_IF_EXISTS;
+using ::wcsncpy _LIBCPP_USING_IF_EXISTS;
+using ::wcscat _LIBCPP_USING_IF_EXISTS;
+using ::wcsncat _LIBCPP_USING_IF_EXISTS;
+using ::wcscmp _LIBCPP_USING_IF_EXISTS;
+using ::wcscoll _LIBCPP_USING_IF_EXISTS;
+using ::wcsncmp _LIBCPP_USING_IF_EXISTS;
+using ::wcsxfrm _LIBCPP_USING_IF_EXISTS;
+using ::wcschr _LIBCPP_USING_IF_EXISTS;
+using ::wcspbrk _LIBCPP_USING_IF_EXISTS;
+using ::wcsrchr _LIBCPP_USING_IF_EXISTS;
+using ::wcsstr _LIBCPP_USING_IF_EXISTS;
+using ::wmemchr _LIBCPP_USING_IF_EXISTS;
+using ::wcscspn _LIBCPP_USING_IF_EXISTS;
+using ::wcslen _LIBCPP_USING_IF_EXISTS;
+using ::wcsspn _LIBCPP_USING_IF_EXISTS;
+using ::wcstok _LIBCPP_USING_IF_EXISTS;
+using ::wmemcmp _LIBCPP_USING_IF_EXISTS;
+using ::wmemcpy _LIBCPP_USING_IF_EXISTS;
+using ::wmemmove _LIBCPP_USING_IF_EXISTS;
+using ::wmemset _LIBCPP_USING_IF_EXISTS;
+using ::wcsftime _LIBCPP_USING_IF_EXISTS;
+using ::btowc _LIBCPP_USING_IF_EXISTS;
+using ::wctob _LIBCPP_USING_IF_EXISTS;
+using ::mbsinit _LIBCPP_USING_IF_EXISTS;
+using ::mbrlen _LIBCPP_USING_IF_EXISTS;
+using ::mbrtowc _LIBCPP_USING_IF_EXISTS;
+using ::wcrtomb _LIBCPP_USING_IF_EXISTS;
+using ::mbsrtowcs _LIBCPP_USING_IF_EXISTS;
+using ::wcsrtombs _LIBCPP_USING_IF_EXISTS;
 
 #ifndef _LIBCPP_HAS_NO_STDIN
-using ::getwchar;
-using ::vwscanf;
-using ::wscanf;
+using ::getwchar _LIBCPP_USING_IF_EXISTS;
+using ::vwscanf _LIBCPP_USING_IF_EXISTS;
+using ::wscanf _LIBCPP_USING_IF_EXISTS;
 #endif
 
 #ifndef _LIBCPP_HAS_NO_STDOUT
-using ::putwchar;
-using ::vwprintf;
-using ::wprintf;
+using ::putwchar _LIBCPP_USING_IF_EXISTS;
+using ::vwprintf _LIBCPP_USING_IF_EXISTS;
+using ::wprintf _LIBCPP_USING_IF_EXISTS;
 #endif
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CWCHAR
+#endif // _LIBCPP_CWCHAR
lib/libcxx/include/cwctype
@@ -59,28 +59,28 @@ wctrans_t wctrans(const char* property);
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-using ::wint_t;
-using ::wctrans_t;
-using ::wctype_t;
-using ::iswalnum;
-using ::iswalpha;
-using ::iswblank;
-using ::iswcntrl;
-using ::iswdigit;
-using ::iswgraph;
-using ::iswlower;
-using ::iswprint;
-using ::iswpunct;
-using ::iswspace;
-using ::iswupper;
-using ::iswxdigit;
-using ::iswctype;
-using ::wctype;
-using ::towlower;
-using ::towupper;
-using ::towctrans;
-using ::wctrans;
+using ::wint_t _LIBCPP_USING_IF_EXISTS;
+using ::wctrans_t _LIBCPP_USING_IF_EXISTS;
+using ::wctype_t _LIBCPP_USING_IF_EXISTS;
+using ::iswalnum _LIBCPP_USING_IF_EXISTS;
+using ::iswalpha _LIBCPP_USING_IF_EXISTS;
+using ::iswblank _LIBCPP_USING_IF_EXISTS;
+using ::iswcntrl _LIBCPP_USING_IF_EXISTS;
+using ::iswdigit _LIBCPP_USING_IF_EXISTS;
+using ::iswgraph _LIBCPP_USING_IF_EXISTS;
+using ::iswlower _LIBCPP_USING_IF_EXISTS;
+using ::iswprint _LIBCPP_USING_IF_EXISTS;
+using ::iswpunct _LIBCPP_USING_IF_EXISTS;
+using ::iswspace _LIBCPP_USING_IF_EXISTS;
+using ::iswupper _LIBCPP_USING_IF_EXISTS;
+using ::iswxdigit _LIBCPP_USING_IF_EXISTS;
+using ::iswctype _LIBCPP_USING_IF_EXISTS;
+using ::wctype _LIBCPP_USING_IF_EXISTS;
+using ::towlower _LIBCPP_USING_IF_EXISTS;
+using ::towupper _LIBCPP_USING_IF_EXISTS;
+using ::towctrans _LIBCPP_USING_IF_EXISTS;
+using ::wctrans _LIBCPP_USING_IF_EXISTS;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_CWCTYPE
+#endif // _LIBCPP_CWCTYPE
lib/libcxx/include/deque
@@ -161,12 +161,16 @@ template <class T, class Allocator, class Predicate>
 */
 
 #include <__config>
+#include <__debug>
 #include <__split_buffer>
-#include <type_traits>
+#include <__utility/forward.h>
+#include <algorithm>
+#include <compare>
 #include <initializer_list>
 #include <iterator>
-#include <algorithm>
+#include <limits>
 #include <stdexcept>
+#include <type_traits>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -1055,7 +1059,7 @@ public:
     __deque_base(__deque_base&& __c)
         _NOEXCEPT_(is_nothrow_move_constructible<allocator_type>::value);
     __deque_base(__deque_base&& __c, const allocator_type& __a);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     void swap(__deque_base& __c)
 #if _LIBCPP_STD_VER >= 14
@@ -1222,7 +1226,7 @@ __deque_base<_Tp, _Allocator>::__deque_base(__deque_base&& __c, const allocator_
     }
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Allocator>
 void
@@ -1315,7 +1319,7 @@ public:
         deque(_InputIter __f, _InputIter __l, const allocator_type& __a,
               typename enable_if<__is_cpp17_input_iterator<_InputIter>::value>::type* = 0);
     deque(const deque& __c);
-    deque(const deque& __c, const allocator_type& __a);
+    deque(const deque& __c, const __identity_t<allocator_type>& __a);
 
     deque& operator=(const deque& __c);
 
@@ -1329,7 +1333,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     deque(deque&& __c) _NOEXCEPT_(is_nothrow_move_constructible<__base>::value);
     _LIBCPP_INLINE_VISIBILITY
-    deque(deque&& __c, const allocator_type& __a);
+    deque(deque&& __c, const __identity_t<allocator_type>& __a);
     _LIBCPP_INLINE_VISIBILITY
     deque& operator=(deque&& __c)
         _NOEXCEPT_(__alloc_traits::propagate_on_container_move_assignment::value &&
@@ -1337,7 +1341,7 @@ public:
 
     _LIBCPP_INLINE_VISIBILITY
     void assign(initializer_list<value_type> __il) {assign(__il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     template <class _InputIter>
         void assign(_InputIter __f, _InputIter __l,
@@ -1440,7 +1444,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     iterator insert(const_iterator __p, initializer_list<value_type> __il)
         {return insert(__p, __il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     iterator insert(const_iterator __p, const value_type& __v);
     iterator insert(const_iterator __p, size_type __n, const value_type& __v);
     template <class _InputIter>
@@ -1586,18 +1590,18 @@ public:
 
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template<class _InputIterator,
-         class _Alloc = allocator<typename iterator_traits<_InputIterator>::value_type>,
-         class = typename enable_if<__is_allocator<_Alloc>::value, void>::type
+         class _Alloc = allocator<__iter_value_type<_InputIterator>>,
+         class = _EnableIf<__is_allocator<_Alloc>::value>
          >
 deque(_InputIterator, _InputIterator)
-  -> deque<typename iterator_traits<_InputIterator>::value_type, _Alloc>;
+  -> deque<__iter_value_type<_InputIterator>, _Alloc>;
 
 template<class _InputIterator,
          class _Alloc,
-         class = typename enable_if<__is_allocator<_Alloc>::value, void>::type
+         class = _EnableIf<__is_allocator<_Alloc>::value>
          >
 deque(_InputIterator, _InputIterator, _Alloc)
-  -> deque<typename iterator_traits<_InputIterator>::value_type, _Alloc>;
+  -> deque<__iter_value_type<_InputIterator>, _Alloc>;
 #endif
 
 
@@ -1658,7 +1662,7 @@ deque<_Tp, _Allocator>::deque(const deque& __c)
 }
 
 template <class _Tp, class _Allocator>
-deque<_Tp, _Allocator>::deque(const deque& __c, const allocator_type& __a)
+deque<_Tp, _Allocator>::deque(const deque& __c, const __identity_t<allocator_type>& __a)
     : __base(__a)
 {
     __append(__c.begin(), __c.end());
@@ -1701,7 +1705,7 @@ deque<_Tp, _Allocator>::deque(deque&& __c)
 
 template <class _Tp, class _Allocator>
 inline
-deque<_Tp, _Allocator>::deque(deque&& __c, const allocator_type& __a)
+deque<_Tp, _Allocator>::deque(deque&& __c, const __identity_t<allocator_type>& __a)
     : __base(_VSTD::move(__c), __a)
 {
     if (__a != __c.__alloc())
@@ -1746,7 +1750,7 @@ deque<_Tp, _Allocator>::__move_assign(deque& __c, true_type)
     __base::__move_assign(__c);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Allocator>
 template <class _InputIter>
@@ -2128,7 +2132,7 @@ deque<_Tp, _Allocator>::emplace(const_iterator __p, _Args&&... __args)
     return __base::begin() + __pos;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 
 template <class _Tp, class _Allocator>
@@ -2532,7 +2536,7 @@ deque<_Tp, _Allocator>::__add_front_capacity(size_type __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (; __nb > 0; --__nb)
                 __buf.push_back(__alloc_traits::allocate(__a, __base::__block_size));
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2544,7 +2548,7 @@ deque<_Tp, _Allocator>::__add_front_capacity(size_type __n)
                 __alloc_traits::deallocate(__a, *__i, __base::__block_size);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         for (; __back_capacity > 0; --__back_capacity)
         {
             __buf.push_back(__base::__map_.back());
@@ -2674,7 +2678,7 @@ deque<_Tp, _Allocator>::__add_back_capacity(size_type __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (; __nb > 0; --__nb)
                 __buf.push_back(__alloc_traits::allocate(__a, __base::__block_size));
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2686,7 +2690,7 @@ deque<_Tp, _Allocator>::__add_back_capacity(size_type __n)
                 __alloc_traits::deallocate(__a, *__i, __base::__block_size);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         for (; __front_capacity > 0; --__front_capacity)
         {
             __buf.push_back(__base::__map_.front());
@@ -2720,7 +2724,7 @@ template <class _Tp, class _Allocator>
 void
 deque<_Tp, _Allocator>::pop_back()
 {
-    _LIBCPP_ASSERT(!empty(), "deque::pop_back called for empty deque");
+    _LIBCPP_ASSERT(!empty(), "deque::pop_back called on an empty deque");
     allocator_type& __a = __base::__alloc();
     size_type __p = __base::size() + __base::__start_ - 1;
     __alloc_traits::destroy(__a, _VSTD::__to_address(*(__base::__map_.begin() +
@@ -3044,4 +3048,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_DEQUE
+#endif // _LIBCPP_DEQUE
lib/libcxx/include/errno.h
@@ -72,9 +72,9 @@ static const int __elast2 = 105;
 #define ELAST ENOTRECOVERABLE
 #endif
 
-#endif  // defined(EOWNERDEAD)
+#endif // defined(EOWNERDEAD)
 
-#endif  // !defined(EOWNERDEAD) || !defined(ENOTRECOVERABLE)
+#endif // !defined(EOWNERDEAD) || !defined(ENOTRECOVERABLE)
 
 //  supply errno values likely to be missing, particularly on Windows
 
@@ -394,4 +394,4 @@ static const int __elast2 = 105;
 
 #endif // __cplusplus
 
-#endif  // _LIBCPP_ERRNO_H
+#endif // _LIBCPP_ERRNO_H
lib/libcxx/include/exception
@@ -76,9 +76,9 @@ template <class E> void rethrow_if_nested(const E& e);
 
 */
 
-#include <__config>
 #include <__availability>
-#include <__memory/base.h>
+#include <__config>
+#include <__memory/addressof.h>
 #include <cstddef>
 #include <cstdlib>
 #include <type_traits>
@@ -151,7 +151,7 @@ public:
     exception_ptr& operator=(const exception_ptr&) _NOEXCEPT;
     ~exception_ptr() _NOEXCEPT;
 
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_EXPLICIT operator bool() const _NOEXCEPT
+    _LIBCPP_INLINE_VISIBILITY explicit operator bool() const _NOEXCEPT
     {return __ptr_ != nullptr;}
 
     friend _LIBCPP_INLINE_VISIBILITY
@@ -205,7 +205,7 @@ public:
     exception_ptr& operator=(const exception_ptr& __other) _NOEXCEPT;
     exception_ptr& operator=(nullptr_t) _NOEXCEPT;
     ~exception_ptr() _NOEXCEPT;
-    _LIBCPP_EXPLICIT operator bool() const _NOEXCEPT;
+    explicit operator bool() const _NOEXCEPT;
 };
 
 _LIBCPP_FUNC_VIS
@@ -266,7 +266,7 @@ struct __throw_with_nested<_Tp, _Up, true> {
     _LIBCPP_NORETURN static inline _LIBCPP_INLINE_VISIBILITY void
     __do_throw(_Tp&& __t)
     {
-        throw __nested<_Up>(_VSTD::forward<_Tp>(__t));
+        throw __nested<_Up>(static_cast<_Tp&&>(__t));
     }
 };
 
@@ -277,9 +277,9 @@ struct __throw_with_nested<_Tp, _Up, false> {
     __do_throw(_Tp&& __t)
 #else
     __do_throw (_Tp& __t)
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     {
-        throw _VSTD::forward<_Tp>(__t);
+        throw static_cast<_Tp&&>(__t);
     }
 };
 #endif
@@ -296,7 +296,7 @@ throw_with_nested(_Tp&& __t)
         is_class<_Up>::value &&
         !is_base_of<nested_exception, _Up>::value &&
         !__libcpp_is_final<_Up>::value>::
-            __do_throw(_VSTD::forward<_Tp>(__t));
+            __do_throw(static_cast<_Tp&&>(__t));
 #else
     ((void)__t);
     // FIXME: Make this abort
@@ -330,4 +330,4 @@ rethrow_if_nested(const _Ep&,
 
 }  // std
 
-#endif  // _LIBCPP_EXCEPTION
+#endif // _LIBCPP_EXCEPTION
lib/libcxx/include/filesystem
@@ -229,19 +229,22 @@
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
+#include <__debug>
+#include <__utility/forward.h>
+#include <chrono>
+#include <compare>
 #include <cstddef>
 #include <cstdlib>
-#include <chrono>
-#include <iterator>
 #include <iosfwd>
+#include <iterator>
 #include <memory>
 #include <stack>
 #include <string>
+#include <string_view>
 #include <system_error>
 #include <utility>
-#include <string_view>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_LOCALIZATION)
@@ -249,8 +252,6 @@
 # include <iomanip> // for quoted
 #endif
 
-#include <__debug>
-
 #if defined(_LIBCPP_HAS_NO_FILESYSTEM_LIBRARY)
 # error "The Filesystem library is not supported by this configuration of libc++"
 #endif
@@ -276,6 +277,8 @@ struct _LIBCPP_TYPE_VIS space_info {
   uintmax_t available;
 };
 
+// On Windows, the library never identifies files as  block, character, fifo
+// or socket.
 enum class _LIBCPP_ENUM_VIS file_type : signed char {
   none = 0,
   not_found = -1,
@@ -289,6 +292,10 @@ enum class _LIBCPP_ENUM_VIS file_type : signed char {
   unknown = 8
 };
 
+// On Windows, these permission bits map to one single readonly flag per
+// file, and the executable bit is always returned as set. When setting
+// permissions, as long as the write bit is set for either owner, group or
+// others, the readonly flag is cleared.
 enum class _LIBCPP_ENUM_VIS perms : unsigned {
   none = 0,
 
@@ -551,7 +558,7 @@ struct __can_convert_char<wchar_t> {
   static const bool value = true;
   using __char_type = wchar_t;
 };
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 template <>
 struct __can_convert_char<char8_t> {
   static const bool value = true;
@@ -579,7 +586,7 @@ __is_separator(_ECharT __e) {
 #endif
 }
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 typedef u8string __u8_string;
 #else
 typedef string __u8_string;
@@ -785,7 +792,7 @@ struct _PathCVT<__path_value> {
   template <class _Iter>
   static typename enable_if<__is_cpp17_forward_iterator<_Iter>::value>::type
   __append_range(__path_string& __dest, _Iter __b, _Iter __e) {
-    __dest.__append_forward_unsafe(__b, __e);
+    __dest.append(__b, __e);
   }
 
   template <class _Iter>
@@ -886,7 +893,7 @@ struct _PathExport<char16_t> {
   }
 };
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 template <>
 struct _PathExport<char8_t> {
   typedef __narrow_to_utf8<sizeof(wchar_t) * __CHAR_BIT__> _Narrower;
@@ -896,7 +903,7 @@ struct _PathExport<char8_t> {
     _Narrower()(back_inserter(__dest), __src.data(), __src.data() + __src.size());
   }
 };
-#endif /* !_LIBCPP_NO_HAS_CHAR8_T */
+#endif /* !_LIBCPP_HAS_NO_CHAR8_T */
 #endif /* _LIBCPP_WIN32API */
 
 class _LIBCPP_TYPE_VIS path {
@@ -921,7 +928,7 @@ public:
   typedef basic_string<value_type> string_type;
   typedef basic_string_view<value_type> __string_view;
 
-  enum class _LIBCPP_ENUM_VIS format : unsigned char {
+  enum _LIBCPP_ENUM_VIS format : unsigned char {
     auto_format,
     native_format,
     generic_format
@@ -973,8 +980,8 @@ public:
     return *this;
   }
 
-  template <class = void>
-  _LIBCPP_INLINE_VISIBILITY path& operator=(string_type&& __s) noexcept {
+  _LIBCPP_INLINE_VISIBILITY
+  path& operator=(string_type&& __s) noexcept {
     __pn_ = _VSTD::move(__s);
     return *this;
   }
@@ -1006,14 +1013,44 @@ public:
     return *this;
   }
 
-private:
-  template <class _ECharT>
-  static bool __source_is_absolute(_ECharT __first_or_null) {
-    return __is_separator(__first_or_null);
-  }
-
 public:
   // appends
+#if defined(_LIBCPP_WIN32API)
+  path& operator/=(const path& __p) {
+    auto __p_root_name = __p.__root_name();
+    auto __p_root_name_size = __p_root_name.size();
+    if (__p.is_absolute() ||
+        (!__p_root_name.empty() && __p_root_name != root_name())) {
+      __pn_ = __p.__pn_;
+      return *this;
+    }
+    if (__p.has_root_directory()) {
+      path __root_name_str = root_name();
+      __pn_ = __root_name_str.native();
+      __pn_ += __string_view(__p.__pn_).substr(__p_root_name_size);
+      return *this;
+    }
+    if (has_filename() || (!has_root_directory() && is_absolute()))
+      __pn_ += preferred_separator;
+    __pn_ += __string_view(__p.__pn_).substr(__p_root_name_size);
+    return *this;
+  }
+  template <class _Source>
+  _LIBCPP_INLINE_VISIBILITY _EnableIfPathable<_Source>
+  operator/=(const _Source& __src) {
+    return operator/=(path(__src));
+  }
+
+  template <class _Source>
+  _EnableIfPathable<_Source> append(const _Source& __src) {
+    return operator/=(path(__src));
+  }
+
+  template <class _InputIt>
+  path& append(_InputIt __first, _InputIt __last) {
+    return operator/=(path(__first, __last));
+  }
+#else
   path& operator/=(const path& __p) {
     if (__p.is_absolute()) {
       __pn_ = __p.__pn_;
@@ -1038,7 +1075,8 @@ public:
   _EnableIfPathable<_Source> append(const _Source& __src) {
     using _Traits = __is_pathable<_Source>;
     using _CVT = _PathCVT<_SourceChar<_Source> >;
-    if (__source_is_absolute(_Traits::__first_or_null(__src)))
+    bool __source_is_absolute = __is_separator(_Traits::__first_or_null(__src));
+    if (__source_is_absolute)
       __pn_.clear();
     else if (has_filename())
       __pn_ += preferred_separator;
@@ -1051,13 +1089,14 @@ public:
     typedef typename iterator_traits<_InputIt>::value_type _ItVal;
     static_assert(__can_convert_char<_ItVal>::value, "Must convertible");
     using _CVT = _PathCVT<_ItVal>;
-    if (__first != __last && __source_is_absolute(*__first))
+    if (__first != __last && __is_separator(*__first))
       __pn_.clear();
     else if (has_filename())
       __pn_ += preferred_separator;
     _CVT::__append_range(__pn_, __first, __last);
     return *this;
   }
+#endif
 
   // concatenation
   _LIBCPP_INLINE_VISIBILITY
@@ -1161,7 +1200,12 @@ public:
 #if defined(_LIBCPP_WIN32API)
   _LIBCPP_INLINE_VISIBILITY _VSTD::wstring wstring() const { return __pn_; }
 
-  _VSTD::wstring generic_wstring() const { return __pn_; }
+  _VSTD::wstring generic_wstring() const {
+    _VSTD::wstring __s;
+    __s.resize(__pn_.size());
+    _VSTD::replace_copy(__pn_.begin(), __pn_.end(), __s.begin(), '\\', '/');
+    return __s;
+  }
 
 #if !defined(_LIBCPP_HAS_NO_LOCALIZATION)
   template <class _ECharT, class _Traits = char_traits<_ECharT>,
@@ -1198,18 +1242,29 @@ public:
             class _Allocator = allocator<_ECharT> >
   basic_string<_ECharT, _Traits, _Allocator>
   generic_string(const _Allocator& __a = _Allocator()) const {
-    return string<_ECharT, _Traits, _Allocator>(__a);
+    using _Str = basic_string<_ECharT, _Traits, _Allocator>;
+    _Str __s = string<_ECharT, _Traits, _Allocator>(__a);
+    // Note: This (and generic_u8string below) is slightly suboptimal as
+    // it iterates twice over the string; once to convert it to the right
+    // character type, and once to replace path delimiters.
+    _VSTD::replace(__s.begin(), __s.end(),
+                   static_cast<_ECharT>('\\'), static_cast<_ECharT>('/'));
+    return __s;
   }
 
   _VSTD::string generic_string() const { return generic_string<char>(); }
   _VSTD::u16string generic_u16string() const { return generic_string<char16_t>(); }
   _VSTD::u32string generic_u32string() const { return generic_string<char32_t>(); }
-  __u8_string generic_u8string() const { return u8string(); }
+  __u8_string generic_u8string() const {
+    __u8_string __s = u8string();
+    _VSTD::replace(__s.begin(), __s.end(), '\\', '/');
+    return __s;
+  }
 #endif /* !_LIBCPP_HAS_NO_LOCALIZATION */
 #else /* _LIBCPP_WIN32API */
 
   _LIBCPP_INLINE_VISIBILITY _VSTD::string string() const { return __pn_; }
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
   _LIBCPP_INLINE_VISIBILITY _VSTD::u8string u8string() const { return _VSTD::u8string(__pn_.begin(), __pn_.end()); }
 #else
   _LIBCPP_INLINE_VISIBILITY _VSTD::string u8string() const { return __pn_; }
@@ -1241,7 +1296,7 @@ public:
 
   // generic format observers
   _VSTD::string generic_string() const { return __pn_; }
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
   _VSTD::u8string generic_u8string() const { return _VSTD::u8string(__pn_.begin(), __pn_.end()); }
 #else
   _VSTD::string generic_u8string() const { return __pn_; }
@@ -1295,7 +1350,11 @@ public:
     return string_type(__root_directory());
   }
   _LIBCPP_INLINE_VISIBILITY path root_path() const {
+#if defined(_LIBCPP_WIN32API)
+    return string_type(__root_path_raw());
+#else
     return root_name().append(string_type(__root_directory()));
+#endif
   }
   _LIBCPP_INLINE_VISIBILITY path relative_path() const {
     return string_type(__relative_path());
@@ -1341,7 +1400,28 @@ public:
   }
 
   _LIBCPP_INLINE_VISIBILITY bool is_absolute() const {
+#if defined(_LIBCPP_WIN32API)
+    __string_view __root_name_str = __root_name();
+    __string_view __root_dir = __root_directory();
+    if (__root_name_str.size() == 2 && __root_name_str[1] == ':') {
+      // A drive letter with no root directory is relative, e.g. x:example.
+      return !__root_dir.empty();
+    }
+    // If no root name, it's relative, e.g. \example is relative to the current drive
+    if (__root_name_str.empty())
+      return false;
+    if (__root_name_str.size() < 3)
+      return false;
+    // A server root name, like \\server, is always absolute
+    if (__root_name_str[0] != '/' && __root_name_str[0] != '\\')
+      return false;
+    if (__root_name_str[1] != '/' && __root_name_str[1] != '\\')
+      return false;
+    // Seems to be a server root name
+    return true;
+#else
     return has_root_directory();
+#endif
   }
   _LIBCPP_INLINE_VISIBILITY bool is_relative() const { return !is_absolute(); }
 
@@ -1440,7 +1520,7 @@ _LIBCPP_INLINE_VISIBILITY _LIBCPP_DEPRECATED_WITH_CHAR8_T
     typename enable_if<__is_pathable<_InputIt>::value, path>::type
     u8path(_InputIt __f, _InputIt __l) {
   static_assert(
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
       is_same<typename __is_pathable<_InputIt>::__char_type, char8_t>::value ||
 #endif
       is_same<typename __is_pathable<_InputIt>::__char_type, char>::value,
@@ -1464,7 +1544,7 @@ _LIBCPP_INLINE_VISIBILITY _LIBCPP_DEPRECATED_WITH_CHAR8_T
     typename enable_if<__is_pathable<_InputIt>::value, path>::type
     u8path(_InputIt __f, _NullSentinel) {
   static_assert(
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
       is_same<typename __is_pathable<_InputIt>::__char_type, char8_t>::value ||
 #endif
       is_same<typename __is_pathable<_InputIt>::__char_type, char>::value,
@@ -1487,7 +1567,7 @@ _LIBCPP_INLINE_VISIBILITY _LIBCPP_DEPRECATED_WITH_CHAR8_T
     typename enable_if<__is_pathable<_Source>::value, path>::type
     u8path(const _Source& __s) {
   static_assert(
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
       is_same<typename __is_pathable<_Source>::__char_type, char8_t>::value ||
 #endif
       is_same<typename __is_pathable<_Source>::__char_type, char>::value,
@@ -1495,7 +1575,7 @@ _LIBCPP_INLINE_VISIBILITY _LIBCPP_DEPRECATED_WITH_CHAR8_T
       "'char' or 'char8_t'");
 #if defined(_LIBCPP_WIN32API)
   using _Traits = __is_pathable<_Source>;
-  return u8path(__unwrap_iter(_Traits::__range_begin(__s)), __unwrap_iter(_Traits::__range_end(__s)));
+  return u8path(_VSTD::__unwrap_iter(_Traits::__range_begin(__s)), _VSTD::__unwrap_iter(_Traits::__range_end(__s)));
 #else
   return path(__s);
 #endif
lib/libcxx/include/float.h
@@ -90,4 +90,4 @@ Macros:
 
 #endif // __cplusplus
 
-#endif  // _LIBCPP_FLOAT_H
+#endif // _LIBCPP_FLOAT_H
lib/libcxx/include/format
@@ -0,0 +1,86 @@
+// -*- C++ -*-
+//===--------------------------- format -----------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP_FORMAT
+#define _LIBCPP_FORMAT
+
+/*
+
+namespace std {
+  // [format.error], class format_error
+  class format_error : public runtime_error {
+  public:
+    explicit format_error(const string& what_arg);
+    explicit format_error(const char* what_arg);
+  };
+
+  // [format.parse.ctx], class template basic_format_parse_context
+  template<class charT>
+  class basic_format_parse_context {
+  public:
+    using char_type = charT;
+    using const_iterator = typename basic_string_view<charT>::const_iterator;
+    using iterator = const_iterator;
+
+  private:
+    iterator begin_;                                    // exposition only
+    iterator end_;                                      // exposition only
+    enum indexing { unknown, manual, automatic };       // exposition only
+    indexing indexing_;                                 // exposition only
+    size_t next_arg_id_;                                // exposition only
+    size_t num_args_;                                   // exposition only
+
+  public:
+    constexpr explicit basic_format_parse_context(basic_string_view<charT> fmt,
+                                                  size_t num_args = 0) noexcept;
+    basic_format_parse_context(const basic_format_parse_context&) = delete;
+    basic_format_parse_context& operator=(const basic_format_parse_context&) = delete;
+
+    constexpr const_iterator begin() const noexcept;
+    constexpr const_iterator end() const noexcept;
+    constexpr void advance_to(const_iterator it);
+
+    constexpr size_t next_arg_id();
+    constexpr void check_arg_id(size_t id);
+  };
+  using format_parse_context = basic_format_parse_context<char>;
+  using wformat_parse_context = basic_format_parse_context<wchar_t>;
+}
+
+*/
+
+// Make sure all feature tests macros are always available.
+#include <version>
+// Only enable the contents of the header when libc++ was build with LIBCXX_ENABLE_INCOMPLETE_FEATURES enabled
+#if !defined(_LIBCPP_HAS_NO_INCOMPLETE_FORMAT)
+
+#include <__config>
+#include <__format/format_error.h>
+#include <__format/format_parse_context.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17
+
+#endif //_LIBCPP_STD_VER > 17
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // !defined(_LIBCPP_HAS_NO_INCOMPLETE_FORMAT)
+
+#endif // _LIBCPP_FORMAT
lib/libcxx/include/forward_list
@@ -180,11 +180,12 @@ template <class T, class Allocator, class Predicate>
 */
 
 #include <__config>
+#include <__utility/forward.h>
+#include <algorithm>
 #include <initializer_list>
-#include <memory>
-#include <limits>
 #include <iterator>
-#include <algorithm>
+#include <limits>
+#include <memory>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -272,7 +273,7 @@ struct _LIBCPP_HIDDEN __begin_node_of
 };
 
 template <class _Tp, class _VoidPtr>
-struct __forward_list_node
+struct _LIBCPP_STANDALONE_DEBUG __forward_list_node
     : public __begin_node_of<_Tp, _VoidPtr>::type
 {
     typedef _Tp value_type;
@@ -506,7 +507,7 @@ public:
         _NOEXCEPT_(is_nothrow_move_constructible<__node_allocator>::value);
     _LIBCPP_INLINE_VISIBILITY
     __forward_list_base(__forward_list_base&& __x, const allocator_type& __a);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 private:
     __forward_list_base(const __forward_list_base&);
@@ -534,7 +535,7 @@ public:
 #if _LIBCPP_STD_VER >= 14
         _NOEXCEPT;
 #else
-        _NOEXCEPT_(!__node_traits::propagate_on_container_move_assignment::value ||
+        _NOEXCEPT_(!__node_traits::propagate_on_container_swap::value ||
                     __is_nothrow_swappable<__node_allocator>::value);
 #endif
 protected:
@@ -584,7 +585,7 @@ __forward_list_base<_Tp, _Alloc>::__forward_list_base(__forward_list_base&& __x,
     }
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Alloc>
 __forward_list_base<_Tp, _Alloc>::~__forward_list_base()
@@ -599,7 +600,7 @@ __forward_list_base<_Tp, _Alloc>::swap(__forward_list_base& __x)
 #if _LIBCPP_STD_VER >= 14
         _NOEXCEPT
 #else
-        _NOEXCEPT_(!__node_traits::propagate_on_container_move_assignment::value ||
+        _NOEXCEPT_(!__node_traits::propagate_on_container_swap::value ||
                     __is_nothrow_swappable<__node_allocator>::value)
 #endif
 {
@@ -681,7 +682,7 @@ public:
                        __is_cpp17_input_iterator<_InputIterator>::value
                      >::type* = nullptr);
     forward_list(const forward_list& __x);
-    forward_list(const forward_list& __x, const allocator_type& __a);
+    forward_list(const forward_list& __x, const __identity_t<allocator_type>& __a);
 
     forward_list& operator=(const forward_list& __x);
 
@@ -690,7 +691,7 @@ public:
     forward_list(forward_list&& __x)
         _NOEXCEPT_(is_nothrow_move_constructible<base>::value)
         : base(_VSTD::move(__x)) {}
-    forward_list(forward_list&& __x, const allocator_type& __a);
+    forward_list(forward_list&& __x, const __identity_t<allocator_type>& __a);
 
     forward_list(initializer_list<value_type> __il);
     forward_list(initializer_list<value_type> __il, const allocator_type& __a);
@@ -706,7 +707,7 @@ public:
 
     _LIBCPP_INLINE_VISIBILITY
     void assign(initializer_list<value_type> __il);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     // ~forward_list() = default;
 
@@ -775,7 +776,7 @@ public:
     template <class... _Args> void      emplace_front(_Args&&... __args);
 #endif
     void push_front(value_type&& __v);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     void push_front(const value_type& __v);
 
     void pop_front();
@@ -787,7 +788,7 @@ public:
     iterator insert_after(const_iterator __p, value_type&& __v);
     iterator insert_after(const_iterator __p, initializer_list<value_type> __il)
         {return insert_after(__p, __il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     iterator insert_after(const_iterator __p, const value_type& __v);
     iterator insert_after(const_iterator __p, size_type __n, const value_type& __v);
     template <class _InputIterator>
@@ -840,7 +841,7 @@ public:
         _LIBCPP_INLINE_VISIBILITY
         void merge(forward_list&& __x, _Compare __comp)
         {merge(__x, _VSTD::move(__comp));}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     void merge(forward_list& __x) {merge(__x, __less<value_type>());}
     template <class _Compare> void merge(forward_list& __x, _Compare __comp);
@@ -855,7 +856,7 @@ private:
     void __move_assign(forward_list& __x, true_type)
         _NOEXCEPT_(is_nothrow_move_assignable<allocator_type>::value);
     void __move_assign(forward_list& __x, false_type);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     template <class _Compare>
         static
@@ -871,18 +872,18 @@ private:
 
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template<class _InputIterator,
-         class _Alloc = allocator<typename iterator_traits<_InputIterator>::value_type>,
-         class = typename enable_if<__is_allocator<_Alloc>::value, void>::type
+         class _Alloc = allocator<__iter_value_type<_InputIterator>>,
+         class = _EnableIf<__is_allocator<_Alloc>::value>
          >
 forward_list(_InputIterator, _InputIterator)
-  -> forward_list<typename iterator_traits<_InputIterator>::value_type, _Alloc>;
+  -> forward_list<__iter_value_type<_InputIterator>, _Alloc>;
 
 template<class _InputIterator,
          class _Alloc,
-         class = typename enable_if<__is_allocator<_Alloc>::value, void>::type
+         class = _EnableIf<__is_allocator<_Alloc>::value>
          >
 forward_list(_InputIterator, _InputIterator, _Alloc)
-  -> forward_list<typename iterator_traits<_InputIterator>::value_type, _Alloc>;
+  -> forward_list<__iter_value_type<_InputIterator>, _Alloc>;
 #endif
 
 template <class _Tp, class _Alloc>
@@ -979,7 +980,7 @@ forward_list<_Tp, _Alloc>::forward_list(const forward_list& __x)
 
 template <class _Tp, class _Alloc>
 forward_list<_Tp, _Alloc>::forward_list(const forward_list& __x,
-                                        const allocator_type& __a)
+                                        const __identity_t<allocator_type>& __a)
     : base(__a)
 {
     insert_after(cbefore_begin(), __x.begin(), __x.end());
@@ -1000,7 +1001,7 @@ forward_list<_Tp, _Alloc>::operator=(const forward_list& __x)
 #ifndef _LIBCPP_CXX03_LANG
 template <class _Tp, class _Alloc>
 forward_list<_Tp, _Alloc>::forward_list(forward_list&& __x,
-                                        const allocator_type& __a)
+                                        const __identity_t<allocator_type>& __a)
     : base(_VSTD::move(__x), __a)
 {
     if (base::__alloc() != __x.__alloc())
@@ -1070,7 +1071,7 @@ forward_list<_Tp, _Alloc>::operator=(initializer_list<value_type> __il)
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Alloc>
 template <class _InputIterator>
@@ -1150,7 +1151,7 @@ forward_list<_Tp, _Alloc>::push_front(value_type&& __v)
     base::__before_begin()->__next_ = __h.release();
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Alloc>
 void
@@ -1207,7 +1208,7 @@ forward_list<_Tp, _Alloc>::insert_after(const_iterator __p, value_type&& __v)
     return iterator(__r->__next_);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Alloc>
 typename forward_list<_Tp, _Alloc>::iterator
@@ -1240,7 +1241,7 @@ forward_list<_Tp, _Alloc>::insert_after(const_iterator __p, size_type __n,
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (--__n; __n != 0; --__n, __last = __last->__next_)
             {
                 __h.reset(__node_traits::allocate(__a, 1));
@@ -1260,7 +1261,7 @@ forward_list<_Tp, _Alloc>::insert_after(const_iterator __p, size_type __n,
             }
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __last->__next_ = __r->__next_;
         __r->__next_ = __first;
         __r = static_cast<__begin_node_pointer>(__last);
@@ -1290,7 +1291,7 @@ forward_list<_Tp, _Alloc>::insert_after(const_iterator __p,
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (++__f; __f != __l; ++__f, ((void)(__last = __last->__next_)))
             {
                 __h.reset(__node_traits::allocate(__a, 1));
@@ -1310,7 +1311,7 @@ forward_list<_Tp, _Alloc>::insert_after(const_iterator __p,
             }
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __last->__next_ = __r->__next_;
         __r->__next_ = __first;
         __r = static_cast<__begin_node_pointer>(__last);
@@ -1784,4 +1785,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_FORWARD_LIST
+#endif // _LIBCPP_FORWARD_LIST
lib/libcxx/include/fstream
@@ -179,13 +179,14 @@ typedef basic_fstream<wchar_t> wfstream;
 
 */
 
-#include <__config>
 #include <__availability>
-#include <ostream>
-#include <istream>
+#include <__config>
+#include <__debug>
 #include <__locale>
 #include <cstdio>
 #include <cstdlib>
+#include <istream>
+#include <ostream>
 
 #if !defined(_LIBCPP_HAS_NO_FILESYSTEM_LIBRARY)
 #   include <filesystem>
@@ -198,6 +199,9 @@ typedef basic_fstream<wchar_t> wfstream;
 _LIBCPP_PUSH_MACROS
 #include <__undef_macros>
 
+#if defined(_LIBCPP_MSVCRT) || defined(_NEWLIB_VERSION)
+#  define _LIBCPP_HAS_NO_OFF_T_FUNCTIONS
+#endif
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
@@ -215,16 +219,12 @@ public:
 
     // 27.9.1.2 Constructors/destructor:
     basic_filebuf();
-#ifndef _LIBCPP_CXX03_LANG
     basic_filebuf(basic_filebuf&& __rhs);
-#endif
     virtual ~basic_filebuf();
 
     // 27.9.1.3 Assign/swap:
-#ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     basic_filebuf& operator=(basic_filebuf&& __rhs);
-#endif
     void swap(basic_filebuf& __rhs);
 
     // 27.9.1.4 Members:
@@ -244,7 +244,7 @@ public:
       return open(__p.c_str(), __mode);
     }
 #endif
-    inline _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY
     basic_filebuf* __open(int __fd, ios_base::openmode __mode);
 #endif
     basic_filebuf* close();
@@ -314,8 +314,6 @@ basic_filebuf<_CharT, _Traits>::basic_filebuf()
     setbuf(nullptr, 4096);
 }
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 basic_filebuf<_CharT, _Traits>::basic_filebuf(basic_filebuf&& __rhs)
     : basic_streambuf<_CharT, _Traits>(__rhs)
@@ -390,22 +388,20 @@ basic_filebuf<_CharT, _Traits>::operator=(basic_filebuf&& __rhs)
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 basic_filebuf<_CharT, _Traits>::~basic_filebuf()
 {
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         close();
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
     catch (...)
     {
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     if (__owns_eb_)
         delete [] __extbuf_;
     if (__owns_ib_)
@@ -574,7 +570,7 @@ basic_filebuf<_CharT, _Traits>::open(const char* __s, ios_base::openmode __mode)
 }
 
 template <class _CharT, class _Traits>
-inline _LIBCPP_INLINE_VISIBILITY
+inline
 basic_filebuf<_CharT, _Traits>*
 basic_filebuf<_CharT, _Traits>::__open(int __fd, ios_base::openmode __mode) {
   basic_filebuf<_CharT, _Traits>* __rt = nullptr;
@@ -1160,13 +1156,10 @@ public:
       : basic_ifstream(__p.c_str(), __mode) {}
 #endif // _LIBCPP_STD_VER >= 17
 #endif
-#ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     basic_ifstream(basic_ifstream&& __rhs);
-
     _LIBCPP_INLINE_VISIBILITY
     basic_ifstream& operator=(basic_ifstream&& __rhs);
-#endif
     _LIBCPP_INLINE_VISIBILITY
     void swap(basic_ifstream& __rhs);
 
@@ -1236,8 +1229,6 @@ basic_ifstream<_CharT, _Traits>::basic_ifstream(const string& __s, ios_base::ope
 }
 #endif
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 inline
 basic_ifstream<_CharT, _Traits>::basic_ifstream(basic_ifstream&& __rhs)
@@ -1257,8 +1248,6 @@ basic_ifstream<_CharT, _Traits>::operator=(basic_ifstream&& __rhs)
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 inline
 void
@@ -1326,6 +1315,7 @@ basic_ifstream<_CharT, _Traits>::open(const string& __s, ios_base::openmode __mo
 }
 
 template <class _CharT, class _Traits>
+inline
 void basic_ifstream<_CharT, _Traits>::__open(int __fd,
                                              ios_base::openmode __mode) {
   if (__sb_.__open(__fd, __mode | ios_base::in))
@@ -1374,13 +1364,10 @@ public:
       : basic_ofstream(__p.c_str(), __mode) {}
 #endif // _LIBCPP_STD_VER >= 17
 
-#ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     basic_ofstream(basic_ofstream&& __rhs);
-
     _LIBCPP_INLINE_VISIBILITY
     basic_ofstream& operator=(basic_ofstream&& __rhs);
-#endif
     _LIBCPP_INLINE_VISIBILITY
     void swap(basic_ofstream& __rhs);
 
@@ -1449,8 +1436,6 @@ basic_ofstream<_CharT, _Traits>::basic_ofstream(const string& __s, ios_base::ope
 }
 #endif
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 inline
 basic_ofstream<_CharT, _Traits>::basic_ofstream(basic_ofstream&& __rhs)
@@ -1470,8 +1455,6 @@ basic_ofstream<_CharT, _Traits>::operator=(basic_ofstream&& __rhs)
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 inline
 void
@@ -1539,6 +1522,7 @@ basic_ofstream<_CharT, _Traits>::open(const string& __s, ios_base::openmode __mo
 }
 
 template <class _CharT, class _Traits>
+inline
 void basic_ofstream<_CharT, _Traits>::__open(int __fd,
                                              ios_base::openmode __mode) {
   if (__sb_.__open(__fd, __mode | ios_base::out))
@@ -1589,13 +1573,12 @@ public:
 #endif // _LIBCPP_STD_VER >= 17
 
 #endif
-#ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     basic_fstream(basic_fstream&& __rhs);
 
     _LIBCPP_INLINE_VISIBILITY
     basic_fstream& operator=(basic_fstream&& __rhs);
-#endif
+
     _LIBCPP_INLINE_VISIBILITY
     void swap(basic_fstream& __rhs);
 
@@ -1662,8 +1645,6 @@ basic_fstream<_CharT, _Traits>::basic_fstream(const string& __s, ios_base::openm
 }
 #endif
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 inline
 basic_fstream<_CharT, _Traits>::basic_fstream(basic_fstream&& __rhs)
@@ -1683,8 +1664,6 @@ basic_fstream<_CharT, _Traits>::operator=(basic_fstream&& __rhs)
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 inline
 void
@@ -1771,4 +1750,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_FSTREAM
+#endif // _LIBCPP_FSTREAM
lib/libcxx/include/functional
@@ -1,5 +1,5 @@
 // -*- C++ -*-
-//===------------------------ functional ----------------------------------===//
+//===----------------------------------------------------------------------===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -42,8 +42,8 @@ public:
     typedef see below result_type; // Not always defined
 
     // construct/copy/destroy
-    reference_wrapper(T&) noexcept;
-    reference_wrapper(T&&) = delete; // do not bind to temps
+    template<class U>
+      reference_wrapper(U&&);
     reference_wrapper(const reference_wrapper<T>& x) noexcept;
 
     // assignment
@@ -59,6 +59,9 @@ public:
           operator() (ArgTypes&&...) const;
 };
 
+template <class T>
+  reference_wrapper(T&) -> reference_wrapper<T>;
+
 template <class T> reference_wrapper<T> ref(T& t) noexcept;
 template <class T> void ref(const T&& t) = delete;
 template <class T> reference_wrapper<T> ref(reference_wrapper<T>t) noexcept;
@@ -73,121 +76,104 @@ template <class T> using unwrap_reference_t = typename unwrap_reference<T>::type
 template <class T> using unwrap_ref_decay_t = typename unwrap_ref_decay<T>::type; // since C++20
 
 template <class T> // <class T=void> in C++14
-struct plus : binary_function<T, T, T>
-{
+struct plus {
     T operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct minus : binary_function<T, T, T>
-{
+struct minus {
     T operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct multiplies : binary_function<T, T, T>
-{
+struct multiplies {
     T operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct divides : binary_function<T, T, T>
-{
+struct divides {
     T operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct modulus : binary_function<T, T, T>
-{
+struct modulus {
     T operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct negate : unary_function<T, T>
-{
+struct negate {
     T operator()(const T& x) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct equal_to : binary_function<T, T, bool>
-{
+struct equal_to {
     bool operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct not_equal_to : binary_function<T, T, bool>
-{
+struct not_equal_to {
     bool operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct greater : binary_function<T, T, bool>
-{
+struct greater {
     bool operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct less : binary_function<T, T, bool>
-{
+struct less {
     bool operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct greater_equal : binary_function<T, T, bool>
-{
+struct greater_equal {
     bool operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct less_equal : binary_function<T, T, bool>
-{
+struct less_equal {
     bool operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct logical_and : binary_function<T, T, bool>
-{
+struct logical_and {
     bool operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct logical_or : binary_function<T, T, bool>
-{
+struct logical_or {
     bool operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct logical_not : unary_function<T, bool>
-{
+struct logical_not {
     bool operator()(const T& x) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct bit_and : unary_function<T, bool>
-{
-    bool operator()(const T& x, const T& y) const;
+struct bit_and {
+    T operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct bit_or : unary_function<T, bool>
-{
-    bool operator()(const T& x, const T& y) const;
+struct bit_or {
+    T operator()(const T& x, const T& y) const;
 };
 
 template <class T> // <class T=void> in C++14
-struct bit_xor : unary_function<T, bool>
-{
-    bool operator()(const T& x, const T& y) const;
+struct bit_xor {
+    T operator()(const T& x, const T& y) const;
 };
 
 template <class T=void> // C++14
-struct bit_xor : unary_function<T, bool>
-{
-    bool operator()(const T& x) const;
+struct bit_not {
+    T operator()(const T& x) const;
 };
 
+struct identity; // C++20
+
 template <class Predicate>
-class unary_negate // deprecated in C++17
+class unary_negate // deprecated in C++17, removed in C++20
     : public unary_function<typename Predicate::argument_type, bool>
 {
 public:
@@ -195,11 +181,11 @@ public:
     bool operator()(const typename Predicate::argument_type& x) const;
 };
 
-template <class Predicate> // deprecated in C++17
+template <class Predicate> // deprecated in C++17, removed in C++20
 unary_negate<Predicate> not1(const Predicate& pred);
 
 template <class Predicate>
-class binary_negate // deprecated in C++17
+class binary_negate // deprecated in C++17, removed in C++20
     : public binary_function<typename Predicate::first_argument_type,
                              typename Predicate::second_argument_type,
                              bool>
@@ -210,7 +196,7 @@ public:
                     const typename Predicate::second_argument_type& y) const;
 };
 
-template <class Predicate> // deprecated in C++17
+template <class Predicate> // deprecated in C++17, removed in C++20
 binary_negate<Predicate> not2(const Predicate& pred);
 
 template <class F>
@@ -501,2687 +487,43 @@ POLICY:  For non-variadic implementations, the number of arguments is limited
 
 */
 
+#include <__algorithm/search.h>
 #include <__config>
-#include <type_traits>
-#include <typeinfo>
+#include <__debug>
+#include <__functional/binary_function.h> // TODO: deprecate
+#include <__functional/binary_negate.h>
+#include <__functional/bind_front.h>
+#include <__functional/bind.h>
+#include <__functional/binder1st.h>
+#include <__functional/binder2nd.h>
+#include <__functional/default_searcher.h>
+#include <__functional/function.h>
+#include <__functional/hash.h>
+#include <__functional/identity.h>
+#include <__functional/invoke.h>
+#include <__functional/mem_fn.h> // TODO: deprecate
+#include <__functional/mem_fun_ref.h>
+#include <__functional/not_fn.h>
+#include <__functional/operations.h>
+#include <__functional/pointer_to_binary_function.h>
+#include <__functional/pointer_to_unary_function.h>
+#include <__functional/ranges_operations.h>
+#include <__functional/reference_wrapper.h>
+#include <__functional/unary_function.h> // TODO: deprecate
+#include <__functional/unary_negate.h>
+#include <__functional/unwrap_ref.h>
+#include <__utility/forward.h>
+#include <concepts>
 #include <exception>
 #include <memory>
 #include <tuple>
+#include <type_traits>
+#include <typeinfo>
 #include <utility>
 #include <version>
 
-#include <__functional_base>
-
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
 
-_LIBCPP_BEGIN_NAMESPACE_STD
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS plus : binary_function<_Tp, _Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x + __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS plus<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS minus : binary_function<_Tp, _Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x - __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS minus<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) - _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS multiplies : binary_function<_Tp, _Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x * __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS multiplies<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) * _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS divides : binary_function<_Tp, _Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x / __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS divides<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) / _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS modulus : binary_function<_Tp, _Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x % __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS modulus<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) % _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS negate : unary_function<_Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x) const
-        {return -__x;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS negate<void>
-{
-    template <class _Tp>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_Tp&& __x) const
-    _NOEXCEPT_(noexcept(- _VSTD::forward<_Tp>(__x)))
-    -> decltype        (- _VSTD::forward<_Tp>(__x))
-        { return        - _VSTD::forward<_Tp>(__x); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS equal_to : binary_function<_Tp, _Tp, bool>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x == __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS equal_to<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) == _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS not_equal_to : binary_function<_Tp, _Tp, bool>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x != __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS not_equal_to<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) != _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS greater : binary_function<_Tp, _Tp, bool>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x > __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS greater<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) > _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-// less in <__functional_base>
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS greater_equal : binary_function<_Tp, _Tp, bool>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x >= __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS greater_equal<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) >= _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS less_equal : binary_function<_Tp, _Tp, bool>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x <= __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS less_equal<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) <= _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS logical_and : binary_function<_Tp, _Tp, bool>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x && __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS logical_and<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) && _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS logical_or : binary_function<_Tp, _Tp, bool>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x || __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS logical_or<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) || _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS logical_not : unary_function<_Tp, bool>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const _Tp& __x) const
-        {return !__x;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS logical_not<void>
-{
-    template <class _Tp>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_Tp&& __x) const
-    _NOEXCEPT_(noexcept(!_VSTD::forward<_Tp>(__x)))
-    -> decltype        (!_VSTD::forward<_Tp>(__x))
-        { return        !_VSTD::forward<_Tp>(__x); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS bit_and : binary_function<_Tp, _Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x & __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS bit_and<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) & _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS bit_or : binary_function<_Tp, _Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x | __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS bit_or<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) | _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-#else
-template <class _Tp>
-#endif
-struct _LIBCPP_TEMPLATE_VIS bit_xor : binary_function<_Tp, _Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x, const _Tp& __y) const
-        {return __x ^ __y;}
-};
-
-#if _LIBCPP_STD_VER > 11
-template <>
-struct _LIBCPP_TEMPLATE_VIS bit_xor<void>
-{
-    template <class _T1, class _T2>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_T1&& __t, _T2&& __u) const
-    _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u)))
-    -> decltype        (_VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u))
-        { return        _VSTD::forward<_T1>(__t) ^ _VSTD::forward<_T2>(__u); }
-    typedef void is_transparent;
-};
-#endif
-
-
-#if _LIBCPP_STD_VER > 11
-template <class _Tp = void>
-struct _LIBCPP_TEMPLATE_VIS bit_not : unary_function<_Tp, _Tp>
-{
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    _Tp operator()(const _Tp& __x) const
-        {return ~__x;}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS bit_not<void>
-{
-    template <class _Tp>
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    auto operator()(_Tp&& __x) const
-    _NOEXCEPT_(noexcept(~_VSTD::forward<_Tp>(__x)))
-    -> decltype        (~_VSTD::forward<_Tp>(__x))
-        { return        ~_VSTD::forward<_Tp>(__x); }
-    typedef void is_transparent;
-};
-#endif
-
-template <class _Predicate>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX17 unary_negate
-    : public unary_function<typename _Predicate::argument_type, bool>
-{
-    _Predicate __pred_;
-public:
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    explicit unary_negate(const _Predicate& __pred)
-        : __pred_(__pred) {}
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const typename _Predicate::argument_type& __x) const
-        {return !__pred_(__x);}
-};
-
-template <class _Predicate>
-_LIBCPP_DEPRECATED_IN_CXX17 inline _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-unary_negate<_Predicate>
-not1(const _Predicate& __pred) {return unary_negate<_Predicate>(__pred);}
-
-template <class _Predicate>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX17 binary_negate
-    : public binary_function<typename _Predicate::first_argument_type,
-                             typename _Predicate::second_argument_type,
-                             bool>
-{
-    _Predicate __pred_;
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit _LIBCPP_CONSTEXPR_AFTER_CXX11
-    binary_negate(const _Predicate& __pred) : __pred_(__pred) {}
-
-    _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    bool operator()(const typename _Predicate::first_argument_type& __x,
-                    const typename _Predicate::second_argument_type& __y) const
-        {return !__pred_(__x, __y);}
-};
-
-template <class _Predicate>
-_LIBCPP_DEPRECATED_IN_CXX17 inline _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-binary_negate<_Predicate>
-not2(const _Predicate& __pred) {return binary_negate<_Predicate>(__pred);}
-
-#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_BINDERS)
-template <class __Operation>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 binder1st
-    : public unary_function<typename __Operation::second_argument_type,
-                            typename __Operation::result_type>
-{
-protected:
-    __Operation                               op;
-    typename __Operation::first_argument_type value;
-public:
-    _LIBCPP_INLINE_VISIBILITY binder1st(const __Operation& __x,
-                               const typename __Operation::first_argument_type __y)
-        : op(__x), value(__y) {}
-    _LIBCPP_INLINE_VISIBILITY typename __Operation::result_type operator()
-        (typename __Operation::second_argument_type& __x) const
-            {return op(value, __x);}
-    _LIBCPP_INLINE_VISIBILITY typename __Operation::result_type operator()
-        (const typename __Operation::second_argument_type& __x) const
-            {return op(value, __x);}
-};
-
-template <class __Operation, class _Tp>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-binder1st<__Operation>
-bind1st(const __Operation& __op, const _Tp& __x)
-    {return binder1st<__Operation>(__op, __x);}
-
-template <class __Operation>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 binder2nd
-    : public unary_function<typename __Operation::first_argument_type,
-                            typename __Operation::result_type>
-{
-protected:
-    __Operation                                op;
-    typename __Operation::second_argument_type value;
-public:
-    _LIBCPP_INLINE_VISIBILITY
-    binder2nd(const __Operation& __x, const typename __Operation::second_argument_type __y)
-        : op(__x), value(__y) {}
-    _LIBCPP_INLINE_VISIBILITY typename __Operation::result_type operator()
-        (      typename __Operation::first_argument_type& __x) const
-            {return op(__x, value);}
-    _LIBCPP_INLINE_VISIBILITY typename __Operation::result_type operator()
-        (const typename __Operation::first_argument_type& __x) const
-            {return op(__x, value);}
-};
-
-template <class __Operation, class _Tp>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-binder2nd<__Operation>
-bind2nd(const __Operation& __op, const _Tp& __x)
-    {return binder2nd<__Operation>(__op, __x);}
-
-template <class _Arg, class _Result>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 pointer_to_unary_function
-    : public unary_function<_Arg, _Result>
-{
-    _Result (*__f_)(_Arg);
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit pointer_to_unary_function(_Result (*__f)(_Arg))
-        : __f_(__f) {}
-    _LIBCPP_INLINE_VISIBILITY _Result operator()(_Arg __x) const
-        {return __f_(__x);}
-};
-
-template <class _Arg, class _Result>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-pointer_to_unary_function<_Arg,_Result>
-ptr_fun(_Result (*__f)(_Arg))
-    {return pointer_to_unary_function<_Arg,_Result>(__f);}
-
-template <class _Arg1, class _Arg2, class _Result>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 pointer_to_binary_function
-    : public binary_function<_Arg1, _Arg2, _Result>
-{
-    _Result (*__f_)(_Arg1, _Arg2);
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit pointer_to_binary_function(_Result (*__f)(_Arg1, _Arg2))
-        : __f_(__f) {}
-    _LIBCPP_INLINE_VISIBILITY _Result operator()(_Arg1 __x, _Arg2 __y) const
-        {return __f_(__x, __y);}
-};
-
-template <class _Arg1, class _Arg2, class _Result>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-pointer_to_binary_function<_Arg1,_Arg2,_Result>
-ptr_fun(_Result (*__f)(_Arg1,_Arg2))
-    {return pointer_to_binary_function<_Arg1,_Arg2,_Result>(__f);}
-
-template<class _Sp, class _Tp>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 mem_fun_t
-    : public unary_function<_Tp*, _Sp>
-{
-    _Sp (_Tp::*__p_)();
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit mem_fun_t(_Sp (_Tp::*__p)())
-        : __p_(__p) {}
-    _LIBCPP_INLINE_VISIBILITY _Sp operator()(_Tp* __p) const
-        {return (__p->*__p_)();}
-};
-
-template<class _Sp, class _Tp, class _Ap>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 mem_fun1_t
-    : public binary_function<_Tp*, _Ap, _Sp>
-{
-    _Sp (_Tp::*__p_)(_Ap);
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit mem_fun1_t(_Sp (_Tp::*__p)(_Ap))
-        : __p_(__p) {}
-    _LIBCPP_INLINE_VISIBILITY _Sp operator()(_Tp* __p, _Ap __x) const
-        {return (__p->*__p_)(__x);}
-};
-
-template<class _Sp, class _Tp>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-mem_fun_t<_Sp,_Tp>
-mem_fun(_Sp (_Tp::*__f)())
-    {return mem_fun_t<_Sp,_Tp>(__f);}
-
-template<class _Sp, class _Tp, class _Ap>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-mem_fun1_t<_Sp,_Tp,_Ap>
-mem_fun(_Sp (_Tp::*__f)(_Ap))
-    {return mem_fun1_t<_Sp,_Tp,_Ap>(__f);}
-
-template<class _Sp, class _Tp>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 mem_fun_ref_t
-    : public unary_function<_Tp, _Sp>
-{
-    _Sp (_Tp::*__p_)();
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit mem_fun_ref_t(_Sp (_Tp::*__p)())
-        : __p_(__p) {}
-    _LIBCPP_INLINE_VISIBILITY _Sp operator()(_Tp& __p) const
-        {return (__p.*__p_)();}
-};
-
-template<class _Sp, class _Tp, class _Ap>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 mem_fun1_ref_t
-    : public binary_function<_Tp, _Ap, _Sp>
-{
-    _Sp (_Tp::*__p_)(_Ap);
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit mem_fun1_ref_t(_Sp (_Tp::*__p)(_Ap))
-        : __p_(__p) {}
-    _LIBCPP_INLINE_VISIBILITY _Sp operator()(_Tp& __p, _Ap __x) const
-        {return (__p.*__p_)(__x);}
-};
-
-template<class _Sp, class _Tp>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-mem_fun_ref_t<_Sp,_Tp>
-mem_fun_ref(_Sp (_Tp::*__f)())
-    {return mem_fun_ref_t<_Sp,_Tp>(__f);}
-
-template<class _Sp, class _Tp, class _Ap>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-mem_fun1_ref_t<_Sp,_Tp,_Ap>
-mem_fun_ref(_Sp (_Tp::*__f)(_Ap))
-    {return mem_fun1_ref_t<_Sp,_Tp,_Ap>(__f);}
-
-template <class _Sp, class _Tp>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun_t
-    : public unary_function<const _Tp*, _Sp>
-{
-    _Sp (_Tp::*__p_)() const;
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit const_mem_fun_t(_Sp (_Tp::*__p)() const)
-        : __p_(__p) {}
-    _LIBCPP_INLINE_VISIBILITY _Sp operator()(const _Tp* __p) const
-        {return (__p->*__p_)();}
-};
-
-template <class _Sp, class _Tp, class _Ap>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun1_t
-    : public binary_function<const _Tp*, _Ap, _Sp>
-{
-    _Sp (_Tp::*__p_)(_Ap) const;
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit const_mem_fun1_t(_Sp (_Tp::*__p)(_Ap) const)
-        : __p_(__p) {}
-    _LIBCPP_INLINE_VISIBILITY _Sp operator()(const _Tp* __p, _Ap __x) const
-        {return (__p->*__p_)(__x);}
-};
-
-template <class _Sp, class _Tp>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-const_mem_fun_t<_Sp,_Tp>
-mem_fun(_Sp (_Tp::*__f)() const)
-    {return const_mem_fun_t<_Sp,_Tp>(__f);}
-
-template <class _Sp, class _Tp, class _Ap>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-const_mem_fun1_t<_Sp,_Tp,_Ap>
-mem_fun(_Sp (_Tp::*__f)(_Ap) const)
-    {return const_mem_fun1_t<_Sp,_Tp,_Ap>(__f);}
-
-template <class _Sp, class _Tp>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun_ref_t
-    : public unary_function<_Tp, _Sp>
-{
-    _Sp (_Tp::*__p_)() const;
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit const_mem_fun_ref_t(_Sp (_Tp::*__p)() const)
-        : __p_(__p) {}
-    _LIBCPP_INLINE_VISIBILITY _Sp operator()(const _Tp& __p) const
-        {return (__p.*__p_)();}
-};
-
-template <class _Sp, class _Tp, class _Ap>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 const_mem_fun1_ref_t
-    : public binary_function<_Tp, _Ap, _Sp>
-{
-    _Sp (_Tp::*__p_)(_Ap) const;
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit const_mem_fun1_ref_t(_Sp (_Tp::*__p)(_Ap) const)
-        : __p_(__p) {}
-    _LIBCPP_INLINE_VISIBILITY _Sp operator()(const _Tp& __p, _Ap __x) const
-        {return (__p.*__p_)(__x);}
-};
-
-template <class _Sp, class _Tp>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-const_mem_fun_ref_t<_Sp,_Tp>
-mem_fun_ref(_Sp (_Tp::*__f)() const)
-    {return const_mem_fun_ref_t<_Sp,_Tp>(__f);}
-
-template <class _Sp, class _Tp, class _Ap>
-_LIBCPP_DEPRECATED_IN_CXX11 inline _LIBCPP_INLINE_VISIBILITY
-const_mem_fun1_ref_t<_Sp,_Tp,_Ap>
-mem_fun_ref(_Sp (_Tp::*__f)(_Ap) const)
-    {return const_mem_fun1_ref_t<_Sp,_Tp,_Ap>(__f);}
-#endif
-
-////////////////////////////////////////////////////////////////////////////////
-//                                MEMFUN
-//==============================================================================
-
-template <class _Tp>
-class __mem_fn
-    : public __weak_result_type<_Tp>
-{
-public:
-    // types
-    typedef _Tp type;
-private:
-    type __f_;
-
-public:
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    __mem_fn(type __f) _NOEXCEPT : __f_(__f) {}
-
-#ifndef _LIBCPP_CXX03_LANG
-    // invoke
-    template <class... _ArgTypes>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    typename __invoke_return<type, _ArgTypes...>::type
-    operator() (_ArgTypes&&... __args) const {
-        return _VSTD::__invoke(__f_, _VSTD::forward<_ArgTypes>(__args)...);
-    }
-#else
-
-    template <class _A0>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return0<type, _A0>::type
-    operator() (_A0& __a0) const {
-        return _VSTD::__invoke(__f_, __a0);
-    }
-
-    template <class _A0>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return0<type, _A0 const>::type
-    operator() (_A0 const& __a0) const {
-        return _VSTD::__invoke(__f_, __a0);
-    }
-
-    template <class _A0, class _A1>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return1<type, _A0, _A1>::type
-    operator() (_A0& __a0, _A1& __a1) const {
-        return _VSTD::__invoke(__f_, __a0, __a1);
-    }
-
-    template <class _A0, class _A1>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return1<type, _A0 const, _A1>::type
-    operator() (_A0 const& __a0, _A1& __a1) const {
-        return _VSTD::__invoke(__f_, __a0, __a1);
-    }
-
-    template <class _A0, class _A1>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return1<type, _A0, _A1 const>::type
-    operator() (_A0& __a0, _A1 const& __a1) const {
-        return _VSTD::__invoke(__f_, __a0, __a1);
-    }
-
-    template <class _A0, class _A1>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return1<type, _A0 const, _A1 const>::type
-    operator() (_A0 const& __a0, _A1 const& __a1) const {
-        return _VSTD::__invoke(__f_, __a0, __a1);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0, _A1, _A2>::type
-    operator() (_A0& __a0, _A1& __a1, _A2& __a2) const {
-        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0 const, _A1, _A2>::type
-    operator() (_A0 const& __a0, _A1& __a1, _A2& __a2) const {
-        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0, _A1 const, _A2>::type
-    operator() (_A0& __a0, _A1 const& __a1, _A2& __a2) const {
-        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0, _A1, _A2 const>::type
-    operator() (_A0& __a0, _A1& __a1, _A2 const& __a2) const {
-        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0 const, _A1 const, _A2>::type
-    operator() (_A0 const& __a0, _A1 const& __a1, _A2& __a2) const {
-        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0 const, _A1, _A2 const>::type
-    operator() (_A0 const& __a0, _A1& __a1, _A2 const& __a2) const {
-        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0, _A1 const, _A2 const>::type
-    operator() (_A0& __a0, _A1 const& __a1, _A2 const& __a2) const {
-        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
-    }
-
-    template <class _A0, class _A1, class _A2>
-    _LIBCPP_INLINE_VISIBILITY
-    typename __invoke_return2<type, _A0 const, _A1 const, _A2 const>::type
-    operator() (_A0 const& __a0, _A1 const& __a1, _A2 const& __a2) const {
-        return _VSTD::__invoke(__f_, __a0, __a1, __a2);
-    }
-#endif
-};
-
-template<class _Rp, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-__mem_fn<_Rp _Tp::*>
-mem_fn(_Rp _Tp::* __pm) _NOEXCEPT
-{
-    return __mem_fn<_Rp _Tp::*>(__pm);
-}
-
-////////////////////////////////////////////////////////////////////////////////
-//                                FUNCTION
-//==============================================================================
-
-// bad_function_call
-
-class _LIBCPP_EXCEPTION_ABI bad_function_call
-    : public exception
-{
-#ifdef _LIBCPP_ABI_BAD_FUNCTION_CALL_KEY_FUNCTION
-public:
-    virtual ~bad_function_call() _NOEXCEPT;
-
-    virtual const char* what() const _NOEXCEPT;
-#endif
-};
-
-_LIBCPP_NORETURN inline _LIBCPP_INLINE_VISIBILITY
-void __throw_bad_function_call()
-{
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    throw bad_function_call();
-#else
-    _VSTD::abort();
-#endif
-}
-
-#if defined(_LIBCPP_CXX03_LANG) && !defined(_LIBCPP_DISABLE_DEPRECATION_WARNINGS) && __has_attribute(deprecated)
-#   define _LIBCPP_DEPRECATED_CXX03_FUNCTION \
-        __attribute__((deprecated("Using std::function in C++03 is not supported anymore. Please upgrade to C++11 or later, or use a different type")))
-#else
-#   define _LIBCPP_DEPRECATED_CXX03_FUNCTION /* nothing */
-#endif
-
-template<class _Fp> class _LIBCPP_DEPRECATED_CXX03_FUNCTION _LIBCPP_TEMPLATE_VIS function; // undefined
-
-namespace __function
-{
-
-template<class _Rp>
-struct __maybe_derive_from_unary_function
-{
-};
-
-template<class _Rp, class _A1>
-struct __maybe_derive_from_unary_function<_Rp(_A1)>
-    : public unary_function<_A1, _Rp>
-{
-};
-
-template<class _Rp>
-struct __maybe_derive_from_binary_function
-{
-};
-
-template<class _Rp, class _A1, class _A2>
-struct __maybe_derive_from_binary_function<_Rp(_A1, _A2)>
-    : public binary_function<_A1, _A2, _Rp>
-{
-};
-
-template <class _Fp>
-_LIBCPP_INLINE_VISIBILITY
-bool __not_null(_Fp const&) { return true; }
-
-template <class _Fp>
-_LIBCPP_INLINE_VISIBILITY
-bool __not_null(_Fp* __ptr) { return __ptr; }
-
-template <class _Ret, class _Class>
-_LIBCPP_INLINE_VISIBILITY
-bool __not_null(_Ret _Class::*__ptr) { return __ptr; }
-
-template <class _Fp>
-_LIBCPP_INLINE_VISIBILITY
-bool __not_null(function<_Fp> const& __f) { return !!__f; }
-
-#ifdef _LIBCPP_HAS_EXTENSION_BLOCKS
-template <class _Rp, class ..._Args>
-_LIBCPP_INLINE_VISIBILITY
-bool __not_null(_Rp (^__p)(_Args...)) { return __p; }
-#endif
-
-} // namespace __function
-
-#ifndef _LIBCPP_CXX03_LANG
-
-namespace __function {
-
-// __alloc_func holds a functor and an allocator.
-
-template <class _Fp, class _Ap, class _FB> class __alloc_func;
-template <class _Fp, class _FB>
-class __default_alloc_func;
-
-template <class _Fp, class _Ap, class _Rp, class... _ArgTypes>
-class __alloc_func<_Fp, _Ap, _Rp(_ArgTypes...)>
-{
-    __compressed_pair<_Fp, _Ap> __f_;
-
-  public:
-    typedef _LIBCPP_NODEBUG_TYPE _Fp _Target;
-    typedef _LIBCPP_NODEBUG_TYPE _Ap _Alloc;
-
-    _LIBCPP_INLINE_VISIBILITY
-    const _Target& __target() const { return __f_.first(); }
-
-    // WIN32 APIs may define __allocator, so use __get_allocator instead.
-    _LIBCPP_INLINE_VISIBILITY
-    const _Alloc& __get_allocator() const { return __f_.second(); }
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __alloc_func(_Target&& __f)
-        : __f_(piecewise_construct, _VSTD::forward_as_tuple(_VSTD::move(__f)),
-               _VSTD::forward_as_tuple())
-    {
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __alloc_func(const _Target& __f, const _Alloc& __a)
-        : __f_(piecewise_construct, _VSTD::forward_as_tuple(__f),
-               _VSTD::forward_as_tuple(__a))
-    {
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __alloc_func(const _Target& __f, _Alloc&& __a)
-        : __f_(piecewise_construct, _VSTD::forward_as_tuple(__f),
-               _VSTD::forward_as_tuple(_VSTD::move(__a)))
-    {
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __alloc_func(_Target&& __f, _Alloc&& __a)
-        : __f_(piecewise_construct, _VSTD::forward_as_tuple(_VSTD::move(__f)),
-               _VSTD::forward_as_tuple(_VSTD::move(__a)))
-    {
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    _Rp operator()(_ArgTypes&&... __arg)
-    {
-        typedef __invoke_void_return_wrapper<_Rp> _Invoker;
-        return _Invoker::__call(__f_.first(),
-                                _VSTD::forward<_ArgTypes>(__arg)...);
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    __alloc_func* __clone() const
-    {
-        typedef allocator_traits<_Alloc> __alloc_traits;
-        typedef
-            typename __rebind_alloc_helper<__alloc_traits, __alloc_func>::type
-                _AA;
-        _AA __a(__f_.second());
-        typedef __allocator_destructor<_AA> _Dp;
-        unique_ptr<__alloc_func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1));
-        ::new ((void*)__hold.get()) __alloc_func(__f_.first(), _Alloc(__a));
-        return __hold.release();
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    void destroy() _NOEXCEPT { __f_.~__compressed_pair<_Target, _Alloc>(); }
-
-    static void __destroy_and_delete(__alloc_func* __f) {
-      typedef allocator_traits<_Alloc> __alloc_traits;
-      typedef typename __rebind_alloc_helper<__alloc_traits, __alloc_func>::type
-          _FunAlloc;
-      _FunAlloc __a(__f->__get_allocator());
-      __f->destroy();
-      __a.deallocate(__f, 1);
-    }
-};
-
-template <class _Fp, class _Rp, class... _ArgTypes>
-class __default_alloc_func<_Fp, _Rp(_ArgTypes...)> {
-  _Fp __f_;
-
-public:
-  typedef _LIBCPP_NODEBUG_TYPE _Fp _Target;
-
-  _LIBCPP_INLINE_VISIBILITY
-  const _Target& __target() const { return __f_; }
-
-  _LIBCPP_INLINE_VISIBILITY
-  explicit __default_alloc_func(_Target&& __f) : __f_(_VSTD::move(__f)) {}
-
-  _LIBCPP_INLINE_VISIBILITY
-  explicit __default_alloc_func(const _Target& __f) : __f_(__f) {}
-
-  _LIBCPP_INLINE_VISIBILITY
-  _Rp operator()(_ArgTypes&&... __arg) {
-    typedef __invoke_void_return_wrapper<_Rp> _Invoker;
-    return _Invoker::__call(__f_, _VSTD::forward<_ArgTypes>(__arg)...);
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  __default_alloc_func* __clone() const {
-      __builtin_new_allocator::__holder_t __hold =
-        __builtin_new_allocator::__allocate_type<__default_alloc_func>(1);
-    __default_alloc_func* __res =
-        ::new ((void*)__hold.get()) __default_alloc_func(__f_);
-    (void)__hold.release();
-    return __res;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  void destroy() _NOEXCEPT { __f_.~_Target(); }
-
-  static void __destroy_and_delete(__default_alloc_func* __f) {
-    __f->destroy();
-      __builtin_new_allocator::__deallocate_type<__default_alloc_func>(__f, 1);
-  }
-};
-
-// __base provides an abstract interface for copyable functors.
-
-template<class _Fp> class _LIBCPP_TEMPLATE_VIS __base;
-
-template<class _Rp, class ..._ArgTypes>
-class __base<_Rp(_ArgTypes...)>
-{
-    __base(const __base&);
-    __base& operator=(const __base&);
-public:
-    _LIBCPP_INLINE_VISIBILITY __base() {}
-    _LIBCPP_INLINE_VISIBILITY virtual ~__base() {}
-    virtual __base* __clone() const = 0;
-    virtual void __clone(__base*) const = 0;
-    virtual void destroy() _NOEXCEPT = 0;
-    virtual void destroy_deallocate() _NOEXCEPT = 0;
-    virtual _Rp operator()(_ArgTypes&& ...) = 0;
-#ifndef _LIBCPP_NO_RTTI
-    virtual const void* target(const type_info&) const _NOEXCEPT = 0;
-    virtual const std::type_info& target_type() const _NOEXCEPT = 0;
-#endif  // _LIBCPP_NO_RTTI
-};
-
-// __func implements __base for a given functor type.
-
-template<class _FD, class _Alloc, class _FB> class __func;
-
-template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
-class __func<_Fp, _Alloc, _Rp(_ArgTypes...)>
-    : public  __base<_Rp(_ArgTypes...)>
-{
-    __alloc_func<_Fp, _Alloc, _Rp(_ArgTypes...)> __f_;
-public:
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __func(_Fp&& __f)
-        : __f_(_VSTD::move(__f)) {}
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __func(const _Fp& __f, const _Alloc& __a)
-        : __f_(__f, __a) {}
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __func(const _Fp& __f, _Alloc&& __a)
-        : __f_(__f, _VSTD::move(__a)) {}
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __func(_Fp&& __f, _Alloc&& __a)
-        : __f_(_VSTD::move(__f), _VSTD::move(__a)) {}
-
-    virtual __base<_Rp(_ArgTypes...)>* __clone() const;
-    virtual void __clone(__base<_Rp(_ArgTypes...)>*) const;
-    virtual void destroy() _NOEXCEPT;
-    virtual void destroy_deallocate() _NOEXCEPT;
-    virtual _Rp operator()(_ArgTypes&&... __arg);
-#ifndef _LIBCPP_NO_RTTI
-    virtual const void* target(const type_info&) const _NOEXCEPT;
-    virtual const std::type_info& target_type() const _NOEXCEPT;
-#endif  // _LIBCPP_NO_RTTI
-};
-
-template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
-__base<_Rp(_ArgTypes...)>*
-__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::__clone() const
-{
-    typedef allocator_traits<_Alloc> __alloc_traits;
-    typedef typename __rebind_alloc_helper<__alloc_traits, __func>::type _Ap;
-    _Ap __a(__f_.__get_allocator());
-    typedef __allocator_destructor<_Ap> _Dp;
-    unique_ptr<__func, _Dp> __hold(__a.allocate(1), _Dp(__a, 1));
-    ::new ((void*)__hold.get()) __func(__f_.__target(), _Alloc(__a));
-    return __hold.release();
-}
-
-template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
-void
-__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::__clone(__base<_Rp(_ArgTypes...)>* __p) const
-{
-    ::new ((void*)__p) __func(__f_.__target(), __f_.__get_allocator());
-}
-
-template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
-void
-__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::destroy() _NOEXCEPT
-{
-    __f_.destroy();
-}
-
-template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
-void
-__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::destroy_deallocate() _NOEXCEPT
-{
-    typedef allocator_traits<_Alloc> __alloc_traits;
-    typedef typename __rebind_alloc_helper<__alloc_traits, __func>::type _Ap;
-    _Ap __a(__f_.__get_allocator());
-    __f_.destroy();
-    __a.deallocate(this, 1);
-}
-
-template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
-_Rp
-__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::operator()(_ArgTypes&& ... __arg)
-{
-    return __f_(_VSTD::forward<_ArgTypes>(__arg)...);
-}
-
-#ifndef _LIBCPP_NO_RTTI
-
-template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
-const void*
-__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::target(const type_info& __ti) const _NOEXCEPT
-{
-    if (__ti == typeid(_Fp))
-        return &__f_.__target();
-    return nullptr;
-}
-
-template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes>
-const std::type_info&
-__func<_Fp, _Alloc, _Rp(_ArgTypes...)>::target_type() const _NOEXCEPT
-{
-    return typeid(_Fp);
-}
-
-#endif  // _LIBCPP_NO_RTTI
-
-// __value_func creates a value-type from a __func.
-
-template <class _Fp> class __value_func;
-
-template <class _Rp, class... _ArgTypes> class __value_func<_Rp(_ArgTypes...)>
-{
-    typename aligned_storage<3 * sizeof(void*)>::type __buf_;
-
-    typedef __base<_Rp(_ArgTypes...)> __func;
-    __func* __f_;
-
-    _LIBCPP_NO_CFI static __func* __as_base(void* p)
-    {
-        return reinterpret_cast<__func*>(p);
-    }
-
-  public:
-    _LIBCPP_INLINE_VISIBILITY
-    __value_func() _NOEXCEPT : __f_(nullptr) {}
-
-    template <class _Fp, class _Alloc>
-    _LIBCPP_INLINE_VISIBILITY __value_func(_Fp&& __f, const _Alloc& __a)
-        : __f_(nullptr)
-    {
-        typedef allocator_traits<_Alloc> __alloc_traits;
-        typedef __function::__func<_Fp, _Alloc, _Rp(_ArgTypes...)> _Fun;
-        typedef typename __rebind_alloc_helper<__alloc_traits, _Fun>::type
-            _FunAlloc;
-
-        if (__function::__not_null(__f))
-        {
-            _FunAlloc __af(__a);
-            if (sizeof(_Fun) <= sizeof(__buf_) &&
-                is_nothrow_copy_constructible<_Fp>::value &&
-                is_nothrow_copy_constructible<_FunAlloc>::value)
-            {
-                __f_ =
-                    ::new ((void*)&__buf_) _Fun(_VSTD::move(__f), _Alloc(__af));
-            }
-            else
-            {
-                typedef __allocator_destructor<_FunAlloc> _Dp;
-                unique_ptr<__func, _Dp> __hold(__af.allocate(1), _Dp(__af, 1));
-                ::new ((void*)__hold.get()) _Fun(_VSTD::move(__f), _Alloc(__a));
-                __f_ = __hold.release();
-            }
-        }
-    }
-
-    template <class _Fp,
-        class = typename enable_if<!is_same<typename decay<_Fp>::type, __value_func>::value>::type>
-    _LIBCPP_INLINE_VISIBILITY explicit __value_func(_Fp&& __f)
-        : __value_func(_VSTD::forward<_Fp>(__f), allocator<_Fp>()) {}
-
-    _LIBCPP_INLINE_VISIBILITY
-    __value_func(const __value_func& __f)
-    {
-        if (__f.__f_ == nullptr)
-            __f_ = nullptr;
-        else if ((void*)__f.__f_ == &__f.__buf_)
-        {
-            __f_ = __as_base(&__buf_);
-            __f.__f_->__clone(__f_);
-        }
-        else
-            __f_ = __f.__f_->__clone();
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    __value_func(__value_func&& __f) _NOEXCEPT
-    {
-        if (__f.__f_ == nullptr)
-            __f_ = nullptr;
-        else if ((void*)__f.__f_ == &__f.__buf_)
-        {
-            __f_ = __as_base(&__buf_);
-            __f.__f_->__clone(__f_);
-        }
-        else
-        {
-            __f_ = __f.__f_;
-            __f.__f_ = nullptr;
-        }
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    ~__value_func()
-    {
-        if ((void*)__f_ == &__buf_)
-            __f_->destroy();
-        else if (__f_)
-            __f_->destroy_deallocate();
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    __value_func& operator=(__value_func&& __f)
-    {
-        *this = nullptr;
-        if (__f.__f_ == nullptr)
-            __f_ = nullptr;
-        else if ((void*)__f.__f_ == &__f.__buf_)
-        {
-            __f_ = __as_base(&__buf_);
-            __f.__f_->__clone(__f_);
-        }
-        else
-        {
-            __f_ = __f.__f_;
-            __f.__f_ = nullptr;
-        }
-        return *this;
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    __value_func& operator=(nullptr_t)
-    {
-        __func* __f = __f_;
-        __f_ = nullptr;
-        if ((void*)__f == &__buf_)
-            __f->destroy();
-        else if (__f)
-            __f->destroy_deallocate();
-        return *this;
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    _Rp operator()(_ArgTypes&&... __args) const
-    {
-        if (__f_ == nullptr)
-            __throw_bad_function_call();
-        return (*__f_)(_VSTD::forward<_ArgTypes>(__args)...);
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    void swap(__value_func& __f) _NOEXCEPT
-    {
-        if (&__f == this)
-            return;
-        if ((void*)__f_ == &__buf_ && (void*)__f.__f_ == &__f.__buf_)
-        {
-            typename aligned_storage<sizeof(__buf_)>::type __tempbuf;
-            __func* __t = __as_base(&__tempbuf);
-            __f_->__clone(__t);
-            __f_->destroy();
-            __f_ = nullptr;
-            __f.__f_->__clone(__as_base(&__buf_));
-            __f.__f_->destroy();
-            __f.__f_ = nullptr;
-            __f_ = __as_base(&__buf_);
-            __t->__clone(__as_base(&__f.__buf_));
-            __t->destroy();
-            __f.__f_ = __as_base(&__f.__buf_);
-        }
-        else if ((void*)__f_ == &__buf_)
-        {
-            __f_->__clone(__as_base(&__f.__buf_));
-            __f_->destroy();
-            __f_ = __f.__f_;
-            __f.__f_ = __as_base(&__f.__buf_);
-        }
-        else if ((void*)__f.__f_ == &__f.__buf_)
-        {
-            __f.__f_->__clone(__as_base(&__buf_));
-            __f.__f_->destroy();
-            __f.__f_ = __f_;
-            __f_ = __as_base(&__buf_);
-        }
-        else
-            _VSTD::swap(__f_, __f.__f_);
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_EXPLICIT operator bool() const _NOEXCEPT { return __f_ != nullptr; }
-
-#ifndef _LIBCPP_NO_RTTI
-    _LIBCPP_INLINE_VISIBILITY
-    const std::type_info& target_type() const _NOEXCEPT
-    {
-        if (__f_ == nullptr)
-            return typeid(void);
-        return __f_->target_type();
-    }
-
-    template <typename _Tp>
-    _LIBCPP_INLINE_VISIBILITY const _Tp* target() const _NOEXCEPT
-    {
-        if (__f_ == nullptr)
-            return nullptr;
-        return (const _Tp*)__f_->target(typeid(_Tp));
-    }
-#endif // _LIBCPP_NO_RTTI
-};
-
-// Storage for a functor object, to be used with __policy to manage copy and
-// destruction.
-union __policy_storage
-{
-    mutable char __small[sizeof(void*) * 2];
-    void* __large;
-};
-
-// True if _Fun can safely be held in __policy_storage.__small.
-template <typename _Fun>
-struct __use_small_storage
-    : public _VSTD::integral_constant<
-          bool, sizeof(_Fun) <= sizeof(__policy_storage) &&
-                    _LIBCPP_ALIGNOF(_Fun) <= _LIBCPP_ALIGNOF(__policy_storage) &&
-                    _VSTD::is_trivially_copy_constructible<_Fun>::value &&
-                    _VSTD::is_trivially_destructible<_Fun>::value> {};
-
-// Policy contains information about how to copy, destroy, and move the
-// underlying functor. You can think of it as a vtable of sorts.
-struct __policy
-{
-    // Used to copy or destroy __large values. null for trivial objects.
-    void* (*const __clone)(const void*);
-    void (*const __destroy)(void*);
-
-    // True if this is the null policy (no value).
-    const bool __is_null;
-
-    // The target type. May be null if RTTI is disabled.
-    const std::type_info* const __type_info;
-
-    // Returns a pointer to a static policy object suitable for the functor
-    // type.
-    template <typename _Fun>
-    _LIBCPP_INLINE_VISIBILITY static const __policy* __create()
-    {
-        return __choose_policy<_Fun>(__use_small_storage<_Fun>());
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    static const __policy* __create_empty()
-    {
-        static const _LIBCPP_CONSTEXPR __policy __policy_ = {nullptr, nullptr,
-                                                             true,
-#ifndef _LIBCPP_NO_RTTI
-                                                             &typeid(void)
-#else
-                                                             nullptr
-#endif
-        };
-        return &__policy_;
-    }
-
-  private:
-    template <typename _Fun> static void* __large_clone(const void* __s)
-    {
-        const _Fun* __f = static_cast<const _Fun*>(__s);
-        return __f->__clone();
-    }
-
-    template <typename _Fun>
-    static void __large_destroy(void* __s) {
-      _Fun::__destroy_and_delete(static_cast<_Fun*>(__s));
-    }
-
-    template <typename _Fun>
-    _LIBCPP_INLINE_VISIBILITY static const __policy*
-    __choose_policy(/* is_small = */ false_type) {
-      static const _LIBCPP_CONSTEXPR __policy __policy_ = {
-          &__large_clone<_Fun>, &__large_destroy<_Fun>, false,
-#ifndef _LIBCPP_NO_RTTI
-          &typeid(typename _Fun::_Target)
-#else
-          nullptr
-#endif
-      };
-        return &__policy_;
-    }
-
-    template <typename _Fun>
-    _LIBCPP_INLINE_VISIBILITY static const __policy*
-        __choose_policy(/* is_small = */ true_type)
-    {
-        static const _LIBCPP_CONSTEXPR __policy __policy_ = {
-            nullptr, nullptr, false,
-#ifndef _LIBCPP_NO_RTTI
-            &typeid(typename _Fun::_Target)
-#else
-            nullptr
-#endif
-        };
-        return &__policy_;
-    }
-};
-
-// Used to choose between perfect forwarding or pass-by-value. Pass-by-value is
-// faster for types that can be passed in registers.
-template <typename _Tp>
-using __fast_forward =
-    typename _VSTD::conditional<_VSTD::is_scalar<_Tp>::value, _Tp, _Tp&&>::type;
-
-// __policy_invoker calls an instance of __alloc_func held in __policy_storage.
-
-template <class _Fp> struct __policy_invoker;
-
-template <class _Rp, class... _ArgTypes>
-struct __policy_invoker<_Rp(_ArgTypes...)>
-{
-    typedef _Rp (*__Call)(const __policy_storage*,
-                          __fast_forward<_ArgTypes>...);
-
-    __Call __call_;
-
-    // Creates an invoker that throws bad_function_call.
-    _LIBCPP_INLINE_VISIBILITY
-    __policy_invoker() : __call_(&__call_empty) {}
-
-    // Creates an invoker that calls the given instance of __func.
-    template <typename _Fun>
-    _LIBCPP_INLINE_VISIBILITY static __policy_invoker __create()
-    {
-        return __policy_invoker(&__call_impl<_Fun>);
-    }
-
-  private:
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __policy_invoker(__Call __c) : __call_(__c) {}
-
-    static _Rp __call_empty(const __policy_storage*,
-                            __fast_forward<_ArgTypes>...)
-    {
-        __throw_bad_function_call();
-    }
-
-    template <typename _Fun>
-    static _Rp __call_impl(const __policy_storage* __buf,
-                           __fast_forward<_ArgTypes>... __args)
-    {
-        _Fun* __f = reinterpret_cast<_Fun*>(__use_small_storage<_Fun>::value
-                                                ? &__buf->__small
-                                                : __buf->__large);
-        return (*__f)(_VSTD::forward<_ArgTypes>(__args)...);
-    }
-};
-
-// __policy_func uses a __policy and __policy_invoker to create a type-erased,
-// copyable functor.
-
-template <class _Fp> class __policy_func;
-
-template <class _Rp, class... _ArgTypes> class __policy_func<_Rp(_ArgTypes...)>
-{
-    // Inline storage for small objects.
-    __policy_storage __buf_;
-
-    // Calls the value stored in __buf_. This could technically be part of
-    // policy, but storing it here eliminates a level of indirection inside
-    // operator().
-    typedef __function::__policy_invoker<_Rp(_ArgTypes...)> __invoker;
-    __invoker __invoker_;
-
-    // The policy that describes how to move / copy / destroy __buf_. Never
-    // null, even if the function is empty.
-    const __policy* __policy_;
-
-  public:
-    _LIBCPP_INLINE_VISIBILITY
-    __policy_func() : __policy_(__policy::__create_empty()) {}
-
-    template <class _Fp, class _Alloc>
-    _LIBCPP_INLINE_VISIBILITY __policy_func(_Fp&& __f, const _Alloc& __a)
-        : __policy_(__policy::__create_empty())
-    {
-        typedef __alloc_func<_Fp, _Alloc, _Rp(_ArgTypes...)> _Fun;
-        typedef allocator_traits<_Alloc> __alloc_traits;
-        typedef typename __rebind_alloc_helper<__alloc_traits, _Fun>::type
-            _FunAlloc;
-
-        if (__function::__not_null(__f))
-        {
-            __invoker_ = __invoker::template __create<_Fun>();
-            __policy_ = __policy::__create<_Fun>();
-
-            _FunAlloc __af(__a);
-            if (__use_small_storage<_Fun>())
-            {
-                ::new ((void*)&__buf_.__small)
-                    _Fun(_VSTD::move(__f), _Alloc(__af));
-            }
-            else
-            {
-                typedef __allocator_destructor<_FunAlloc> _Dp;
-                unique_ptr<_Fun, _Dp> __hold(__af.allocate(1), _Dp(__af, 1));
-                ::new ((void*)__hold.get())
-                    _Fun(_VSTD::move(__f), _Alloc(__af));
-                __buf_.__large = __hold.release();
-            }
-        }
-    }
-
-    template <class _Fp, class = typename enable_if<!is_same<typename decay<_Fp>::type, __policy_func>::value>::type>
-    _LIBCPP_INLINE_VISIBILITY explicit __policy_func(_Fp&& __f)
-        : __policy_(__policy::__create_empty()) {
-      typedef __default_alloc_func<_Fp, _Rp(_ArgTypes...)> _Fun;
-
-      if (__function::__not_null(__f)) {
-        __invoker_ = __invoker::template __create<_Fun>();
-        __policy_ = __policy::__create<_Fun>();
-        if (__use_small_storage<_Fun>()) {
-          ::new ((void*)&__buf_.__small) _Fun(_VSTD::move(__f));
-        } else {
-          __builtin_new_allocator::__holder_t __hold =
-              __builtin_new_allocator::__allocate_type<_Fun>(1);
-          __buf_.__large = ::new ((void*)__hold.get()) _Fun(_VSTD::move(__f));
-          (void)__hold.release();
-        }
-      }
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    __policy_func(const __policy_func& __f)
-        : __buf_(__f.__buf_), __invoker_(__f.__invoker_),
-          __policy_(__f.__policy_)
-    {
-        if (__policy_->__clone)
-            __buf_.__large = __policy_->__clone(__f.__buf_.__large);
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    __policy_func(__policy_func&& __f)
-        : __buf_(__f.__buf_), __invoker_(__f.__invoker_),
-          __policy_(__f.__policy_)
-    {
-        if (__policy_->__destroy)
-        {
-            __f.__policy_ = __policy::__create_empty();
-            __f.__invoker_ = __invoker();
-        }
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    ~__policy_func()
-    {
-        if (__policy_->__destroy)
-            __policy_->__destroy(__buf_.__large);
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    __policy_func& operator=(__policy_func&& __f)
-    {
-        *this = nullptr;
-        __buf_ = __f.__buf_;
-        __invoker_ = __f.__invoker_;
-        __policy_ = __f.__policy_;
-        __f.__policy_ = __policy::__create_empty();
-        __f.__invoker_ = __invoker();
-        return *this;
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    __policy_func& operator=(nullptr_t)
-    {
-        const __policy* __p = __policy_;
-        __policy_ = __policy::__create_empty();
-        __invoker_ = __invoker();
-        if (__p->__destroy)
-            __p->__destroy(__buf_.__large);
-        return *this;
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    _Rp operator()(_ArgTypes&&... __args) const
-    {
-        return __invoker_.__call_(_VSTD::addressof(__buf_),
-                                  _VSTD::forward<_ArgTypes>(__args)...);
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    void swap(__policy_func& __f)
-    {
-        _VSTD::swap(__invoker_, __f.__invoker_);
-        _VSTD::swap(__policy_, __f.__policy_);
-        _VSTD::swap(__buf_, __f.__buf_);
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit operator bool() const _NOEXCEPT
-    {
-        return !__policy_->__is_null;
-    }
-
-#ifndef _LIBCPP_NO_RTTI
-    _LIBCPP_INLINE_VISIBILITY
-    const std::type_info& target_type() const _NOEXCEPT
-    {
-        return *__policy_->__type_info;
-    }
-
-    template <typename _Tp>
-    _LIBCPP_INLINE_VISIBILITY const _Tp* target() const _NOEXCEPT
-    {
-        if (__policy_->__is_null || typeid(_Tp) != *__policy_->__type_info)
-            return nullptr;
-        if (__policy_->__clone) // Out of line storage.
-            return reinterpret_cast<const _Tp*>(__buf_.__large);
-        else
-            return reinterpret_cast<const _Tp*>(&__buf_.__small);
-    }
-#endif // _LIBCPP_NO_RTTI
-};
-
-#if defined(_LIBCPP_HAS_BLOCKS_RUNTIME) && !defined(_LIBCPP_HAS_OBJC_ARC)
-
-extern "C" void *_Block_copy(const void *);
-extern "C" void _Block_release(const void *);
-
-template<class _Rp1, class ..._ArgTypes1, class _Alloc, class _Rp, class ..._ArgTypes>
-class __func<_Rp1(^)(_ArgTypes1...), _Alloc, _Rp(_ArgTypes...)>
-    : public  __base<_Rp(_ArgTypes...)>
-{
-    typedef _Rp1(^__block_type)(_ArgTypes1...);
-    __block_type __f_;
-
-public:
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __func(__block_type const& __f)
-        : __f_(reinterpret_cast<__block_type>(__f ? _Block_copy(__f) : nullptr))
-    { }
-
-    // [TODO] add && to save on a retain
-
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __func(__block_type __f, const _Alloc& /* unused */)
-        : __f_(reinterpret_cast<__block_type>(__f ? _Block_copy(__f) : nullptr))
-    { }
-
-    virtual __base<_Rp(_ArgTypes...)>* __clone() const {
-        _LIBCPP_ASSERT(false,
-            "Block pointers are just pointers, so they should always fit into "
-            "std::function's small buffer optimization. This function should "
-            "never be invoked.");
-        return nullptr;
-    }
-
-    virtual void __clone(__base<_Rp(_ArgTypes...)>* __p) const {
-        ::new ((void*)__p) __func(__f_);
-    }
-
-    virtual void destroy() _NOEXCEPT {
-        if (__f_)
-            _Block_release(__f_);
-        __f_ = 0;
-    }
-
-    virtual void destroy_deallocate() _NOEXCEPT {
-        _LIBCPP_ASSERT(false,
-            "Block pointers are just pointers, so they should always fit into "
-            "std::function's small buffer optimization. This function should "
-            "never be invoked.");
-    }
-
-    virtual _Rp operator()(_ArgTypes&& ... __arg) {
-        return _VSTD::__invoke(__f_, _VSTD::forward<_ArgTypes>(__arg)...);
-    }
-
-#ifndef _LIBCPP_NO_RTTI
-    virtual const void* target(type_info const& __ti) const _NOEXCEPT {
-        if (__ti == typeid(__func::__block_type))
-            return &__f_;
-        return (const void*)nullptr;
-    }
-
-    virtual const std::type_info& target_type() const _NOEXCEPT {
-        return typeid(__func::__block_type);
-    }
-#endif  // _LIBCPP_NO_RTTI
-};
-
-#endif  // _LIBCPP_HAS_EXTENSION_BLOCKS && !_LIBCPP_HAS_OBJC_ARC
-
-}  // __function
-
-template<class _Rp, class ..._ArgTypes>
-class _LIBCPP_TEMPLATE_VIS function<_Rp(_ArgTypes...)>
-    : public __function::__maybe_derive_from_unary_function<_Rp(_ArgTypes...)>,
-      public __function::__maybe_derive_from_binary_function<_Rp(_ArgTypes...)>
-{
-#ifndef _LIBCPP_ABI_OPTIMIZED_FUNCTION
-    typedef __function::__value_func<_Rp(_ArgTypes...)> __func;
-#else
-    typedef __function::__policy_func<_Rp(_ArgTypes...)> __func;
-#endif
-
-    __func __f_;
-
-    template <class _Fp, bool = _And<
-        _IsNotSame<__uncvref_t<_Fp>, function>,
-        __invokable<_Fp, _ArgTypes...>
-    >::value>
-    struct __callable;
-    template <class _Fp>
-        struct __callable<_Fp, true>
-        {
-            static const bool value = is_void<_Rp>::value ||
-                __is_core_convertible<typename __invoke_of<_Fp, _ArgTypes...>::type,
-                                      _Rp>::value;
-        };
-    template <class _Fp>
-        struct __callable<_Fp, false>
-        {
-            static const bool value = false;
-        };
-
-  template <class _Fp>
-  using _EnableIfLValueCallable = typename enable_if<__callable<_Fp&>::value>::type;
-public:
-    typedef _Rp result_type;
-
-    // construct/copy/destroy:
-    _LIBCPP_INLINE_VISIBILITY
-    function() _NOEXCEPT { }
-    _LIBCPP_INLINE_VISIBILITY
-    function(nullptr_t) _NOEXCEPT {}
-    function(const function&);
-    function(function&&) _NOEXCEPT;
-    template<class _Fp, class = _EnableIfLValueCallable<_Fp>>
-    function(_Fp);
-
-#if _LIBCPP_STD_VER <= 14
-    template<class _Alloc>
-      _LIBCPP_INLINE_VISIBILITY
-      function(allocator_arg_t, const _Alloc&) _NOEXCEPT {}
-    template<class _Alloc>
-      _LIBCPP_INLINE_VISIBILITY
-      function(allocator_arg_t, const _Alloc&, nullptr_t) _NOEXCEPT {}
-    template<class _Alloc>
-      function(allocator_arg_t, const _Alloc&, const function&);
-    template<class _Alloc>
-      function(allocator_arg_t, const _Alloc&, function&&);
-    template<class _Fp, class _Alloc, class = _EnableIfLValueCallable<_Fp>>
-      function(allocator_arg_t, const _Alloc& __a, _Fp __f);
-#endif
-
-    function& operator=(const function&);
-    function& operator=(function&&) _NOEXCEPT;
-    function& operator=(nullptr_t) _NOEXCEPT;
-    template<class _Fp, class = _EnableIfLValueCallable<typename decay<_Fp>::type>>
-    function& operator=(_Fp&&);
-
-    ~function();
-
-    // function modifiers:
-    void swap(function&) _NOEXCEPT;
-
-#if _LIBCPP_STD_VER <= 14
-    template<class _Fp, class _Alloc>
-      _LIBCPP_INLINE_VISIBILITY
-      void assign(_Fp&& __f, const _Alloc& __a)
-        {function(allocator_arg, __a, _VSTD::forward<_Fp>(__f)).swap(*this);}
-#endif
-
-    // function capacity:
-    _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_EXPLICIT operator bool() const _NOEXCEPT {
-      return static_cast<bool>(__f_);
-    }
-
-    // deleted overloads close possible hole in the type system
-    template<class _R2, class... _ArgTypes2>
-      bool operator==(const function<_R2(_ArgTypes2...)>&) const = delete;
-    template<class _R2, class... _ArgTypes2>
-      bool operator!=(const function<_R2(_ArgTypes2...)>&) const = delete;
-public:
-    // function invocation:
-    _Rp operator()(_ArgTypes...) const;
-
-#ifndef _LIBCPP_NO_RTTI
-    // function target access:
-    const std::type_info& target_type() const _NOEXCEPT;
-    template <typename _Tp> _Tp* target() _NOEXCEPT;
-    template <typename _Tp> const _Tp* target() const _NOEXCEPT;
-#endif  // _LIBCPP_NO_RTTI
-};
-
-#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
-template<class _Rp, class ..._Ap>
-function(_Rp(*)(_Ap...)) -> function<_Rp(_Ap...)>;
-
-template<class _Fp>
-struct __strip_signature;
-
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...)> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) const> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) volatile> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) const volatile> { using type = _Rp(_Ap...); };
-
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) &> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) const &> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) volatile &> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) const volatile &> { using type = _Rp(_Ap...); };
-
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) noexcept> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) const noexcept> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) volatile noexcept> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) const volatile noexcept> { using type = _Rp(_Ap...); };
-
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) & noexcept> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) const & noexcept> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) volatile & noexcept> { using type = _Rp(_Ap...); };
-template<class _Rp, class _Gp, class ..._Ap>
-struct __strip_signature<_Rp (_Gp::*) (_Ap...) const volatile & noexcept> { using type = _Rp(_Ap...); };
-
-template<class _Fp, class _Stripped = typename __strip_signature<decltype(&_Fp::operator())>::type>
-function(_Fp) -> function<_Stripped>;
-#endif // !_LIBCPP_HAS_NO_DEDUCTION_GUIDES
-
-template<class _Rp, class ..._ArgTypes>
-function<_Rp(_ArgTypes...)>::function(const function& __f) : __f_(__f.__f_) {}
-
-#if _LIBCPP_STD_VER <= 14
-template<class _Rp, class ..._ArgTypes>
-template <class _Alloc>
-function<_Rp(_ArgTypes...)>::function(allocator_arg_t, const _Alloc&,
-                                     const function& __f) : __f_(__f.__f_) {}
-#endif
-
-template <class _Rp, class... _ArgTypes>
-function<_Rp(_ArgTypes...)>::function(function&& __f) _NOEXCEPT
-    : __f_(_VSTD::move(__f.__f_)) {}
-
-#if _LIBCPP_STD_VER <= 14
-template<class _Rp, class ..._ArgTypes>
-template <class _Alloc>
-function<_Rp(_ArgTypes...)>::function(allocator_arg_t, const _Alloc&,
-                                      function&& __f)
-    : __f_(_VSTD::move(__f.__f_)) {}
-#endif
-
-template <class _Rp, class... _ArgTypes>
-template <class _Fp, class>
-function<_Rp(_ArgTypes...)>::function(_Fp __f) : __f_(_VSTD::move(__f)) {}
-
-#if _LIBCPP_STD_VER <= 14
-template <class _Rp, class... _ArgTypes>
-template <class _Fp, class _Alloc, class>
-function<_Rp(_ArgTypes...)>::function(allocator_arg_t, const _Alloc& __a,
-                                      _Fp __f)
-    : __f_(_VSTD::move(__f), __a) {}
-#endif
-
-template<class _Rp, class ..._ArgTypes>
-function<_Rp(_ArgTypes...)>&
-function<_Rp(_ArgTypes...)>::operator=(const function& __f)
-{
-    function(__f).swap(*this);
-    return *this;
-}
-
-template<class _Rp, class ..._ArgTypes>
-function<_Rp(_ArgTypes...)>&
-function<_Rp(_ArgTypes...)>::operator=(function&& __f) _NOEXCEPT
-{
-    __f_ = _VSTD::move(__f.__f_);
-    return *this;
-}
-
-template<class _Rp, class ..._ArgTypes>
-function<_Rp(_ArgTypes...)>&
-function<_Rp(_ArgTypes...)>::operator=(nullptr_t) _NOEXCEPT
-{
-    __f_ = nullptr;
-    return *this;
-}
-
-template<class _Rp, class ..._ArgTypes>
-template <class _Fp, class>
-function<_Rp(_ArgTypes...)>&
-function<_Rp(_ArgTypes...)>::operator=(_Fp&& __f)
-{
-    function(_VSTD::forward<_Fp>(__f)).swap(*this);
-    return *this;
-}
-
-template<class _Rp, class ..._ArgTypes>
-function<_Rp(_ArgTypes...)>::~function() {}
-
-template<class _Rp, class ..._ArgTypes>
-void
-function<_Rp(_ArgTypes...)>::swap(function& __f) _NOEXCEPT
-{
-    __f_.swap(__f.__f_);
-}
-
-template<class _Rp, class ..._ArgTypes>
-_Rp
-function<_Rp(_ArgTypes...)>::operator()(_ArgTypes... __arg) const
-{
-    return __f_(_VSTD::forward<_ArgTypes>(__arg)...);
-}
-
-#ifndef _LIBCPP_NO_RTTI
-
-template<class _Rp, class ..._ArgTypes>
-const std::type_info&
-function<_Rp(_ArgTypes...)>::target_type() const _NOEXCEPT
-{
-    return __f_.target_type();
-}
-
-template<class _Rp, class ..._ArgTypes>
-template <typename _Tp>
-_Tp*
-function<_Rp(_ArgTypes...)>::target() _NOEXCEPT
-{
-    return (_Tp*)(__f_.template target<_Tp>());
-}
-
-template<class _Rp, class ..._ArgTypes>
-template <typename _Tp>
-const _Tp*
-function<_Rp(_ArgTypes...)>::target() const _NOEXCEPT
-{
-    return __f_.template target<_Tp>();
-}
-
-#endif  // _LIBCPP_NO_RTTI
-
-template <class _Rp, class... _ArgTypes>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator==(const function<_Rp(_ArgTypes...)>& __f, nullptr_t) _NOEXCEPT {return !__f;}
-
-template <class _Rp, class... _ArgTypes>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator==(nullptr_t, const function<_Rp(_ArgTypes...)>& __f) _NOEXCEPT {return !__f;}
-
-template <class _Rp, class... _ArgTypes>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(const function<_Rp(_ArgTypes...)>& __f, nullptr_t) _NOEXCEPT {return (bool)__f;}
-
-template <class _Rp, class... _ArgTypes>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(nullptr_t, const function<_Rp(_ArgTypes...)>& __f) _NOEXCEPT {return (bool)__f;}
-
-template <class _Rp, class... _ArgTypes>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-swap(function<_Rp(_ArgTypes...)>& __x, function<_Rp(_ArgTypes...)>& __y) _NOEXCEPT
-{return __x.swap(__y);}
-
-#else // _LIBCPP_CXX03_LANG
-
-#include <__functional_03>
-
-#endif
-
-////////////////////////////////////////////////////////////////////////////////
-//                                  BIND
-//==============================================================================
-
-template<class _Tp> struct __is_bind_expression : public false_type {};
-template<class _Tp> struct _LIBCPP_TEMPLATE_VIS is_bind_expression
-    : public __is_bind_expression<typename remove_cv<_Tp>::type> {};
-
-#if _LIBCPP_STD_VER > 14
-template <class _Tp>
-_LIBCPP_INLINE_VAR constexpr size_t is_bind_expression_v = is_bind_expression<_Tp>::value;
-#endif
-
-template<class _Tp> struct __is_placeholder : public integral_constant<int, 0> {};
-template<class _Tp> struct _LIBCPP_TEMPLATE_VIS is_placeholder
-    : public __is_placeholder<typename remove_cv<_Tp>::type> {};
-
-#if _LIBCPP_STD_VER > 14
-template <class _Tp>
-_LIBCPP_INLINE_VAR constexpr size_t is_placeholder_v = is_placeholder<_Tp>::value;
-#endif
-
-namespace placeholders
-{
-
-template <int _Np> struct __ph {};
-
-#if defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
-_LIBCPP_FUNC_VIS extern const __ph<1>   _1;
-_LIBCPP_FUNC_VIS extern const __ph<2>   _2;
-_LIBCPP_FUNC_VIS extern const __ph<3>   _3;
-_LIBCPP_FUNC_VIS extern const __ph<4>   _4;
-_LIBCPP_FUNC_VIS extern const __ph<5>   _5;
-_LIBCPP_FUNC_VIS extern const __ph<6>   _6;
-_LIBCPP_FUNC_VIS extern const __ph<7>   _7;
-_LIBCPP_FUNC_VIS extern const __ph<8>   _8;
-_LIBCPP_FUNC_VIS extern const __ph<9>   _9;
-_LIBCPP_FUNC_VIS extern const __ph<10> _10;
-#else
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<1>   _1{};
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<2>   _2{};
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<3>   _3{};
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<4>   _4{};
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<5>   _5{};
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<6>   _6{};
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<7>   _7{};
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<8>   _8{};
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<9>   _9{};
-/* _LIBCPP_INLINE_VAR */ constexpr __ph<10> _10{};
-#endif // defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
-
-}  // placeholders
-
-template<int _Np>
-struct __is_placeholder<placeholders::__ph<_Np> >
-    : public integral_constant<int, _Np> {};
-
-
-#ifndef _LIBCPP_CXX03_LANG
-
-template <class _Tp, class _Uj>
-inline _LIBCPP_INLINE_VISIBILITY
-_Tp&
-__mu(reference_wrapper<_Tp> __t, _Uj&)
-{
-    return __t.get();
-}
-
-template <class _Ti, class ..._Uj, size_t ..._Indx>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __invoke_of<_Ti&, _Uj...>::type
-__mu_expand(_Ti& __ti, tuple<_Uj...>& __uj, __tuple_indices<_Indx...>)
-{
-    return __ti(_VSTD::forward<_Uj>(_VSTD::get<_Indx>(__uj))...);
-}
-
-template <class _Ti, class ..._Uj>
-inline _LIBCPP_INLINE_VISIBILITY
-typename _EnableIf
-<
-    is_bind_expression<_Ti>::value,
-    __invoke_of<_Ti&, _Uj...>
->::type
-__mu(_Ti& __ti, tuple<_Uj...>& __uj)
-{
-    typedef typename __make_tuple_indices<sizeof...(_Uj)>::type __indices;
-    return _VSTD::__mu_expand(__ti, __uj, __indices());
-}
-
-template <bool IsPh, class _Ti, class _Uj>
-struct __mu_return2 {};
-
-template <class _Ti, class _Uj>
-struct __mu_return2<true, _Ti, _Uj>
-{
-    typedef typename tuple_element<is_placeholder<_Ti>::value - 1, _Uj>::type type;
-};
-
-template <class _Ti, class _Uj>
-inline _LIBCPP_INLINE_VISIBILITY
-typename enable_if
-<
-    0 < is_placeholder<_Ti>::value,
-    typename __mu_return2<0 < is_placeholder<_Ti>::value, _Ti, _Uj>::type
->::type
-__mu(_Ti&, _Uj& __uj)
-{
-    const size_t _Indx = is_placeholder<_Ti>::value - 1;
-    return _VSTD::forward<typename tuple_element<_Indx, _Uj>::type>(_VSTD::get<_Indx>(__uj));
-}
-
-template <class _Ti, class _Uj>
-inline _LIBCPP_INLINE_VISIBILITY
-typename enable_if
-<
-    !is_bind_expression<_Ti>::value &&
-    is_placeholder<_Ti>::value == 0 &&
-    !__is_reference_wrapper<_Ti>::value,
-    _Ti&
->::type
-__mu(_Ti& __ti, _Uj&)
-{
-    return __ti;
-}
-
-template <class _Ti, bool IsReferenceWrapper, bool IsBindEx, bool IsPh,
-          class _TupleUj>
-struct __mu_return_impl;
-
-template <bool _Invokable, class _Ti, class ..._Uj>
-struct __mu_return_invokable  // false
-{
-    typedef __nat type;
-};
-
-template <class _Ti, class ..._Uj>
-struct __mu_return_invokable<true, _Ti, _Uj...>
-{
-    typedef typename __invoke_of<_Ti&, _Uj...>::type type;
-};
-
-template <class _Ti, class ..._Uj>
-struct __mu_return_impl<_Ti, false, true, false, tuple<_Uj...> >
-    : public __mu_return_invokable<__invokable<_Ti&, _Uj...>::value, _Ti, _Uj...>
-{
-};
-
-template <class _Ti, class _TupleUj>
-struct __mu_return_impl<_Ti, false, false, true, _TupleUj>
-{
-    typedef typename tuple_element<is_placeholder<_Ti>::value - 1,
-                                   _TupleUj>::type&& type;
-};
-
-template <class _Ti, class _TupleUj>
-struct __mu_return_impl<_Ti, true, false, false, _TupleUj>
-{
-    typedef typename _Ti::type& type;
-};
-
-template <class _Ti, class _TupleUj>
-struct __mu_return_impl<_Ti, false, false, false, _TupleUj>
-{
-    typedef _Ti& type;
-};
-
-template <class _Ti, class _TupleUj>
-struct __mu_return
-    : public __mu_return_impl<_Ti,
-                              __is_reference_wrapper<_Ti>::value,
-                              is_bind_expression<_Ti>::value,
-                              0 < is_placeholder<_Ti>::value &&
-                              is_placeholder<_Ti>::value <= tuple_size<_TupleUj>::value,
-                              _TupleUj>
-{
-};
-
-template <class _Fp, class _BoundArgs, class _TupleUj>
-struct __is_valid_bind_return
-{
-    static const bool value = false;
-};
-
-template <class _Fp, class ..._BoundArgs, class _TupleUj>
-struct __is_valid_bind_return<_Fp, tuple<_BoundArgs...>, _TupleUj>
-{
-    static const bool value = __invokable<_Fp,
-                    typename __mu_return<_BoundArgs, _TupleUj>::type...>::value;
-};
-
-template <class _Fp, class ..._BoundArgs, class _TupleUj>
-struct __is_valid_bind_return<_Fp, const tuple<_BoundArgs...>, _TupleUj>
-{
-    static const bool value = __invokable<_Fp,
-                    typename __mu_return<const _BoundArgs, _TupleUj>::type...>::value;
-};
-
-template <class _Fp, class _BoundArgs, class _TupleUj,
-          bool = __is_valid_bind_return<_Fp, _BoundArgs, _TupleUj>::value>
-struct __bind_return;
-
-template <class _Fp, class ..._BoundArgs, class _TupleUj>
-struct __bind_return<_Fp, tuple<_BoundArgs...>, _TupleUj, true>
-{
-    typedef typename __invoke_of
-    <
-        _Fp&,
-        typename __mu_return
-        <
-            _BoundArgs,
-            _TupleUj
-        >::type...
-    >::type type;
-};
-
-template <class _Fp, class ..._BoundArgs, class _TupleUj>
-struct __bind_return<_Fp, const tuple<_BoundArgs...>, _TupleUj, true>
-{
-    typedef typename __invoke_of
-    <
-        _Fp&,
-        typename __mu_return
-        <
-            const _BoundArgs,
-            _TupleUj
-        >::type...
-    >::type type;
-};
-
-template <class _Fp, class _BoundArgs, size_t ..._Indx, class _Args>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __bind_return<_Fp, _BoundArgs, _Args>::type
-__apply_functor(_Fp& __f, _BoundArgs& __bound_args, __tuple_indices<_Indx...>,
-                _Args&& __args)
-{
-    return _VSTD::__invoke(__f, _VSTD::__mu(_VSTD::get<_Indx>(__bound_args), __args)...);
-}
-
-template<class _Fp, class ..._BoundArgs>
-class __bind
-    : public __weak_result_type<typename decay<_Fp>::type>
-{
-protected:
-    typedef typename decay<_Fp>::type _Fd;
-    typedef tuple<typename decay<_BoundArgs>::type...> _Td;
-private:
-    _Fd __f_;
-    _Td __bound_args_;
-
-    typedef typename __make_tuple_indices<sizeof...(_BoundArgs)>::type __indices;
-public:
-    template <class _Gp, class ..._BA,
-              class = typename enable_if
-                               <
-                                  is_constructible<_Fd, _Gp>::value &&
-                                  !is_same<typename remove_reference<_Gp>::type,
-                                           __bind>::value
-                               >::type>
-      _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-      explicit __bind(_Gp&& __f, _BA&& ...__bound_args)
-        : __f_(_VSTD::forward<_Gp>(__f)),
-          __bound_args_(_VSTD::forward<_BA>(__bound_args)...) {}
-
-    template <class ..._Args>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-        typename __bind_return<_Fd, _Td, tuple<_Args&&...> >::type
-        operator()(_Args&& ...__args)
-        {
-            return _VSTD::__apply_functor(__f_, __bound_args_, __indices(),
-                                  tuple<_Args&&...>(_VSTD::forward<_Args>(__args)...));
-        }
-
-    template <class ..._Args>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-        typename __bind_return<const _Fd, const _Td, tuple<_Args&&...> >::type
-        operator()(_Args&& ...__args) const
-        {
-            return _VSTD::__apply_functor(__f_, __bound_args_, __indices(),
-                                   tuple<_Args&&...>(_VSTD::forward<_Args>(__args)...));
-        }
-};
-
-template<class _Fp, class ..._BoundArgs>
-struct __is_bind_expression<__bind<_Fp, _BoundArgs...> > : public true_type {};
-
-template<class _Rp, class _Fp, class ..._BoundArgs>
-class __bind_r
-    : public __bind<_Fp, _BoundArgs...>
-{
-    typedef __bind<_Fp, _BoundArgs...> base;
-    typedef typename base::_Fd _Fd;
-    typedef typename base::_Td _Td;
-public:
-    typedef _Rp result_type;
-
-
-    template <class _Gp, class ..._BA,
-              class = typename enable_if
-                               <
-                                  is_constructible<_Fd, _Gp>::value &&
-                                  !is_same<typename remove_reference<_Gp>::type,
-                                           __bind_r>::value
-                               >::type>
-      _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-      explicit __bind_r(_Gp&& __f, _BA&& ...__bound_args)
-        : base(_VSTD::forward<_Gp>(__f),
-               _VSTD::forward<_BA>(__bound_args)...) {}
-
-    template <class ..._Args>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-        typename enable_if
-        <
-            is_convertible<typename __bind_return<_Fd, _Td, tuple<_Args&&...> >::type,
-                           result_type>::value || is_void<_Rp>::value,
-            result_type
-        >::type
-        operator()(_Args&& ...__args)
-        {
-            typedef __invoke_void_return_wrapper<_Rp> _Invoker;
-            return _Invoker::__call(static_cast<base&>(*this), _VSTD::forward<_Args>(__args)...);
-        }
-
-    template <class ..._Args>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-        typename enable_if
-        <
-            is_convertible<typename __bind_return<const _Fd, const _Td, tuple<_Args&&...> >::type,
-                           result_type>::value || is_void<_Rp>::value,
-            result_type
-        >::type
-        operator()(_Args&& ...__args) const
-        {
-            typedef __invoke_void_return_wrapper<_Rp> _Invoker;
-            return _Invoker::__call(static_cast<base const&>(*this), _VSTD::forward<_Args>(__args)...);
-        }
-};
-
-template<class _Rp, class _Fp, class ..._BoundArgs>
-struct __is_bind_expression<__bind_r<_Rp, _Fp, _BoundArgs...> > : public true_type {};
-
-template<class _Fp, class ..._BoundArgs>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-__bind<_Fp, _BoundArgs...>
-bind(_Fp&& __f, _BoundArgs&&... __bound_args)
-{
-    typedef __bind<_Fp, _BoundArgs...> type;
-    return type(_VSTD::forward<_Fp>(__f), _VSTD::forward<_BoundArgs>(__bound_args)...);
-}
-
-template<class _Rp, class _Fp, class ..._BoundArgs>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-__bind_r<_Rp, _Fp, _BoundArgs...>
-bind(_Fp&& __f, _BoundArgs&&... __bound_args)
-{
-    typedef __bind_r<_Rp, _Fp, _BoundArgs...> type;
-    return type(_VSTD::forward<_Fp>(__f), _VSTD::forward<_BoundArgs>(__bound_args)...);
-}
-
-#endif  // _LIBCPP_CXX03_LANG
-
-#if _LIBCPP_STD_VER > 14
-
-template <class _Fn, class ..._Args>
-_LIBCPP_CONSTEXPR_AFTER_CXX17 invoke_result_t<_Fn, _Args...>
-invoke(_Fn&& __f, _Args&&... __args)
-    noexcept(is_nothrow_invocable_v<_Fn, _Args...>)
-{
-    return _VSTD::__invoke(_VSTD::forward<_Fn>(__f), _VSTD::forward<_Args>(__args)...);
-}
-
-template <class _DecayFunc>
-class _LIBCPP_TEMPLATE_VIS __not_fn_imp {
-  _DecayFunc __fd;
-
-public:
-    __not_fn_imp() = delete;
-
-    template <class ..._Args>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    auto operator()(_Args&& ...__args) &
-            noexcept(noexcept(!_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...)))
-        -> decltype(          !_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...))
-        { return              !_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...); }
-
-    template <class ..._Args>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    auto operator()(_Args&& ...__args) &&
-            noexcept(noexcept(!_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...)))
-        -> decltype(          !_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...))
-        { return              !_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...); }
-
-    template <class ..._Args>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    auto operator()(_Args&& ...__args) const&
-            noexcept(noexcept(!_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...)))
-        -> decltype(          !_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...))
-        { return              !_VSTD::invoke(__fd, _VSTD::forward<_Args>(__args)...); }
-
-
-    template <class ..._Args>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    auto operator()(_Args&& ...__args) const&&
-            noexcept(noexcept(!_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...)))
-        -> decltype(          !_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...))
-        { return              !_VSTD::invoke(_VSTD::move(__fd), _VSTD::forward<_Args>(__args)...); }
-
-private:
-    template <class _RawFunc,
-              class = enable_if_t<!is_same<decay_t<_RawFunc>, __not_fn_imp>::value>>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    explicit __not_fn_imp(_RawFunc&& __rf)
-        : __fd(_VSTD::forward<_RawFunc>(__rf)) {}
-
-    template <class _RawFunc>
-    friend inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    __not_fn_imp<decay_t<_RawFunc>> not_fn(_RawFunc&&);
-};
-
-template <class _RawFunc>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-__not_fn_imp<decay_t<_RawFunc>> not_fn(_RawFunc&& __fn) {
-    return __not_fn_imp<decay_t<_RawFunc>>(_VSTD::forward<_RawFunc>(__fn));
-}
-
-#endif
-
-// struct hash<T*> in <memory>
-
-template <class _BinaryPredicate, class _ForwardIterator1, class _ForwardIterator2>
-pair<_ForwardIterator1, _ForwardIterator1> _LIBCPP_CONSTEXPR_AFTER_CXX11
-__search(_ForwardIterator1 __first1, _ForwardIterator1 __last1,
-         _ForwardIterator2 __first2, _ForwardIterator2 __last2, _BinaryPredicate __pred,
-         forward_iterator_tag, forward_iterator_tag)
-{
-    if (__first2 == __last2)
-        return _VSTD::make_pair(__first1, __first1);  // Everything matches an empty sequence
-    while (true)
-    {
-        // Find first element in sequence 1 that matchs *__first2, with a mininum of loop checks
-        while (true)
-        {
-            if (__first1 == __last1)  // return __last1 if no element matches *__first2
-                return _VSTD::make_pair(__last1, __last1);
-            if (__pred(*__first1, *__first2))
-                break;
-            ++__first1;
-        }
-        // *__first1 matches *__first2, now match elements after here
-        _ForwardIterator1 __m1 = __first1;
-        _ForwardIterator2 __m2 = __first2;
-        while (true)
-        {
-            if (++__m2 == __last2)  // If pattern exhausted, __first1 is the answer (works for 1 element pattern)
-                return _VSTD::make_pair(__first1, __m1);
-            if (++__m1 == __last1)  // Otherwise if source exhaused, pattern not found
-                return _VSTD::make_pair(__last1, __last1);
-            if (!__pred(*__m1, *__m2))  // if there is a mismatch, restart with a new __first1
-            {
-                ++__first1;
-                break;
-            }  // else there is a match, check next elements
-        }
-    }
-}
-
-template <class _BinaryPredicate, class _RandomAccessIterator1, class _RandomAccessIterator2>
-_LIBCPP_CONSTEXPR_AFTER_CXX11
-pair<_RandomAccessIterator1, _RandomAccessIterator1>
-__search(_RandomAccessIterator1 __first1, _RandomAccessIterator1 __last1,
-         _RandomAccessIterator2 __first2, _RandomAccessIterator2 __last2, _BinaryPredicate __pred,
-           random_access_iterator_tag, random_access_iterator_tag)
-{
-    typedef typename iterator_traits<_RandomAccessIterator1>::difference_type _D1;
-    typedef typename iterator_traits<_RandomAccessIterator2>::difference_type _D2;
-    // Take advantage of knowing source and pattern lengths.  Stop short when source is smaller than pattern
-    const _D2 __len2 = __last2 - __first2;
-    if (__len2 == 0)
-        return _VSTD::make_pair(__first1, __first1);
-    const _D1 __len1 = __last1 - __first1;
-    if (__len1 < __len2)
-        return _VSTD::make_pair(__last1, __last1);
-    const _RandomAccessIterator1 __s = __last1 - (__len2 - 1);  // Start of pattern match can't go beyond here
-
-    while (true)
-    {
-        while (true)
-        {
-            if (__first1 == __s)
-                return _VSTD::make_pair(__last1, __last1);
-            if (__pred(*__first1, *__first2))
-                break;
-            ++__first1;
-        }
-
-        _RandomAccessIterator1 __m1 = __first1;
-        _RandomAccessIterator2 __m2 = __first2;
-         while (true)
-         {
-             if (++__m2 == __last2)
-                 return _VSTD::make_pair(__first1, __first1 + __len2);
-             ++__m1;          // no need to check range on __m1 because __s guarantees we have enough source
-             if (!__pred(*__m1, *__m2))
-             {
-                 ++__first1;
-                 break;
-             }
-         }
-    }
-}
-
-#if _LIBCPP_STD_VER > 14
-
-// default searcher
-template<class _ForwardIterator, class _BinaryPredicate = equal_to<>>
-class _LIBCPP_TYPE_VIS default_searcher {
-public:
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    default_searcher(_ForwardIterator __f, _ForwardIterator __l,
-                       _BinaryPredicate __p = _BinaryPredicate())
-        : __first_(__f), __last_(__l), __pred_(__p) {}
-
-    template <typename _ForwardIterator2>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    pair<_ForwardIterator2, _ForwardIterator2>
-    operator () (_ForwardIterator2 __f, _ForwardIterator2 __l) const
-    {
-        return _VSTD::__search(__f, __l, __first_, __last_, __pred_,
-            typename _VSTD::iterator_traits<_ForwardIterator>::iterator_category(),
-            typename _VSTD::iterator_traits<_ForwardIterator2>::iterator_category());
-    }
-
-private:
-    _ForwardIterator __first_;
-    _ForwardIterator __last_;
-    _BinaryPredicate __pred_;
-    };
-
-#endif // _LIBCPP_STD_VER > 14
-
-#if _LIBCPP_STD_VER > 17
-template <class _Tp>
-using unwrap_reference_t = typename unwrap_reference<_Tp>::type;
-
-template <class _Tp>
-using unwrap_ref_decay_t = typename unwrap_ref_decay<_Tp>::type;
-#endif // > C++17
-
-template <class _Container, class _Predicate>
-inline typename _Container::size_type
-__libcpp_erase_if_container(_Container& __c, _Predicate __pred) {
-  typename _Container::size_type __old_size = __c.size();
-
-  const typename _Container::iterator __last = __c.end();
-  for (typename _Container::iterator __iter = __c.begin(); __iter != __last;) {
-    if (__pred(*__iter))
-      __iter = __c.erase(__iter);
-    else
-      ++__iter;
-  }
-
-  return __old_size - __c.size();
-}
-
-_LIBCPP_END_NAMESPACE_STD
-
-#endif  // _LIBCPP_FUNCTIONAL
+#endif // _LIBCPP_FUNCTIONAL
lib/libcxx/include/future
@@ -361,13 +361,18 @@ template <class R, class Alloc> struct uses_allocator<packaged_task<R>, Alloc>;
 
 */
 
-#include <__config>
 #include <__availability>
-#include <system_error>
-#include <memory>
+#include <__config>
+#include <__debug>
+#include <__memory/allocator_arg_t.h>
+#include <__memory/uses_allocator.h>
+#include <__utility/__decay_copy.h>
+#include <__utility/forward.h>
 #include <chrono>
 #include <exception>
+#include <memory>
 #include <mutex>
+#include <system_error>
 #include <thread>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -467,7 +472,7 @@ operator^=(launch& __x, launch __y)
     __x = __x ^ __y; return __x;
 }
 
-#endif  // !_LIBCPP_HAS_NO_STRONG_ENUMS
+#endif // !_LIBCPP_HAS_NO_STRONG_ENUMS
 
 //enum class future_status
 _LIBCPP_DECLARE_STRONG_ENUM(future_status)
@@ -501,9 +506,7 @@ class _LIBCPP_EXCEPTION_ABI _LIBCPP_AVAILABILITY_FUTURE_ERROR future_error
     error_code __ec_;
 public:
     future_error(error_code __ec);
-#if _LIBCPP_STD_VERS > 14
-    explicit future_error(future_errc _Ev) : logic_error(), __ec_(make_error_code(_Ev)) {}
-#endif
+
     _LIBCPP_INLINE_VISIBILITY
     const error_code& code() const _NOEXCEPT {return __ec_;}
 
@@ -862,7 +865,7 @@ __deferred_assoc_state<_Rp, _Fp>::__execute()
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         this->set_value(__func_());
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
@@ -870,7 +873,7 @@ __deferred_assoc_state<_Rp, _Fp>::__execute()
     {
         this->set_exception(current_exception());
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template <class _Fp>
@@ -903,7 +906,7 @@ __deferred_assoc_state<void, _Fp>::__execute()
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __func_();
         this->set_value();
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -912,7 +915,7 @@ __deferred_assoc_state<void, _Fp>::__execute()
     {
         this->set_exception(current_exception());
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template <class _Rp, class _Fp>
@@ -945,7 +948,7 @@ __async_assoc_state<_Rp, _Fp>::__execute()
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         this->set_value(__func_());
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
@@ -953,7 +956,7 @@ __async_assoc_state<_Rp, _Fp>::__execute()
     {
         this->set_exception(current_exception());
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template <class _Rp, class _Fp>
@@ -994,7 +997,7 @@ __async_assoc_state<void, _Fp>::__execute()
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __func_();
         this->set_value();
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -1003,7 +1006,7 @@ __async_assoc_state<void, _Fp>::__execute()
     {
         this->set_exception(current_exception());
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template <class _Fp>
@@ -1953,7 +1956,7 @@ packaged_task<_Rp(_ArgTypes...)>::operator()(_ArgTypes... __args)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __p_.set_value(__f_(_VSTD::forward<_ArgTypes>(__args)...));
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
@@ -1961,7 +1964,7 @@ packaged_task<_Rp(_ArgTypes...)>::operator()(_ArgTypes... __args)
     {
         __p_.set_exception(current_exception());
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template<class _Rp, class ..._ArgTypes>
@@ -1975,7 +1978,7 @@ packaged_task<_Rp(_ArgTypes...)>::make_ready_at_thread_exit(_ArgTypes... __args)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __p_.set_value_at_thread_exit(__f_(_VSTD::forward<_ArgTypes>(__args)...));
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
@@ -1983,7 +1986,7 @@ packaged_task<_Rp(_ArgTypes...)>::make_ready_at_thread_exit(_ArgTypes... __args)
     {
         __p_.set_exception_at_thread_exit(current_exception());
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template<class _Rp, class ..._ArgTypes>
@@ -2082,7 +2085,7 @@ packaged_task<void(_ArgTypes...)>::operator()(_ArgTypes... __args)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __f_(_VSTD::forward<_ArgTypes>(__args)...);
         __p_.set_value();
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2091,7 +2094,7 @@ packaged_task<void(_ArgTypes...)>::operator()(_ArgTypes... __args)
     {
         __p_.set_exception(current_exception());
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template<class ..._ArgTypes>
@@ -2105,7 +2108,7 @@ packaged_task<void(_ArgTypes...)>::make_ready_at_thread_exit(_ArgTypes... __args
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __f_(_VSTD::forward<_ArgTypes>(__args)...);
         __p_.set_value_at_thread_exit();
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2114,7 +2117,7 @@ packaged_task<void(_ArgTypes...)>::make_ready_at_thread_exit(_ArgTypes... __args
     {
         __p_.set_exception_at_thread_exit(current_exception());
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template<class ..._ArgTypes>
@@ -2126,10 +2129,10 @@ packaged_task<void(_ArgTypes...)>::reset()
     __p_ = promise<result_type>();
 }
 
-template <class _Callable>
+template <class _Rp, class... _ArgTypes>
 inline _LIBCPP_INLINE_VISIBILITY
 void
-swap(packaged_task<_Callable>& __x, packaged_task<_Callable>& __y) _NOEXCEPT
+swap(packaged_task<_Rp(_ArgTypes...)>& __x, packaged_task<_Rp(_ArgTypes...)>& __y) _NOEXCEPT
 {
     __x.swap(__y);
 }
@@ -2456,4 +2459,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 #endif // !_LIBCPP_HAS_NO_THREADS
 
-#endif  // _LIBCPP_FUTURE
+#endif // _LIBCPP_FUTURE
lib/libcxx/include/initializer_list
@@ -110,8 +110,8 @@ end(initializer_list<_Ep> __il) _NOEXCEPT
     return __il.end();
 }
 
-#endif  // !defined(_LIBCPP_CXX03_LANG)
+#endif // !defined(_LIBCPP_CXX03_LANG)
 
 }  // std
 
-#endif  // _LIBCPP_INITIALIZER_LIST
+#endif // _LIBCPP_INITIALIZER_LIST
lib/libcxx/include/inttypes.h
@@ -259,4 +259,4 @@ uintmax_t wcstoumax(const wchar_t* restrict nptr, wchar_t** restrict endptr, int
 
 #endif // __cplusplus
 
-#endif  // _LIBCPP_INTTYPES_H
+#endif // _LIBCPP_INTTYPES_H
lib/libcxx/include/iomanip
@@ -304,7 +304,7 @@ operator>>(basic_istream<_CharT, _Traits>& __is, const __iom_t7<_MoneyT>& __x)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         typename basic_istream<_CharT, _Traits>::sentry __s(__is);
         if (__s)
         {
@@ -321,7 +321,7 @@ operator>>(basic_istream<_CharT, _Traits>& __is, const __iom_t7<_MoneyT>& __x)
     {
         __is.__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return __is;
 }
 
@@ -364,7 +364,7 @@ operator<<(basic_ostream<_CharT, _Traits>& __os, const __iom_t8<_MoneyT>& __x)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         typename basic_ostream<_CharT, _Traits>::sentry __s(__os);
         if (__s)
         {
@@ -380,7 +380,7 @@ operator<<(basic_ostream<_CharT, _Traits>& __os, const __iom_t8<_MoneyT>& __x)
     {
         __os.__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return __os;
 }
 
@@ -423,7 +423,7 @@ operator>>(basic_istream<_CharT, _Traits>& __is, const __iom_t9<_CharT>& __x)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         typename basic_istream<_CharT, _Traits>::sentry __s(__is);
         if (__s)
         {
@@ -441,7 +441,7 @@ operator>>(basic_istream<_CharT, _Traits>& __is, const __iom_t9<_CharT>& __x)
     {
         __is.__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return __is;
 }
 
@@ -484,7 +484,7 @@ operator<<(basic_ostream<_CharT, _Traits>& __os, const __iom_t10<_CharT>& __x)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         typename basic_ostream<_CharT, _Traits>::sentry __s(__os);
         if (__s)
         {
@@ -501,7 +501,7 @@ operator<<(basic_ostream<_CharT, _Traits>& __os, const __iom_t10<_CharT>& __x)
     {
         __os.__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return __os;
 }
 
@@ -518,7 +518,7 @@ basic_ostream<_CharT, _Traits> &
 __quoted_output ( basic_ostream<_CharT, _Traits> &__os,
         _ForwardIterator __first, _ForwardIterator __last, _CharT __delim, _CharT __escape )
 {
-    _VSTD::basic_string<_CharT, _Traits> __str;
+    basic_string<_CharT, _Traits> __str;
     __str.push_back(__delim);
     for ( ; __first != __last; ++ __first )
     {
@@ -667,4 +667,4 @@ quoted (basic_string_view <_CharT, _Traits> __sv,
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_IOMANIP
+#endif // _LIBCPP_IOMANIP
lib/libcxx/include/ios
@@ -211,8 +211,8 @@ storage-class-specifier const error_category& iostream_category() noexcept;
 */
 
 #include <__config>
-#include <iosfwd>
 #include <__locale>
+#include <iosfwd>
 #include <system_error>
 
 #if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
@@ -591,13 +591,6 @@ ios_base::exceptions(iostate __iostate)
     clear(__rdstate_);
 }
 
-#if defined(_LIBCPP_CXX03_LANG)
-struct _LIBCPP_TYPE_VIS __cxx03_bool {
-  typedef void (__cxx03_bool::*__bool_type)();
-  void __true_value() {}
-};
-#endif
-
 template <class _CharT, class _Traits>
 class _LIBCPP_TEMPLATE_VIS basic_ios
     : public ios_base
@@ -614,17 +607,14 @@ public:
     static_assert((is_same<_CharT, typename traits_type::char_type>::value),
                   "traits_type::char_type must be the same type as CharT");
 
-  // __true_value will generate undefined references when linking unless
-  // we give it internal linkage.
-
-#if defined(_LIBCPP_CXX03_LANG)
+#ifdef _LIBCPP_CXX03_LANG
+    // Preserve the ability to compare with literal 0,
+    // and implicitly convert to bool, but not implicitly convert to int.
     _LIBCPP_INLINE_VISIBILITY
-    operator __cxx03_bool::__bool_type() const {
-        return !fail() ? &__cxx03_bool::__true_value : nullptr;
-    }
+    operator void*() const {return fail() ? nullptr : (void*)this;}
 #else
     _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_EXPLICIT operator bool() const {return !fail();}
+    explicit operator bool() const {return !fail();}
 #endif
 
     _LIBCPP_INLINE_VISIBILITY bool operator!() const    {return  fail();}
@@ -679,10 +669,8 @@ protected:
 
     _LIBCPP_INLINE_VISIBILITY
     void move(basic_ios& __rhs);
-#ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     void move(basic_ios&& __rhs) {move(__rhs);}
-#endif
     _LIBCPP_INLINE_VISIBILITY
     void swap(basic_ios& __rhs) _NOEXCEPT;
     _LIBCPP_INLINE_VISIBILITY
@@ -1037,4 +1025,4 @@ defaultfloat(ios_base& __str)
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_IOS
+#endif // _LIBCPP_IOS
lib/libcxx/include/iosfwd
@@ -84,8 +84,11 @@ typedef basic_ofstream<wchar_t>      wofstream;
 typedef basic_fstream<wchar_t>       wfstream;
 
 template <class state> class fpos;
-typedef fpos<char_traits<char>::state_type>    streampos;
-typedef fpos<char_traits<wchar_t>::state_type> wstreampos;
+using streampos  = fpos<char_traits<char>::state_type>;
+using wstreampos = fpos<char_traits<wchar_t>::state_type>;
+using u8streampos = fpos<char_traits<char8_t>::state_type>; // C++20
+using u16streampos = fpos<char_traits<char16_t>::state_type>;
+using u32streampos = fpos<char_traits<char32_t>::state_type>;
 
 }  // std
 
@@ -104,7 +107,7 @@ class _LIBCPP_TYPE_VIS ios_base;
 
 template<class _CharT>  struct _LIBCPP_TEMPLATE_VIS char_traits;
 template<> struct char_traits<char>;
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 template<> struct char_traits<char8_t>;
 #endif
 template<> struct char_traits<char16_t>;
@@ -218,13 +221,13 @@ template <class _CharT, class _Traits>
 template <class _State>             class _LIBCPP_TEMPLATE_VIS fpos;
 typedef fpos<mbstate_t>    streampos;
 typedef fpos<mbstate_t>    wstreampos;
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 typedef fpos<mbstate_t>    u8streampos;
 #endif
 #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
 typedef fpos<mbstate_t>    u16streampos;
 typedef fpos<mbstate_t>    u32streampos;
-#endif  // _LIBCPP_HAS_NO_UNICODE_CHARS
+#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
 
 #if defined(_NEWLIB_VERSION)
 // On newlib, off_t is 'long int'
@@ -276,4 +279,4 @@ public:
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_IOSFWD
+#endif // _LIBCPP_IOSFWD
lib/libcxx/include/iostream
@@ -14,9 +14,9 @@
     iostream synopsis
 
 #include <ios>
-#include <streambuf>
 #include <istream>
 #include <ostream>
+#include <streambuf>
 
 namespace std {
 
@@ -35,9 +35,9 @@ extern wostream wclog;
 
 #include <__config>
 #include <ios>
-#include <streambuf>
 #include <istream>
 #include <ostream>
+#include <streambuf>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -60,4 +60,4 @@ extern _LIBCPP_FUNC_VIS wostream wclog;
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_IOSTREAM
+#endif // _LIBCPP_IOSTREAM
lib/libcxx/include/istream
@@ -159,8 +159,9 @@ template <class Stream, class T>
 */
 
 #include <__config>
-#include <version>
+#include <__utility/forward.h>
 #include <ostream>
+#include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -191,14 +192,12 @@ public:
     { this->init(__sb); }
     virtual ~basic_istream();
 protected:
-#ifndef _LIBCPP_CXX03_LANG
     inline _LIBCPP_INLINE_VISIBILITY
     basic_istream(basic_istream&& __rhs);
 
     // 27.7.1.1.2 Assign/swap:
     inline _LIBCPP_INLINE_VISIBILITY
     basic_istream& operator=(basic_istream&& __rhs);
-#endif
 
     inline _LIBCPP_HIDE_FROM_ABI_AFTER_V1
     void swap(basic_istream& __rhs) {
@@ -206,10 +205,8 @@ protected:
       basic_ios<char_type, traits_type>::swap(__rhs);
     }
 
-#ifndef _LIBCPP_CXX03_LANG
     basic_istream           (const basic_istream& __rhs) = delete;
     basic_istream& operator=(const basic_istream& __rhs) = delete;
-#endif
 public:
 
     // 27.7.1.1.3 Prefix/suffix:
@@ -302,8 +299,7 @@ public:
 //    ~sentry() = default;
 
     _LIBCPP_INLINE_VISIBILITY
-        _LIBCPP_EXPLICIT
-        operator bool() const {return __ok_;}
+    explicit operator bool() const {return __ok_;}
 };
 
 template <class _CharT, class _Traits>
@@ -333,8 +329,6 @@ basic_istream<_CharT, _Traits>::sentry::sentry(basic_istream<_CharT, _Traits>& _
         __is.setstate(ios_base::failbit);
 }
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 basic_istream<_CharT, _Traits>::basic_istream(basic_istream&& __rhs)
     : __gc_(__rhs.__gc_)
@@ -351,8 +345,6 @@ basic_istream<_CharT, _Traits>::operator=(basic_istream&& __rhs)
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 basic_istream<_CharT, _Traits>::~basic_istream()
 {
@@ -369,7 +361,7 @@ __input_arithmetic(basic_istream<_CharT, _Traits>& __is, _Tp& __n) {
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             typedef istreambuf_iterator<_CharT, _Traits> _Ip;
             typedef num_get<_CharT, _Ip> _Fp;
             use_facet<_Fp>(__is.getloc()).get(_Ip(__is), _Ip(), __is, __state, __n);
@@ -478,7 +470,7 @@ __input_arithmetic_with_numeric_limits(basic_istream<_CharT, _Traits>& __is, _Tp
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             typedef istreambuf_iterator<_CharT, _Traits> _Ip;
             typedef num_get<_CharT, _Ip> _Fp;
             long __temp;
@@ -508,7 +500,7 @@ __input_arithmetic_with_numeric_limits(basic_istream<_CharT, _Traits>& __is, _Tp
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __is.setstate(__state);
     }
     return __is;
@@ -636,7 +628,7 @@ operator>>(basic_istream<char, _Traits>& __is, signed char* __s)
     return __is >> (char*)__s;
 }
 
-#endif  // _LIBCPP_STD_VER > 17
+#endif // _LIBCPP_STD_VER > 17
 
 template<class _CharT, class _Traits>
 basic_istream<_CharT, _Traits>&
@@ -734,7 +726,7 @@ basic_istream<_CharT, _Traits>::operator>>(basic_streambuf<char_type, traits_typ
                     throw;
                 }
             }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         }
         else
         {
@@ -854,7 +846,7 @@ basic_istream<_CharT, _Traits>::get(basic_streambuf<char_type, traits_type>& __s
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             while (true)
             {
                 typename traits_type::int_type __i = this->rdbuf()->sgetc();
@@ -878,7 +870,7 @@ basic_istream<_CharT, _Traits>::get(basic_streambuf<char_type, traits_type>& __s
             __state |= ios_base::badbit;
             // according to the spec, exceptions here are caught but not rethrown
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         if (__gc_ == 0)
            __state |= ios_base::failbit;
         this->setstate(__state);
@@ -898,7 +890,7 @@ basic_istream<_CharT, _Traits>::getline(char_type* __s, streamsize __n, char_typ
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             while (true)
             {
                 typename traits_type::int_type __i = this->rdbuf()->sgetc();
@@ -938,7 +930,7 @@ basic_istream<_CharT, _Traits>::getline(char_type* __s, streamsize __n, char_typ
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
     if (__n > 0)
         *__s = char_type();
@@ -960,7 +952,7 @@ basic_istream<_CharT, _Traits>::ignore(streamsize __n, int_type __dlm)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             if (__n == numeric_limits<streamsize>::max())
             {
                 while (true)
@@ -1002,7 +994,7 @@ basic_istream<_CharT, _Traits>::ignore(streamsize __n, int_type __dlm)
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         this->setstate(__state);
     }
     return *this;
@@ -1021,7 +1013,7 @@ basic_istream<_CharT, _Traits>::peek()
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             __r = this->rdbuf()->sgetc();
             if (traits_type::eq_int_type(__r, traits_type::eof()))
                 __state |= ios_base::eofbit;
@@ -1036,7 +1028,7 @@ basic_istream<_CharT, _Traits>::peek()
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         this->setstate(__state);
     }
     return __r;
@@ -1054,7 +1046,7 @@ basic_istream<_CharT, _Traits>::read(char_type* __s, streamsize __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             __gc_ = this->rdbuf()->sgetn(__s, __n);
             if (__gc_ != __n)
                 __state |= ios_base::failbit | ios_base::eofbit;
@@ -1069,7 +1061,7 @@ basic_istream<_CharT, _Traits>::read(char_type* __s, streamsize __n)
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
     else
     {
@@ -1091,7 +1083,7 @@ basic_istream<_CharT, _Traits>::readsome(char_type* __s, streamsize __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             streamsize __c = this->rdbuf()->in_avail();
             switch (__c)
             {
@@ -1118,7 +1110,7 @@ basic_istream<_CharT, _Traits>::readsome(char_type* __s, streamsize __n)
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
     else
     {
@@ -1141,7 +1133,7 @@ basic_istream<_CharT, _Traits>::putback(char_type __c)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             if (this->rdbuf() == nullptr || this->rdbuf()->sputbackc(__c) == traits_type::eof())
                 __state |= ios_base::badbit;
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -1155,7 +1147,7 @@ basic_istream<_CharT, _Traits>::putback(char_type __c)
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
     else
     {
@@ -1178,7 +1170,7 @@ basic_istream<_CharT, _Traits>::unget()
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             if (this->rdbuf() == nullptr || this->rdbuf()->sungetc() == traits_type::eof())
                 __state |= ios_base::badbit;
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -1192,7 +1184,7 @@ basic_istream<_CharT, _Traits>::unget()
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
     else
     {
@@ -1214,7 +1206,7 @@ basic_istream<_CharT, _Traits>::sync()
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             if (this->rdbuf() == nullptr)
                 return -1;
             if (this->rdbuf()->pubsync() == -1)
@@ -1233,7 +1225,7 @@ basic_istream<_CharT, _Traits>::sync()
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         this->setstate(__state);
     }
     return __r;
@@ -1251,7 +1243,7 @@ basic_istream<_CharT, _Traits>::tellg()
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __r = this->rdbuf()->pubseekoff(0, ios_base::cur, ios_base::in);
 #ifndef _LIBCPP_NO_EXCEPTIONS
         }
@@ -1264,7 +1256,7 @@ basic_istream<_CharT, _Traits>::tellg()
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         this->setstate(__state);
     }
     return __r;
@@ -1282,7 +1274,7 @@ basic_istream<_CharT, _Traits>::seekg(pos_type __pos)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             if (this->rdbuf()->pubseekpos(__pos, ios_base::in) == pos_type(-1))
                 __state |= ios_base::failbit;
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -1296,7 +1288,7 @@ basic_istream<_CharT, _Traits>::seekg(pos_type __pos)
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         this->setstate(__state);
     }
     return *this;
@@ -1314,7 +1306,7 @@ basic_istream<_CharT, _Traits>::seekg(off_type __off, ios_base::seekdir __dir)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             if (this->rdbuf()->pubseekoff(__off, __dir, ios_base::in) == pos_type(-1))
                 __state |= ios_base::failbit;
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -1328,7 +1320,7 @@ basic_istream<_CharT, _Traits>::seekg(off_type __off, ios_base::seekdir __dir)
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         this->setstate(__state);
     }
     return *this;
@@ -1345,7 +1337,7 @@ ws(basic_istream<_CharT, _Traits>& __is)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             const ctype<_CharT>& __ct = use_facet<ctype<_CharT> >(__is.getloc());
             while (true)
             {
@@ -1370,25 +1362,23 @@ ws(basic_istream<_CharT, _Traits>& __is)
                 throw;
             }
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __is.setstate(__state);
     }
     return __is;
 }
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template <class _Stream, class _Tp, class = void>
 struct __is_istreamable : false_type { };
 
 template <class _Stream, class _Tp>
 struct __is_istreamable<_Stream, _Tp, decltype(
-    _VSTD::declval<_Stream>() >> _VSTD::declval<_Tp>(), void()
+    declval<_Stream>() >> declval<_Tp>(), void()
 )> : true_type { };
 
 template <class _Stream, class _Tp, class = typename enable_if<
     _And<is_base_of<ios_base, _Stream>,
-         __is_istreamable<_Stream&, _Tp&&>>::value
+         __is_istreamable<_Stream&, _Tp&&> >::value
 >::type>
 _LIBCPP_INLINE_VISIBILITY
 _Stream&& operator>>(_Stream&& __is, _Tp&& __x)
@@ -1397,8 +1387,6 @@ _Stream&& operator>>(_Stream&& __is, _Tp&& __x)
     return _VSTD::move(__is);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 class _LIBCPP_TEMPLATE_VIS basic_iostream
     : public basic_istream<_CharT, _Traits>,
@@ -1420,21 +1408,18 @@ public:
 
     virtual ~basic_iostream();
 protected:
-#ifndef _LIBCPP_CXX03_LANG
     inline _LIBCPP_INLINE_VISIBILITY
     basic_iostream(basic_iostream&& __rhs);
 
     // assign/swap
     inline _LIBCPP_INLINE_VISIBILITY
     basic_iostream& operator=(basic_iostream&& __rhs);
-#endif
+
     inline _LIBCPP_HIDE_FROM_ABI_AFTER_V1
     void swap(basic_iostream& __rhs)
     { basic_istream<char_type, traits_type>::swap(__rhs); }
 };
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 basic_iostream<_CharT, _Traits>::basic_iostream(basic_iostream&& __rhs)
     : basic_istream<_CharT, _Traits>(_VSTD::move(__rhs))
@@ -1449,8 +1434,6 @@ basic_iostream<_CharT, _Traits>::operator=(basic_iostream&& __rhs)
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 basic_iostream<_CharT, _Traits>::~basic_iostream()
 {
@@ -1574,8 +1557,6 @@ getline(basic_istream<_CharT, _Traits>& __is,
     return getline(__is, __str, __is.widen('\n'));
 }
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template<class _CharT, class _Traits, class _Allocator>
 inline _LIBCPP_INLINE_VISIBILITY
 basic_istream<_CharT, _Traits>&
@@ -1594,8 +1575,6 @@ getline(basic_istream<_CharT, _Traits>&& __is,
     return getline(__is, __str, __is.widen('\n'));
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits, size_t _Size>
 basic_istream<_CharT, _Traits>&
 operator>>(basic_istream<_CharT, _Traits>& __is, bitset<_Size>& __x)
@@ -1656,4 +1635,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_ISTREAM
+#endif // _LIBCPP_ISTREAM
lib/libcxx/include/iterator
@@ -13,32 +13,140 @@
 /*
     iterator synopsis
 
+#include <concepts>
+
 namespace std
 {
+template<class> struct incrementable_traits;       // since C++20
+template<class T>
+  using iter_difference_t = see below;             // since C++20
+
+template<class> struct indirectly_readable_traits; // since C++20
+template<class T>
+  using iter_value_t = see below;                  // since C++20
 
 template<class Iterator>
-struct iterator_traits
-{
-    typedef typename Iterator::difference_type difference_type;
-    typedef typename Iterator::value_type value_type;
-    typedef typename Iterator::pointer pointer;
-    typedef typename Iterator::reference reference;
-    typedef typename Iterator::iterator_category iterator_category;
-};
+struct iterator_traits;
 
 template<class T>
-struct iterator_traits<T*>
-{
-    typedef ptrdiff_t difference_type;
-    typedef T value_type;
-    typedef T* pointer;
-    typedef T& reference;
-    typedef random_access_iterator_tag iterator_category;
-};
+  requires is_object_v<T>                    // since C++20
+struct iterator_traits<T*>;
+
+template<dereferenceable T>
+  using iter_reference_t = decltype(*declval<T&>());
+
+namespace ranges::inline unspecified {
+    inline constexpr unspecified iter_move = unspecified; // since C++20, nodiscard as an extension
+}}
+
+template<dereferenceable T>
+  requires ...
+using iter_rvalue_reference_t = decltype(ranges::iter_move(declval<T&>())); // since C++20
+
+// [iterator.concepts], iterator concepts
+// [iterator.concept.readable], concept indirectly_readable
+template<class In>
+  concept indirectly_readable = see below;                      // since C++20
+
+template<indirectly_readable T>
+  using iter_common_reference_t =
+    common_reference_t<iter_reference_t<T>, iter_value_t<T>&>;  // since C++20
+
+// [iterator.concept.writable], concept indirectly_writable
+template<class Out, class T>
+  concept indirectly_writable = see below;                // since C++20
+
+// [iterator.concept.winc], concept weakly_incrementable
+template<class I>
+  concept weakly_incrementable = see below;                // since C++20
+
+// [iterator.concept.inc], concept incrementable
+template<class I>
+  concept incrementable = see below;                       // since C++20
+
+// [iterator.concept.iterator], concept input_or_output_iterator
+  template<class I>
+    concept input_or_output_iterator = see below;          // since C++20
+
+// [iterator.concept.sentinel], concept sentinel_for
+template<class S, class I>
+  concept sentinel_for = see below;                        // since C++20
+
+// [iterator.concept.sizedsentinel], concept sized_sentinel_for
+template<class S, class I>
+  inline constexpr bool disable_sized_sentinel_for = false;
+
+template<class S, class I>
+  concept sized_sentinel_for = see below;
+
+// [iterator.concept.input], concept input_iterator
+template<class I>
+  concept input_iterator = see below;                      // since C++20
+
+// [iterator.concept.output], concept output_iterator
+template<class I, class T>
+  concept output_iterator = see below;                     // since C++20
+
+// [iterator.concept.forward], concept forward_iterator
+template<class I>
+  concept forward_iterator = see below;                    // since C++20
+
+// [iterator.concept.bidir], concept bidirectional_iterator
+template<class I>
+  concept bidirectional_iterator = see below;              // since C++20
+
+// [iterator.concept.random.access], concept random_access_iterator
+template<class I>
+  concept random_access_iterator = see below;              // since C++20
+
+// [indirectcallable]
+// [indirectcallable.indirectinvocable]
+template<class F, class I>
+  concept indirectly_unary_invocable = see below;          // since C++20
+
+template<class F, class I>
+  concept indirectly_regular_unary_invocable = see below;  // since C++20
+
+template<class F, class I>
+  concept indirect_unary_predicate = see below;            // since C++20
+
+template<class F, class I1, class I2>
+  concept indirect_binary_predicate = see below;           // since C++20
+
+template<class F, class I1, class I2 = I1>
+  concept indirect_equivalence_relation = see below;       // since C++20
+
+template<class F, class I1, class I2 = I1>
+  concept indirect_strict_weak_order = see below;          // since C++20
+
+template<class F, class... Is>
+  using indirect_result_t = see below;                     // since C++20
+
+// [projected], projected
+template<indirectly_readable I, indirectly_regular_unary_invocable<I> Proj>
+  struct projected;                                        // since C++20
+
+template<weakly_incrementable I, indirectly_regular_unary_invocable<I> Proj>
+  struct incrementable_traits<projected<I, Proj>>;         // since C++20
+
+// [alg.req.ind.move], concept indirectly_movable
+template<class In, class Out>
+  concept indirectly_movable = see below;                  // since C++20
+
+template<class In, class Out>
+  concept indirectly_movable_storable = see below;         // since C++20
+
+// [alg.req.ind.swap], concept indirectly_swappable
+template<class I1, class I2 = I1>
+  concept indirectly_swappable = see below;                // since C++20
+
+template<input_or_output_iterator I, sentinel_for<I> S>
+  requires (!same_as<I, S> && copyable<I>)
+class common_iterator;                                     // since C++20
 
 template<class Category, class T, class Distance = ptrdiff_t,
          class Pointer = T*, class Reference = T&>
-struct iterator
+struct iterator                                            // deprecated in C++17
 {
     typedef T         value_type;
     typedef Distance  difference_type;
@@ -69,9 +177,20 @@ template <class BidirectionalIterator>  // constexpr in C++17
   constexpr BidirectionalIterator prev(BidirectionalIterator x,
     typename iterator_traits<BidirectionalIterator>::difference_type n = 1);
 
+// [range.iter.ops], range iterator operations
+namespace ranges {
+  // [range.iter.op.advance], ranges::advance
+  template<input_or_output_iterator I>
+    constexpr void advance(I& i, iter_difference_t<I> n);                          // since C++20
+  template<input_or_output_iterator I, sentinel_for<I> S>
+    constexpr void advance(I& i, S bound);                                         // since C++20
+  template<input_or_output_iterator I, sentinel_for<I> S>
+    constexpr iter_difference_t<I> advance(I& i, iter_difference_t<I> n, S bound); // since C++20
+}
+
 template <class Iterator>
 class reverse_iterator
-    : public iterator<typename iterator_traits<Iterator>::iterator_category,
+    : public iterator<typename iterator_traits<Iterator>::iterator_category, // until C++17
                       typename iterator_traits<Iterator>::value_type,
                       typename iterator_traits<Iterator>::difference_type,
                       typename iterator_traits<Iterator>::pointer,
@@ -142,48 +261,53 @@ constexpr reverse_iterator<Iterator> make_reverse_iterator(Iterator i); // C++14
 
 template <class Container>
 class back_insert_iterator
+    : public iterator<output_iterator_tag, void, void, void, void> // until C++17
 {
 protected:
     Container* container;
 public:
     typedef Container                   container_type;
     typedef void                        value_type;
-    typedef void                        difference_type;
+    typedef void                        difference_type; // until C++20
+    typedef ptrdiff_t                   difference_type; // since C++20
     typedef void                        reference;
     typedef void                        pointer;
 
-    explicit back_insert_iterator(Container& x);
-    back_insert_iterator& operator=(const typename Container::value_type& value);
-    back_insert_iterator& operator*();
-    back_insert_iterator& operator++();
-    back_insert_iterator  operator++(int);
+    explicit back_insert_iterator(Container& x);  // constexpr in C++20
+    back_insert_iterator& operator=(const typename Container::value_type& value);  // constexpr in C++20
+    back_insert_iterator& operator*();  // constexpr in C++20
+    back_insert_iterator& operator++();  // constexpr in C++20
+    back_insert_iterator  operator++(int);  // constexpr in C++20
 };
 
-template <class Container> back_insert_iterator<Container> back_inserter(Container& x);
+template <class Container> back_insert_iterator<Container> back_inserter(Container& x);  // constexpr in C++20
 
 template <class Container>
 class front_insert_iterator
+    : public iterator<output_iterator_tag, void, void, void, void> // until C++17
 {
 protected:
     Container* container;
 public:
     typedef Container                    container_type;
     typedef void                         value_type;
-    typedef void                         difference_type;
+    typedef void                         difference_type; // until C++20
+    typedef ptrdiff_t                    difference_type; // since C++20
     typedef void                         reference;
     typedef void                         pointer;
 
-    explicit front_insert_iterator(Container& x);
-    front_insert_iterator& operator=(const typename Container::value_type& value);
-    front_insert_iterator& operator*();
-    front_insert_iterator& operator++();
-    front_insert_iterator  operator++(int);
+    explicit front_insert_iterator(Container& x);  // constexpr in C++20
+    front_insert_iterator& operator=(const typename Container::value_type& value);  // constexpr in C++20
+    front_insert_iterator& operator*();  // constexpr in C++20
+    front_insert_iterator& operator++();  // constexpr in C++20
+    front_insert_iterator  operator++(int);  // constexpr in C++20
 };
 
-template <class Container> front_insert_iterator<Container> front_inserter(Container& x);
+template <class Container> front_insert_iterator<Container> front_inserter(Container& x);  // constexpr in C++20
 
 template <class Container>
 class insert_iterator
+    : public iterator<output_iterator_tag, void, void, void, void> // until C++17
 {
 protected:
     Container* container;
@@ -191,19 +315,20 @@ protected:
 public:
     typedef Container              container_type;
     typedef void                   value_type;
-    typedef void                   difference_type;
+    typedef void                   difference_type; // until C++20
+    typedef ptrdiff_t              difference_type; // since C++20
     typedef void                   reference;
     typedef void                   pointer;
 
-    insert_iterator(Container& x, typename Container::iterator i);
-    insert_iterator& operator=(const typename Container::value_type& value);
-    insert_iterator& operator*();
-    insert_iterator& operator++();
-    insert_iterator& operator++(int);
+    insert_iterator(Container& x, typename Container::iterator i);  // constexpr in C++20
+    insert_iterator& operator=(const typename Container::value_type& value);  // constexpr in C++20
+    insert_iterator& operator*();  // constexpr in C++20
+    insert_iterator& operator++();  // constexpr in C++20
+    insert_iterator& operator++(int);  // constexpr in C++20
 };
 
 template <class Container, class Iterator>
-insert_iterator<Container> inserter(Container& x, Iterator i);
+insert_iterator<Container> inserter(Container& x, Iterator i);  // constexpr in C++20
 
 template <class Iterator>
 class move_iterator {
@@ -274,15 +399,31 @@ constexpr move_iterator<Iterator> operator+(   // constexpr in C++17
 template <class Iterator>   // constexpr in C++17
 constexpr  move_iterator<Iterator> make_move_iterator(const Iterator& i);
 
+// [default.sentinel], default sentinel
+struct default_sentinel_t;
+inline constexpr default_sentinel_t default_sentinel{};
+
+// [iterators.counted], counted iterators
+template<input_or_output_iterator I> class counted_iterator;
+
+template<input_iterator I>
+  requires see below
+  struct iterator_traits<counted_iterator<I>>;
 
 template <class T, class charT = char, class traits = char_traits<charT>, class Distance = ptrdiff_t>
 class istream_iterator
-    : public iterator<input_iterator_tag, T, Distance, const T*, const T&>
+    : public iterator<input_iterator_tag, T, Distance, const T*, const T&> // until C++17
 {
 public:
-    typedef charT char_type;
-    typedef traits traits_type;
-    typedef basic_istream<charT,traits> istream_type;
+    typedef input_iterator_tag           iterator_category;
+    typedef T                            value_type;
+    typedef Distance                     difference_type;
+    typedef const T*                     pointer;
+    typedef const T&                     reference;
+
+    typedef charT                        char_type;
+    typedef traits                       traits_type;
+    typedef basic_istream<charT, traits> istream_type;
 
     constexpr istream_iterator();
     istream_iterator(istream_type& s);
@@ -304,9 +445,16 @@ bool operator!=(const istream_iterator<T,charT,traits,Distance>& x,
 
 template <class T, class charT = char, class traits = char_traits<charT> >
 class ostream_iterator
-    : public iterator<output_iterator_tag, void, void, void ,void>
+    : public iterator<output_iterator_tag, void, void, void, void> // until C++17
 {
 public:
+    typedef output_iterator_tag         iterator_category;
+    typedef void                        value_type;
+    typedef void                        difference_type; // until C++20
+    typedef ptrdiff_t                   difference_type; // since C++20
+    typedef void                        pointer;
+    typedef void                        reference;
+
     typedef charT char_type;
     typedef traits traits_type;
     typedef basic_ostream<charT,traits> ostream_type;
@@ -324,16 +472,20 @@ public:
 
 template<class charT, class traits = char_traits<charT> >
 class istreambuf_iterator
-    : public iterator<input_iterator_tag, charT,
-                      typename traits::off_type, unspecified,
-                      charT>
+    : public iterator<input_iterator_tag, charT, traits::off_type, unspecified, charT> // until C++17
 {
 public:
-    typedef charT                         char_type;
-    typedef traits                        traits_type;
-    typedef typename traits::int_type     int_type;
-    typedef basic_streambuf<charT,traits> streambuf_type;
-    typedef basic_istream<charT,traits>   istream_type;
+    typedef input_iterator_tag              iterator_category;
+    typedef charT                           value_type;
+    typedef traits::off_type                difference_type;
+    typedef unspecified                     pointer;
+    typedef charT                           reference;
+
+    typedef charT                           char_type;
+    typedef traits                          traits_type;
+    typedef traits::int_type                int_type;
+    typedef basic_streambuf<charT, traits>  streambuf_type;
+    typedef basic_istream<charT, traits>    istream_type;
 
     istreambuf_iterator() noexcept;
     istreambuf_iterator(istream_type& s) noexcept;
@@ -357,13 +509,20 @@ bool operator!=(const istreambuf_iterator<charT,traits>& a,
 
 template <class charT, class traits = char_traits<charT> >
 class ostreambuf_iterator
-    : public iterator<output_iterator_tag, void, void, void, void>
+    : public iterator<output_iterator_tag, void, void, void, void> // until C++17
 {
 public:
-    typedef charT                         char_type;
-    typedef traits                        traits_type;
-    typedef basic_streambuf<charT,traits> streambuf_type;
-    typedef basic_ostream<charT,traits>   ostream_type;
+    typedef output_iterator_tag            iterator_category;
+    typedef void                           value_type;
+    typedef void                           difference_type; // until C++20
+    typedef ptrdiff_t                      difference_type; // since C++20
+    typedef void                           pointer;
+    typedef void                           reference;
+
+    typedef charT                          char_type;
+    typedef traits                         traits_type;
+    typedef basic_streambuf<charT, traits> streambuf_type;
+    typedef basic_ostream<charT, traits>   ostream_type;
 
     ostreambuf_iterator(ostream_type& s) noexcept;
     ostreambuf_iterator(streambuf_type* s) noexcept;
@@ -399,7 +558,7 @@ template <class C> constexpr auto size(const C& c) -> decltype(c.size());
 template <class T, size_t N> constexpr size_t size(const T (&array)[N]) noexcept; // C++17
 
 template <class C> constexpr auto ssize(const C& c)
-    -> common_type_t<ptrdiff_t, make_signed_t<decltype(c.size())>>;				       // C++20
+    -> common_type_t<ptrdiff_t, make_signed_t<decltype(c.size())>>;                    // C++20
 template <class T, ptrdiff_t> constexpr ptrdiff_t ssize(const T (&array)[N]) noexcept; // C++20
 
 template <class C> constexpr auto empty(const C& c) -> decltype(c.empty());       // C++17
@@ -415,1608 +574,51 @@ template <class E> constexpr const E* data(initializer_list<E> il) noexcept;
 */
 
 #include <__config>
-#include <iosfwd> // for forward declarations of vector and string.
+#include <__debug>
 #include <__functional_base>
-#include <type_traits>
+#include <__iterator/access.h>
+#include <__iterator/advance.h>
+#include <__iterator/back_insert_iterator.h>
+#include <__iterator/common_iterator.h>
+#include <__iterator/concepts.h>
+#include <__iterator/counted_iterator.h>
+#include <__iterator/data.h>
+#include <__iterator/default_sentinel.h>
+#include <__iterator/distance.h>
+#include <__iterator/empty.h>
+#include <__iterator/erase_if_container.h>
+#include <__iterator/front_insert_iterator.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/insert_iterator.h>
+#include <__iterator/istreambuf_iterator.h>
+#include <__iterator/istream_iterator.h>
+#include <__iterator/iterator.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iter_swap.h>
+#include <__iterator/move_iterator.h>
+#include <__iterator/next.h>
+#include <__iterator/ostreambuf_iterator.h>
+#include <__iterator/ostream_iterator.h>
+#include <__iterator/prev.h>
+#include <__iterator/projected.h>
+#include <__iterator/readable_traits.h>
+#include <__iterator/reverse_access.h>
+#include <__iterator/reverse_iterator.h>
+#include <__iterator/size.h>
+#include <__iterator/wrap_iter.h>
+#include <__memory/addressof.h>
+#include <__memory/pointer_traits.h>
+#include <__utility/forward.h>
+#include <compare>
+#include <concepts> // Mandated by the Standard.
 #include <cstddef>
 #include <initializer_list>
-#include <__memory/base.h>
+#include <type_traits>
 #include <version>
 
-#include <__debug>
-
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
 
-_LIBCPP_BEGIN_NAMESPACE_STD
-template <class _Iter>
-struct _LIBCPP_TEMPLATE_VIS iterator_traits;
-
-struct _LIBCPP_TEMPLATE_VIS input_iterator_tag {};
-struct _LIBCPP_TEMPLATE_VIS output_iterator_tag {};
-struct _LIBCPP_TEMPLATE_VIS forward_iterator_tag       : public input_iterator_tag {};
-struct _LIBCPP_TEMPLATE_VIS bidirectional_iterator_tag : public forward_iterator_tag {};
-struct _LIBCPP_TEMPLATE_VIS random_access_iterator_tag : public bidirectional_iterator_tag {};
-#if _LIBCPP_STD_VER > 17
-// TODO(EricWF)  contiguous_iterator_tag is provided as an extension prior to
-//  C++20 to allow optimizations for users providing wrapped iterator types.
-struct _LIBCPP_TEMPLATE_VIS contiguous_iterator_tag: public random_access_iterator_tag { };
-#endif
-
-template <class _Iter>
-struct __iter_traits_cache {
-  using type = _If<
-    __is_primary_template<iterator_traits<_Iter> >::value,
-    _Iter,
-    iterator_traits<_Iter>
-  >;
-};
-template <class _Iter>
-using _ITER_TRAITS = typename __iter_traits_cache<_Iter>::type;
-
-struct __iter_concept_concept_test {
-  template <class _Iter>
-  using _Apply = typename _ITER_TRAITS<_Iter>::iterator_concept;
-};
-struct __iter_concept_category_test {
-  template <class _Iter>
-  using _Apply = typename _ITER_TRAITS<_Iter>::iterator_category;
-};
-struct __iter_concept_random_fallback {
-  template <class _Iter>
-  using _Apply = _EnableIf<
-                          __is_primary_template<iterator_traits<_Iter> >::value,
-                          random_access_iterator_tag
-                        >;
-};
-
-template <class _Iter, class _Tester> struct __test_iter_concept
-    : _IsValidExpansion<_Tester::template _Apply, _Iter>,
-      _Tester
-{
-};
-
-template <class _Iter>
-struct __iter_concept_cache {
-  using type = _Or<
-    __test_iter_concept<_Iter, __iter_concept_concept_test>,
-    __test_iter_concept<_Iter, __iter_concept_category_test>,
-    __test_iter_concept<_Iter, __iter_concept_random_fallback>
-  >;
-};
-
-template <class _Iter>
-using _ITER_CONCEPT = typename __iter_concept_cache<_Iter>::type::template _Apply<_Iter>;
-
-
-template <class _Tp>
-struct __has_iterator_typedefs
-{
-private:
-    struct __two {char __lx; char __lxx;};
-    template <class _Up> static __two __test(...);
-    template <class _Up> static char __test(typename __void_t<typename _Up::iterator_category>::type* = 0,
-                                            typename __void_t<typename _Up::difference_type>::type* = 0,
-                                            typename __void_t<typename _Up::value_type>::type* = 0,
-                                            typename __void_t<typename _Up::reference>::type* = 0,
-                                            typename __void_t<typename _Up::pointer>::type* = 0);
-public:
-    static const bool value = sizeof(__test<_Tp>(0,0,0,0,0)) == 1;
-};
-
-
-template <class _Tp>
-struct __has_iterator_category
-{
-private:
-    struct __two {char __lx; char __lxx;};
-    template <class _Up> static __two __test(...);
-    template <class _Up> static char __test(typename _Up::iterator_category* = nullptr);
-public:
-    static const bool value = sizeof(__test<_Tp>(nullptr)) == 1;
-};
-
-template <class _Iter, bool> struct __iterator_traits_impl {};
-
-template <class _Iter>
-struct __iterator_traits_impl<_Iter, true>
-{
-    typedef typename _Iter::difference_type   difference_type;
-    typedef typename _Iter::value_type        value_type;
-    typedef typename _Iter::pointer           pointer;
-    typedef typename _Iter::reference         reference;
-    typedef typename _Iter::iterator_category iterator_category;
-};
-
-template <class _Iter, bool> struct __iterator_traits {};
-
-template <class _Iter>
-struct __iterator_traits<_Iter, true>
-    :  __iterator_traits_impl
-      <
-        _Iter,
-        is_convertible<typename _Iter::iterator_category, input_iterator_tag>::value ||
-        is_convertible<typename _Iter::iterator_category, output_iterator_tag>::value
-      >
-{};
-
-// iterator_traits<Iterator> will only have the nested types if Iterator::iterator_category
-//    exists.  Else iterator_traits<Iterator> will be an empty class.  This is a
-//    conforming extension which allows some programs to compile and behave as
-//    the client expects instead of failing at compile time.
-
-template <class _Iter>
-struct _LIBCPP_TEMPLATE_VIS iterator_traits
-    : __iterator_traits<_Iter, __has_iterator_typedefs<_Iter>::value> {
-
-  using __primary_template = iterator_traits;
-};
-
-template<class _Tp>
-struct _LIBCPP_TEMPLATE_VIS iterator_traits<_Tp*>
-{
-    typedef ptrdiff_t difference_type;
-    typedef typename remove_cv<_Tp>::type value_type;
-    typedef _Tp* pointer;
-    typedef _Tp& reference;
-    typedef random_access_iterator_tag iterator_category;
-#if _LIBCPP_STD_VER > 17
-    typedef contiguous_iterator_tag    iterator_concept;
-#endif
-};
-
-template <class _Tp, class _Up, bool = __has_iterator_category<iterator_traits<_Tp> >::value>
-struct __has_iterator_category_convertible_to
-    : public integral_constant<bool, is_convertible<typename iterator_traits<_Tp>::iterator_category, _Up>::value>
-{};
-
-template <class _Tp, class _Up>
-struct __has_iterator_category_convertible_to<_Tp, _Up, false> : public false_type {};
-
-template <class _Tp>
-struct __is_cpp17_input_iterator : public __has_iterator_category_convertible_to<_Tp, input_iterator_tag> {};
-
-template <class _Tp>
-struct __is_cpp17_forward_iterator : public __has_iterator_category_convertible_to<_Tp, forward_iterator_tag> {};
-
-template <class _Tp>
-struct __is_cpp17_bidirectional_iterator : public __has_iterator_category_convertible_to<_Tp, bidirectional_iterator_tag> {};
-
-template <class _Tp>
-struct __is_cpp17_random_access_iterator : public __has_iterator_category_convertible_to<_Tp, random_access_iterator_tag> {};
-
-#if _LIBCPP_STD_VER > 17
-template <class _Tp>
-struct __is_cpp17_contiguous_iterator : public __has_iterator_category_convertible_to<_Tp, contiguous_iterator_tag> {};
-#else
-template <class _Tp>
-struct __is_cpp17_contiguous_iterator : public false_type {};
-#endif
-
-
-template <class _Tp>
-struct __is_exactly_cpp17_input_iterator
-    : public integral_constant<bool,
-         __has_iterator_category_convertible_to<_Tp, input_iterator_tag>::value &&
-        !__has_iterator_category_convertible_to<_Tp, forward_iterator_tag>::value> {};
-
-#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
-template<class _InputIterator>
-using __iter_value_type = typename iterator_traits<_InputIterator>::value_type;
-
-template<class _InputIterator>
-using __iter_key_type = remove_const_t<typename iterator_traits<_InputIterator>::value_type::first_type>;
-
-template<class _InputIterator>
-using __iter_mapped_type = typename iterator_traits<_InputIterator>::value_type::second_type;
-
-template<class _InputIterator>
-using __iter_to_alloc_type = pair<
-    add_const_t<typename iterator_traits<_InputIterator>::value_type::first_type>,
-    typename iterator_traits<_InputIterator>::value_type::second_type>;
-#endif
-
-template<class _Category, class _Tp, class _Distance = ptrdiff_t,
-         class _Pointer = _Tp*, class _Reference = _Tp&>
-struct _LIBCPP_TEMPLATE_VIS iterator
-{
-    typedef _Tp        value_type;
-    typedef _Distance  difference_type;
-    typedef _Pointer   pointer;
-    typedef _Reference reference;
-    typedef _Category  iterator_category;
-};
-
-template <class _InputIter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-void __advance(_InputIter& __i,
-             typename iterator_traits<_InputIter>::difference_type __n, input_iterator_tag)
-{
-    for (; __n > 0; --__n)
-        ++__i;
-}
-
-template <class _BiDirIter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-void __advance(_BiDirIter& __i,
-             typename iterator_traits<_BiDirIter>::difference_type __n, bidirectional_iterator_tag)
-{
-    if (__n >= 0)
-        for (; __n > 0; --__n)
-            ++__i;
-    else
-        for (; __n < 0; ++__n)
-            --__i;
-}
-
-template <class _RandIter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-void __advance(_RandIter& __i,
-             typename iterator_traits<_RandIter>::difference_type __n, random_access_iterator_tag)
-{
-   __i += __n;
-}
-
-template <class _InputIter, class _Distance>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-void advance(_InputIter& __i, _Distance __orig_n)
-{
-    _LIBCPP_ASSERT(__orig_n >= 0 || __is_cpp17_bidirectional_iterator<_InputIter>::value,
-                   "Attempt to advance(it, n) with negative n on a non-bidirectional iterator");
-    typedef decltype(_VSTD::__convert_to_integral(__orig_n)) _IntegralSize;
-    _IntegralSize __n = __orig_n;
-    _VSTD::__advance(__i, __n, typename iterator_traits<_InputIter>::iterator_category());
-}
-
-template <class _InputIter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-typename iterator_traits<_InputIter>::difference_type
-__distance(_InputIter __first, _InputIter __last, input_iterator_tag)
-{
-    typename iterator_traits<_InputIter>::difference_type __r(0);
-    for (; __first != __last; ++__first)
-        ++__r;
-    return __r;
-}
-
-template <class _RandIter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-typename iterator_traits<_RandIter>::difference_type
-__distance(_RandIter __first, _RandIter __last, random_access_iterator_tag)
-{
-    return __last - __first;
-}
-
-template <class _InputIter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-typename iterator_traits<_InputIter>::difference_type
-distance(_InputIter __first, _InputIter __last)
-{
-    return _VSTD::__distance(__first, __last, typename iterator_traits<_InputIter>::iterator_category());
-}
-
-template <class _InputIter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-typename enable_if
-<
-    __is_cpp17_input_iterator<_InputIter>::value,
-    _InputIter
->::type
-next(_InputIter __x,
-     typename iterator_traits<_InputIter>::difference_type __n = 1)
-{
-    _LIBCPP_ASSERT(__n >= 0 || __is_cpp17_bidirectional_iterator<_InputIter>::value,
-                       "Attempt to next(it, n) with negative n on a non-bidirectional iterator");
-
-    _VSTD::advance(__x, __n);
-    return __x;
-}
-
-template <class _InputIter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-typename enable_if
-<
-    __is_cpp17_input_iterator<_InputIter>::value,
-    _InputIter
->::type
-prev(_InputIter __x,
-     typename iterator_traits<_InputIter>::difference_type __n = 1)
-{
-    _LIBCPP_ASSERT(__n <= 0 || __is_cpp17_bidirectional_iterator<_InputIter>::value,
-                       "Attempt to prev(it, n) with a positive n on a non-bidirectional iterator");
-    _VSTD::advance(__x, -__n);
-    return __x;
-}
-
-
-template <class _Tp, class = void>
-struct __is_stashing_iterator : false_type {};
-
-template <class _Tp>
-struct __is_stashing_iterator<_Tp, typename __void_t<typename _Tp::__stashing_iterator_tag>::type>
-  : true_type {};
-
-template <class _Iter>
-class _LIBCPP_TEMPLATE_VIS reverse_iterator
-    : public iterator<typename iterator_traits<_Iter>::iterator_category,
-                      typename iterator_traits<_Iter>::value_type,
-                      typename iterator_traits<_Iter>::difference_type,
-                      typename iterator_traits<_Iter>::pointer,
-                      typename iterator_traits<_Iter>::reference>
-{
-private:
-    /*mutable*/ _Iter __t;  // no longer used as of LWG #2360, not removed due to ABI break
-
-    static_assert(!__is_stashing_iterator<_Iter>::value,
-      "The specified iterator type cannot be used with reverse_iterator; "
-      "Using stashing iterators with reverse_iterator causes undefined behavior");
-
-protected:
-    _Iter current;
-public:
-    typedef _Iter                                            iterator_type;
-    typedef typename iterator_traits<_Iter>::difference_type difference_type;
-    typedef typename iterator_traits<_Iter>::reference       reference;
-    typedef typename iterator_traits<_Iter>::pointer         pointer;
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reverse_iterator() : __t(), current() {}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    explicit reverse_iterator(_Iter __x) : __t(__x), current(__x) {}
-    template <class _Up>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-        reverse_iterator(const reverse_iterator<_Up>& __u) : __t(__u.base()), current(__u.base()) {}
-    template <class _Up>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-        reverse_iterator& operator=(const reverse_iterator<_Up>& __u)
-            { __t = current = __u.base(); return *this; }
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    _Iter base() const {return current;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reference operator*() const {_Iter __tmp = current; return *--__tmp;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    pointer  operator->() const {return _VSTD::addressof(operator*());}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reverse_iterator& operator++() {--current; return *this;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reverse_iterator  operator++(int) {reverse_iterator __tmp(*this); --current; return __tmp;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reverse_iterator& operator--() {++current; return *this;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reverse_iterator  operator--(int) {reverse_iterator __tmp(*this); ++current; return __tmp;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reverse_iterator  operator+ (difference_type __n) const {return reverse_iterator(current - __n);}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reverse_iterator& operator+=(difference_type __n) {current -= __n; return *this;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reverse_iterator  operator- (difference_type __n) const {return reverse_iterator(current + __n);}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reverse_iterator& operator-=(difference_type __n) {current += __n; return *this;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reference         operator[](difference_type __n) const {return *(*this + __n);}
-};
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator==(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
-{
-    return __x.base() == __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator<(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
-{
-    return __x.base() > __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator!=(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
-{
-    return __x.base() != __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator>(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
-{
-    return __x.base() < __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator>=(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
-{
-    return __x.base() <= __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator<=(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
-{
-    return __x.base() >= __y.base();
-}
-
-#ifndef _LIBCPP_CXX03_LANG
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto
-operator-(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
--> decltype(__y.base() - __x.base())
-{
-    return __y.base() - __x.base();
-}
-#else
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY
-typename reverse_iterator<_Iter1>::difference_type
-operator-(const reverse_iterator<_Iter1>& __x, const reverse_iterator<_Iter2>& __y)
-{
-    return __y.base() - __x.base();
-}
-#endif
-
-template <class _Iter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-reverse_iterator<_Iter>
-operator+(typename reverse_iterator<_Iter>::difference_type __n, const reverse_iterator<_Iter>& __x)
-{
-    return reverse_iterator<_Iter>(__x.base() - __n);
-}
-
-#if _LIBCPP_STD_VER > 11
-template <class _Iter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-reverse_iterator<_Iter> make_reverse_iterator(_Iter __i)
-{
-    return reverse_iterator<_Iter>(__i);
-}
-#endif
-
-template <class _Container>
-class _LIBCPP_TEMPLATE_VIS back_insert_iterator
-    : public iterator<output_iterator_tag,
-                      void,
-                      void,
-                      void,
-                      void>
-{
-protected:
-    _Container* container;
-public:
-    typedef _Container container_type;
-
-    _LIBCPP_INLINE_VISIBILITY explicit back_insert_iterator(_Container& __x) : container(_VSTD::addressof(__x)) {}
-    _LIBCPP_INLINE_VISIBILITY back_insert_iterator& operator=(const typename _Container::value_type& __value_)
-        {container->push_back(__value_); return *this;}
-#ifndef _LIBCPP_CXX03_LANG
-    _LIBCPP_INLINE_VISIBILITY back_insert_iterator& operator=(typename _Container::value_type&& __value_)
-        {container->push_back(_VSTD::move(__value_)); return *this;}
-#endif  // _LIBCPP_CXX03_LANG
-    _LIBCPP_INLINE_VISIBILITY back_insert_iterator& operator*()     {return *this;}
-    _LIBCPP_INLINE_VISIBILITY back_insert_iterator& operator++()    {return *this;}
-    _LIBCPP_INLINE_VISIBILITY back_insert_iterator  operator++(int) {return *this;}
-};
-
-template <class _Container>
-inline _LIBCPP_INLINE_VISIBILITY
-back_insert_iterator<_Container>
-back_inserter(_Container& __x)
-{
-    return back_insert_iterator<_Container>(__x);
-}
-
-template <class _Container>
-class _LIBCPP_TEMPLATE_VIS front_insert_iterator
-    : public iterator<output_iterator_tag,
-                      void,
-                      void,
-                      void,
-                      void>
-{
-protected:
-    _Container* container;
-public:
-    typedef _Container container_type;
-
-    _LIBCPP_INLINE_VISIBILITY explicit front_insert_iterator(_Container& __x) : container(_VSTD::addressof(__x)) {}
-    _LIBCPP_INLINE_VISIBILITY front_insert_iterator& operator=(const typename _Container::value_type& __value_)
-        {container->push_front(__value_); return *this;}
-#ifndef _LIBCPP_CXX03_LANG
-    _LIBCPP_INLINE_VISIBILITY front_insert_iterator& operator=(typename _Container::value_type&& __value_)
-        {container->push_front(_VSTD::move(__value_)); return *this;}
-#endif  // _LIBCPP_CXX03_LANG
-    _LIBCPP_INLINE_VISIBILITY front_insert_iterator& operator*()     {return *this;}
-    _LIBCPP_INLINE_VISIBILITY front_insert_iterator& operator++()    {return *this;}
-    _LIBCPP_INLINE_VISIBILITY front_insert_iterator  operator++(int) {return *this;}
-};
-
-template <class _Container>
-inline _LIBCPP_INLINE_VISIBILITY
-front_insert_iterator<_Container>
-front_inserter(_Container& __x)
-{
-    return front_insert_iterator<_Container>(__x);
-}
-
-template <class _Container>
-class _LIBCPP_TEMPLATE_VIS insert_iterator
-    : public iterator<output_iterator_tag,
-                      void,
-                      void,
-                      void,
-                      void>
-{
-protected:
-    _Container* container;
-    typename _Container::iterator iter;
-public:
-    typedef _Container container_type;
-
-    _LIBCPP_INLINE_VISIBILITY insert_iterator(_Container& __x, typename _Container::iterator __i)
-        : container(_VSTD::addressof(__x)), iter(__i) {}
-    _LIBCPP_INLINE_VISIBILITY insert_iterator& operator=(const typename _Container::value_type& __value_)
-        {iter = container->insert(iter, __value_); ++iter; return *this;}
-#ifndef _LIBCPP_CXX03_LANG
-    _LIBCPP_INLINE_VISIBILITY insert_iterator& operator=(typename _Container::value_type&& __value_)
-        {iter = container->insert(iter, _VSTD::move(__value_)); ++iter; return *this;}
-#endif  // _LIBCPP_CXX03_LANG
-    _LIBCPP_INLINE_VISIBILITY insert_iterator& operator*()        {return *this;}
-    _LIBCPP_INLINE_VISIBILITY insert_iterator& operator++()       {return *this;}
-    _LIBCPP_INLINE_VISIBILITY insert_iterator& operator++(int)    {return *this;}
-};
-
-template <class _Container>
-inline _LIBCPP_INLINE_VISIBILITY
-insert_iterator<_Container>
-inserter(_Container& __x, typename _Container::iterator __i)
-{
-    return insert_iterator<_Container>(__x, __i);
-}
-
-template <class _Tp, class _CharT = char,
-          class _Traits = char_traits<_CharT>, class _Distance = ptrdiff_t>
-class _LIBCPP_TEMPLATE_VIS istream_iterator
-    : public iterator<input_iterator_tag, _Tp, _Distance, const _Tp*, const _Tp&>
-{
-public:
-    typedef _CharT char_type;
-    typedef _Traits traits_type;
-    typedef basic_istream<_CharT,_Traits> istream_type;
-private:
-    istream_type* __in_stream_;
-    _Tp __value_;
-public:
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR istream_iterator() : __in_stream_(nullptr), __value_() {}
-    _LIBCPP_INLINE_VISIBILITY istream_iterator(istream_type& __s) : __in_stream_(_VSTD::addressof(__s))
-        {
-            if (!(*__in_stream_ >> __value_))
-                __in_stream_ = nullptr;
-        }
-
-    _LIBCPP_INLINE_VISIBILITY const _Tp& operator*() const {return __value_;}
-    _LIBCPP_INLINE_VISIBILITY const _Tp* operator->() const {return _VSTD::addressof((operator*()));}
-    _LIBCPP_INLINE_VISIBILITY istream_iterator& operator++()
-        {
-            if (!(*__in_stream_ >> __value_))
-                __in_stream_ = nullptr;
-            return *this;
-        }
-    _LIBCPP_INLINE_VISIBILITY istream_iterator  operator++(int)
-        {istream_iterator __t(*this); ++(*this); return __t;}
-
-    template <class _Up, class _CharU, class _TraitsU, class _DistanceU>
-    friend _LIBCPP_INLINE_VISIBILITY
-    bool
-    operator==(const istream_iterator<_Up, _CharU, _TraitsU, _DistanceU>& __x,
-               const istream_iterator<_Up, _CharU, _TraitsU, _DistanceU>& __y);
-
-    template <class _Up, class _CharU, class _TraitsU, class _DistanceU>
-    friend _LIBCPP_INLINE_VISIBILITY
-    bool
-    operator==(const istream_iterator<_Up, _CharU, _TraitsU, _DistanceU>& __x,
-               const istream_iterator<_Up, _CharU, _TraitsU, _DistanceU>& __y);
-};
-
-template <class _Tp, class _CharT, class _Traits, class _Distance>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator==(const istream_iterator<_Tp, _CharT, _Traits, _Distance>& __x,
-           const istream_iterator<_Tp, _CharT, _Traits, _Distance>& __y)
-{
-    return __x.__in_stream_ == __y.__in_stream_;
-}
-
-template <class _Tp, class _CharT, class _Traits, class _Distance>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(const istream_iterator<_Tp, _CharT, _Traits, _Distance>& __x,
-           const istream_iterator<_Tp, _CharT, _Traits, _Distance>& __y)
-{
-    return !(__x == __y);
-}
-
-template <class _Tp, class _CharT = char, class _Traits = char_traits<_CharT> >
-class _LIBCPP_TEMPLATE_VIS ostream_iterator
-    : public iterator<output_iterator_tag, void, void, void, void>
-{
-public:
-    typedef output_iterator_tag             iterator_category;
-    typedef void                            value_type;
-#if _LIBCPP_STD_VER > 17
-    typedef std::ptrdiff_t                  difference_type;
-#else
-    typedef void                            difference_type;
-#endif
-    typedef void                            pointer;
-    typedef void                            reference;
-    typedef _CharT                          char_type;
-    typedef _Traits                         traits_type;
-    typedef basic_ostream<_CharT, _Traits>  ostream_type;
-
-private:
-    ostream_type* __out_stream_;
-    const char_type* __delim_;
-public:
-    _LIBCPP_INLINE_VISIBILITY ostream_iterator(ostream_type& __s) _NOEXCEPT
-        : __out_stream_(_VSTD::addressof(__s)), __delim_(nullptr) {}
-    _LIBCPP_INLINE_VISIBILITY ostream_iterator(ostream_type& __s, const _CharT* __delimiter) _NOEXCEPT
-        : __out_stream_(_VSTD::addressof(__s)), __delim_(__delimiter) {}
-    _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator=(const _Tp& __value_)
-        {
-            *__out_stream_ << __value_;
-            if (__delim_)
-                *__out_stream_ << __delim_;
-            return *this;
-        }
-
-    _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator*()     {return *this;}
-    _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator++()    {return *this;}
-    _LIBCPP_INLINE_VISIBILITY ostream_iterator& operator++(int) {return *this;}
-};
-
-template<class _CharT, class _Traits>
-class _LIBCPP_TEMPLATE_VIS istreambuf_iterator
-    : public iterator<input_iterator_tag, _CharT,
-                      typename _Traits::off_type, _CharT*,
-                      _CharT>
-{
-public:
-    typedef _CharT                          char_type;
-    typedef _Traits                         traits_type;
-    typedef typename _Traits::int_type      int_type;
-    typedef basic_streambuf<_CharT,_Traits> streambuf_type;
-    typedef basic_istream<_CharT,_Traits>   istream_type;
-private:
-    mutable streambuf_type* __sbuf_;
-
-    class __proxy
-    {
-        char_type __keep_;
-        streambuf_type* __sbuf_;
-        _LIBCPP_INLINE_VISIBILITY __proxy(char_type __c, streambuf_type* __s)
-            : __keep_(__c), __sbuf_(__s) {}
-        friend class istreambuf_iterator;
-    public:
-        _LIBCPP_INLINE_VISIBILITY char_type operator*() const {return __keep_;}
-    };
-
-    _LIBCPP_INLINE_VISIBILITY
-    bool __test_for_eof() const
-    {
-        if (__sbuf_ && traits_type::eq_int_type(__sbuf_->sgetc(), traits_type::eof()))
-            __sbuf_ = nullptr;
-        return __sbuf_ == nullptr;
-    }
-public:
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR istreambuf_iterator() _NOEXCEPT : __sbuf_(nullptr) {}
-    _LIBCPP_INLINE_VISIBILITY istreambuf_iterator(istream_type& __s) _NOEXCEPT
-        : __sbuf_(__s.rdbuf()) {}
-    _LIBCPP_INLINE_VISIBILITY istreambuf_iterator(streambuf_type* __s) _NOEXCEPT
-        : __sbuf_(__s) {}
-    _LIBCPP_INLINE_VISIBILITY istreambuf_iterator(const __proxy& __p) _NOEXCEPT
-        : __sbuf_(__p.__sbuf_) {}
-
-    _LIBCPP_INLINE_VISIBILITY char_type  operator*() const
-        {return static_cast<char_type>(__sbuf_->sgetc());}
-    _LIBCPP_INLINE_VISIBILITY istreambuf_iterator& operator++()
-        {
-            __sbuf_->sbumpc();
-            return *this;
-        }
-    _LIBCPP_INLINE_VISIBILITY __proxy              operator++(int)
-        {
-            return __proxy(__sbuf_->sbumpc(), __sbuf_);
-        }
-
-    _LIBCPP_INLINE_VISIBILITY bool equal(const istreambuf_iterator& __b) const
-        {return __test_for_eof() == __b.__test_for_eof();}
-};
-
-template <class _CharT, class _Traits>
-inline _LIBCPP_INLINE_VISIBILITY
-bool operator==(const istreambuf_iterator<_CharT,_Traits>& __a,
-                const istreambuf_iterator<_CharT,_Traits>& __b)
-                {return __a.equal(__b);}
-
-template <class _CharT, class _Traits>
-inline _LIBCPP_INLINE_VISIBILITY
-bool operator!=(const istreambuf_iterator<_CharT,_Traits>& __a,
-                const istreambuf_iterator<_CharT,_Traits>& __b)
-                {return !__a.equal(__b);}
-
-template <class _CharT, class _Traits>
-class _LIBCPP_TEMPLATE_VIS ostreambuf_iterator
-    : public iterator<output_iterator_tag, void, void, void, void>
-{
-public:
-    typedef output_iterator_tag                 iterator_category;
-    typedef void                                value_type;
-#if _LIBCPP_STD_VER > 17
-    typedef std::ptrdiff_t                      difference_type;
-#else
-    typedef void                                difference_type;
-#endif
-    typedef void                                pointer;
-    typedef void                                reference;
-    typedef _CharT                              char_type;
-    typedef _Traits                             traits_type;
-    typedef basic_streambuf<_CharT, _Traits>    streambuf_type;
-    typedef basic_ostream<_CharT, _Traits>      ostream_type;
-
-private:
-    streambuf_type* __sbuf_;
-public:
-    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator(ostream_type& __s) _NOEXCEPT
-        : __sbuf_(__s.rdbuf()) {}
-    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator(streambuf_type* __s) _NOEXCEPT
-        : __sbuf_(__s) {}
-    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator& operator=(_CharT __c)
-        {
-            if (__sbuf_ && traits_type::eq_int_type(__sbuf_->sputc(__c), traits_type::eof()))
-                __sbuf_ = nullptr;
-            return *this;
-        }
-    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator& operator*()     {return *this;}
-    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator& operator++()    {return *this;}
-    _LIBCPP_INLINE_VISIBILITY ostreambuf_iterator& operator++(int) {return *this;}
-    _LIBCPP_INLINE_VISIBILITY bool failed() const _NOEXCEPT {return __sbuf_ == nullptr;}
-
-    template <class _Ch, class _Tr>
-    friend
-    _LIBCPP_HIDDEN
-    ostreambuf_iterator<_Ch, _Tr>
-    __pad_and_output(ostreambuf_iterator<_Ch, _Tr> __s,
-                     const _Ch* __ob, const _Ch* __op, const _Ch* __oe,
-                     ios_base& __iob, _Ch __fl);
-};
-
-template <class _Iter>
-class _LIBCPP_TEMPLATE_VIS move_iterator
-{
-private:
-    _Iter __i;
-public:
-    typedef _Iter                                            iterator_type;
-    typedef typename iterator_traits<iterator_type>::iterator_category iterator_category;
-    typedef typename iterator_traits<iterator_type>::value_type value_type;
-    typedef typename iterator_traits<iterator_type>::difference_type difference_type;
-    typedef iterator_type pointer;
-#ifndef _LIBCPP_CXX03_LANG
-    typedef typename iterator_traits<iterator_type>::reference __reference;
-    typedef typename conditional<
-            is_reference<__reference>::value,
-            typename remove_reference<__reference>::type&&,
-            __reference
-        >::type reference;
-#else
-    typedef typename iterator_traits<iterator_type>::reference reference;
-#endif
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    move_iterator() : __i() {}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    explicit move_iterator(_Iter __x) : __i(__x) {}
-    template <class _Up>
-      _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-      move_iterator(const move_iterator<_Up>& __u) : __i(__u.base()) {}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14 _Iter base() const {return __i;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reference operator*() const { return static_cast<reference>(*__i); }
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    pointer  operator->() const { return __i;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    move_iterator& operator++() {++__i; return *this;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    move_iterator  operator++(int) {move_iterator __tmp(*this); ++__i; return __tmp;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    move_iterator& operator--() {--__i; return *this;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    move_iterator  operator--(int) {move_iterator __tmp(*this); --__i; return __tmp;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    move_iterator  operator+ (difference_type __n) const {return move_iterator(__i + __n);}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    move_iterator& operator+=(difference_type __n) {__i += __n; return *this;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    move_iterator  operator- (difference_type __n) const {return move_iterator(__i - __n);}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    move_iterator& operator-=(difference_type __n) {__i -= __n; return *this;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-    reference operator[](difference_type __n) const { return static_cast<reference>(__i[__n]); }
-};
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator==(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
-{
-    return __x.base() == __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator<(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
-{
-    return __x.base() < __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator!=(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
-{
-    return __x.base() != __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator>(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
-{
-    return __x.base() > __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator>=(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
-{
-    return __x.base() >= __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-bool
-operator<=(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
-{
-    return __x.base() <= __y.base();
-}
-
-#ifndef _LIBCPP_CXX03_LANG
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto
-operator-(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
--> decltype(__x.base() - __y.base())
-{
-    return __x.base() - __y.base();
-}
-#else
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY
-typename move_iterator<_Iter1>::difference_type
-operator-(const move_iterator<_Iter1>& __x, const move_iterator<_Iter2>& __y)
-{
-    return __x.base() - __y.base();
-}
-#endif
-
-template <class _Iter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-move_iterator<_Iter>
-operator+(typename move_iterator<_Iter>::difference_type __n, const move_iterator<_Iter>& __x)
-{
-    return move_iterator<_Iter>(__x.base() + __n);
-}
-
-template <class _Iter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-move_iterator<_Iter>
-make_move_iterator(_Iter __i)
-{
-    return move_iterator<_Iter>(__i);
-}
-
-// __wrap_iter
-
-template <class _Iter> class __wrap_iter;
-
-template <class _Iter1, class _Iter2>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator==(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-template <class _Iter1, class _Iter2>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator<(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-template <class _Iter1, class _Iter2>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator!=(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-template <class _Iter1, class _Iter2>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator>(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-template <class _Iter1, class _Iter2>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator>=(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-template <class _Iter1, class _Iter2>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator<=(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-#ifndef _LIBCPP_CXX03_LANG
-template <class _Iter1, class _Iter2>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-auto
-operator-(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
--> decltype(__x.base() - __y.base());
-#else
-template <class _Iter1, class _Iter2>
-_LIBCPP_INLINE_VISIBILITY
-typename __wrap_iter<_Iter1>::difference_type
-operator-(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-#endif
-
-template <class _Iter>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-__wrap_iter<_Iter>
-operator+(typename __wrap_iter<_Iter>::difference_type, __wrap_iter<_Iter>) _NOEXCEPT;
-
-template <class _Ip, class _Op> _Op _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 copy(_Ip, _Ip, _Op);
-template <class _B1, class _B2> _B2 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 copy_backward(_B1, _B1, _B2);
-template <class _Ip, class _Op> _Op _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 move(_Ip, _Ip, _Op);
-template <class _B1, class _B2> _B2 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17 move_backward(_B1, _B1, _B2);
-
-#if _LIBCPP_DEBUG_LEVEL < 2
-
-template <class _Tp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename enable_if
-<
-    is_trivially_copy_assignable<_Tp>::value,
-    _Tp*
->::type
-__unwrap_iter(__wrap_iter<_Tp*>);
-
-#else
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename enable_if
-<
-    is_trivially_copy_assignable<_Tp>::value,
-    __wrap_iter<_Tp*>
->::type
-__unwrap_iter(__wrap_iter<_Tp*> __i);
-
-#endif
-
-template <class _Iter>
-class __wrap_iter
-{
-public:
-    typedef _Iter                                                      iterator_type;
-    typedef typename iterator_traits<iterator_type>::iterator_category iterator_category;
-    typedef typename iterator_traits<iterator_type>::value_type        value_type;
-    typedef typename iterator_traits<iterator_type>::difference_type   difference_type;
-    typedef typename iterator_traits<iterator_type>::pointer           pointer;
-    typedef typename iterator_traits<iterator_type>::reference         reference;
-private:
-    iterator_type __i;
-public:
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter() _NOEXCEPT
-#if _LIBCPP_STD_VER > 11
-                : __i{}
-#endif
-    {
-#if _LIBCPP_DEBUG_LEVEL == 2
-        __get_db()->__insert_i(this);
-#endif
-    }
-    template <class _Up> _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-        __wrap_iter(const __wrap_iter<_Up>& __u,
-            typename enable_if<is_convertible<_Up, iterator_type>::value>::type* = nullptr) _NOEXCEPT
-            : __i(__u.base())
-    {
-#if _LIBCPP_DEBUG_LEVEL == 2
-        __get_db()->__iterator_copy(this, &__u);
-#endif
-    }
-#if _LIBCPP_DEBUG_LEVEL == 2
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-    __wrap_iter(const __wrap_iter& __x)
-        : __i(__x.base())
-    {
-        __get_db()->__iterator_copy(this, &__x);
-    }
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-    __wrap_iter& operator=(const __wrap_iter& __x)
-    {
-        if (this != &__x)
-        {
-            __get_db()->__iterator_copy(this, &__x);
-            __i = __x.__i;
-        }
-        return *this;
-    }
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-    ~__wrap_iter()
-    {
-        __get_db()->__erase_i(this);
-    }
-#endif
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG reference operator*() const _NOEXCEPT
-    {
-#if _LIBCPP_DEBUG_LEVEL == 2
-        _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this),
-                       "Attempted to dereference a non-dereferenceable iterator");
-#endif
-        return *__i;
-    }
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG pointer  operator->() const _NOEXCEPT
-    {
-#if _LIBCPP_DEBUG_LEVEL == 2
-        _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this),
-                       "Attempted to dereference a non-dereferenceable iterator");
-#endif
-        return (pointer)_VSTD::addressof(*__i);
-    }
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter& operator++() _NOEXCEPT
-    {
-#if _LIBCPP_DEBUG_LEVEL == 2
-        _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this),
-                       "Attempted to increment non-incrementable iterator");
-#endif
-        ++__i;
-        return *this;
-    }
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter  operator++(int) _NOEXCEPT
-        {__wrap_iter __tmp(*this); ++(*this); return __tmp;}
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter& operator--() _NOEXCEPT
-    {
-#if _LIBCPP_DEBUG_LEVEL == 2
-        _LIBCPP_ASSERT(__get_const_db()->__decrementable(this),
-                       "Attempted to decrement non-decrementable iterator");
-#endif
-        --__i;
-        return *this;
-    }
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter  operator--(int) _NOEXCEPT
-        {__wrap_iter __tmp(*this); --(*this); return __tmp;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter  operator+ (difference_type __n) const _NOEXCEPT
-        {__wrap_iter __w(*this); __w += __n; return __w;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter& operator+=(difference_type __n) _NOEXCEPT
-    {
-#if _LIBCPP_DEBUG_LEVEL == 2
-        _LIBCPP_ASSERT(__get_const_db()->__addable(this, __n),
-                   "Attempted to add/subtract iterator outside of valid range");
-#endif
-        __i += __n;
-        return *this;
-    }
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter  operator- (difference_type __n) const _NOEXCEPT
-        {return *this + (-__n);}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter& operator-=(difference_type __n) _NOEXCEPT
-        {*this += -__n; return *this;}
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG reference    operator[](difference_type __n) const _NOEXCEPT
-    {
-#if _LIBCPP_DEBUG_LEVEL == 2
-        _LIBCPP_ASSERT(__get_const_db()->__subscriptable(this, __n),
-                   "Attempted to subscript iterator outside of valid range");
-#endif
-        return __i[__n];
-    }
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG iterator_type base() const _NOEXCEPT {return __i;}
-
-private:
-#if _LIBCPP_DEBUG_LEVEL == 2
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter(const void* __p, iterator_type __x) : __i(__x)
-    {
-        __get_db()->__insert_ic(this, __p);
-    }
-#else
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG __wrap_iter(iterator_type __x) _NOEXCEPT : __i(__x) {}
-#endif
-
-    template <class _Up> friend class __wrap_iter;
-    template <class _CharT, class _Traits, class _Alloc> friend class basic_string;
-    template <class _Tp, class _Alloc> friend class _LIBCPP_TEMPLATE_VIS vector;
-    template <class _Tp, size_t> friend class _LIBCPP_TEMPLATE_VIS span;
-
-    template <class _Iter1, class _Iter2>
-    _LIBCPP_CONSTEXPR_IF_NODEBUG friend
-    bool
-    operator==(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-    template <class _Iter1, class _Iter2>
-    _LIBCPP_CONSTEXPR_IF_NODEBUG friend
-    bool
-    operator<(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-    template <class _Iter1, class _Iter2>
-    _LIBCPP_CONSTEXPR_IF_NODEBUG friend
-    bool
-    operator!=(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-    template <class _Iter1, class _Iter2>
-    _LIBCPP_CONSTEXPR_IF_NODEBUG friend
-    bool
-    operator>(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-    template <class _Iter1, class _Iter2>
-    _LIBCPP_CONSTEXPR_IF_NODEBUG friend
-    bool
-    operator>=(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-    template <class _Iter1, class _Iter2>
-    _LIBCPP_CONSTEXPR_IF_NODEBUG friend
-    bool
-    operator<=(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-
-#ifndef _LIBCPP_CXX03_LANG
-    template <class _Iter1, class _Iter2>
-    _LIBCPP_CONSTEXPR_IF_NODEBUG friend
-    auto
-    operator-(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
-    -> decltype(__x.base() - __y.base());
-#else
-    template <class _Iter1, class _Iter2>
-    _LIBCPP_CONSTEXPR_IF_NODEBUG friend
-    typename __wrap_iter<_Iter1>::difference_type
-    operator-(const __wrap_iter<_Iter1>&, const __wrap_iter<_Iter2>&) _NOEXCEPT;
-#endif
-
-    template <class _Iter1>
-    _LIBCPP_CONSTEXPR_IF_NODEBUG friend
-    __wrap_iter<_Iter1>
-    operator+(typename __wrap_iter<_Iter1>::difference_type, __wrap_iter<_Iter1>) _NOEXCEPT;
-
-    template <class _Ip, class _Op> friend _LIBCPP_CONSTEXPR_AFTER_CXX17 _Op copy(_Ip, _Ip, _Op);
-    template <class _B1, class _B2> friend _LIBCPP_CONSTEXPR_AFTER_CXX17 _B2 copy_backward(_B1, _B1, _B2);
-    template <class _Ip, class _Op> friend _LIBCPP_CONSTEXPR_AFTER_CXX17 _Op move(_Ip, _Ip, _Op);
-    template <class _B1, class _B2> friend _LIBCPP_CONSTEXPR_AFTER_CXX17 _B2 move_backward(_B1, _B1, _B2);
-
-#if _LIBCPP_DEBUG_LEVEL < 2
-    template <class _Tp>
-    _LIBCPP_CONSTEXPR friend
-    typename enable_if
-    <
-        is_trivially_copy_assignable<_Tp>::value,
-        _Tp*
-    >::type
-    __unwrap_iter(__wrap_iter<_Tp*>);
-#else
-  template <class _Tp>
-  inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR friend
-  typename enable_if
-  <
-      is_trivially_copy_assignable<_Tp>::value,
-      __wrap_iter<_Tp*>
-  >::type
-  __unwrap_iter(__wrap_iter<_Tp*> __i);
-#endif
-};
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator==(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
-{
-    return __x.base() == __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator<(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
-{
-#if _LIBCPP_DEBUG_LEVEL == 2
-    _LIBCPP_ASSERT(__get_const_db()->__less_than_comparable(&__x, &__y),
-                   "Attempted to compare incomparable iterators");
-#endif
-    return __x.base() < __y.base();
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator!=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
-{
-    return !(__x == __y);
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator>(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
-{
-    return __y < __x;
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator>=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
-{
-    return !(__x < __y);
-}
-
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator<=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
-{
-    return !(__y < __x);
-}
-
-template <class _Iter1>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator!=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
-{
-    return !(__x == __y);
-}
-
-template <class _Iter1>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator>(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
-{
-    return __y < __x;
-}
-
-template <class _Iter1>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator>=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
-{
-    return !(__x < __y);
-}
-
-template <class _Iter1>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-bool
-operator<=(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter1>& __y) _NOEXCEPT
-{
-    return !(__y < __x);
-}
-
-#ifndef _LIBCPP_CXX03_LANG
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-auto
-operator-(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
--> decltype(__x.base() - __y.base())
-{
-#if _LIBCPP_DEBUG_LEVEL == 2
-    _LIBCPP_ASSERT(__get_const_db()->__less_than_comparable(&__x, &__y),
-                   "Attempted to subtract incompatible iterators");
-#endif
-    return __x.base() - __y.base();
-}
-#else
-template <class _Iter1, class _Iter2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-typename __wrap_iter<_Iter1>::difference_type
-operator-(const __wrap_iter<_Iter1>& __x, const __wrap_iter<_Iter2>& __y) _NOEXCEPT
-{
-#if _LIBCPP_DEBUG_LEVEL == 2
-    _LIBCPP_ASSERT(__get_const_db()->__less_than_comparable(&__x, &__y),
-                   "Attempted to subtract incompatible iterators");
-#endif
-    return __x.base() - __y.base();
-}
-#endif
-
-template <class _Iter>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_IF_NODEBUG
-__wrap_iter<_Iter>
-operator+(typename __wrap_iter<_Iter>::difference_type __n,
-          __wrap_iter<_Iter> __x) _NOEXCEPT
-{
-    __x += __n;
-    return __x;
-}
-
-template <class _Iter>
-struct __libcpp_is_trivial_iterator
-    : public _LIBCPP_BOOL_CONSTANT(is_pointer<_Iter>::value) {};
-
-template <class _Iter>
-struct __libcpp_is_trivial_iterator<move_iterator<_Iter> >
-    : public _LIBCPP_BOOL_CONSTANT(__libcpp_is_trivial_iterator<_Iter>::value) {};
-
-template <class _Iter>
-struct __libcpp_is_trivial_iterator<reverse_iterator<_Iter> >
-    : public _LIBCPP_BOOL_CONSTANT(__libcpp_is_trivial_iterator<_Iter>::value) {};
-
-template <class _Iter>
-struct __libcpp_is_trivial_iterator<__wrap_iter<_Iter> >
-    : public _LIBCPP_BOOL_CONSTANT(__libcpp_is_trivial_iterator<_Iter>::value) {};
-
-
-template <class _Tp, size_t _Np>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_Tp*
-begin(_Tp (&__array)[_Np])
-{
-    return __array;
-}
-
-template <class _Tp, size_t _Np>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-_Tp*
-end(_Tp (&__array)[_Np])
-{
-    return __array + _Np;
-}
-
-#if !defined(_LIBCPP_CXX03_LANG)
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto
-begin(_Cp& __c) -> decltype(__c.begin())
-{
-    return __c.begin();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto
-begin(const _Cp& __c) -> decltype(__c.begin())
-{
-    return __c.begin();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto
-end(_Cp& __c) -> decltype(__c.end())
-{
-    return __c.end();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto
-end(const _Cp& __c) -> decltype(__c.end())
-{
-    return __c.end();
-}
-
-#if _LIBCPP_STD_VER > 11
-
-template <class _Tp, size_t _Np>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-reverse_iterator<_Tp*> rbegin(_Tp (&__array)[_Np])
-{
-    return reverse_iterator<_Tp*>(__array + _Np);
-}
-
-template <class _Tp, size_t _Np>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-reverse_iterator<_Tp*> rend(_Tp (&__array)[_Np])
-{
-    return reverse_iterator<_Tp*>(__array);
-}
-
-template <class _Ep>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-reverse_iterator<const _Ep*> rbegin(initializer_list<_Ep> __il)
-{
-    return reverse_iterator<const _Ep*>(__il.end());
-}
-
-template <class _Ep>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-reverse_iterator<const _Ep*> rend(initializer_list<_Ep> __il)
-{
-    return reverse_iterator<const _Ep*>(__il.begin());
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-auto cbegin(const _Cp& __c) -> decltype(_VSTD::begin(__c))
-{
-    return _VSTD::begin(__c);
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-auto cend(const _Cp& __c) -> decltype(_VSTD::end(__c))
-{
-    return _VSTD::end(__c);
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto rbegin(_Cp& __c) -> decltype(__c.rbegin())
-{
-    return __c.rbegin();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto rbegin(const _Cp& __c) -> decltype(__c.rbegin())
-{
-    return __c.rbegin();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto rend(_Cp& __c) -> decltype(__c.rend())
-{
-    return __c.rend();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto rend(const _Cp& __c) -> decltype(__c.rend())
-{
-    return __c.rend();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto crbegin(const _Cp& __c) -> decltype(_VSTD::rbegin(__c))
-{
-    return _VSTD::rbegin(__c);
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-auto crend(const _Cp& __c) -> decltype(_VSTD::rend(__c))
-{
-    return _VSTD::rend(__c);
-}
-
-#endif
-
-
-#else  // defined(_LIBCPP_CXX03_LANG)
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY
-typename _Cp::iterator
-begin(_Cp& __c)
-{
-    return __c.begin();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY
-typename _Cp::const_iterator
-begin(const _Cp& __c)
-{
-    return __c.begin();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY
-typename _Cp::iterator
-end(_Cp& __c)
-{
-    return __c.end();
-}
-
-template <class _Cp>
-_LIBCPP_INLINE_VISIBILITY
-typename _Cp::const_iterator
-end(const _Cp& __c)
-{
-    return __c.end();
-}
-
-#endif  // !defined(_LIBCPP_CXX03_LANG)
-
-#if _LIBCPP_STD_VER > 14
-
-// #if _LIBCPP_STD_VER > 11
-// template <>
-// struct _LIBCPP_TEMPLATE_VIS plus<void>
-// {
-//     template <class _T1, class _T2>
-//     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-//     auto operator()(_T1&& __t, _T2&& __u) const
-//     _NOEXCEPT_(noexcept(_VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u)))
-//     -> decltype        (_VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u))
-//         { return        _VSTD::forward<_T1>(__t) + _VSTD::forward<_T2>(__u); }
-//     typedef void is_transparent;
-// };
-// #endif
-
-template <class _Cont>
-_LIBCPP_INLINE_VISIBILITY
-constexpr auto size(const _Cont& __c)
-_NOEXCEPT_(noexcept(__c.size()))
--> decltype        (__c.size())
-{ return            __c.size(); }
-
-template <class _Tp, size_t _Sz>
-_LIBCPP_INLINE_VISIBILITY
-constexpr size_t size(const _Tp (&)[_Sz]) noexcept { return _Sz; }
-
-#if _LIBCPP_STD_VER > 17
-template <class _Cont>
-_LIBCPP_INLINE_VISIBILITY
-constexpr auto ssize(const _Cont& __c)
-_NOEXCEPT_(noexcept(static_cast<common_type_t<ptrdiff_t, make_signed_t<decltype(__c.size())>>>(__c.size())))
-->                              common_type_t<ptrdiff_t, make_signed_t<decltype(__c.size())>>
-{ return            static_cast<common_type_t<ptrdiff_t, make_signed_t<decltype(__c.size())>>>(__c.size()); }
-
-template <class _Tp, ptrdiff_t _Sz>
-_LIBCPP_INLINE_VISIBILITY
-constexpr ptrdiff_t ssize(const _Tp (&)[_Sz]) noexcept { return _Sz; }
-#endif
-
-template <class _Cont>
-_LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
-constexpr auto empty(const _Cont& __c)
-_NOEXCEPT_(noexcept(__c.empty()))
--> decltype        (__c.empty())
-{ return            __c.empty(); }
-
-template <class _Tp, size_t _Sz>
-_LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
-constexpr bool empty(const _Tp (&)[_Sz]) noexcept { return false; }
-
-template <class _Ep>
-_LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
-constexpr bool empty(initializer_list<_Ep> __il) noexcept { return __il.size() == 0; }
-
-template <class _Cont> constexpr
-_LIBCPP_INLINE_VISIBILITY
-auto data(_Cont& __c)
-_NOEXCEPT_(noexcept(__c.data()))
--> decltype        (__c.data())
-{ return            __c.data(); }
-
-template <class _Cont> constexpr
-_LIBCPP_INLINE_VISIBILITY
-auto data(const _Cont& __c)
-_NOEXCEPT_(noexcept(__c.data()))
--> decltype        (__c.data())
-{ return            __c.data(); }
-
-template <class _Tp, size_t _Sz>
-_LIBCPP_INLINE_VISIBILITY
-constexpr _Tp* data(_Tp (&__array)[_Sz]) noexcept { return __array; }
-
-template <class _Ep>
-_LIBCPP_INLINE_VISIBILITY
-constexpr const _Ep* data(initializer_list<_Ep> __il) noexcept { return __il.begin(); }
-#endif
-
-
-_LIBCPP_END_NAMESPACE_STD
-
-#endif  // _LIBCPP_ITERATOR
+#endif // _LIBCPP_ITERATOR
lib/libcxx/include/latch
@@ -40,8 +40,8 @@ namespace std
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <atomic>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
lib/libcxx/include/limits
@@ -815,4 +815,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_LIMITS
+#endif // _LIBCPP_LIMITS
lib/libcxx/include/limits.h
@@ -61,4 +61,4 @@ Macros:
 #include_next <limits.h>
 #endif // __GNUC__
 
-#endif  // _LIBCPP_LIMITS_H
+#endif // _LIBCPP_LIMITS_H
lib/libcxx/include/list
@@ -181,17 +181,16 @@ template <class T, class Allocator, class Predicate>
 */
 
 #include <__config>
-
-#include <memory>
-#include <limits>
+#include <__debug>
+#include <__utility/forward.h>
+#include <algorithm>
 #include <initializer_list>
 #include <iterator>
-#include <algorithm>
+#include <limits>
+#include <memory>
 #include <type_traits>
 #include <version>
 
-#include <__debug>
-
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
@@ -267,7 +266,7 @@ struct __list_node_base
 };
 
 template <class _Tp, class _VoidPtr>
-struct __list_node
+struct _LIBCPP_STANDALONE_DEBUG __list_node
     : public __list_node_base<_Tp, _VoidPtr>
 {
     _Tp __value_;
@@ -351,7 +350,7 @@ public:
         return *this;
     }
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
     _LIBCPP_INLINE_VISIBILITY
     reference operator*() const
@@ -377,7 +376,7 @@ public:
     {
 #if _LIBCPP_DEBUG_LEVEL == 2
         _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this),
-                       "Attempted to increment non-incrementable list::iterator");
+                       "Attempted to increment a non-incrementable list::iterator");
 #endif
         __ptr_ = __ptr_->__next_;
         return *this;
@@ -390,7 +389,7 @@ public:
     {
 #if _LIBCPP_DEBUG_LEVEL == 2
         _LIBCPP_ASSERT(__get_const_db()->__decrementable(this),
-                       "Attempted to decrement non-decrementable list::iterator");
+                       "Attempted to decrement a non-decrementable list::iterator");
 #endif
         __ptr_ = __ptr_->__prev_;
         return *this;
@@ -479,7 +478,7 @@ public:
         return *this;
     }
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
     _LIBCPP_INLINE_VISIBILITY
     reference operator*() const
     {
@@ -504,7 +503,7 @@ public:
     {
 #if _LIBCPP_DEBUG_LEVEL == 2
         _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(this),
-                       "Attempted to increment non-incrementable list::const_iterator");
+                       "Attempted to increment a non-incrementable list::const_iterator");
 #endif
         __ptr_ = __ptr_->__next_;
         return *this;
@@ -517,7 +516,7 @@ public:
     {
 #if _LIBCPP_DEBUG_LEVEL == 2
         _LIBCPP_ASSERT(__get_const_db()->__decrementable(this),
-                       "Attempted to decrement non-decrementable list::const_iterator");
+                       "Attempted to decrement a non-decrementable list::const_iterator");
 #endif
         __ptr_ = __ptr_->__prev_;
         return *this;
@@ -895,7 +894,7 @@ public:
              typename enable_if<__is_cpp17_input_iterator<_InpIter>::value>::type* = 0);
 
     list(const list& __c);
-    list(const list& __c, const allocator_type& __a);
+    list(const list& __c, const __identity_t<allocator_type>& __a);
     _LIBCPP_INLINE_VISIBILITY
     list& operator=(const list& __c);
 #ifndef _LIBCPP_CXX03_LANG
@@ -906,7 +905,7 @@ public:
     list(list&& __c)
         _NOEXCEPT_(is_nothrow_move_constructible<__node_allocator>::value);
     _LIBCPP_INLINE_VISIBILITY
-    list(list&& __c, const allocator_type& __a);
+    list(list&& __c, const __identity_t<allocator_type>& __a);
     _LIBCPP_INLINE_VISIBILITY
     list& operator=(list&& __c)
         _NOEXCEPT_(
@@ -920,7 +919,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     void assign(initializer_list<value_type> __il)
         {assign(__il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     template <class _InpIter>
         void assign(_InpIter __f, _InpIter __l,
@@ -1023,7 +1022,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     iterator insert(const_iterator __p, initializer_list<value_type> __il)
         {return insert(__p, __il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     void push_front(const value_type& __x);
     void push_back(const value_type& __x);
@@ -1124,7 +1123,7 @@ public:
     bool __addable(const const_iterator* __i, ptrdiff_t __n) const;
     bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const;
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 private:
     _LIBCPP_INLINE_VISIBILITY
@@ -1144,18 +1143,18 @@ private:
 
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template<class _InputIterator,
-         class _Alloc = allocator<typename iterator_traits<_InputIterator>::value_type>,
-         class = typename enable_if<__is_allocator<_Alloc>::value, void>::type
+         class _Alloc = allocator<__iter_value_type<_InputIterator>>,
+         class = _EnableIf<__is_allocator<_Alloc>::value>
          >
 list(_InputIterator, _InputIterator)
-  -> list<typename iterator_traits<_InputIterator>::value_type, _Alloc>;
+  -> list<__iter_value_type<_InputIterator>, _Alloc>;
 
 template<class _InputIterator,
          class _Alloc,
-         class = typename enable_if<__is_allocator<_Alloc>::value, void>::type
+         class = _EnableIf<__is_allocator<_Alloc>::value>
          >
 list(_InputIterator, _InputIterator, _Alloc)
-  -> list<typename iterator_traits<_InputIterator>::value_type, _Alloc>;
+  -> list<__iter_value_type<_InputIterator>, _Alloc>;
 #endif
 
 // Link in nodes [__f, __l] just prior to __p
@@ -1288,7 +1287,7 @@ list<_Tp, _Alloc>::list(const list& __c)
 }
 
 template <class _Tp, class _Alloc>
-list<_Tp, _Alloc>::list(const list& __c, const allocator_type& __a)
+list<_Tp, _Alloc>::list(const list& __c, const __identity_t<allocator_type>& __a)
     : base(__a)
 {
 #if _LIBCPP_DEBUG_LEVEL == 2
@@ -1335,7 +1334,7 @@ inline list<_Tp, _Alloc>::list(list&& __c)
 
 template <class _Tp, class _Alloc>
 inline
-list<_Tp, _Alloc>::list(list&& __c, const allocator_type& __a)
+list<_Tp, _Alloc>::list(list&& __c, const __identity_t<allocator_type>& __a)
     : base(__a)
 {
 #if _LIBCPP_DEBUG_LEVEL == 2
@@ -1386,7 +1385,7 @@ list<_Tp, _Alloc>::__move_assign(list& __c, true_type)
     splice(end(), __c);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Alloc>
 inline
@@ -1495,7 +1494,7 @@ list<_Tp, _Alloc>::insert(const_iterator __p, size_type __n, const value_type& _
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (--__n; __n != 0; --__n, ++__e, ++__ds)
             {
                 __hold.reset(__node_alloc_traits::allocate(__na, 1));
@@ -1523,7 +1522,7 @@ list<_Tp, _Alloc>::insert(const_iterator __p, size_type __n, const value_type& _
             }
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __link_nodes(__p.__ptr_, __r.__ptr_, __e.__ptr_);
         base::__sz() += __ds;
     }
@@ -1561,7 +1560,7 @@ list<_Tp, _Alloc>::insert(const_iterator __p, _InpIter __f, _InpIter __l,
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (++__f; __f != __l; ++__f, (void) ++__e, (void) ++__ds)
             {
                 __hold.reset(__node_alloc_traits::allocate(__na, 1));
@@ -1589,7 +1588,7 @@ list<_Tp, _Alloc>::insert(const_iterator __p, _InpIter __f, _InpIter __l,
             }
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __link_nodes(__p.__ptr_, __r.__ptr_, __e.__ptr_);
         base::__sz() += __ds;
     }
@@ -1737,7 +1736,7 @@ list<_Tp, _Alloc>::insert(const_iterator __p, value_type&& __x)
 #endif
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Alloc>
 void
@@ -1772,7 +1771,7 @@ template <class _Tp, class _Alloc>
 void
 list<_Tp, _Alloc>::pop_back()
 {
-    _LIBCPP_ASSERT(!empty(), "list::pop_back() called with empty list");
+    _LIBCPP_ASSERT(!empty(), "list::pop_back() called on an empty list");
     __node_allocator& __na = base::__node_alloc();
     __link_pointer __n = base::__end_.__prev_;
     base::__unlink_nodes(__n, __n);
@@ -1909,7 +1908,7 @@ list<_Tp, _Alloc>::resize(size_type __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (--__n; __n != 0; --__n, ++__e, ++__ds)
             {
                 __hold.reset(__node_alloc_traits::allocate(__na, 1));
@@ -1937,7 +1936,7 @@ list<_Tp, _Alloc>::resize(size_type __n)
             }
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __link_nodes_at_back(__r.__ptr_, __e.__ptr_);
         base::__sz() += __ds;
     }
@@ -1967,7 +1966,7 @@ list<_Tp, _Alloc>::resize(size_type __n, const value_type& __x)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (--__n; __n != 0; --__n, ++__e, ++__ds)
             {
                 __hold.reset(__node_alloc_traits::allocate(__na, 1));
@@ -1995,7 +1994,7 @@ list<_Tp, _Alloc>::resize(size_type __n, const value_type& __x)
             }
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         __link_nodes(base::__end_as_link(), __r.__ptr_, __e.__ptr_);
         base::__sz() += __ds;
     }
@@ -2049,14 +2048,14 @@ list<_Tp, _Alloc>::splice(const_iterator __p, list& __c, const_iterator __i)
 {
 #if _LIBCPP_DEBUG_LEVEL == 2
     _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__p) == this,
-        "list::splice(iterator, list, iterator) called with first iterator not"
-        " referring to this list");
+        "list::splice(iterator, list, iterator) called with the first iterator"
+        " not referring to this list");
     _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__i) == &__c,
-        "list::splice(iterator, list, iterator) called with second iterator not"
-        " referring to list argument");
+        "list::splice(iterator, list, iterator) called with the second iterator"
+        " not referring to the list argument");
     _LIBCPP_ASSERT(__get_const_db()->__dereferenceable(&__i),
-        "list::splice(iterator, list, iterator) called with second iterator not"
-        " dereferenceable");
+        "list::splice(iterator, list, iterator) called with the second iterator"
+        " not dereferenceable");
 #endif
     if (__p.__ptr_ != __i.__ptr_ && __p.__ptr_ != __i.__ptr_->__next_)
     {
@@ -2098,7 +2097,10 @@ list<_Tp, _Alloc>::splice(const_iterator __p, list& __c, const_iterator __f, con
         " referring to this list");
     _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__f) == &__c,
         "list::splice(iterator, list, iterator, iterator) called with second iterator not"
-        " referring to list argument");
+        " referring to the list argument");
+    _LIBCPP_ASSERT(__get_const_db()->__find_c_from_i(&__l) == &__c,
+        "list::splice(iterator, list, iterator, iterator) called with third iterator not"
+        " referring to the list argument");
     if (this == &__c)
     {
         for (const_iterator __i = __f; __i != __l; ++__i)
@@ -2412,7 +2414,7 @@ list<_Tp, _Alloc>::__subscriptable(const const_iterator*, ptrdiff_t) const
     return false;
 }
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 template <class _Tp, class _Alloc>
 inline _LIBCPP_INLINE_VISIBILITY
@@ -2489,4 +2491,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_LIST
+#endif // _LIBCPP_LIST
lib/libcxx/include/locale
@@ -188,23 +188,28 @@ template <class charT> class messages_byname;
 */
 
 #include <__config>
-#include <__locale>
 #include <__debug>
+#include <__locale>
 #include <algorithm>
-#include <memory>
-#include <ios>
-#include <streambuf>
-#include <iterator>
-#include <limits>
-#include <version>
 #ifndef __APPLE__
-#include <cstdarg>
+# include <cstdarg>
 #endif
+#include <cstdio>
 #include <cstdlib>
 #include <ctime>
-#include <cstdio>
-#ifdef _LIBCPP_HAS_CATOPEN
-#include <nl_types.h>
+#include <ios>
+#include <iterator>
+#include <limits>
+#include <memory>
+#include <streambuf>
+#include <version>
+
+#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+// Most unix variants have catopen.  These are the specific ones that don't.
+#  if !defined(__BIONIC__) && !defined(_NEWLIB_VERSION)
+#    define _LIBCPP_HAS_CATOPEN 1
+#    include <nl_types.h>
+#  endif
 #endif
 
 #ifdef _LIBCPP_LOCALE__L_EXTENSIONS
@@ -1453,10 +1458,12 @@ num_put<_CharT, _OutputIterator>::do_put(iter_type __s, ios_base& __iob,
     char __fmt[6] = {'%', 0};
     const char* __len = "l";
     this->__format_int(__fmt+1, __len, true, __iob.flags());
-    const unsigned __nbuf = (numeric_limits<long>::digits / 3)
-                          + ((numeric_limits<long>::digits % 3) != 0)
-                          + ((__iob.flags() & ios_base::showbase) != 0)
-                          + 2;
+    // Worst case is octal, with showbase enabled. Note that octal is always
+    // printed as an unsigned value.
+    _LIBCPP_CONSTEXPR const unsigned __nbuf
+        = (numeric_limits<unsigned long>::digits / 3)        // 1 char per 3 bits
+        + ((numeric_limits<unsigned long>::digits % 3) != 0) // round up
+        + 2; // base prefix + terminating null character
     char __nar[__nbuf];
     int __nc = __libcpp_snprintf_l(__nar, sizeof(__nar), _LIBCPP_GET_C_LOCALE, __fmt, __v);
     char* __ne = __nar + __nc;
@@ -1480,10 +1487,12 @@ num_put<_CharT, _OutputIterator>::do_put(iter_type __s, ios_base& __iob,
     char __fmt[8] = {'%', 0};
     const char* __len = "ll";
     this->__format_int(__fmt+1, __len, true, __iob.flags());
-    const unsigned __nbuf = (numeric_limits<long long>::digits / 3)
-                          + ((numeric_limits<long long>::digits % 3) != 0)
-                          + ((__iob.flags() & ios_base::showbase) != 0)
-                          + 2;
+    // Worst case is octal, with showbase enabled. Note that octal is always
+    // printed as an unsigned value.
+    _LIBCPP_CONSTEXPR const unsigned __nbuf
+        = (numeric_limits<unsigned long long>::digits / 3)        // 1 char per 3 bits
+        + ((numeric_limits<unsigned long long>::digits % 3) != 0) // round up
+        + 2; // base prefix + terminating null character
     char __nar[__nbuf];
     int __nc = __libcpp_snprintf_l(__nar, sizeof(__nar), _LIBCPP_GET_C_LOCALE, __fmt, __v);
     char* __ne = __nar + __nc;
@@ -1507,10 +1516,11 @@ num_put<_CharT, _OutputIterator>::do_put(iter_type __s, ios_base& __iob,
     char __fmt[6] = {'%', 0};
     const char* __len = "l";
     this->__format_int(__fmt+1, __len, false, __iob.flags());
-    const unsigned __nbuf = (numeric_limits<unsigned long>::digits / 3)
-                          + ((numeric_limits<unsigned long>::digits % 3) != 0)
-                          + ((__iob.flags() & ios_base::showbase) != 0)
-                          + 1;
+    // Worst case is octal, with showbase enabled.
+    _LIBCPP_CONSTEXPR const unsigned __nbuf
+        = (numeric_limits<unsigned long>::digits / 3)        // 1 char per 3 bits
+        + ((numeric_limits<unsigned long>::digits % 3) != 0) // round up
+        + 2; // base prefix + terminating null character
     char __nar[__nbuf];
     int __nc = __libcpp_snprintf_l(__nar, sizeof(__nar), _LIBCPP_GET_C_LOCALE, __fmt, __v);
     char* __ne = __nar + __nc;
@@ -1534,10 +1544,11 @@ num_put<_CharT, _OutputIterator>::do_put(iter_type __s, ios_base& __iob,
     char __fmt[8] = {'%', 0};
     const char* __len = "ll";
     this->__format_int(__fmt+1, __len, false, __iob.flags());
-    const unsigned __nbuf = (numeric_limits<unsigned long long>::digits / 3)
-                          + ((numeric_limits<unsigned long long>::digits % 3) != 0)
-                          + ((__iob.flags() & ios_base::showbase) != 0)
-                          + 1;
+    // Worst case is octal, with showbase enabled.
+    _LIBCPP_CONSTEXPR const unsigned __nbuf
+        = (numeric_limits<unsigned long long>::digits / 3)        // 1 char per 3 bits
+        + ((numeric_limits<unsigned long long>::digits % 3) != 0) // round up
+        + 2; // base prefix + terminating null character
     char __nar[__nbuf];
     int __nc = __libcpp_snprintf_l(__nar, sizeof(__nar), _LIBCPP_GET_C_LOCALE, __fmt, __v);
     char* __ne = __nar + __nc;
@@ -3567,7 +3578,7 @@ messages<_CharT>::do_open(const basic_string<char>& __nm, const locale&) const
         __cat = static_cast<catalog>((static_cast<size_t>(__cat) >> 1));
     return __cat;
 #else // !_LIBCPP_HAS_CATOPEN
-    _LIBCPP_UNUSED_VAR(__nm);
+    (void)__nm;
     return -1;
 #endif // _LIBCPP_HAS_CATOPEN
 }
@@ -3591,9 +3602,9 @@ messages<_CharT>::do_get(catalog __c, int __set, int __msgid,
                                                         __n, __n + _VSTD::strlen(__n));
     return __w;
 #else // !_LIBCPP_HAS_CATOPEN
-    _LIBCPP_UNUSED_VAR(__c);
-    _LIBCPP_UNUSED_VAR(__set);
-    _LIBCPP_UNUSED_VAR(__msgid);
+    (void)__c;
+    (void)__set;
+    (void)__msgid;
     return __dflt;
 #endif // _LIBCPP_HAS_CATOPEN
 }
@@ -3608,7 +3619,7 @@ messages<_CharT>::do_close(catalog __c) const
     nl_catd __cat = (nl_catd)__c;
     catclose(__cat);
 #else // !_LIBCPP_HAS_CATOPEN
-    _LIBCPP_UNUSED_VAR(__c);
+    (void)__c;
 #endif // _LIBCPP_HAS_CATOPEN
 }
 
@@ -3748,7 +3759,7 @@ wstring_convert<_Codecvt, _Elem, _Wide_alloc, _Byte_alloc>::
     __wc.__cvtptr_ = nullptr;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template<class _Codecvt, class _Elem, class _Wide_alloc, class _Byte_alloc>
 wstring_convert<_Codecvt, _Elem, _Wide_alloc, _Byte_alloc>::~wstring_convert()
@@ -4376,4 +4387,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_LOCALE
+#endif // _LIBCPP_LOCALE
lib/libcxx/include/locale.h
@@ -45,4 +45,4 @@ Functions:
 
 #include_next <locale.h>
 
-#endif  // _LIBCPP_LOCALE_H
+#endif // _LIBCPP_LOCALE_H
lib/libcxx/include/map
@@ -43,7 +43,6 @@ public:
     typedef INSERT_RETURN_TYPE<iterator, node_type>  insert_return_type;     // C++17
 
     class value_compare
-        : public binary_function<value_type, value_type, bool>
     {
         friend class map;
     protected:
@@ -51,6 +50,9 @@ public:
 
         value_compare(key_compare c);
     public:
+        typedef bool result_type;  // deprecated in C++17, removed in C++20
+        typedef value_type first_argument_type;  // deprecated in C++17, removed in C++20
+        typedef value_type second_argument_type;  // deprecated in C++17, removed in C++20
         bool operator()(const value_type& x, const value_type& y) const;
     };
 
@@ -191,10 +193,14 @@ public:
         iterator find(const K& x);              // C++14
     template<typename K>
         const_iterator find(const K& x) const;  // C++14
+
     template<typename K>
       size_type count(const K& x) const;        // C++14
     size_type      count(const key_type& k) const;
-        bool contains(const key_type& x) const; // C++20
+
+    bool           contains(const key_type& x) const;  // C++20
+    template<class K> bool contains(const K& x) const; // C++20
+
           iterator lower_bound(const key_type& k);
     const_iterator lower_bound(const key_type& k) const;
     template<typename K>
@@ -283,13 +289,15 @@ public:
     typedef unspecified                              node_type;              // C++17
 
     class value_compare
-        : public binary_function<value_type,value_type,bool>
     {
         friend class multimap;
     protected:
         key_compare comp;
         value_compare(key_compare c);
     public:
+        typedef bool result_type;  // deprecated in C++17, removed in C++20
+        typedef value_type first_argument_type;  // deprecated in C++17, removed in C++20
+        typedef value_type second_argument_type;  // deprecated in C++17, removed in C++20
         bool operator()(const value_type& x, const value_type& y) const;
     };
 
@@ -406,10 +414,14 @@ public:
         iterator find(const K& x);              // C++14
     template<typename K>
         const_iterator find(const K& x) const;  // C++14
+
     template<typename K>
       size_type count(const K& x) const;        // C++14
     size_type      count(const key_type& k) const;
-        bool contains(const key_type& x) const; // C++20
+
+    bool           contains(const key_type& x) const;  // C++20
+    template<class K> bool contains(const K& x) const; // C++20
+
           iterator lower_bound(const key_type& k);
     const_iterator lower_bound(const key_type& k) const;
     template<typename K>
@@ -478,14 +490,18 @@ erase_if(multimap<Key, T, Compare, Allocator>& c, Predicate pred);  // C++20
 */
 
 #include <__config>
-#include <__tree>
+#include <__debug>
+#include <__functional/is_transparent.h>
 #include <__node_handle>
-#include <iterator>
-#include <memory>
-#include <utility>
+#include <__tree>
+#include <__utility/forward.h>
+#include <compare>
 #include <functional>
 #include <initializer_list>
+#include <iterator> // __libcpp_erase_if_container
+#include <memory>
 #include <type_traits>
+#include <utility>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -633,7 +649,7 @@ public:
         {
             __x.__value_constructed = false;
         }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     void operator()(pointer __p) _NOEXCEPT
@@ -656,7 +672,7 @@ template <class _TreeIterator> class __map_const_iterator;
 #ifndef _LIBCPP_CXX03_LANG
 
 template <class _Key, class _Tp>
-struct __value_type
+struct _LIBCPP_STANDALONE_DEBUG __value_type
 {
     typedef _Key                                     key_type;
     typedef _Tp                                      mapped_type;
@@ -904,23 +920,32 @@ public:
     typedef _Key                                     key_type;
     typedef _Tp                                      mapped_type;
     typedef pair<const key_type, mapped_type>        value_type;
-    typedef typename __identity<_Compare>::type      key_compare;
-    typedef typename __identity<_Allocator>::type    allocator_type;
+    typedef __identity_t<_Compare>                   key_compare;
+    typedef __identity_t<_Allocator>                 allocator_type;
     typedef value_type&                              reference;
     typedef const value_type&                        const_reference;
 
     static_assert((is_same<typename allocator_type::value_type, value_type>::value),
                   "Allocator::value_type must be same type as value_type");
 
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
     class _LIBCPP_TEMPLATE_VIS value_compare
+#if defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
         : public binary_function<value_type, value_type, bool>
+#endif
     {
+_LIBCPP_SUPPRESS_DEPRECATED_POP
         friend class map;
     protected:
         key_compare comp;
 
         _LIBCPP_INLINE_VISIBILITY value_compare(key_compare c) : comp(c) {}
     public:
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+        _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+        _LIBCPP_DEPRECATED_IN_CXX17 typedef value_type first_argument_type;
+        _LIBCPP_DEPRECATED_IN_CXX17 typedef value_type second_argument_type;
+#endif
         _LIBCPP_INLINE_VISIBILITY
         bool operator()(const value_type& __x, const value_type& __y) const
             {return comp(__x.first, __y.first);}
@@ -1071,7 +1096,7 @@ public:
             return *this;
         }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     explicit map(const allocator_type& __a)
@@ -1168,7 +1193,7 @@ public:
         iterator insert(const_iterator __pos, _Pp&& __p)
             {return __tree_.__insert_unique(__pos.__i_, _VSTD::forward<_Pp>(__p));}
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     pair<iterator, bool>
@@ -1404,6 +1429,10 @@ public:
 #if _LIBCPP_STD_VER > 17
     _LIBCPP_INLINE_VISIBILITY
     bool contains(const key_type& __k) const {return find(__k) != end();}
+    template <typename _K2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename enable_if<__is_transparent<_Compare, _K2>::value, bool>::type
+    contains(const _K2& __k) const { return find(__k) != end(); }
 #endif // _LIBCPP_STD_VER > 17
 
     _LIBCPP_INLINE_VISIBILITY
@@ -1565,7 +1594,7 @@ map<_Key, _Tp, _Compare, _Allocator>::operator[](const key_type& __k)
     return __r->__value_.__get_value().second;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Key, class _Tp, class _Compare, class _Allocator>
 _Tp&
@@ -1660,7 +1689,7 @@ template <class _Key, class _Tp, class _Compare, class _Allocator,
 inline _LIBCPP_INLINE_VISIBILITY
     typename map<_Key, _Tp, _Compare, _Allocator>::size_type
     erase_if(map<_Key, _Tp, _Compare, _Allocator>& __c, _Predicate __pred) {
-  return __libcpp_erase_if_container(__c, __pred);
+  return _VSTD::__libcpp_erase_if_container(__c, __pred);
 }
 #endif
 
@@ -1674,17 +1703,21 @@ public:
     typedef _Key                                     key_type;
     typedef _Tp                                      mapped_type;
     typedef pair<const key_type, mapped_type>        value_type;
-    typedef typename __identity<_Compare>::type      key_compare;
-    typedef typename __identity<_Allocator>::type    allocator_type;
+    typedef __identity_t<_Compare>                   key_compare;
+    typedef __identity_t<_Allocator>                 allocator_type;
     typedef value_type&                              reference;
     typedef const value_type&                        const_reference;
 
     static_assert((is_same<typename allocator_type::value_type, value_type>::value),
                   "Allocator::value_type must be same type as value_type");
 
+_LIBCPP_SUPPRESS_DEPRECATED_PUSH
     class _LIBCPP_TEMPLATE_VIS value_compare
+#if defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
         : public binary_function<value_type, value_type, bool>
+#endif
     {
+_LIBCPP_SUPPRESS_DEPRECATED_POP
         friend class multimap;
     protected:
         key_compare comp;
@@ -1692,6 +1725,11 @@ public:
         _LIBCPP_INLINE_VISIBILITY
         value_compare(key_compare c) : comp(c) {}
     public:
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+        _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
+        _LIBCPP_DEPRECATED_IN_CXX17 typedef value_type first_argument_type;
+        _LIBCPP_DEPRECATED_IN_CXX17 typedef value_type second_argument_type;
+#endif
         _LIBCPP_INLINE_VISIBILITY
         bool operator()(const value_type& __x, const value_type& __y) const
             {return comp(__x.first, __y.first);}
@@ -1842,7 +1880,7 @@ public:
             return *this;
         }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     explicit multimap(const allocator_type& __a)
@@ -1945,7 +1983,7 @@ public:
     void insert(initializer_list<value_type> __il)
         {insert(__il.begin(), __il.end());}
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     iterator insert(const value_type& __v) {return __tree_.__insert_multi(__v);}
@@ -2070,6 +2108,10 @@ public:
 #if _LIBCPP_STD_VER > 17
     _LIBCPP_INLINE_VISIBILITY
     bool contains(const key_type& __k) const {return find(__k) != end();}
+    template <typename _K2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename enable_if<__is_transparent<_Compare, _K2>::value, bool>::type
+    contains(const _K2& __k) const { return find(__k) != end(); }
 #endif // _LIBCPP_STD_VER > 17
 
     _LIBCPP_INLINE_VISIBILITY
@@ -2246,10 +2288,10 @@ inline _LIBCPP_INLINE_VISIBILITY
     typename multimap<_Key, _Tp, _Compare, _Allocator>::size_type
     erase_if(multimap<_Key, _Tp, _Compare, _Allocator>& __c,
              _Predicate __pred) {
-  return __libcpp_erase_if_container(__c, __pred);
+  return _VSTD::__libcpp_erase_if_container(__c, __pred);
 }
 #endif
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_MAP
+#endif // _LIBCPP_MAP
lib/libcxx/include/math.h
@@ -318,7 +318,11 @@ _LIBCPP_INLINE_VISIBILITY
 bool
 __libcpp_signbit(_A1 __lcpp_x) _NOEXCEPT
 {
+#if __has_builtin(__builtin_signbit)
+    return __builtin_signbit(__lcpp_x);
+#else
     return signbit(__lcpp_x);
+#endif
 }
 
 #undef signbit
@@ -369,7 +373,7 @@ typename std::enable_if<
 signbit(_A1) _NOEXCEPT
 { return false; }
 
-#endif  // signbit
+#endif // signbit
 
 // fpclassify
 
@@ -380,7 +384,12 @@ _LIBCPP_INLINE_VISIBILITY
 int
 __libcpp_fpclassify(_A1 __lcpp_x) _NOEXCEPT
 {
+#if __has_builtin(__builtin_fpclassify)
+  return __builtin_fpclassify(FP_NAN, FP_INFINITE, FP_NORMAL, FP_SUBNORMAL,
+                                FP_ZERO, __lcpp_x);
+#else
     return fpclassify(__lcpp_x);
+#endif
 }
 
 #undef fpclassify
@@ -415,7 +424,7 @@ typename std::enable_if<std::is_integral<_A1>::value, int>::type
 fpclassify(_A1 __lcpp_x) _NOEXCEPT
 { return __lcpp_x == 0 ? FP_ZERO : FP_NORMAL; }
 
-#endif  // fpclassify
+#endif // fpclassify
 
 // isfinite
 
@@ -426,7 +435,11 @@ _LIBCPP_INLINE_VISIBILITY
 bool
 __libcpp_isfinite(_A1 __lcpp_x) _NOEXCEPT
 {
+#if __has_builtin(__builtin_isfinite)
+    return __builtin_isfinite(__lcpp_x);
+#else
     return isfinite(__lcpp_x);
+#endif
 }
 
 #undef isfinite
@@ -449,7 +462,7 @@ typename std::enable_if<
 isfinite(_A1) _NOEXCEPT
 { return true; }
 
-#endif  // isfinite
+#endif // isfinite
 
 // isinf
 
@@ -460,7 +473,11 @@ _LIBCPP_INLINE_VISIBILITY
 bool
 __libcpp_isinf(_A1 __lcpp_x) _NOEXCEPT
 {
+#if __has_builtin(__builtin_isinf)
+    return __builtin_isinf(__lcpp_x);
+#else
     return isinf(__lcpp_x);
+#endif
 }
 
 #undef isinf
@@ -497,7 +514,7 @@ bool
 isinf(long double __lcpp_x) _NOEXCEPT { return __libcpp_isinf(__lcpp_x); }
 #endif
 
-#endif  // isinf
+#endif // isinf
 
 // isnan
 
@@ -545,7 +562,7 @@ bool
 isnan(long double __lcpp_x) _NOEXCEPT { return __libcpp_isnan(__lcpp_x); }
 #endif
 
-#endif  // isnan
+#endif // isnan
 
 // isnormal
 
@@ -556,7 +573,11 @@ _LIBCPP_INLINE_VISIBILITY
 bool
 __libcpp_isnormal(_A1 __lcpp_x) _NOEXCEPT
 {
+#if __has_builtin(__builtin_isnormal)
+    return __builtin_isnormal(__lcpp_x);
+#else
     return isnormal(__lcpp_x);
+#endif
 }
 
 #undef isnormal
@@ -575,7 +596,7 @@ typename std::enable_if<std::is_integral<_A1>::value, bool>::type
 isnormal(_A1 __lcpp_x) _NOEXCEPT
 { return __lcpp_x != 0; }
 
-#endif  // isnormal
+#endif // isnormal
 
 // isgreater
 
@@ -605,7 +626,7 @@ isgreater(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT
     return __libcpp_isgreater((type)__lcpp_x, (type)__lcpp_y);
 }
 
-#endif  // isgreater
+#endif // isgreater
 
 // isgreaterequal
 
@@ -635,7 +656,7 @@ isgreaterequal(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT
     return __libcpp_isgreaterequal((type)__lcpp_x, (type)__lcpp_y);
 }
 
-#endif  // isgreaterequal
+#endif // isgreaterequal
 
 // isless
 
@@ -665,7 +686,7 @@ isless(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT
     return __libcpp_isless((type)__lcpp_x, (type)__lcpp_y);
 }
 
-#endif  // isless
+#endif // isless
 
 // islessequal
 
@@ -695,7 +716,7 @@ islessequal(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT
     return __libcpp_islessequal((type)__lcpp_x, (type)__lcpp_y);
 }
 
-#endif  // islessequal
+#endif // islessequal
 
 // islessgreater
 
@@ -725,7 +746,7 @@ islessgreater(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT
     return __libcpp_islessgreater((type)__lcpp_x, (type)__lcpp_y);
 }
 
-#endif  // islessgreater
+#endif // islessgreater
 
 // isunordered
 
@@ -755,7 +776,7 @@ isunordered(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT
     return __libcpp_isunordered((type)__lcpp_x, (type)__lcpp_y);
 }
 
-#endif  // isunordered
+#endif // isunordered
 
 // abs
 //
@@ -1099,16 +1120,43 @@ cbrt(_A1 __lcpp_x) _NOEXCEPT {return ::cbrt((double)__lcpp_x);}
 
 // copysign
 
-inline _LIBCPP_INLINE_VISIBILITY float copysign(float __lcpp_x,
-                                                float __lcpp_y) _NOEXCEPT {
+#if __has_builtin(__builtin_copysignf)
+_LIBCPP_CONSTEXPR
+#endif
+inline _LIBCPP_INLINE_VISIBILITY float __libcpp_copysign(float __lcpp_x, float __lcpp_y) _NOEXCEPT {
+#if __has_builtin(__builtin_copysignf)
+  return __builtin_copysignf(__lcpp_x, __lcpp_y);
+#else
   return ::copysignf(__lcpp_x, __lcpp_y);
+#endif
+}
+
+#if __has_builtin(__builtin_copysign)
+_LIBCPP_CONSTEXPR
+#endif
+inline _LIBCPP_INLINE_VISIBILITY double __libcpp_copysign(double __lcpp_x, double __lcpp_y) _NOEXCEPT {
+#if __has_builtin(__builtin_copysign)
+  return __builtin_copysign(__lcpp_x, __lcpp_y);
+#else
+  return ::copysign(__lcpp_x, __lcpp_y);
+#endif
 }
-inline _LIBCPP_INLINE_VISIBILITY long double
-copysign(long double __lcpp_x, long double __lcpp_y) _NOEXCEPT {
+
+#if __has_builtin(__builtin_copysignl)
+_LIBCPP_CONSTEXPR
+#endif
+inline _LIBCPP_INLINE_VISIBILITY long double __libcpp_copysign(long double __lcpp_x, long double __lcpp_y) _NOEXCEPT {
+#if __has_builtin(__builtin_copysignl)
+  return __builtin_copysignl(__lcpp_x, __lcpp_y);
+#else
   return ::copysignl(__lcpp_x, __lcpp_y);
+#endif
 }
 
 template <class _A1, class _A2>
+#if __has_builtin(__builtin_copysign)
+_LIBCPP_CONSTEXPR
+#endif
 inline _LIBCPP_INLINE_VISIBILITY
 typename std::_EnableIf
 <
@@ -1116,12 +1164,35 @@ typename std::_EnableIf
     std::is_arithmetic<_A2>::value,
     std::__promote<_A1, _A2>
 >::type
-copysign(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT
-{
+__libcpp_copysign(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT {
     typedef typename std::__promote<_A1, _A2>::type __result_type;
     static_assert((!(std::_IsSame<_A1, __result_type>::value &&
                      std::_IsSame<_A2, __result_type>::value)), "");
+#if __has_builtin(__builtin_copysign)
+    return __builtin_copysign((__result_type)__lcpp_x, (__result_type)__lcpp_y);
+#else
     return ::copysign((__result_type)__lcpp_x, (__result_type)__lcpp_y);
+#endif
+}
+
+inline _LIBCPP_INLINE_VISIBILITY float copysign(float __lcpp_x, float __lcpp_y) _NOEXCEPT {
+  return ::__libcpp_copysign(__lcpp_x, __lcpp_y);
+}
+
+inline _LIBCPP_INLINE_VISIBILITY long double copysign(long double __lcpp_x, long double __lcpp_y) _NOEXCEPT {
+  return ::__libcpp_copysign(__lcpp_x, __lcpp_y);
+}
+
+template <class _A1, class _A2>
+inline _LIBCPP_INLINE_VISIBILITY
+typename std::_EnableIf
+<
+    std::is_arithmetic<_A1>::value &&
+    std::is_arithmetic<_A2>::value,
+    std::__promote<_A1, _A2>
+>::type
+    copysign(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT {
+  return ::__libcpp_copysign(__lcpp_x, __lcpp_y);
 }
 
 // erf
@@ -1187,8 +1258,22 @@ fdim(_A1 __lcpp_x, _A2 __lcpp_y) _NOEXCEPT
 
 // fma
 
-inline _LIBCPP_INLINE_VISIBILITY float       fma(float __lcpp_x, float __lcpp_y, float __lcpp_z) _NOEXCEPT                   {return ::fmaf(__lcpp_x, __lcpp_y, __lcpp_z);}
-inline _LIBCPP_INLINE_VISIBILITY long double fma(long double __lcpp_x, long double __lcpp_y, long double __lcpp_z) _NOEXCEPT {return ::fmal(__lcpp_x, __lcpp_y, __lcpp_z);}
+inline _LIBCPP_INLINE_VISIBILITY float       fma(float __lcpp_x, float __lcpp_y, float __lcpp_z) _NOEXCEPT
+{
+#if __has_builtin(__builtin_fmaf)
+    return __builtin_fmaf(__lcpp_x, __lcpp_y, __lcpp_z);
+#else
+    return ::fmaf(__lcpp_x, __lcpp_y, __lcpp_z);
+#endif
+}
+inline _LIBCPP_INLINE_VISIBILITY long double fma(long double __lcpp_x, long double __lcpp_y, long double __lcpp_z) _NOEXCEPT
+{
+#if __has_builtin(__builtin_fmal)
+    return __builtin_fmal(__lcpp_x, __lcpp_y, __lcpp_z);
+#else
+    return ::fmal(__lcpp_x, __lcpp_y, __lcpp_z);
+#endif
+}
 
 template <class _A1, class _A2, class _A3>
 inline _LIBCPP_INLINE_VISIBILITY
@@ -1205,7 +1290,11 @@ fma(_A1 __lcpp_x, _A2 __lcpp_y, _A3 __lcpp_z) _NOEXCEPT
     static_assert((!(std::_IsSame<_A1, __result_type>::value &&
                      std::_IsSame<_A2, __result_type>::value &&
                      std::_IsSame<_A3, __result_type>::value)), "");
+#if __has_builtin(__builtin_fma)
+    return __builtin_fma((__result_type)__lcpp_x, (__result_type)__lcpp_y, (__result_type)__lcpp_z);
+#else
     return ::fma((__result_type)__lcpp_x, (__result_type)__lcpp_y, (__result_type)__lcpp_z);
+#endif
 }
 
 // fmax
@@ -1293,23 +1382,65 @@ lgamma(_A1 __lcpp_x) _NOEXCEPT {return ::lgamma((double)__lcpp_x);}
 
 // llrint
 
-inline _LIBCPP_INLINE_VISIBILITY long long llrint(float __lcpp_x) _NOEXCEPT       {return ::llrintf(__lcpp_x);}
-inline _LIBCPP_INLINE_VISIBILITY long long llrint(long double __lcpp_x) _NOEXCEPT {return ::llrintl(__lcpp_x);}
+inline _LIBCPP_INLINE_VISIBILITY long long llrint(float __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_llrintf)
+    return __builtin_llrintf(__lcpp_x);
+#else
+    return ::llrintf(__lcpp_x);
+#endif
+}
+inline _LIBCPP_INLINE_VISIBILITY long long llrint(long double __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_llrintl)
+    return __builtin_llrintl(__lcpp_x);
+#else
+    return ::llrintl(__lcpp_x);
+#endif
+}
 
 template <class _A1>
 inline _LIBCPP_INLINE_VISIBILITY
 typename std::enable_if<std::is_integral<_A1>::value, long long>::type
-llrint(_A1 __lcpp_x) _NOEXCEPT {return ::llrint((double)__lcpp_x);}
+llrint(_A1 __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_llrint)
+    return __builtin_llrint((double)__lcpp_x);
+#else
+    return ::llrint((double)__lcpp_x);
+#endif
+}
 
 // llround
 
-inline _LIBCPP_INLINE_VISIBILITY long long llround(float __lcpp_x) _NOEXCEPT       {return ::llroundf(__lcpp_x);}
-inline _LIBCPP_INLINE_VISIBILITY long long llround(long double __lcpp_x) _NOEXCEPT {return ::llroundl(__lcpp_x);}
+inline _LIBCPP_INLINE_VISIBILITY long long llround(float __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_llroundf)
+    return __builtin_llroundf(__lcpp_x);
+#else
+    return ::llroundf(__lcpp_x);
+#endif
+}
+inline _LIBCPP_INLINE_VISIBILITY long long llround(long double __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_llroundl)
+    return __builtin_llroundl(__lcpp_x);
+#else
+    return ::llroundl(__lcpp_x);
+#endif
+}
 
 template <class _A1>
 inline _LIBCPP_INLINE_VISIBILITY
 typename std::enable_if<std::is_integral<_A1>::value, long long>::type
-llround(_A1 __lcpp_x) _NOEXCEPT {return ::llround((double)__lcpp_x);}
+llround(_A1 __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_llround)
+    return __builtin_llround((double)__lcpp_x);
+#else
+    return ::llround((double)__lcpp_x);
+#endif
+}
 
 // log1p
 
@@ -1343,23 +1474,65 @@ logb(_A1 __lcpp_x) _NOEXCEPT {return ::logb((double)__lcpp_x);}
 
 // lrint
 
-inline _LIBCPP_INLINE_VISIBILITY long lrint(float __lcpp_x) _NOEXCEPT       {return ::lrintf(__lcpp_x);}
-inline _LIBCPP_INLINE_VISIBILITY long lrint(long double __lcpp_x) _NOEXCEPT {return ::lrintl(__lcpp_x);}
+inline _LIBCPP_INLINE_VISIBILITY long lrint(float __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_lrintf)
+    return __builtin_lrintf(__lcpp_x);
+#else
+    return ::lrintf(__lcpp_x);
+#endif
+}
+inline _LIBCPP_INLINE_VISIBILITY long lrint(long double __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_lrintl)
+    return __builtin_lrintl(__lcpp_x);
+#else
+    return ::lrintl(__lcpp_x);
+#endif
+}
 
 template <class _A1>
 inline _LIBCPP_INLINE_VISIBILITY
 typename std::enable_if<std::is_integral<_A1>::value, long>::type
-lrint(_A1 __lcpp_x) _NOEXCEPT {return ::lrint((double)__lcpp_x);}
+lrint(_A1 __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_lrint)
+    return __builtin_lrint((double)__lcpp_x);
+#else
+    return ::lrint((double)__lcpp_x);
+#endif
+}
 
 // lround
 
-inline _LIBCPP_INLINE_VISIBILITY long lround(float __lcpp_x) _NOEXCEPT       {return ::lroundf(__lcpp_x);}
-inline _LIBCPP_INLINE_VISIBILITY long lround(long double __lcpp_x) _NOEXCEPT {return ::lroundl(__lcpp_x);}
+inline _LIBCPP_INLINE_VISIBILITY long lround(float __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_lroundf)
+    return __builtin_lroundf(__lcpp_x);
+#else
+    return ::lroundf(__lcpp_x);
+#endif
+}
+inline _LIBCPP_INLINE_VISIBILITY long lround(long double __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_lroundl)
+    return __builtin_lroundl(__lcpp_x);
+#else
+    return ::lroundl(__lcpp_x);
+#endif
+}
 
 template <class _A1>
 inline _LIBCPP_INLINE_VISIBILITY
 typename std::enable_if<std::is_integral<_A1>::value, long>::type
-lround(_A1 __lcpp_x) _NOEXCEPT {return ::lround((double)__lcpp_x);}
+lround(_A1 __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_lround)
+    return __builtin_lround((double)__lcpp_x);
+#else
+    return ::lround((double)__lcpp_x);
+#endif
+}
 
 // nan
 
@@ -1448,23 +1621,65 @@ remquo(_A1 __lcpp_x, _A2 __lcpp_y, int* __lcpp_z) _NOEXCEPT
 
 // rint
 
-inline _LIBCPP_INLINE_VISIBILITY float       rint(float __lcpp_x) _NOEXCEPT       {return ::rintf(__lcpp_x);}
-inline _LIBCPP_INLINE_VISIBILITY long double rint(long double __lcpp_x) _NOEXCEPT {return ::rintl(__lcpp_x);}
+inline _LIBCPP_INLINE_VISIBILITY float       rint(float __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_rintf)
+    return __builtin_rintf(__lcpp_x);
+#else
+    return ::rintf(__lcpp_x);
+#endif
+}
+inline _LIBCPP_INLINE_VISIBILITY long double rint(long double __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_rintl)
+    return __builtin_rintl(__lcpp_x);
+#else
+    return ::rintl(__lcpp_x);
+#endif
+}
 
 template <class _A1>
 inline _LIBCPP_INLINE_VISIBILITY
 typename std::enable_if<std::is_integral<_A1>::value, double>::type
-rint(_A1 __lcpp_x) _NOEXCEPT {return ::rint((double)__lcpp_x);}
+rint(_A1 __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_rint)
+    return __builtin_rint((double)__lcpp_x);
+#else
+    return ::rint((double)__lcpp_x);
+#endif
+}
 
 // round
 
-inline _LIBCPP_INLINE_VISIBILITY float       round(float __lcpp_x) _NOEXCEPT       {return ::roundf(__lcpp_x);}
-inline _LIBCPP_INLINE_VISIBILITY long double round(long double __lcpp_x) _NOEXCEPT {return ::roundl(__lcpp_x);}
+inline _LIBCPP_INLINE_VISIBILITY float       round(float __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_round)
+    return __builtin_round(__lcpp_x);
+#else
+    return ::round(__lcpp_x);
+#endif
+}
+inline _LIBCPP_INLINE_VISIBILITY long double round(long double __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_roundl)
+    return __builtin_roundl(__lcpp_x);
+#else
+    return ::roundl(__lcpp_x);
+#endif
+}
 
 template <class _A1>
 inline _LIBCPP_INLINE_VISIBILITY
 typename std::enable_if<std::is_integral<_A1>::value, double>::type
-round(_A1 __lcpp_x) _NOEXCEPT {return ::round((double)__lcpp_x);}
+round(_A1 __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_round)
+    return __builtin_round((double)__lcpp_x);
+#else
+    return ::round((double)__lcpp_x);
+#endif
+}
 
 // scalbln
 
@@ -1498,13 +1713,34 @@ tgamma(_A1 __lcpp_x) _NOEXCEPT {return ::tgamma((double)__lcpp_x);}
 
 // trunc
 
-inline _LIBCPP_INLINE_VISIBILITY float       trunc(float __lcpp_x) _NOEXCEPT       {return ::truncf(__lcpp_x);}
-inline _LIBCPP_INLINE_VISIBILITY long double trunc(long double __lcpp_x) _NOEXCEPT {return ::truncl(__lcpp_x);}
+inline _LIBCPP_INLINE_VISIBILITY float       trunc(float __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_trunc)
+    return __builtin_trunc(__lcpp_x);
+#else
+    return ::trunc(__lcpp_x);
+#endif
+}
+inline _LIBCPP_INLINE_VISIBILITY long double trunc(long double __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_truncl)
+    return __builtin_truncl(__lcpp_x);
+#else
+    return ::truncl(__lcpp_x);
+#endif
+}
 
 template <class _A1>
 inline _LIBCPP_INLINE_VISIBILITY
 typename std::enable_if<std::is_integral<_A1>::value, double>::type
-trunc(_A1 __lcpp_x) _NOEXCEPT {return ::trunc((double)__lcpp_x);}
+trunc(_A1 __lcpp_x) _NOEXCEPT
+{
+#if __has_builtin(__builtin_trunc)
+    return __builtin_trunc((double)__lcpp_x);
+#else
+    return ::trunc((double)__lcpp_x);
+#endif
+}
 
 } // extern "C++"
 
@@ -1524,4 +1760,4 @@ trunc(_A1 __lcpp_x) _NOEXCEPT {return ::trunc((double)__lcpp_x);}
 #include_next <math.h>
 #endif
 
-#endif  // _LIBCPP_MATH_H
+#endif // _LIBCPP_MATH_H
lib/libcxx/include/memory
@@ -99,7 +99,7 @@ struct allocator_traits
 };
 
 template <>
-class allocator<void> // deprecated in C++17, removed in C++20
+class allocator<void> // removed in C++20
 {
 public:
     typedef void*                                 pointer;
@@ -153,14 +153,17 @@ template <class T, class U>
 bool operator!=(const allocator<T>&, const allocator<U>&) noexcept; // constexpr in C++20
 
 template <class OutputIterator, class T>
-class raw_storage_iterator
-    : public iterator<output_iterator_tag,
-                      T,                               // purposefully not C++03
-                      ptrdiff_t,                       // purposefully not C++03
-                      T*,                              // purposefully not C++03
-                      raw_storage_iterator&>           // purposefully not C++03
+class raw_storage_iterator // deprecated in C++17, removed in C++20
+    : public iterator<output_iterator_tag, void, void, void, void> // until C++17
 {
 public:
+    typedef output_iterator_tag iterator_category;
+    typedef void                value_type;
+    typedef void                difference_type; // until C++20
+    typedef ptrdiff_t           difference_type; // since C++20
+    typedef void                pointer;
+    typedef void                reference;
+
     explicit raw_storage_iterator(OutputIterator x);
     raw_storage_iterator& operator*();
     raw_storage_iterator& operator=(const T& element);
@@ -651,12 +654,12 @@ template <class T, class Alloc>
   inline constexpr bool uses_allocator_v = uses_allocator<T, Alloc>::value;
 
 // Pointer safety
-enum class pointer_safety { relaxed, preferred, strict };
-void declare_reachable(void *p);
-template <class T> T *undeclare_reachable(T *p);
-void declare_no_pointers(char *p, size_t n);
-void undeclare_no_pointers(char *p, size_t n);
-pointer_safety get_pointer_safety() noexcept;
+enum class pointer_safety { relaxed, preferred, strict }; // since C++11
+void declare_reachable(void *p);                          // since C++11
+template <class T> T *undeclare_reachable(T *p);          // since C++11
+void declare_no_pointers(char *p, size_t n);              // since C++11
+void undeclare_no_pointers(char *p, size_t n);            // since C++11
+pointer_safety get_pointer_safety() noexcept;             // since C++11
 
 void* align(size_t alignment, size_t size, void*& ptr, size_t& space);
 
@@ -665,29 +668,40 @@ void* align(size_t alignment, size_t size, void*& ptr, size_t& space);
 */
 
 #include <__config>
-#include <__availability>
-#include <type_traits>
-#include <typeinfo>
+#include <__functional_base>
+#include <__memory/addressof.h>
+#include <__memory/allocation_guard.h>
+#include <__memory/allocator.h>
+#include <__memory/allocator_arg_t.h>
+#include <__memory/allocator_traits.h>
+#include <__memory/compressed_pair.h>
+#include <__memory/construct_at.h>
+#include <__memory/pointer_safety.h>
+#include <__memory/pointer_traits.h>
+#include <__memory/raw_storage_iterator.h>
+#include <__memory/shared_ptr.h>
+#include <__memory/temporary_buffer.h>
+#include <__memory/uninitialized_algorithms.h>
+#include <__memory/unique_ptr.h>
+#include <__memory/uses_allocator.h>
+#include <compare>
 #include <cstddef>
 #include <cstdint>
-#include <new>
-#include <utility>
-#include <limits>
-#include <iterator>
-#include <__functional_base>
+#include <cstring>
 #include <iosfwd>
-#include <tuple>
+#include <iterator>
+#include <new>
 #include <stdexcept>
-#include <cstring>
-#include <__memory/allocator_traits.h>
-#include <__memory/base.h>
-#include <__memory/pointer_traits.h>
-#include <__memory/utilities.h>
-#if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
-#  include <atomic>
-#endif
+#include <tuple>
+#include <type_traits>
+#include <typeinfo>
+#include <utility>
 #include <version>
 
+#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
+#   include <__memory/auto_ptr.h>
+#endif
+
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
@@ -698,286 +712,6 @@ _LIBCPP_PUSH_MACROS
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
-template <class _ValueType>
-inline _LIBCPP_INLINE_VISIBILITY
-_ValueType __libcpp_relaxed_load(_ValueType const* __value) {
-#if !defined(_LIBCPP_HAS_NO_THREADS) && \
-    defined(__ATOMIC_RELAXED) &&        \
-    (__has_builtin(__atomic_load_n) || defined(_LIBCPP_COMPILER_GCC))
-    return __atomic_load_n(__value, __ATOMIC_RELAXED);
-#else
-    return *__value;
-#endif
-}
-
-template <class _ValueType>
-inline _LIBCPP_INLINE_VISIBILITY
-_ValueType __libcpp_acquire_load(_ValueType const* __value) {
-#if !defined(_LIBCPP_HAS_NO_THREADS) && \
-    defined(__ATOMIC_ACQUIRE) &&        \
-    (__has_builtin(__atomic_load_n) || defined(_LIBCPP_COMPILER_GCC))
-    return __atomic_load_n(__value, __ATOMIC_ACQUIRE);
-#else
-    return *__value;
-#endif
-}
-
-template <bool _UsePointerTraits> struct __to_address_helper;
-
-template <> struct __to_address_helper<true> {
-    template <class _Pointer>
-    using __return_type = decltype(pointer_traits<_Pointer>::to_address(_VSTD::declval<const _Pointer&>()));
-
-    template <class _Pointer>
-    _LIBCPP_CONSTEXPR
-    static __return_type<_Pointer>
-    __do_it(const _Pointer &__p) _NOEXCEPT { return pointer_traits<_Pointer>::to_address(__p); }
-};
-
-template <class _Pointer, bool _Dummy = true>
-using __choose_to_address = __to_address_helper<_IsValidExpansion<__to_address_helper<_Dummy>::template __return_type, _Pointer>::value>;
-
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-_Tp*
-__to_address(_Tp* __p) _NOEXCEPT
-{
-    static_assert(!is_function<_Tp>::value, "_Tp is a function type");
-    return __p;
-}
-
-template <class _Pointer>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename __choose_to_address<_Pointer>::template __return_type<_Pointer>
-__to_address(const _Pointer& __p) _NOEXCEPT {
-  return __choose_to_address<_Pointer>::__do_it(__p);
-}
-
-template <> struct __to_address_helper<false> {
-    template <class _Pointer>
-    using __return_type = typename pointer_traits<_Pointer>::element_type*;
-
-    template <class _Pointer>
-    _LIBCPP_CONSTEXPR
-    static __return_type<_Pointer>
-    __do_it(const _Pointer &__p) _NOEXCEPT { return _VSTD::__to_address(__p.operator->()); }
-};
-
-
-#if _LIBCPP_STD_VER > 17
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY constexpr
-_Tp*
-to_address(_Tp* __p) _NOEXCEPT
-{
-    static_assert(!is_function_v<_Tp>, "_Tp is a function type");
-    return __p;
-}
-
-template <class _Pointer>
-inline _LIBCPP_INLINE_VISIBILITY constexpr
-auto
-to_address(const _Pointer& __p) _NOEXCEPT
-{
-    return _VSTD::__to_address(__p);
-}
-#endif
-
-template <class _Tp> class allocator;
-
-#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS)
-template <>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX17 allocator<void>
-{
-public:
-    typedef void*             pointer;
-    typedef const void*       const_pointer;
-    typedef void              value_type;
-
-    template <class _Up> struct rebind {typedef allocator<_Up> other;};
-};
-
-template <>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX17 allocator<const void>
-{
-public:
-    typedef const void*       pointer;
-    typedef const void*       const_pointer;
-    typedef const void        value_type;
-
-    template <class _Up> struct rebind {typedef allocator<_Up> other;};
-};
-#endif
-
-// allocator
-
-template <class _Tp>
-class _LIBCPP_TEMPLATE_VIS allocator
-{
-public:
-    typedef size_t      size_type;
-    typedef ptrdiff_t   difference_type;
-    typedef _Tp         value_type;
-    typedef true_type   propagate_on_container_move_assignment;
-    typedef true_type   is_always_equal;
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    allocator() _NOEXCEPT { }
-
-    template <class _Up>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    allocator(const allocator<_Up>&) _NOEXCEPT { }
-
-    _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    _Tp* allocate(size_t __n) {
-        if (__n > allocator_traits<allocator>::max_size(*this))
-            __throw_length_error("allocator<T>::allocate(size_t n)"
-                                 " 'n' exceeds maximum supported size");
-        if (__libcpp_is_constant_evaluated()) {
-            return static_cast<_Tp*>(::operator new(__n * sizeof(_Tp)));
-        } else {
-            return static_cast<_Tp*>(_VSTD::__libcpp_allocate(__n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp)));
-        }
-    }
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    void deallocate(_Tp* __p, size_t __n) _NOEXCEPT {
-        if (__libcpp_is_constant_evaluated()) {
-            ::operator delete(__p);
-        } else {
-            _VSTD::__libcpp_deallocate((void*)__p, __n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp));
-        }
-    }
-
-    // C++20 Removed members
-#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS)
-    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp*       pointer;
-    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp* const_pointer;
-    _LIBCPP_DEPRECATED_IN_CXX17 typedef _Tp&       reference;
-    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp& const_reference;
-
-    template <class _Up>
-    struct _LIBCPP_DEPRECATED_IN_CXX17 rebind {
-        typedef allocator<_Up> other;
-    };
-
-    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
-    pointer address(reference __x) const _NOEXCEPT {
-        return _VSTD::addressof(__x);
-    }
-    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
-    const_pointer address(const_reference __x) const _NOEXCEPT {
-        return _VSTD::addressof(__x);
-    }
-
-    _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_DEPRECATED_IN_CXX17
-    _Tp* allocate(size_t __n, const void*) {
-        return allocate(__n);
-    }
-
-    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY size_type max_size() const _NOEXCEPT {
-        return size_type(~0) / sizeof(_Tp);
-    }
-
-    template <class _Up, class... _Args>
-    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
-    void construct(_Up* __p, _Args&&... __args) {
-        ::new ((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
-    }
-
-    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
-    void destroy(pointer __p) {
-        __p->~_Tp();
-    }
-#endif
-};
-
-template <class _Tp>
-class _LIBCPP_TEMPLATE_VIS allocator<const _Tp>
-{
-public:
-    typedef size_t      size_type;
-    typedef ptrdiff_t   difference_type;
-    typedef const _Tp   value_type;
-    typedef true_type   propagate_on_container_move_assignment;
-    typedef true_type   is_always_equal;
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    allocator() _NOEXCEPT { }
-
-    template <class _Up>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    allocator(const allocator<_Up>&) _NOEXCEPT { }
-
-    _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    const _Tp* allocate(size_t __n) {
-        if (__n > allocator_traits<allocator>::max_size(*this))
-            __throw_length_error("allocator<const T>::allocate(size_t n)"
-                                 " 'n' exceeds maximum supported size");
-        if (__libcpp_is_constant_evaluated()) {
-            return static_cast<const _Tp*>(::operator new(__n * sizeof(_Tp)));
-        } else {
-            return static_cast<const _Tp*>(_VSTD::__libcpp_allocate(__n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp)));
-        }
-    }
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    void deallocate(const _Tp* __p, size_t __n) {
-        if (__libcpp_is_constant_evaluated()) {
-            ::operator delete(const_cast<_Tp*>(__p));
-        } else {
-            _VSTD::__libcpp_deallocate((void*) const_cast<_Tp *>(__p), __n * sizeof(_Tp), _LIBCPP_ALIGNOF(_Tp));
-        }
-    }
-
-    // C++20 Removed members
-#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_ALLOCATOR_MEMBERS)
-    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp* pointer;
-    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp* const_pointer;
-    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp& reference;
-    _LIBCPP_DEPRECATED_IN_CXX17 typedef const _Tp& const_reference;
-
-    template <class _Up>
-    struct _LIBCPP_DEPRECATED_IN_CXX17 rebind {
-        typedef allocator<_Up> other;
-    };
-
-    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
-    const_pointer address(const_reference __x) const _NOEXCEPT {
-        return _VSTD::addressof(__x);
-    }
-
-    _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY _LIBCPP_DEPRECATED_IN_CXX17
-    const _Tp* allocate(size_t __n, const void*) {
-        return allocate(__n);
-    }
-
-    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY size_type max_size() const _NOEXCEPT {
-        return size_type(~0) / sizeof(_Tp);
-    }
-
-    template <class _Up, class... _Args>
-    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
-    void construct(_Up* __p, _Args&&... __args) {
-        ::new ((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
-    }
-
-    _LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VISIBILITY
-    void destroy(pointer __p) {
-        __p->~_Tp();
-    }
-#endif
-};
-
-template <class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool operator==(const allocator<_Tp>&, const allocator<_Up>&) _NOEXCEPT {return true;}
-
-template <class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-bool operator!=(const allocator<_Tp>&, const allocator<_Up>&) _NOEXCEPT {return false;}
-
 template <class _Alloc, class _Ptr>
 _LIBCPP_INLINE_VISIBILITY
 void __construct_forward_with_exception_guarantees(_Alloc& __a, _Ptr __begin1, _Ptr __end1, _Ptr& __begin2) {
@@ -1062,3107 +796,48 @@ void __construct_backward_with_exception_guarantees(_Alloc&, _Tp* __begin1, _Tp*
     ptrdiff_t _Np = __end1 - __begin1;
     __end2 -= _Np;
     if (_Np > 0)
-        _VSTD::memcpy(__end2, __begin1, _Np * sizeof(_Tp));
-}
-
-template <class _OutputIterator, class _Tp>
-class _LIBCPP_TEMPLATE_VIS raw_storage_iterator
-    : public iterator<output_iterator_tag,
-                      _Tp,                                         // purposefully not C++03
-                      ptrdiff_t,                                   // purposefully not C++03
-                      _Tp*,                                        // purposefully not C++03
-                      raw_storage_iterator<_OutputIterator, _Tp>&> // purposefully not C++03
-{
-private:
-    _OutputIterator __x_;
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit raw_storage_iterator(_OutputIterator __x) : __x_(__x) {}
-    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator& operator*() {return *this;}
-    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator& operator=(const _Tp& __element)
-        {::new ((void*)_VSTD::addressof(*__x_)) _Tp(__element); return *this;}
-#if _LIBCPP_STD_VER >= 14
-    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator& operator=(_Tp&& __element)
-        {::new ((void*)_VSTD::addressof(*__x_)) _Tp(_VSTD::move(__element)); return *this;}
-#endif
-    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator& operator++() {++__x_; return *this;}
-    _LIBCPP_INLINE_VISIBILITY raw_storage_iterator  operator++(int)
-        {raw_storage_iterator __t(*this); ++__x_; return __t;}
-#if _LIBCPP_STD_VER >= 14
-    _LIBCPP_INLINE_VISIBILITY _OutputIterator base() const { return __x_; }
-#endif
-};
-
-template <class _Tp>
-_LIBCPP_NODISCARD_EXT _LIBCPP_NO_CFI
-pair<_Tp*, ptrdiff_t>
-get_temporary_buffer(ptrdiff_t __n) _NOEXCEPT
-{
-    pair<_Tp*, ptrdiff_t> __r(0, 0);
-    const ptrdiff_t __m = (~ptrdiff_t(0) ^
-                           ptrdiff_t(ptrdiff_t(1) << (sizeof(ptrdiff_t) * __CHAR_BIT__ - 1)))
-                           / sizeof(_Tp);
-    if (__n > __m)
-        __n = __m;
-    while (__n > 0)
-    {
-#if !defined(_LIBCPP_HAS_NO_ALIGNED_ALLOCATION)
-    if (__is_overaligned_for_new(_LIBCPP_ALIGNOF(_Tp)))
-        {
-            align_val_t __al =
-                align_val_t(alignment_of<_Tp>::value);
-            __r.first = static_cast<_Tp*>(::operator new(
-                __n * sizeof(_Tp), __al, nothrow));
-        } else {
-            __r.first = static_cast<_Tp*>(::operator new(
-                __n * sizeof(_Tp), nothrow));
-        }
-#else
-    if (__is_overaligned_for_new(_LIBCPP_ALIGNOF(_Tp)))
-        {
-            // Since aligned operator new is unavailable, return an empty
-            // buffer rather than one with invalid alignment.
-            return __r;
-        }
-
-        __r.first = static_cast<_Tp*>(::operator new(__n * sizeof(_Tp), nothrow));
-#endif
-
-        if (__r.first)
-        {
-            __r.second = __n;
-            break;
-        }
-        __n /= 2;
-    }
-    return __r;
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-void return_temporary_buffer(_Tp* __p) _NOEXCEPT
-{
-  _VSTD::__libcpp_deallocate_unsized((void*)__p, _LIBCPP_ALIGNOF(_Tp));
+        _VSTD::memcpy(static_cast<void*>(__end2), static_cast<void const*>(__begin1), _Np * sizeof(_Tp));
 }
 
-#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
-template <class _Tp>
-struct _LIBCPP_DEPRECATED_IN_CXX11 auto_ptr_ref
-{
-    _Tp* __ptr_;
-};
-
-template<class _Tp>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 auto_ptr
-{
-private:
-    _Tp* __ptr_;
-public:
-    typedef _Tp element_type;
-
-    _LIBCPP_INLINE_VISIBILITY explicit auto_ptr(_Tp* __p = 0) _NOEXCEPT : __ptr_(__p) {}
-    _LIBCPP_INLINE_VISIBILITY auto_ptr(auto_ptr& __p) _NOEXCEPT : __ptr_(__p.release()) {}
-    template<class _Up> _LIBCPP_INLINE_VISIBILITY auto_ptr(auto_ptr<_Up>& __p) _NOEXCEPT
-        : __ptr_(__p.release()) {}
-    _LIBCPP_INLINE_VISIBILITY auto_ptr& operator=(auto_ptr& __p) _NOEXCEPT
-        {reset(__p.release()); return *this;}
-    template<class _Up> _LIBCPP_INLINE_VISIBILITY auto_ptr& operator=(auto_ptr<_Up>& __p) _NOEXCEPT
-        {reset(__p.release()); return *this;}
-    _LIBCPP_INLINE_VISIBILITY auto_ptr& operator=(auto_ptr_ref<_Tp> __p) _NOEXCEPT
-        {reset(__p.__ptr_); return *this;}
-    _LIBCPP_INLINE_VISIBILITY ~auto_ptr() _NOEXCEPT {delete __ptr_;}
-
-    _LIBCPP_INLINE_VISIBILITY _Tp& operator*() const _NOEXCEPT
-        {return *__ptr_;}
-    _LIBCPP_INLINE_VISIBILITY _Tp* operator->() const _NOEXCEPT {return __ptr_;}
-    _LIBCPP_INLINE_VISIBILITY _Tp* get() const _NOEXCEPT {return __ptr_;}
-    _LIBCPP_INLINE_VISIBILITY _Tp* release() _NOEXCEPT
-    {
-        _Tp* __t = __ptr_;
-        __ptr_ = nullptr;
-        return __t;
-    }
-    _LIBCPP_INLINE_VISIBILITY void reset(_Tp* __p = 0) _NOEXCEPT
-    {
-        if (__ptr_ != __p)
-            delete __ptr_;
-        __ptr_ = __p;
-    }
-
-    _LIBCPP_INLINE_VISIBILITY auto_ptr(auto_ptr_ref<_Tp> __p) _NOEXCEPT : __ptr_(__p.__ptr_) {}
-    template<class _Up> _LIBCPP_INLINE_VISIBILITY operator auto_ptr_ref<_Up>() _NOEXCEPT
-        {auto_ptr_ref<_Up> __t; __t.__ptr_ = release(); return __t;}
-    template<class _Up> _LIBCPP_INLINE_VISIBILITY operator auto_ptr<_Up>() _NOEXCEPT
-        {return auto_ptr<_Up>(release());}
-};
-
-template <>
-class _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 auto_ptr<void>
+struct __destruct_n
 {
-public:
-    typedef void element_type;
-};
-#endif
-
-// Tag used to default initialize one or both of the pair's elements.
-struct __default_init_tag {};
-struct __value_init_tag {};
-
-template <class _Tp, int _Idx,
-          bool _CanBeEmptyBase =
-              is_empty<_Tp>::value && !__libcpp_is_final<_Tp>::value>
-struct __compressed_pair_elem {
-  typedef _Tp _ParamT;
-  typedef _Tp& reference;
-  typedef const _Tp& const_reference;
-
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-  __compressed_pair_elem(__default_init_tag) {}
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-  __compressed_pair_elem(__value_init_tag) : __value_() {}
-
-  template <class _Up, class = typename enable_if<
-      !is_same<__compressed_pair_elem, typename decay<_Up>::type>::value
-  >::type>
-  _LIBCPP_INLINE_VISIBILITY
-  _LIBCPP_CONSTEXPR explicit
-  __compressed_pair_elem(_Up&& __u)
-      : __value_(_VSTD::forward<_Up>(__u))
-    {
-    }
-
-
-#ifndef _LIBCPP_CXX03_LANG
-  template <class... _Args, size_t... _Indexes>
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-  __compressed_pair_elem(piecewise_construct_t, tuple<_Args...> __args,
-                         __tuple_indices<_Indexes...>)
-      : __value_(_VSTD::forward<_Args>(_VSTD::get<_Indexes>(__args))...) {}
-#endif
-
-
-  _LIBCPP_INLINE_VISIBILITY reference __get() _NOEXCEPT { return __value_; }
-  _LIBCPP_INLINE_VISIBILITY
-  const_reference __get() const _NOEXCEPT { return __value_; }
-
 private:
-  _Tp __value_;
-};
-
-template <class _Tp, int _Idx>
-struct __compressed_pair_elem<_Tp, _Idx, true> : private _Tp {
-  typedef _Tp _ParamT;
-  typedef _Tp& reference;
-  typedef const _Tp& const_reference;
-  typedef _Tp __value_type;
-
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR __compressed_pair_elem() = default;
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-  __compressed_pair_elem(__default_init_tag) {}
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-  __compressed_pair_elem(__value_init_tag) : __value_type() {}
-
-  template <class _Up, class = typename enable_if<
-        !is_same<__compressed_pair_elem, typename decay<_Up>::type>::value
-  >::type>
-  _LIBCPP_INLINE_VISIBILITY
-  _LIBCPP_CONSTEXPR explicit
-  __compressed_pair_elem(_Up&& __u)
-      : __value_type(_VSTD::forward<_Up>(__u))
-  {}
-
-#ifndef _LIBCPP_CXX03_LANG
-  template <class... _Args, size_t... _Indexes>
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-  __compressed_pair_elem(piecewise_construct_t, tuple<_Args...> __args,
-                         __tuple_indices<_Indexes...>)
-      : __value_type(_VSTD::forward<_Args>(_VSTD::get<_Indexes>(__args))...) {}
-#endif
-
-  _LIBCPP_INLINE_VISIBILITY reference __get() _NOEXCEPT { return *this; }
-  _LIBCPP_INLINE_VISIBILITY
-  const_reference __get() const _NOEXCEPT { return *this; }
-};
-
-template <class _T1, class _T2>
-class __compressed_pair : private __compressed_pair_elem<_T1, 0>,
-                          private __compressed_pair_elem<_T2, 1> {
-public:
-  // NOTE: This static assert should never fire because __compressed_pair
-  // is *almost never* used in a scenario where it's possible for T1 == T2.
-  // (The exception is std::function where it is possible that the function
-  //  object and the allocator have the same type).
-  static_assert((!is_same<_T1, _T2>::value),
-    "__compressed_pair cannot be instantiated when T1 and T2 are the same type; "
-    "The current implementation is NOT ABI-compatible with the previous "
-    "implementation for this configuration");
-
-    typedef _LIBCPP_NODEBUG_TYPE __compressed_pair_elem<_T1, 0> _Base1;
-    typedef _LIBCPP_NODEBUG_TYPE __compressed_pair_elem<_T2, 1> _Base2;
-
-    template <bool _Dummy = true,
-      class = typename enable_if<
-          __dependent_type<is_default_constructible<_T1>, _Dummy>::value &&
-          __dependent_type<is_default_constructible<_T2>, _Dummy>::value
-      >::type
-  >
-  _LIBCPP_INLINE_VISIBILITY
-  _LIBCPP_CONSTEXPR __compressed_pair() : _Base1(__value_init_tag()), _Base2(__value_init_tag()) {}
-
-  template <class _U1, class _U2>
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-  __compressed_pair(_U1&& __t1, _U2&& __t2)
-      : _Base1(_VSTD::forward<_U1>(__t1)), _Base2(_VSTD::forward<_U2>(__t2)) {}
-
-#ifndef _LIBCPP_CXX03_LANG
-  template <class... _Args1, class... _Args2>
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX14
-  __compressed_pair(piecewise_construct_t __pc, tuple<_Args1...> __first_args,
-                    tuple<_Args2...> __second_args)
-      : _Base1(__pc, _VSTD::move(__first_args),
-               typename __make_tuple_indices<sizeof...(_Args1)>::type()),
-        _Base2(__pc, _VSTD::move(__second_args),
-               typename __make_tuple_indices<sizeof...(_Args2)>::type()) {}
-#endif
-
-  _LIBCPP_INLINE_VISIBILITY
-  typename _Base1::reference first() _NOEXCEPT {
-    return static_cast<_Base1&>(*this).__get();
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  typename _Base1::const_reference first() const _NOEXCEPT {
-    return static_cast<_Base1 const&>(*this).__get();
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  typename _Base2::reference second() _NOEXCEPT {
-    return static_cast<_Base2&>(*this).__get();
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  typename _Base2::const_reference second() const _NOEXCEPT {
-    return static_cast<_Base2 const&>(*this).__get();
-  }
-
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-  static _Base1* __get_first_base(__compressed_pair* __pair) _NOEXCEPT {
-    return static_cast<_Base1*>(__pair);
-  }
-  _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-  static _Base2* __get_second_base(__compressed_pair* __pair) _NOEXCEPT {
-    return static_cast<_Base2*>(__pair);
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  void swap(__compressed_pair& __x)
-    _NOEXCEPT_(__is_nothrow_swappable<_T1>::value &&
-               __is_nothrow_swappable<_T2>::value)
-  {
-    using _VSTD::swap;
-    swap(first(), __x.first());
-    swap(second(), __x.second());
-  }
-};
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-void swap(__compressed_pair<_T1, _T2>& __x, __compressed_pair<_T1, _T2>& __y)
-    _NOEXCEPT_(__is_nothrow_swappable<_T1>::value &&
-               __is_nothrow_swappable<_T2>::value) {
-  __x.swap(__y);
-}
+    size_t __size_;
 
-// default_delete
+    template <class _Tp>
+    _LIBCPP_INLINE_VISIBILITY void __process(_Tp* __p, false_type) _NOEXCEPT
+        {for (size_t __i = 0; __i < __size_; ++__i, ++__p) __p->~_Tp();}
 
-template <class _Tp>
-struct _LIBCPP_TEMPLATE_VIS default_delete {
-    static_assert(!is_function<_Tp>::value,
-                  "default_delete cannot be instantiated for function types");
-#ifndef _LIBCPP_CXX03_LANG
-  _LIBCPP_INLINE_VISIBILITY constexpr default_delete() _NOEXCEPT = default;
-#else
-  _LIBCPP_INLINE_VISIBILITY default_delete() {}
-#endif
-  template <class _Up>
-  _LIBCPP_INLINE_VISIBILITY
-  default_delete(const default_delete<_Up>&,
-                 typename enable_if<is_convertible<_Up*, _Tp*>::value>::type* =
-                     0) _NOEXCEPT {}
-
-  _LIBCPP_INLINE_VISIBILITY void operator()(_Tp* __ptr) const _NOEXCEPT {
-    static_assert(sizeof(_Tp) > 0,
-                  "default_delete can not delete incomplete type");
-    static_assert(!is_void<_Tp>::value,
-                  "default_delete can not delete incomplete type");
-    delete __ptr;
-  }
-};
+    template <class _Tp>
+    _LIBCPP_INLINE_VISIBILITY void __process(_Tp*, true_type) _NOEXCEPT
+        {}
 
-template <class _Tp>
-struct _LIBCPP_TEMPLATE_VIS default_delete<_Tp[]> {
-private:
-  template <class _Up>
-  struct _EnableIfConvertible
-      : enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value> {};
+    _LIBCPP_INLINE_VISIBILITY void __incr(false_type) _NOEXCEPT
+        {++__size_;}
+    _LIBCPP_INLINE_VISIBILITY void __incr(true_type) _NOEXCEPT
+        {}
 
+    _LIBCPP_INLINE_VISIBILITY void __set(size_t __s, false_type) _NOEXCEPT
+        {__size_ = __s;}
+    _LIBCPP_INLINE_VISIBILITY void __set(size_t, true_type) _NOEXCEPT
+        {}
 public:
-#ifndef _LIBCPP_CXX03_LANG
-  _LIBCPP_INLINE_VISIBILITY constexpr default_delete() _NOEXCEPT = default;
-#else
-  _LIBCPP_INLINE_VISIBILITY default_delete() {}
-#endif
-
-  template <class _Up>
-  _LIBCPP_INLINE_VISIBILITY
-  default_delete(const default_delete<_Up[]>&,
-                 typename _EnableIfConvertible<_Up>::type* = 0) _NOEXCEPT {}
-
-  template <class _Up>
-  _LIBCPP_INLINE_VISIBILITY
-  typename _EnableIfConvertible<_Up>::type
-  operator()(_Up* __ptr) const _NOEXCEPT {
-    static_assert(sizeof(_Tp) > 0,
-                  "default_delete can not delete incomplete type");
-    static_assert(!is_void<_Tp>::value,
-                  "default_delete can not delete void type");
-    delete[] __ptr;
-  }
-};
+    _LIBCPP_INLINE_VISIBILITY explicit __destruct_n(size_t __s) _NOEXCEPT
+        : __size_(__s) {}
 
-template <class _Deleter>
-struct __unique_ptr_deleter_sfinae {
-  static_assert(!is_reference<_Deleter>::value, "incorrect specialization");
-  typedef const _Deleter& __lval_ref_type;
-  typedef _Deleter&& __good_rval_ref_type;
-  typedef true_type __enable_rval_overload;
-};
+    template <class _Tp>
+    _LIBCPP_INLINE_VISIBILITY void __incr() _NOEXCEPT
+        {__incr(integral_constant<bool, is_trivially_destructible<_Tp>::value>());}
 
-template <class _Deleter>
-struct __unique_ptr_deleter_sfinae<_Deleter const&> {
-  typedef const _Deleter& __lval_ref_type;
-  typedef const _Deleter&& __bad_rval_ref_type;
-  typedef false_type __enable_rval_overload;
-};
+    template <class _Tp>
+    _LIBCPP_INLINE_VISIBILITY void __set(size_t __s, _Tp*) _NOEXCEPT
+        {__set(__s, integral_constant<bool, is_trivially_destructible<_Tp>::value>());}
 
-template <class _Deleter>
-struct __unique_ptr_deleter_sfinae<_Deleter&> {
-  typedef _Deleter& __lval_ref_type;
-  typedef _Deleter&& __bad_rval_ref_type;
-  typedef false_type __enable_rval_overload;
+    template <class _Tp>
+    _LIBCPP_INLINE_VISIBILITY void operator()(_Tp* __p) _NOEXCEPT
+        {__process(__p, integral_constant<bool, is_trivially_destructible<_Tp>::value>());}
 };
 
-#if defined(_LIBCPP_ABI_ENABLE_UNIQUE_PTR_TRIVIAL_ABI)
-#  define _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI __attribute__((trivial_abi))
-#else
-#  define _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI
-#endif
-
-template <class _Tp, class _Dp = default_delete<_Tp> >
-class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS unique_ptr {
-public:
-  typedef _Tp element_type;
-  typedef _Dp deleter_type;
-  typedef _LIBCPP_NODEBUG_TYPE typename __pointer<_Tp, deleter_type>::type pointer;
-
-  static_assert(!is_rvalue_reference<deleter_type>::value,
-                "the specified deleter type cannot be an rvalue reference");
-
-private:
-  __compressed_pair<pointer, deleter_type> __ptr_;
-
-  struct __nat { int __for_bool_; };
-
-  typedef _LIBCPP_NODEBUG_TYPE __unique_ptr_deleter_sfinae<_Dp> _DeleterSFINAE;
-
-  template <bool _Dummy>
-  using _LValRefType _LIBCPP_NODEBUG_TYPE =
-      typename __dependent_type<_DeleterSFINAE, _Dummy>::__lval_ref_type;
-
-  template <bool _Dummy>
-  using _GoodRValRefType _LIBCPP_NODEBUG_TYPE =
-      typename __dependent_type<_DeleterSFINAE, _Dummy>::__good_rval_ref_type;
-
-  template <bool _Dummy>
-  using _BadRValRefType _LIBCPP_NODEBUG_TYPE  =
-      typename __dependent_type<_DeleterSFINAE, _Dummy>::__bad_rval_ref_type;
-
-  template <bool _Dummy, class _Deleter = typename __dependent_type<
-                             __identity<deleter_type>, _Dummy>::type>
-  using _EnableIfDeleterDefaultConstructible _LIBCPP_NODEBUG_TYPE =
-      typename enable_if<is_default_constructible<_Deleter>::value &&
-                         !is_pointer<_Deleter>::value>::type;
-
-  template <class _ArgType>
-  using _EnableIfDeleterConstructible _LIBCPP_NODEBUG_TYPE  =
-      typename enable_if<is_constructible<deleter_type, _ArgType>::value>::type;
-
-  template <class _UPtr, class _Up>
-  using _EnableIfMoveConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
-      is_convertible<typename _UPtr::pointer, pointer>::value &&
-      !is_array<_Up>::value
-  >::type;
-
-  template <class _UDel>
-  using _EnableIfDeleterConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
-      (is_reference<_Dp>::value && is_same<_Dp, _UDel>::value) ||
-      (!is_reference<_Dp>::value && is_convertible<_UDel, _Dp>::value)
-    >::type;
-
-  template <class _UDel>
-  using _EnableIfDeleterAssignable = typename enable_if<
-      is_assignable<_Dp&, _UDel&&>::value
-    >::type;
-
-public:
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
-  _LIBCPP_INLINE_VISIBILITY
-  _LIBCPP_CONSTEXPR unique_ptr() _NOEXCEPT : __ptr_(pointer(), __default_init_tag()) {}
-
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
-  _LIBCPP_INLINE_VISIBILITY
-  _LIBCPP_CONSTEXPR unique_ptr(nullptr_t) _NOEXCEPT : __ptr_(pointer(), __default_init_tag()) {}
-
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
-  _LIBCPP_INLINE_VISIBILITY
-  explicit unique_ptr(pointer __p) _NOEXCEPT : __ptr_(__p, __default_init_tag()) {}
-
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> > >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(pointer __p, _LValRefType<_Dummy> __d) _NOEXCEPT
-      : __ptr_(__p, __d) {}
-
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> > >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(pointer __p, _GoodRValRefType<_Dummy> __d) _NOEXCEPT
-      : __ptr_(__p, _VSTD::move(__d)) {
-    static_assert(!is_reference<deleter_type>::value,
-                  "rvalue deleter bound to reference");
-  }
-
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterConstructible<_BadRValRefType<_Dummy> > >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(pointer __p, _BadRValRefType<_Dummy> __d) = delete;
-
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(unique_ptr&& __u) _NOEXCEPT
-      : __ptr_(__u.release(), _VSTD::forward<deleter_type>(__u.get_deleter())) {
-  }
-
-  template <class _Up, class _Ep,
-      class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
-      class = _EnableIfDeleterConvertible<_Ep>
-  >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPT
-      : __ptr_(__u.release(), _VSTD::forward<_Ep>(__u.get_deleter())) {}
-
-#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
-  template <class _Up>
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(auto_ptr<_Up>&& __p,
-             typename enable_if<is_convertible<_Up*, _Tp*>::value &&
-                                    is_same<_Dp, default_delete<_Tp> >::value,
-                                __nat>::type = __nat()) _NOEXCEPT
-      : __ptr_(__p.release(), __default_init_tag()) {}
-#endif
-
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr& operator=(unique_ptr&& __u) _NOEXCEPT {
-    reset(__u.release());
-    __ptr_.second() = _VSTD::forward<deleter_type>(__u.get_deleter());
-    return *this;
-  }
-
-  template <class _Up, class _Ep,
-      class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
-      class = _EnableIfDeleterAssignable<_Ep>
-  >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr& operator=(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPT {
-    reset(__u.release());
-    __ptr_.second() = _VSTD::forward<_Ep>(__u.get_deleter());
-    return *this;
-  }
-
-#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
-  template <class _Up>
-  _LIBCPP_INLINE_VISIBILITY
-      typename enable_if<is_convertible<_Up*, _Tp*>::value &&
-                             is_same<_Dp, default_delete<_Tp> >::value,
-                         unique_ptr&>::type
-      operator=(auto_ptr<_Up> __p) {
-    reset(__p.release());
-    return *this;
-  }
-#endif
-
-#ifdef _LIBCPP_CXX03_LANG
-  unique_ptr(unique_ptr const&) = delete;
-  unique_ptr& operator=(unique_ptr const&) = delete;
-#endif
-
-
-  _LIBCPP_INLINE_VISIBILITY
-  ~unique_ptr() { reset(); }
-
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr& operator=(nullptr_t) _NOEXCEPT {
-    reset();
-    return *this;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  typename add_lvalue_reference<_Tp>::type
-  operator*() const {
-    return *__ptr_.first();
-  }
-  _LIBCPP_INLINE_VISIBILITY
-  pointer operator->() const _NOEXCEPT {
-    return __ptr_.first();
-  }
-  _LIBCPP_INLINE_VISIBILITY
-  pointer get() const _NOEXCEPT {
-    return __ptr_.first();
-  }
-  _LIBCPP_INLINE_VISIBILITY
-  deleter_type& get_deleter() _NOEXCEPT {
-    return __ptr_.second();
-  }
-  _LIBCPP_INLINE_VISIBILITY
-  const deleter_type& get_deleter() const _NOEXCEPT {
-    return __ptr_.second();
-  }
-  _LIBCPP_INLINE_VISIBILITY
-  _LIBCPP_EXPLICIT operator bool() const _NOEXCEPT {
-    return __ptr_.first() != nullptr;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  pointer release() _NOEXCEPT {
-    pointer __t = __ptr_.first();
-    __ptr_.first() = pointer();
-    return __t;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  void reset(pointer __p = pointer()) _NOEXCEPT {
-    pointer __tmp = __ptr_.first();
-    __ptr_.first() = __p;
-    if (__tmp)
-      __ptr_.second()(__tmp);
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  void swap(unique_ptr& __u) _NOEXCEPT {
-    __ptr_.swap(__u.__ptr_);
-  }
-};
-
-
-template <class _Tp, class _Dp>
-class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS unique_ptr<_Tp[], _Dp> {
-public:
-  typedef _Tp element_type;
-  typedef _Dp deleter_type;
-  typedef typename __pointer<_Tp, deleter_type>::type pointer;
-
-private:
-  __compressed_pair<pointer, deleter_type> __ptr_;
-
-  template <class _From>
-  struct _CheckArrayPointerConversion : is_same<_From, pointer> {};
-
-  template <class _FromElem>
-  struct _CheckArrayPointerConversion<_FromElem*>
-      : integral_constant<bool,
-          is_same<_FromElem*, pointer>::value ||
-            (is_same<pointer, element_type*>::value &&
-             is_convertible<_FromElem(*)[], element_type(*)[]>::value)
-      >
-  {};
-
-  typedef __unique_ptr_deleter_sfinae<_Dp> _DeleterSFINAE;
-
-  template <bool _Dummy>
-  using _LValRefType _LIBCPP_NODEBUG_TYPE =
-      typename __dependent_type<_DeleterSFINAE, _Dummy>::__lval_ref_type;
-
-  template <bool _Dummy>
-  using _GoodRValRefType _LIBCPP_NODEBUG_TYPE =
-      typename __dependent_type<_DeleterSFINAE, _Dummy>::__good_rval_ref_type;
-
-  template <bool _Dummy>
-  using _BadRValRefType _LIBCPP_NODEBUG_TYPE =
-      typename __dependent_type<_DeleterSFINAE, _Dummy>::__bad_rval_ref_type;
-
-  template <bool _Dummy, class _Deleter = typename __dependent_type<
-                             __identity<deleter_type>, _Dummy>::type>
-  using _EnableIfDeleterDefaultConstructible _LIBCPP_NODEBUG_TYPE  =
-      typename enable_if<is_default_constructible<_Deleter>::value &&
-                         !is_pointer<_Deleter>::value>::type;
-
-  template <class _ArgType>
-  using _EnableIfDeleterConstructible _LIBCPP_NODEBUG_TYPE  =
-      typename enable_if<is_constructible<deleter_type, _ArgType>::value>::type;
-
-  template <class _Pp>
-  using _EnableIfPointerConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
-      _CheckArrayPointerConversion<_Pp>::value
-  >::type;
-
-  template <class _UPtr, class _Up,
-        class _ElemT = typename _UPtr::element_type>
-  using _EnableIfMoveConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
-      is_array<_Up>::value &&
-      is_same<pointer, element_type*>::value &&
-      is_same<typename _UPtr::pointer, _ElemT*>::value &&
-      is_convertible<_ElemT(*)[], element_type(*)[]>::value
-    >::type;
-
-  template <class _UDel>
-  using _EnableIfDeleterConvertible _LIBCPP_NODEBUG_TYPE  = typename enable_if<
-      (is_reference<_Dp>::value && is_same<_Dp, _UDel>::value) ||
-      (!is_reference<_Dp>::value && is_convertible<_UDel, _Dp>::value)
-    >::type;
-
-  template <class _UDel>
-  using _EnableIfDeleterAssignable _LIBCPP_NODEBUG_TYPE  = typename enable_if<
-      is_assignable<_Dp&, _UDel&&>::value
-    >::type;
-
-public:
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
-  _LIBCPP_INLINE_VISIBILITY
-  _LIBCPP_CONSTEXPR unique_ptr() _NOEXCEPT : __ptr_(pointer(), __default_init_tag()) {}
-
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterDefaultConstructible<_Dummy> >
-  _LIBCPP_INLINE_VISIBILITY
-  _LIBCPP_CONSTEXPR unique_ptr(nullptr_t) _NOEXCEPT : __ptr_(pointer(), __default_init_tag()) {}
-
-  template <class _Pp, bool _Dummy = true,
-            class = _EnableIfDeleterDefaultConstructible<_Dummy>,
-            class = _EnableIfPointerConvertible<_Pp> >
-  _LIBCPP_INLINE_VISIBILITY
-  explicit unique_ptr(_Pp __p) _NOEXCEPT
-      : __ptr_(__p, __default_init_tag()) {}
-
-  template <class _Pp, bool _Dummy = true,
-            class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> >,
-            class = _EnableIfPointerConvertible<_Pp> >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(_Pp __p, _LValRefType<_Dummy> __d) _NOEXCEPT
-      : __ptr_(__p, __d) {}
-
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> > >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(nullptr_t, _LValRefType<_Dummy> __d) _NOEXCEPT
-      : __ptr_(nullptr, __d) {}
-
-  template <class _Pp, bool _Dummy = true,
-            class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> >,
-            class = _EnableIfPointerConvertible<_Pp> >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(_Pp __p, _GoodRValRefType<_Dummy> __d) _NOEXCEPT
-      : __ptr_(__p, _VSTD::move(__d)) {
-    static_assert(!is_reference<deleter_type>::value,
-                  "rvalue deleter bound to reference");
-  }
-
-  template <bool _Dummy = true,
-            class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> > >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(nullptr_t, _GoodRValRefType<_Dummy> __d) _NOEXCEPT
-      : __ptr_(nullptr, _VSTD::move(__d)) {
-    static_assert(!is_reference<deleter_type>::value,
-                  "rvalue deleter bound to reference");
-  }
-
-  template <class _Pp, bool _Dummy = true,
-            class = _EnableIfDeleterConstructible<_BadRValRefType<_Dummy> >,
-            class = _EnableIfPointerConvertible<_Pp> >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(_Pp __p, _BadRValRefType<_Dummy> __d) = delete;
-
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(unique_ptr&& __u) _NOEXCEPT
-      : __ptr_(__u.release(), _VSTD::forward<deleter_type>(__u.get_deleter())) {
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr& operator=(unique_ptr&& __u) _NOEXCEPT {
-    reset(__u.release());
-    __ptr_.second() = _VSTD::forward<deleter_type>(__u.get_deleter());
-    return *this;
-  }
-
-  template <class _Up, class _Ep,
-      class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
-      class = _EnableIfDeleterConvertible<_Ep>
-  >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPT
-      : __ptr_(__u.release(), _VSTD::forward<_Ep>(__u.get_deleter())) {
-  }
-
-  template <class _Up, class _Ep,
-      class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
-      class = _EnableIfDeleterAssignable<_Ep>
-  >
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr&
-  operator=(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPT {
-    reset(__u.release());
-    __ptr_.second() = _VSTD::forward<_Ep>(__u.get_deleter());
-    return *this;
-  }
-
-#ifdef _LIBCPP_CXX03_LANG
-  unique_ptr(unique_ptr const&) = delete;
-  unique_ptr& operator=(unique_ptr const&) = delete;
-#endif
-
-public:
-  _LIBCPP_INLINE_VISIBILITY
-  ~unique_ptr() { reset(); }
-
-  _LIBCPP_INLINE_VISIBILITY
-  unique_ptr& operator=(nullptr_t) _NOEXCEPT {
-    reset();
-    return *this;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  typename add_lvalue_reference<_Tp>::type
-  operator[](size_t __i) const {
-    return __ptr_.first()[__i];
-  }
-  _LIBCPP_INLINE_VISIBILITY
-  pointer get() const _NOEXCEPT {
-    return __ptr_.first();
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  deleter_type& get_deleter() _NOEXCEPT {
-    return __ptr_.second();
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  const deleter_type& get_deleter() const _NOEXCEPT {
-    return __ptr_.second();
-  }
-  _LIBCPP_INLINE_VISIBILITY
-  _LIBCPP_EXPLICIT operator bool() const _NOEXCEPT {
-    return __ptr_.first() != nullptr;
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  pointer release() _NOEXCEPT {
-    pointer __t = __ptr_.first();
-    __ptr_.first() = pointer();
-    return __t;
-  }
-
-  template <class _Pp>
-  _LIBCPP_INLINE_VISIBILITY
-  typename enable_if<
-      _CheckArrayPointerConversion<_Pp>::value
-  >::type
-  reset(_Pp __p) _NOEXCEPT {
-    pointer __tmp = __ptr_.first();
-    __ptr_.first() = __p;
-    if (__tmp)
-      __ptr_.second()(__tmp);
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  void reset(nullptr_t = nullptr) _NOEXCEPT {
-    pointer __tmp = __ptr_.first();
-    __ptr_.first() = nullptr;
-    if (__tmp)
-      __ptr_.second()(__tmp);
-  }
-
-  _LIBCPP_INLINE_VISIBILITY
-  void swap(unique_ptr& __u) _NOEXCEPT {
-    __ptr_.swap(__u.__ptr_);
-  }
-
-};
-
-template <class _Tp, class _Dp>
-inline _LIBCPP_INLINE_VISIBILITY
-typename enable_if<
-    __is_swappable<_Dp>::value,
-    void
->::type
-swap(unique_ptr<_Tp, _Dp>& __x, unique_ptr<_Tp, _Dp>& __y) _NOEXCEPT {__x.swap(__y);}
-
-template <class _T1, class _D1, class _T2, class _D2>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator==(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return __x.get() == __y.get();}
-
-template <class _T1, class _D1, class _T2, class _D2>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__x == __y);}
-
-template <class _T1, class _D1, class _T2, class _D2>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator< (const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y)
-{
-    typedef typename unique_ptr<_T1, _D1>::pointer _P1;
-    typedef typename unique_ptr<_T2, _D2>::pointer _P2;
-    typedef typename common_type<_P1, _P2>::type _Vp;
-    return less<_Vp>()(__x.get(), __y.get());
-}
-
-template <class _T1, class _D1, class _T2, class _D2>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator> (const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return __y < __x;}
-
-template <class _T1, class _D1, class _T2, class _D2>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__y < __x);}
-
-template <class _T1, class _D1, class _T2, class _D2>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__x < __y);}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator==(const unique_ptr<_T1, _D1>& __x, nullptr_t) _NOEXCEPT
-{
-    return !__x;
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator==(nullptr_t, const unique_ptr<_T1, _D1>& __x) _NOEXCEPT
-{
-    return !__x;
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(const unique_ptr<_T1, _D1>& __x, nullptr_t) _NOEXCEPT
-{
-    return static_cast<bool>(__x);
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(nullptr_t, const unique_ptr<_T1, _D1>& __x) _NOEXCEPT
-{
-    return static_cast<bool>(__x);
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<(const unique_ptr<_T1, _D1>& __x, nullptr_t)
-{
-    typedef typename unique_ptr<_T1, _D1>::pointer _P1;
-    return less<_P1>()(__x.get(), nullptr);
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<(nullptr_t, const unique_ptr<_T1, _D1>& __x)
-{
-    typedef typename unique_ptr<_T1, _D1>::pointer _P1;
-    return less<_P1>()(nullptr, __x.get());
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>(const unique_ptr<_T1, _D1>& __x, nullptr_t)
-{
-    return nullptr < __x;
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>(nullptr_t, const unique_ptr<_T1, _D1>& __x)
-{
-    return __x < nullptr;
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<=(const unique_ptr<_T1, _D1>& __x, nullptr_t)
-{
-    return !(nullptr < __x);
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<=(nullptr_t, const unique_ptr<_T1, _D1>& __x)
-{
-    return !(__x < nullptr);
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>=(const unique_ptr<_T1, _D1>& __x, nullptr_t)
-{
-    return !(__x < nullptr);
-}
-
-template <class _T1, class _D1>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>=(nullptr_t, const unique_ptr<_T1, _D1>& __x)
-{
-    return !(nullptr < __x);
-}
-
-#if _LIBCPP_STD_VER > 11
-
-template<class _Tp>
-struct __unique_if
-{
-    typedef unique_ptr<_Tp> __unique_single;
-};
-
-template<class _Tp>
-struct __unique_if<_Tp[]>
-{
-    typedef unique_ptr<_Tp[]> __unique_array_unknown_bound;
-};
-
-template<class _Tp, size_t _Np>
-struct __unique_if<_Tp[_Np]>
-{
-    typedef void __unique_array_known_bound;
-};
-
-template<class _Tp, class... _Args>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __unique_if<_Tp>::__unique_single
-make_unique(_Args&&... __args)
-{
-    return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...));
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-typename __unique_if<_Tp>::__unique_array_unknown_bound
-make_unique(size_t __n)
-{
-    typedef typename remove_extent<_Tp>::type _Up;
-    return unique_ptr<_Tp>(new _Up[__n]());
-}
-
-template<class _Tp, class... _Args>
-    typename __unique_if<_Tp>::__unique_array_known_bound
-    make_unique(_Args&&...) = delete;
-
-#endif  // _LIBCPP_STD_VER > 11
-
-template <class _Tp, class _Dp>
-#ifdef _LIBCPP_CXX03_LANG
-struct _LIBCPP_TEMPLATE_VIS hash<unique_ptr<_Tp, _Dp> >
-#else
-struct _LIBCPP_TEMPLATE_VIS hash<__enable_hash_helper<
-    unique_ptr<_Tp, _Dp>, typename unique_ptr<_Tp, _Dp>::pointer> >
-#endif
-{
-    typedef unique_ptr<_Tp, _Dp> argument_type;
-    typedef size_t               result_type;
-    _LIBCPP_INLINE_VISIBILITY
-    result_type operator()(const argument_type& __ptr) const
-    {
-        typedef typename argument_type::pointer pointer;
-        return hash<pointer>()(__ptr.get());
-    }
-};
-
-struct __destruct_n
-{
-private:
-    size_t __size_;
-
-    template <class _Tp>
-    _LIBCPP_INLINE_VISIBILITY void __process(_Tp* __p, false_type) _NOEXCEPT
-        {for (size_t __i = 0; __i < __size_; ++__i, ++__p) __p->~_Tp();}
-
-    template <class _Tp>
-    _LIBCPP_INLINE_VISIBILITY void __process(_Tp*, true_type) _NOEXCEPT
-        {}
-
-    _LIBCPP_INLINE_VISIBILITY void __incr(false_type) _NOEXCEPT
-        {++__size_;}
-    _LIBCPP_INLINE_VISIBILITY void __incr(true_type) _NOEXCEPT
-        {}
-
-    _LIBCPP_INLINE_VISIBILITY void __set(size_t __s, false_type) _NOEXCEPT
-        {__size_ = __s;}
-    _LIBCPP_INLINE_VISIBILITY void __set(size_t, true_type) _NOEXCEPT
-        {}
-public:
-    _LIBCPP_INLINE_VISIBILITY explicit __destruct_n(size_t __s) _NOEXCEPT
-        : __size_(__s) {}
-
-    template <class _Tp>
-    _LIBCPP_INLINE_VISIBILITY void __incr() _NOEXCEPT
-        {__incr(integral_constant<bool, is_trivially_destructible<_Tp>::value>());}
-
-    template <class _Tp>
-    _LIBCPP_INLINE_VISIBILITY void __set(size_t __s, _Tp*) _NOEXCEPT
-        {__set(__s, integral_constant<bool, is_trivially_destructible<_Tp>::value>());}
-
-    template <class _Tp>
-    _LIBCPP_INLINE_VISIBILITY void operator()(_Tp* __p) _NOEXCEPT
-        {__process(__p, integral_constant<bool, is_trivially_destructible<_Tp>::value>());}
-};
-
-template <class _Alloc>
-class __allocator_destructor
-{
-    typedef _LIBCPP_NODEBUG_TYPE allocator_traits<_Alloc> __alloc_traits;
-public:
-    typedef _LIBCPP_NODEBUG_TYPE typename __alloc_traits::pointer pointer;
-    typedef _LIBCPP_NODEBUG_TYPE typename __alloc_traits::size_type size_type;
-private:
-    _Alloc& __alloc_;
-    size_type __s_;
-public:
-    _LIBCPP_INLINE_VISIBILITY __allocator_destructor(_Alloc& __a, size_type __s)
-             _NOEXCEPT
-        : __alloc_(__a), __s_(__s) {}
-    _LIBCPP_INLINE_VISIBILITY
-    void operator()(pointer __p) _NOEXCEPT
-        {__alloc_traits::deallocate(__alloc_, __p, __s_);}
-};
-
-template <class _InputIterator, class _ForwardIterator>
-_ForwardIterator
-uninitialized_copy(_InputIterator __f, _InputIterator __l, _ForwardIterator __r)
-{
-    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    _ForwardIterator __s = __r;
-    try
-    {
-#endif
-        for (; __f != __l; ++__f, (void) ++__r)
-            ::new ((void*)_VSTD::addressof(*__r)) value_type(*__f);
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-        for (; __s != __r; ++__s)
-            __s->~value_type();
-        throw;
-    }
-#endif
-    return __r;
-}
-
-template <class _InputIterator, class _Size, class _ForwardIterator>
-_ForwardIterator
-uninitialized_copy_n(_InputIterator __f, _Size __n, _ForwardIterator __r)
-{
-    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    _ForwardIterator __s = __r;
-    try
-    {
-#endif
-        for (; __n > 0; ++__f, (void) ++__r, (void) --__n)
-            ::new ((void*)_VSTD::addressof(*__r)) value_type(*__f);
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-        for (; __s != __r; ++__s)
-            __s->~value_type();
-        throw;
-    }
-#endif
-    return __r;
-}
-
-template <class _ForwardIterator, class _Tp>
-void
-uninitialized_fill(_ForwardIterator __f, _ForwardIterator __l, const _Tp& __x)
-{
-    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    _ForwardIterator __s = __f;
-    try
-    {
-#endif
-        for (; __f != __l; ++__f)
-            ::new ((void*)_VSTD::addressof(*__f)) value_type(__x);
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-        for (; __s != __f; ++__s)
-            __s->~value_type();
-        throw;
-    }
-#endif
-}
-
-template <class _ForwardIterator, class _Size, class _Tp>
-_ForwardIterator
-uninitialized_fill_n(_ForwardIterator __f, _Size __n, const _Tp& __x)
-{
-    typedef typename iterator_traits<_ForwardIterator>::value_type value_type;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    _ForwardIterator __s = __f;
-    try
-    {
-#endif
-        for (; __n > 0; ++__f, (void) --__n)
-            ::new ((void*)_VSTD::addressof(*__f)) value_type(__x);
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-        for (; __s != __f; ++__s)
-            __s->~value_type();
-        throw;
-    }
-#endif
-    return __f;
-}
-
-#if _LIBCPP_STD_VER > 14
-
-template <class _ForwardIterator>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void destroy(_ForwardIterator __first, _ForwardIterator __last) {
-    for (; __first != __last; ++__first)
-        _VSTD::destroy_at(_VSTD::addressof(*__first));
-}
-
-template <class _ForwardIterator, class _Size>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator destroy_n(_ForwardIterator __first, _Size __n) {
-    for (; __n > 0; (void)++__first, --__n)
-        _VSTD::destroy_at(_VSTD::addressof(*__first));
-    return __first;
-}
-
-template <class _ForwardIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void uninitialized_default_construct(_ForwardIterator __first, _ForwardIterator __last) {
-    using _Vt = typename iterator_traits<_ForwardIterator>::value_type;
-    auto __idx = __first;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try {
-#endif
-    for (; __idx != __last; ++__idx)
-        ::new ((void*)_VSTD::addressof(*__idx)) _Vt;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    } catch (...) {
-        _VSTD::destroy(__first, __idx);
-        throw;
-    }
-#endif
-}
-
-template <class _ForwardIterator, class _Size>
-inline _LIBCPP_INLINE_VISIBILITY
-_ForwardIterator uninitialized_default_construct_n(_ForwardIterator __first, _Size __n) {
-    using _Vt = typename iterator_traits<_ForwardIterator>::value_type;
-    auto __idx = __first;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try {
-#endif
-    for (; __n > 0; (void)++__idx, --__n)
-        ::new ((void*)_VSTD::addressof(*__idx)) _Vt;
-    return __idx;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    } catch (...) {
-        _VSTD::destroy(__first, __idx);
-        throw;
-    }
-#endif
-}
-
-
-template <class _ForwardIterator>
-inline _LIBCPP_INLINE_VISIBILITY
-void uninitialized_value_construct(_ForwardIterator __first, _ForwardIterator __last) {
-    using _Vt = typename iterator_traits<_ForwardIterator>::value_type;
-    auto __idx = __first;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try {
-#endif
-    for (; __idx != __last; ++__idx)
-        ::new ((void*)_VSTD::addressof(*__idx)) _Vt();
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    } catch (...) {
-        _VSTD::destroy(__first, __idx);
-        throw;
-    }
-#endif
-}
-
-template <class _ForwardIterator, class _Size>
-inline _LIBCPP_INLINE_VISIBILITY
-_ForwardIterator uninitialized_value_construct_n(_ForwardIterator __first, _Size __n) {
-    using _Vt = typename iterator_traits<_ForwardIterator>::value_type;
-    auto __idx = __first;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try {
-#endif
-    for (; __n > 0; (void)++__idx, --__n)
-        ::new ((void*)_VSTD::addressof(*__idx)) _Vt();
-    return __idx;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    } catch (...) {
-        _VSTD::destroy(__first, __idx);
-        throw;
-    }
-#endif
-}
-
-
-template <class _InputIt, class _ForwardIt>
-inline _LIBCPP_INLINE_VISIBILITY
-_ForwardIt uninitialized_move(_InputIt __first, _InputIt __last, _ForwardIt __first_res) {
-    using _Vt = typename iterator_traits<_ForwardIt>::value_type;
-    auto __idx = __first_res;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try {
-#endif
-    for (; __first != __last; (void)++__idx, ++__first)
-        ::new ((void*)_VSTD::addressof(*__idx)) _Vt(_VSTD::move(*__first));
-    return __idx;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    } catch (...) {
-        _VSTD::destroy(__first_res, __idx);
-        throw;
-    }
-#endif
-}
-
-template <class _InputIt, class _Size, class _ForwardIt>
-inline _LIBCPP_INLINE_VISIBILITY
-pair<_InputIt, _ForwardIt>
-uninitialized_move_n(_InputIt __first, _Size __n, _ForwardIt __first_res) {
-    using _Vt = typename iterator_traits<_ForwardIt>::value_type;
-    auto __idx = __first_res;
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try {
-#endif
-    for (; __n > 0; ++__idx, (void)++__first, --__n)
-        ::new ((void*)_VSTD::addressof(*__idx)) _Vt(_VSTD::move(*__first));
-    return {__first, __idx};
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    } catch (...) {
-        _VSTD::destroy(__first_res, __idx);
-        throw;
-    }
-#endif
-}
-
-
-#endif // _LIBCPP_STD_VER > 14
-
-// NOTE: Relaxed and acq/rel atomics (for increment and decrement respectively)
-// should be sufficient for thread safety.
-// See https://bugs.llvm.org/show_bug.cgi?id=22803
-#if defined(__clang__) && __has_builtin(__atomic_add_fetch)          \
-                       && defined(__ATOMIC_RELAXED)                  \
-                       && defined(__ATOMIC_ACQ_REL)
-#   define _LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT
-#elif defined(_LIBCPP_COMPILER_GCC)
-#   define _LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT
-#endif
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _Tp
-__libcpp_atomic_refcount_increment(_Tp& __t) _NOEXCEPT
-{
-#if defined(_LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT) && !defined(_LIBCPP_HAS_NO_THREADS)
-    return __atomic_add_fetch(&__t, 1, __ATOMIC_RELAXED);
-#else
-    return __t += 1;
-#endif
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _Tp
-__libcpp_atomic_refcount_decrement(_Tp& __t) _NOEXCEPT
-{
-#if defined(_LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT) && !defined(_LIBCPP_HAS_NO_THREADS)
-    return __atomic_add_fetch(&__t, -1, __ATOMIC_ACQ_REL);
-#else
-    return __t -= 1;
-#endif
-}
-
-class _LIBCPP_EXCEPTION_ABI bad_weak_ptr
-    : public std::exception
-{
-public:
-    bad_weak_ptr() _NOEXCEPT = default;
-    bad_weak_ptr(const bad_weak_ptr&) _NOEXCEPT = default;
-    virtual ~bad_weak_ptr() _NOEXCEPT;
-    virtual const char* what() const  _NOEXCEPT;
-};
-
-_LIBCPP_NORETURN inline _LIBCPP_INLINE_VISIBILITY
-void __throw_bad_weak_ptr()
-{
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    throw bad_weak_ptr();
-#else
-    _VSTD::abort();
-#endif
-}
-
-template<class _Tp> class _LIBCPP_TEMPLATE_VIS weak_ptr;
-
-class _LIBCPP_TYPE_VIS __shared_count
-{
-    __shared_count(const __shared_count&);
-    __shared_count& operator=(const __shared_count&);
-
-protected:
-    long __shared_owners_;
-    virtual ~__shared_count();
-private:
-    virtual void __on_zero_shared() _NOEXCEPT = 0;
-
-public:
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __shared_count(long __refs = 0) _NOEXCEPT
-        : __shared_owners_(__refs) {}
-
-#if defined(_LIBCPP_BUILDING_LIBRARY) && \
-    defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
-    void __add_shared() _NOEXCEPT;
-    bool __release_shared() _NOEXCEPT;
-#else
-    _LIBCPP_INLINE_VISIBILITY
-    void __add_shared() _NOEXCEPT {
-      __libcpp_atomic_refcount_increment(__shared_owners_);
-    }
-    _LIBCPP_INLINE_VISIBILITY
-    bool __release_shared() _NOEXCEPT {
-      if (__libcpp_atomic_refcount_decrement(__shared_owners_) == -1) {
-        __on_zero_shared();
-        return true;
-      }
-      return false;
-    }
-#endif
-    _LIBCPP_INLINE_VISIBILITY
-    long use_count() const _NOEXCEPT {
-        return __libcpp_relaxed_load(&__shared_owners_) + 1;
-    }
-};
-
-class _LIBCPP_TYPE_VIS __shared_weak_count
-    : private __shared_count
-{
-    long __shared_weak_owners_;
-
-public:
-    _LIBCPP_INLINE_VISIBILITY
-    explicit __shared_weak_count(long __refs = 0) _NOEXCEPT
-        : __shared_count(__refs),
-          __shared_weak_owners_(__refs) {}
-protected:
-    virtual ~__shared_weak_count();
-
-public:
-#if defined(_LIBCPP_BUILDING_LIBRARY) && \
-    defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
-    void __add_shared() _NOEXCEPT;
-    void __add_weak() _NOEXCEPT;
-    void __release_shared() _NOEXCEPT;
-#else
-    _LIBCPP_INLINE_VISIBILITY
-    void __add_shared() _NOEXCEPT {
-      __shared_count::__add_shared();
-    }
-    _LIBCPP_INLINE_VISIBILITY
-    void __add_weak() _NOEXCEPT {
-      __libcpp_atomic_refcount_increment(__shared_weak_owners_);
-    }
-    _LIBCPP_INLINE_VISIBILITY
-    void __release_shared() _NOEXCEPT {
-      if (__shared_count::__release_shared())
-        __release_weak();
-    }
-#endif
-    void __release_weak() _NOEXCEPT;
-    _LIBCPP_INLINE_VISIBILITY
-    long use_count() const _NOEXCEPT {return __shared_count::use_count();}
-    __shared_weak_count* lock() _NOEXCEPT;
-
-    virtual const void* __get_deleter(const type_info&) const _NOEXCEPT;
-private:
-    virtual void __on_zero_shared_weak() _NOEXCEPT = 0;
-};
-
-template <class _Tp, class _Dp, class _Alloc>
-class __shared_ptr_pointer
-    : public __shared_weak_count
-{
-    __compressed_pair<__compressed_pair<_Tp, _Dp>, _Alloc> __data_;
-public:
-    _LIBCPP_INLINE_VISIBILITY
-    __shared_ptr_pointer(_Tp __p, _Dp __d, _Alloc __a)
-        :  __data_(__compressed_pair<_Tp, _Dp>(__p, _VSTD::move(__d)), _VSTD::move(__a)) {}
-
-#ifndef _LIBCPP_NO_RTTI
-    virtual const void* __get_deleter(const type_info&) const _NOEXCEPT;
-#endif
-
-private:
-    virtual void __on_zero_shared() _NOEXCEPT;
-    virtual void __on_zero_shared_weak() _NOEXCEPT;
-};
-
-#ifndef _LIBCPP_NO_RTTI
-
-template <class _Tp, class _Dp, class _Alloc>
-const void*
-__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__get_deleter(const type_info& __t) const _NOEXCEPT
-{
-    return __t == typeid(_Dp) ? _VSTD::addressof(__data_.first().second()) : nullptr;
-}
-
-#endif  // _LIBCPP_NO_RTTI
-
-template <class _Tp, class _Dp, class _Alloc>
-void
-__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__on_zero_shared() _NOEXCEPT
-{
-    __data_.first().second()(__data_.first().first());
-    __data_.first().second().~_Dp();
-}
-
-template <class _Tp, class _Dp, class _Alloc>
-void
-__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__on_zero_shared_weak() _NOEXCEPT
-{
-    typedef typename __allocator_traits_rebind<_Alloc, __shared_ptr_pointer>::type _Al;
-    typedef allocator_traits<_Al> _ATraits;
-    typedef pointer_traits<typename _ATraits::pointer> _PTraits;
-
-    _Al __a(__data_.second());
-    __data_.second().~_Alloc();
-    __a.deallocate(_PTraits::pointer_to(*this), 1);
-}
-
-template <class _Tp, class _Alloc>
-struct __shared_ptr_emplace
-    : __shared_weak_count
-{
-    template<class ..._Args>
-    _LIBCPP_HIDE_FROM_ABI
-    explicit __shared_ptr_emplace(_Alloc __a, _Args&& ...__args)
-        : __storage_(_VSTD::move(__a))
-    {
-#if _LIBCPP_STD_VER > 17
-        using _TpAlloc = typename __allocator_traits_rebind<_Alloc, _Tp>::type;
-        _TpAlloc __tmp(*__get_alloc());
-        allocator_traits<_TpAlloc>::construct(__tmp, __get_elem(), _VSTD::forward<_Args>(__args)...);
-#else
-        ::new ((void*)__get_elem()) _Tp(_VSTD::forward<_Args>(__args)...);
-#endif
-    }
-
-    _LIBCPP_HIDE_FROM_ABI
-    _Alloc* __get_alloc() _NOEXCEPT { return __storage_.__get_alloc(); }
-
-    _LIBCPP_HIDE_FROM_ABI
-    _Tp* __get_elem() _NOEXCEPT { return __storage_.__get_elem(); }
-
-private:
-    virtual void __on_zero_shared() _NOEXCEPT {
-#if _LIBCPP_STD_VER > 17
-        using _TpAlloc = typename __allocator_traits_rebind<_Alloc, _Tp>::type;
-        _TpAlloc __tmp(*__get_alloc());
-        allocator_traits<_TpAlloc>::destroy(__tmp, __get_elem());
-#else
-        __get_elem()->~_Tp();
-#endif
-    }
-
-    virtual void __on_zero_shared_weak() _NOEXCEPT {
-        using _ControlBlockAlloc = typename __allocator_traits_rebind<_Alloc, __shared_ptr_emplace>::type;
-        using _ControlBlockPointer = typename allocator_traits<_ControlBlockAlloc>::pointer;
-        _ControlBlockAlloc __tmp(*__get_alloc());
-        __storage_.~_Storage();
-        allocator_traits<_ControlBlockAlloc>::deallocate(__tmp,
-            pointer_traits<_ControlBlockPointer>::pointer_to(*this), 1);
-    }
-
-    // This class implements the control block for non-array shared pointers created
-    // through `std::allocate_shared` and `std::make_shared`.
-    //
-    // In previous versions of the library, we used a compressed pair to store
-    // both the _Alloc and the _Tp. This implies using EBO, which is incompatible
-    // with Allocator construction for _Tp. To allow implementing P0674 in C++20,
-    // we now use a properly aligned char buffer while making sure that we maintain
-    // the same layout that we had when we used a compressed pair.
-    using _CompressedPair = __compressed_pair<_Alloc, _Tp>;
-    struct _ALIGNAS_TYPE(_CompressedPair) _Storage {
-        char __blob_[sizeof(_CompressedPair)];
-
-        _LIBCPP_HIDE_FROM_ABI explicit _Storage(_Alloc&& __a) {
-            ::new ((void*)__get_alloc()) _Alloc(_VSTD::move(__a));
-        }
-        _LIBCPP_HIDE_FROM_ABI ~_Storage() {
-            __get_alloc()->~_Alloc();
-        }
-        _Alloc* __get_alloc() _NOEXCEPT {
-            _CompressedPair *__as_pair = reinterpret_cast<_CompressedPair*>(__blob_);
-            typename _CompressedPair::_Base1* __first = _CompressedPair::__get_first_base(__as_pair);
-            _Alloc *__alloc = reinterpret_cast<_Alloc*>(__first);
-            return __alloc;
-        }
-        _LIBCPP_NO_CFI _Tp* __get_elem() _NOEXCEPT {
-            _CompressedPair *__as_pair = reinterpret_cast<_CompressedPair*>(__blob_);
-            typename _CompressedPair::_Base2* __second = _CompressedPair::__get_second_base(__as_pair);
-            _Tp *__elem = reinterpret_cast<_Tp*>(__second);
-            return __elem;
-        }
-    };
-
-    static_assert(_LIBCPP_ALIGNOF(_Storage) == _LIBCPP_ALIGNOF(_CompressedPair), "");
-    static_assert(sizeof(_Storage) == sizeof(_CompressedPair), "");
-    _Storage __storage_;
-};
-
-struct __shared_ptr_dummy_rebind_allocator_type;
-template <>
-class _LIBCPP_TEMPLATE_VIS allocator<__shared_ptr_dummy_rebind_allocator_type>
-{
-public:
-    template <class _Other>
-    struct rebind
-    {
-        typedef allocator<_Other> other;
-    };
-};
-
-template<class _Tp> class _LIBCPP_TEMPLATE_VIS enable_shared_from_this;
-
-template<class _Tp, class _Up>
-struct __compatible_with
-#if _LIBCPP_STD_VER > 14
-    : is_convertible<remove_extent_t<_Tp>*, remove_extent_t<_Up>*> {};
-#else
-    : is_convertible<_Tp*, _Up*> {};
-#endif // _LIBCPP_STD_VER > 14
-
-#if defined(_LIBCPP_ABI_ENABLE_SHARED_PTR_TRIVIAL_ABI)
-#  define _LIBCPP_SHARED_PTR_TRIVIAL_ABI __attribute__((trivial_abi))
-#else
-#  define _LIBCPP_SHARED_PTR_TRIVIAL_ABI
-#endif
-
-template<class _Tp>
-class _LIBCPP_SHARED_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS shared_ptr
-{
-public:
-#if _LIBCPP_STD_VER > 14
-    typedef weak_ptr<_Tp> weak_type;
-    typedef remove_extent_t<_Tp> element_type;
-#else
-    typedef _Tp element_type;
-#endif
-
-private:
-    element_type*      __ptr_;
-    __shared_weak_count* __cntrl_;
-
-    struct __nat {int __for_bool_;};
-public:
-    _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_CONSTEXPR shared_ptr() _NOEXCEPT;
-    _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_CONSTEXPR shared_ptr(nullptr_t) _NOEXCEPT;
-    template<class _Yp>
-        explicit shared_ptr(_Yp* __p,
-                            typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat());
-    template<class _Yp, class _Dp>
-        shared_ptr(_Yp* __p, _Dp __d,
-                   typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat());
-    template<class _Yp, class _Dp, class _Alloc>
-        shared_ptr(_Yp* __p, _Dp __d, _Alloc __a,
-                   typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat());
-    template <class _Dp> shared_ptr(nullptr_t __p, _Dp __d);
-    template <class _Dp, class _Alloc> shared_ptr(nullptr_t __p, _Dp __d, _Alloc __a);
-    template<class _Yp> _LIBCPP_INLINE_VISIBILITY shared_ptr(const shared_ptr<_Yp>& __r, element_type* __p) _NOEXCEPT;
-    _LIBCPP_INLINE_VISIBILITY
-    shared_ptr(const shared_ptr& __r) _NOEXCEPT;
-    template<class _Yp>
-        _LIBCPP_INLINE_VISIBILITY
-        shared_ptr(const shared_ptr<_Yp>& __r,
-                   typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat())
-                       _NOEXCEPT;
-    _LIBCPP_INLINE_VISIBILITY
-    shared_ptr(shared_ptr&& __r) _NOEXCEPT;
-    template<class _Yp> _LIBCPP_INLINE_VISIBILITY  shared_ptr(shared_ptr<_Yp>&& __r,
-                   typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat())
-                       _NOEXCEPT;
-    template<class _Yp> explicit shared_ptr(const weak_ptr<_Yp>& __r,
-                   typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type= __nat());
-#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
-    template<class _Yp>
-        shared_ptr(auto_ptr<_Yp>&& __r,
-                   typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type = __nat());
-#endif
-    template <class _Yp, class _Dp>
-        shared_ptr(unique_ptr<_Yp, _Dp>&&,
-                   typename enable_if
-                   <
-                       !is_lvalue_reference<_Dp>::value &&
-                       !is_array<_Yp>::value &&
-                       is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
-                       __nat
-                   >::type = __nat());
-    template <class _Yp, class _Dp>
-        shared_ptr(unique_ptr<_Yp, _Dp>&&,
-                   typename enable_if
-                   <
-                       is_lvalue_reference<_Dp>::value &&
-                       !is_array<_Yp>::value &&
-                       is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
-                       __nat
-                   >::type = __nat());
-
-    ~shared_ptr();
-
-    _LIBCPP_INLINE_VISIBILITY
-    shared_ptr& operator=(const shared_ptr& __r) _NOEXCEPT;
-    template<class _Yp>
-        typename enable_if
-        <
-            __compatible_with<_Yp, element_type>::value,
-            shared_ptr&
-        >::type
-        _LIBCPP_INLINE_VISIBILITY
-        operator=(const shared_ptr<_Yp>& __r) _NOEXCEPT;
-    _LIBCPP_INLINE_VISIBILITY
-    shared_ptr& operator=(shared_ptr&& __r) _NOEXCEPT;
-    template<class _Yp>
-        typename enable_if
-        <
-            __compatible_with<_Yp, element_type>::value,
-            shared_ptr&
-        >::type
-        _LIBCPP_INLINE_VISIBILITY
-        operator=(shared_ptr<_Yp>&& __r);
-#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
-    template<class _Yp>
-        _LIBCPP_INLINE_VISIBILITY
-        typename enable_if
-        <
-            !is_array<_Yp>::value &&
-            is_convertible<_Yp*, element_type*>::value,
-            shared_ptr
-        >::type&
-        operator=(auto_ptr<_Yp>&& __r);
-#endif
-    template <class _Yp, class _Dp>
-        typename enable_if
-        <
-            !is_array<_Yp>::value &&
-            is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
-            shared_ptr&
-        >::type
-        _LIBCPP_INLINE_VISIBILITY
-        operator=(unique_ptr<_Yp, _Dp>&& __r);
-
-    _LIBCPP_INLINE_VISIBILITY
-    void swap(shared_ptr& __r) _NOEXCEPT;
-    _LIBCPP_INLINE_VISIBILITY
-    void reset() _NOEXCEPT;
-    template<class _Yp>
-        typename enable_if
-        <
-            __compatible_with<_Yp, element_type>::value,
-            void
-        >::type
-        _LIBCPP_INLINE_VISIBILITY
-        reset(_Yp* __p);
-    template<class _Yp, class _Dp>
-        typename enable_if
-        <
-            __compatible_with<_Yp, element_type>::value,
-            void
-        >::type
-        _LIBCPP_INLINE_VISIBILITY
-        reset(_Yp* __p, _Dp __d);
-    template<class _Yp, class _Dp, class _Alloc>
-        typename enable_if
-        <
-            __compatible_with<_Yp, element_type>::value,
-            void
-        >::type
-        _LIBCPP_INLINE_VISIBILITY
-        reset(_Yp* __p, _Dp __d, _Alloc __a);
-
-    _LIBCPP_INLINE_VISIBILITY
-    element_type* get() const _NOEXCEPT {return __ptr_;}
-    _LIBCPP_INLINE_VISIBILITY
-    typename add_lvalue_reference<element_type>::type operator*() const _NOEXCEPT
-        {return *__ptr_;}
-    _LIBCPP_INLINE_VISIBILITY
-    element_type* operator->() const _NOEXCEPT
-    {
-        static_assert(!_VSTD::is_array<_Tp>::value,
-                      "std::shared_ptr<T>::operator-> is only valid when T is not an array type.");
-        return __ptr_;
-    }
-    _LIBCPP_INLINE_VISIBILITY
-    long use_count() const _NOEXCEPT {return __cntrl_ ? __cntrl_->use_count() : 0;}
-    _LIBCPP_INLINE_VISIBILITY
-    bool unique() const _NOEXCEPT {return use_count() == 1;}
-    _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_EXPLICIT operator bool() const _NOEXCEPT {return get() != nullptr;}
-    template <class _Up>
-        _LIBCPP_INLINE_VISIBILITY
-        bool owner_before(shared_ptr<_Up> const& __p) const _NOEXCEPT
-        {return __cntrl_ < __p.__cntrl_;}
-    template <class _Up>
-        _LIBCPP_INLINE_VISIBILITY
-        bool owner_before(weak_ptr<_Up> const& __p) const _NOEXCEPT
-        {return __cntrl_ < __p.__cntrl_;}
-    _LIBCPP_INLINE_VISIBILITY
-    bool
-    __owner_equivalent(const shared_ptr& __p) const
-        {return __cntrl_ == __p.__cntrl_;}
-
-#if _LIBCPP_STD_VER > 14
-    typename add_lvalue_reference<element_type>::type
-    _LIBCPP_INLINE_VISIBILITY
-    operator[](ptrdiff_t __i) const
-    {
-            static_assert(_VSTD::is_array<_Tp>::value,
-                          "std::shared_ptr<T>::operator[] is only valid when T is an array type.");
-            return __ptr_[__i];
-    }
-#endif
-
-#ifndef _LIBCPP_NO_RTTI
-    template <class _Dp>
-        _LIBCPP_INLINE_VISIBILITY
-        _Dp* __get_deleter() const _NOEXCEPT
-            {return static_cast<_Dp*>(__cntrl_
-                    ? const_cast<void *>(__cntrl_->__get_deleter(typeid(_Dp)))
-                      : nullptr);}
-#endif  // _LIBCPP_NO_RTTI
-
-    template<class _Yp, class _CntrlBlk>
-    static shared_ptr<_Tp>
-    __create_with_control_block(_Yp* __p, _CntrlBlk* __cntrl) _NOEXCEPT
-    {
-        shared_ptr<_Tp> __r;
-        __r.__ptr_ = __p;
-        __r.__cntrl_ = __cntrl;
-        __r.__enable_weak_this(__r.__ptr_, __r.__ptr_);
-        return __r;
-    }
-
-private:
-    template <class _Yp, bool = is_function<_Yp>::value>
-        struct __shared_ptr_default_allocator
-        {
-            typedef allocator<_Yp> type;
-        };
-
-    template <class _Yp>
-        struct __shared_ptr_default_allocator<_Yp, true>
-        {
-            typedef allocator<__shared_ptr_dummy_rebind_allocator_type> type;
-        };
-
-    template <class _Yp, class _OrigPtr>
-        _LIBCPP_INLINE_VISIBILITY
-        typename enable_if<is_convertible<_OrigPtr*,
-                                          const enable_shared_from_this<_Yp>*
-        >::value,
-            void>::type
-        __enable_weak_this(const enable_shared_from_this<_Yp>* __e,
-                           _OrigPtr* __ptr) _NOEXCEPT
-        {
-            typedef typename remove_cv<_Yp>::type _RawYp;
-            if (__e && __e->__weak_this_.expired())
-            {
-                __e->__weak_this_ = shared_ptr<_RawYp>(*this,
-                    const_cast<_RawYp*>(static_cast<const _Yp*>(__ptr)));
-            }
-        }
-
-    _LIBCPP_INLINE_VISIBILITY void __enable_weak_this(...) _NOEXCEPT {}
-
-    template <class, class _Yp>
-        struct __shared_ptr_default_delete
-            : default_delete<_Yp> {};
-
-    template <class _Yp, class _Un, size_t _Sz>
-        struct __shared_ptr_default_delete<_Yp[_Sz], _Un>
-            : default_delete<_Yp[]> {};
-
-    template <class _Yp, class _Un>
-        struct __shared_ptr_default_delete<_Yp[], _Un>
-            : default_delete<_Yp[]> {};
-
-    template <class _Up> friend class _LIBCPP_TEMPLATE_VIS shared_ptr;
-    template <class _Up> friend class _LIBCPP_TEMPLATE_VIS weak_ptr;
-};
-
-#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
-template<class _Tp>
-shared_ptr(weak_ptr<_Tp>) -> shared_ptr<_Tp>;
-template<class _Tp, class _Dp>
-shared_ptr(unique_ptr<_Tp, _Dp>) -> shared_ptr<_Tp>;
-#endif
-
-template<class _Tp>
-inline
-_LIBCPP_CONSTEXPR
-shared_ptr<_Tp>::shared_ptr() _NOEXCEPT
-    : __ptr_(nullptr),
-      __cntrl_(nullptr)
-{
-}
-
-template<class _Tp>
-inline
-_LIBCPP_CONSTEXPR
-shared_ptr<_Tp>::shared_ptr(nullptr_t) _NOEXCEPT
-    : __ptr_(nullptr),
-      __cntrl_(nullptr)
-{
-}
-
-template<class _Tp>
-template<class _Yp>
-shared_ptr<_Tp>::shared_ptr(_Yp* __p,
-                            typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
-    : __ptr_(__p)
-{
-    unique_ptr<_Yp> __hold(__p);
-    typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
-    typedef __shared_ptr_pointer<_Yp*, __shared_ptr_default_delete<_Tp, _Yp>, _AllocT > _CntrlBlk;
-    __cntrl_ = new _CntrlBlk(__p, __shared_ptr_default_delete<_Tp, _Yp>(), _AllocT());
-    __hold.release();
-    __enable_weak_this(__p, __p);
-}
-
-template<class _Tp>
-template<class _Yp, class _Dp>
-shared_ptr<_Tp>::shared_ptr(_Yp* __p, _Dp __d,
-                            typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
-    : __ptr_(__p)
-{
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try
-    {
-#endif  // _LIBCPP_NO_EXCEPTIONS
-        typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
-        typedef __shared_ptr_pointer<_Yp*, _Dp, _AllocT > _CntrlBlk;
-        __cntrl_ = new _CntrlBlk(__p, __d, _AllocT());
-        __enable_weak_this(__p, __p);
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-        __d(__p);
-        throw;
-    }
-#endif  // _LIBCPP_NO_EXCEPTIONS
-}
-
-template<class _Tp>
-template<class _Dp>
-shared_ptr<_Tp>::shared_ptr(nullptr_t __p, _Dp __d)
-    : __ptr_(nullptr)
-{
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try
-    {
-#endif  // _LIBCPP_NO_EXCEPTIONS
-        typedef typename __shared_ptr_default_allocator<_Tp>::type _AllocT;
-        typedef __shared_ptr_pointer<nullptr_t, _Dp, _AllocT > _CntrlBlk;
-        __cntrl_ = new _CntrlBlk(__p, __d, _AllocT());
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-        __d(__p);
-        throw;
-    }
-#endif  // _LIBCPP_NO_EXCEPTIONS
-}
-
-template<class _Tp>
-template<class _Yp, class _Dp, class _Alloc>
-shared_ptr<_Tp>::shared_ptr(_Yp* __p, _Dp __d, _Alloc __a,
-                            typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
-    : __ptr_(__p)
-{
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try
-    {
-#endif  // _LIBCPP_NO_EXCEPTIONS
-        typedef __shared_ptr_pointer<_Yp*, _Dp, _Alloc> _CntrlBlk;
-        typedef typename __allocator_traits_rebind<_Alloc, _CntrlBlk>::type _A2;
-        typedef __allocator_destructor<_A2> _D2;
-        _A2 __a2(__a);
-        unique_ptr<_CntrlBlk, _D2> __hold2(__a2.allocate(1), _D2(__a2, 1));
-        ::new ((void*)_VSTD::addressof(*__hold2.get())) _CntrlBlk(__p, __d, __a);
-        __cntrl_ = _VSTD::addressof(*__hold2.release());
-        __enable_weak_this(__p, __p);
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-        __d(__p);
-        throw;
-    }
-#endif  // _LIBCPP_NO_EXCEPTIONS
-}
-
-template<class _Tp>
-template<class _Dp, class _Alloc>
-shared_ptr<_Tp>::shared_ptr(nullptr_t __p, _Dp __d, _Alloc __a)
-    : __ptr_(nullptr)
-{
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    try
-    {
-#endif  // _LIBCPP_NO_EXCEPTIONS
-        typedef __shared_ptr_pointer<nullptr_t, _Dp, _Alloc> _CntrlBlk;
-        typedef typename __allocator_traits_rebind<_Alloc, _CntrlBlk>::type _A2;
-        typedef __allocator_destructor<_A2> _D2;
-        _A2 __a2(__a);
-        unique_ptr<_CntrlBlk, _D2> __hold2(__a2.allocate(1), _D2(__a2, 1));
-        ::new ((void*)_VSTD::addressof(*__hold2.get())) _CntrlBlk(__p, __d, __a);
-        __cntrl_ = _VSTD::addressof(*__hold2.release());
-#ifndef _LIBCPP_NO_EXCEPTIONS
-    }
-    catch (...)
-    {
-        __d(__p);
-        throw;
-    }
-#endif  // _LIBCPP_NO_EXCEPTIONS
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-shared_ptr<_Tp>::shared_ptr(const shared_ptr<_Yp>& __r, element_type *__p) _NOEXCEPT
-    : __ptr_(__p),
-      __cntrl_(__r.__cntrl_)
-{
-    if (__cntrl_)
-        __cntrl_->__add_shared();
-}
-
-template<class _Tp>
-inline
-shared_ptr<_Tp>::shared_ptr(const shared_ptr& __r) _NOEXCEPT
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_)
-{
-    if (__cntrl_)
-        __cntrl_->__add_shared();
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-shared_ptr<_Tp>::shared_ptr(const shared_ptr<_Yp>& __r,
-                            typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
-         _NOEXCEPT
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_)
-{
-    if (__cntrl_)
-        __cntrl_->__add_shared();
-}
-
-template<class _Tp>
-inline
-shared_ptr<_Tp>::shared_ptr(shared_ptr&& __r) _NOEXCEPT
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_)
-{
-    __r.__ptr_ = nullptr;
-    __r.__cntrl_ = nullptr;
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-shared_ptr<_Tp>::shared_ptr(shared_ptr<_Yp>&& __r,
-                            typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
-         _NOEXCEPT
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_)
-{
-    __r.__ptr_ = nullptr;
-    __r.__cntrl_ = nullptr;
-}
-
-#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
-template<class _Tp>
-template<class _Yp>
-shared_ptr<_Tp>::shared_ptr(auto_ptr<_Yp>&& __r,
-                            typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type)
-    : __ptr_(__r.get())
-{
-    typedef __shared_ptr_pointer<_Yp*, default_delete<_Yp>, allocator<_Yp> > _CntrlBlk;
-    __cntrl_ = new _CntrlBlk(__r.get(), default_delete<_Yp>(), allocator<_Yp>());
-    __enable_weak_this(__r.get(), __r.get());
-    __r.release();
-}
-#endif
-
-template<class _Tp>
-template <class _Yp, class _Dp>
-shared_ptr<_Tp>::shared_ptr(unique_ptr<_Yp, _Dp>&& __r,
-                            typename enable_if
-                            <
-                                !is_lvalue_reference<_Dp>::value &&
-                                !is_array<_Yp>::value &&
-                                is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
-                                __nat
-                            >::type)
-    : __ptr_(__r.get())
-{
-#if _LIBCPP_STD_VER > 11
-    if (__ptr_ == nullptr)
-        __cntrl_ = nullptr;
-    else
-#endif
-    {
-        typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
-        typedef __shared_ptr_pointer<_Yp*, _Dp, _AllocT > _CntrlBlk;
-        __cntrl_ = new _CntrlBlk(__r.get(), __r.get_deleter(), _AllocT());
-        __enable_weak_this(__r.get(), __r.get());
-    }
-    __r.release();
-}
-
-template<class _Tp>
-template <class _Yp, class _Dp>
-shared_ptr<_Tp>::shared_ptr(unique_ptr<_Yp, _Dp>&& __r,
-                            typename enable_if
-                            <
-                                is_lvalue_reference<_Dp>::value &&
-                                !is_array<_Yp>::value &&
-                                is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
-                                __nat
-                            >::type)
-    : __ptr_(__r.get())
-{
-#if _LIBCPP_STD_VER > 11
-    if (__ptr_ == nullptr)
-        __cntrl_ = nullptr;
-    else
-#endif
-    {
-        typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
-        typedef __shared_ptr_pointer<_Yp*,
-                                     reference_wrapper<typename remove_reference<_Dp>::type>,
-                                     _AllocT > _CntrlBlk;
-        __cntrl_ = new _CntrlBlk(__r.get(), _VSTD::ref(__r.get_deleter()), _AllocT());
-        __enable_weak_this(__r.get(), __r.get());
-    }
-    __r.release();
-}
-
-template<class _Tp>
-shared_ptr<_Tp>::~shared_ptr()
-{
-    if (__cntrl_)
-        __cntrl_->__release_shared();
-}
-
-template<class _Tp>
-inline
-shared_ptr<_Tp>&
-shared_ptr<_Tp>::operator=(const shared_ptr& __r) _NOEXCEPT
-{
-    shared_ptr(__r).swap(*this);
-    return *this;
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-typename enable_if
-<
-    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
-    shared_ptr<_Tp>&
->::type
-shared_ptr<_Tp>::operator=(const shared_ptr<_Yp>& __r) _NOEXCEPT
-{
-    shared_ptr(__r).swap(*this);
-    return *this;
-}
-
-template<class _Tp>
-inline
-shared_ptr<_Tp>&
-shared_ptr<_Tp>::operator=(shared_ptr&& __r) _NOEXCEPT
-{
-    shared_ptr(_VSTD::move(__r)).swap(*this);
-    return *this;
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-typename enable_if
-<
-    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
-    shared_ptr<_Tp>&
->::type
-shared_ptr<_Tp>::operator=(shared_ptr<_Yp>&& __r)
-{
-    shared_ptr(_VSTD::move(__r)).swap(*this);
-    return *this;
-}
-
-#if _LIBCPP_STD_VER <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
-template<class _Tp>
-template<class _Yp>
-inline
-typename enable_if
-<
-    !is_array<_Yp>::value &&
-    is_convertible<_Yp*, typename shared_ptr<_Tp>::element_type*>::value,
-    shared_ptr<_Tp>
->::type&
-shared_ptr<_Tp>::operator=(auto_ptr<_Yp>&& __r)
-{
-    shared_ptr(_VSTD::move(__r)).swap(*this);
-    return *this;
-}
-#endif
-
-template<class _Tp>
-template <class _Yp, class _Dp>
-inline
-typename enable_if
-<
-    !is_array<_Yp>::value &&
-    is_convertible<typename unique_ptr<_Yp, _Dp>::pointer,
-                   typename shared_ptr<_Tp>::element_type*>::value,
-    shared_ptr<_Tp>&
->::type
-shared_ptr<_Tp>::operator=(unique_ptr<_Yp, _Dp>&& __r)
-{
-    shared_ptr(_VSTD::move(__r)).swap(*this);
-    return *this;
-}
-
-template<class _Tp>
-inline
-void
-shared_ptr<_Tp>::swap(shared_ptr& __r) _NOEXCEPT
-{
-    _VSTD::swap(__ptr_, __r.__ptr_);
-    _VSTD::swap(__cntrl_, __r.__cntrl_);
-}
-
-template<class _Tp>
-inline
-void
-shared_ptr<_Tp>::reset() _NOEXCEPT
-{
-    shared_ptr().swap(*this);
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-typename enable_if
-<
-    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
-    void
->::type
-shared_ptr<_Tp>::reset(_Yp* __p)
-{
-    shared_ptr(__p).swap(*this);
-}
-
-template<class _Tp>
-template<class _Yp, class _Dp>
-inline
-typename enable_if
-<
-    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
-    void
->::type
-shared_ptr<_Tp>::reset(_Yp* __p, _Dp __d)
-{
-    shared_ptr(__p, __d).swap(*this);
-}
-
-template<class _Tp>
-template<class _Yp, class _Dp, class _Alloc>
-inline
-typename enable_if
-<
-    __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
-    void
->::type
-shared_ptr<_Tp>::reset(_Yp* __p, _Dp __d, _Alloc __a)
-{
-    shared_ptr(__p, __d, __a).swap(*this);
-}
-
-//
-// std::allocate_shared and std::make_shared
-//
-template<class _Tp, class _Alloc, class ..._Args, class = _EnableIf<!is_array<_Tp>::value> >
-_LIBCPP_HIDE_FROM_ABI
-shared_ptr<_Tp> allocate_shared(const _Alloc& __a, _Args&& ...__args)
-{
-    using _ControlBlock = __shared_ptr_emplace<_Tp, _Alloc>;
-    using _ControlBlockAllocator = typename __allocator_traits_rebind<_Alloc, _ControlBlock>::type;
-    __allocation_guard<_ControlBlockAllocator> __guard(__a, 1);
-    ::new ((void*)_VSTD::addressof(*__guard.__get())) _ControlBlock(__a, _VSTD::forward<_Args>(__args)...);
-    auto __control_block = __guard.__release_ptr();
-    return shared_ptr<_Tp>::__create_with_control_block((*__control_block).__get_elem(), _VSTD::addressof(*__control_block));
-}
-
-template<class _Tp, class ..._Args, class = _EnableIf<!is_array<_Tp>::value> >
-_LIBCPP_HIDE_FROM_ABI
-shared_ptr<_Tp> make_shared(_Args&& ...__args)
-{
-    return _VSTD::allocate_shared<_Tp>(allocator<_Tp>(), _VSTD::forward<_Args>(__args)...);
-}
-
-template<class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator==(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
-{
-    return __x.get() == __y.get();
-}
-
-template<class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
-{
-    return !(__x == __y);
-}
-
-template<class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
-{
-#if _LIBCPP_STD_VER <= 11
-    typedef typename common_type<_Tp*, _Up*>::type _Vp;
-    return less<_Vp>()(__x.get(), __y.get());
-#else
-    return less<>()(__x.get(), __y.get());
-#endif
-
-}
-
-template<class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
-{
-    return __y < __x;
-}
-
-template<class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
-{
-    return !(__y < __x);
-}
-
-template<class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPT
-{
-    return !(__x < __y);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator==(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
-{
-    return !__x;
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator==(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
-{
-    return !__x;
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
-{
-    return static_cast<bool>(__x);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
-{
-    return static_cast<bool>(__x);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
-{
-    return less<_Tp*>()(__x.get(), nullptr);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
-{
-    return less<_Tp*>()(nullptr, __x.get());
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
-{
-    return nullptr < __x;
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
-{
-    return __x < nullptr;
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
-{
-    return !(nullptr < __x);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
-{
-    return !(__x < nullptr);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPT
-{
-    return !(__x < nullptr);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPT
-{
-    return !(nullptr < __x);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-swap(shared_ptr<_Tp>& __x, shared_ptr<_Tp>& __y) _NOEXCEPT
-{
-    __x.swap(__y);
-}
-
-template<class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-shared_ptr<_Tp>
-static_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPT
-{
-    return shared_ptr<_Tp>(__r,
-                           static_cast<
-                               typename shared_ptr<_Tp>::element_type*>(__r.get()));
-}
-
-template<class _Tp, class _Up>
-inline _LIBCPP_INLINE_VISIBILITY
-shared_ptr<_Tp>
-dynamic_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPT
-{
-    typedef typename shared_ptr<_Tp>::element_type _ET;
-    _ET* __p = dynamic_cast<_ET*>(__r.get());
-    return __p ? shared_ptr<_Tp>(__r, __p) : shared_ptr<_Tp>();
-}
-
-template<class _Tp, class _Up>
-shared_ptr<_Tp>
-const_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPT
-{
-    typedef typename shared_ptr<_Tp>::element_type _RTp;
-    return shared_ptr<_Tp>(__r, const_cast<_RTp*>(__r.get()));
-}
-
-template<class _Tp, class _Up>
-shared_ptr<_Tp>
-reinterpret_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPT
-{
-    return shared_ptr<_Tp>(__r,
-                           reinterpret_cast<
-                               typename shared_ptr<_Tp>::element_type*>(__r.get()));
-}
-
-#ifndef _LIBCPP_NO_RTTI
-
-template<class _Dp, class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-_Dp*
-get_deleter(const shared_ptr<_Tp>& __p) _NOEXCEPT
-{
-    return __p.template __get_deleter<_Dp>();
-}
-
-#endif  // _LIBCPP_NO_RTTI
-
-template<class _Tp>
-class _LIBCPP_SHARED_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS weak_ptr
-{
-public:
-    typedef _Tp element_type;
-private:
-    element_type*        __ptr_;
-    __shared_weak_count* __cntrl_;
-
-public:
-    _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_CONSTEXPR weak_ptr() _NOEXCEPT;
-    template<class _Yp> _LIBCPP_INLINE_VISIBILITY weak_ptr(shared_ptr<_Yp> const& __r,
-                   typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
-                        _NOEXCEPT;
-    _LIBCPP_INLINE_VISIBILITY
-    weak_ptr(weak_ptr const& __r) _NOEXCEPT;
-    template<class _Yp> _LIBCPP_INLINE_VISIBILITY weak_ptr(weak_ptr<_Yp> const& __r,
-                   typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
-                         _NOEXCEPT;
-
-    _LIBCPP_INLINE_VISIBILITY
-    weak_ptr(weak_ptr&& __r) _NOEXCEPT;
-    template<class _Yp> _LIBCPP_INLINE_VISIBILITY weak_ptr(weak_ptr<_Yp>&& __r,
-                   typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
-                         _NOEXCEPT;
-    ~weak_ptr();
-
-    _LIBCPP_INLINE_VISIBILITY
-    weak_ptr& operator=(weak_ptr const& __r) _NOEXCEPT;
-    template<class _Yp>
-        typename enable_if
-        <
-            is_convertible<_Yp*, element_type*>::value,
-            weak_ptr&
-        >::type
-        _LIBCPP_INLINE_VISIBILITY
-        operator=(weak_ptr<_Yp> const& __r) _NOEXCEPT;
-
-    _LIBCPP_INLINE_VISIBILITY
-    weak_ptr& operator=(weak_ptr&& __r) _NOEXCEPT;
-    template<class _Yp>
-        typename enable_if
-        <
-            is_convertible<_Yp*, element_type*>::value,
-            weak_ptr&
-        >::type
-        _LIBCPP_INLINE_VISIBILITY
-        operator=(weak_ptr<_Yp>&& __r) _NOEXCEPT;
-
-    template<class _Yp>
-        typename enable_if
-        <
-            is_convertible<_Yp*, element_type*>::value,
-            weak_ptr&
-        >::type
-        _LIBCPP_INLINE_VISIBILITY
-        operator=(shared_ptr<_Yp> const& __r) _NOEXCEPT;
-
-    _LIBCPP_INLINE_VISIBILITY
-    void swap(weak_ptr& __r) _NOEXCEPT;
-    _LIBCPP_INLINE_VISIBILITY
-    void reset() _NOEXCEPT;
-
-    _LIBCPP_INLINE_VISIBILITY
-    long use_count() const _NOEXCEPT
-        {return __cntrl_ ? __cntrl_->use_count() : 0;}
-    _LIBCPP_INLINE_VISIBILITY
-    bool expired() const _NOEXCEPT
-        {return __cntrl_ == nullptr || __cntrl_->use_count() == 0;}
-    shared_ptr<_Tp> lock() const _NOEXCEPT;
-    template<class _Up>
-        _LIBCPP_INLINE_VISIBILITY
-        bool owner_before(const shared_ptr<_Up>& __r) const _NOEXCEPT
-        {return __cntrl_ < __r.__cntrl_;}
-    template<class _Up>
-        _LIBCPP_INLINE_VISIBILITY
-        bool owner_before(const weak_ptr<_Up>& __r) const _NOEXCEPT
-        {return __cntrl_ < __r.__cntrl_;}
-
-    template <class _Up> friend class _LIBCPP_TEMPLATE_VIS weak_ptr;
-    template <class _Up> friend class _LIBCPP_TEMPLATE_VIS shared_ptr;
-};
-
-#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
-template<class _Tp>
-weak_ptr(shared_ptr<_Tp>) -> weak_ptr<_Tp>;
-#endif
-
-template<class _Tp>
-inline
-_LIBCPP_CONSTEXPR
-weak_ptr<_Tp>::weak_ptr() _NOEXCEPT
-    : __ptr_(nullptr),
-      __cntrl_(nullptr)
-{
-}
-
-template<class _Tp>
-inline
-weak_ptr<_Tp>::weak_ptr(weak_ptr const& __r) _NOEXCEPT
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_)
-{
-    if (__cntrl_)
-        __cntrl_->__add_weak();
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-weak_ptr<_Tp>::weak_ptr(shared_ptr<_Yp> const& __r,
-                        typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
-                         _NOEXCEPT
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_)
-{
-    if (__cntrl_)
-        __cntrl_->__add_weak();
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-weak_ptr<_Tp>::weak_ptr(weak_ptr<_Yp> const& __r,
-                        typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
-         _NOEXCEPT
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_)
-{
-    if (__cntrl_)
-        __cntrl_->__add_weak();
-}
-
-template<class _Tp>
-inline
-weak_ptr<_Tp>::weak_ptr(weak_ptr&& __r) _NOEXCEPT
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_)
-{
-    __r.__ptr_ = nullptr;
-    __r.__cntrl_ = nullptr;
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-weak_ptr<_Tp>::weak_ptr(weak_ptr<_Yp>&& __r,
-                        typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
-         _NOEXCEPT
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_)
-{
-    __r.__ptr_ = nullptr;
-    __r.__cntrl_ = nullptr;
-}
-
-template<class _Tp>
-weak_ptr<_Tp>::~weak_ptr()
-{
-    if (__cntrl_)
-        __cntrl_->__release_weak();
-}
-
-template<class _Tp>
-inline
-weak_ptr<_Tp>&
-weak_ptr<_Tp>::operator=(weak_ptr const& __r) _NOEXCEPT
-{
-    weak_ptr(__r).swap(*this);
-    return *this;
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-typename enable_if
-<
-    is_convertible<_Yp*, _Tp*>::value,
-    weak_ptr<_Tp>&
->::type
-weak_ptr<_Tp>::operator=(weak_ptr<_Yp> const& __r) _NOEXCEPT
-{
-    weak_ptr(__r).swap(*this);
-    return *this;
-}
-
-template<class _Tp>
-inline
-weak_ptr<_Tp>&
-weak_ptr<_Tp>::operator=(weak_ptr&& __r) _NOEXCEPT
-{
-    weak_ptr(_VSTD::move(__r)).swap(*this);
-    return *this;
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-typename enable_if
-<
-    is_convertible<_Yp*, _Tp*>::value,
-    weak_ptr<_Tp>&
->::type
-weak_ptr<_Tp>::operator=(weak_ptr<_Yp>&& __r) _NOEXCEPT
-{
-    weak_ptr(_VSTD::move(__r)).swap(*this);
-    return *this;
-}
-
-template<class _Tp>
-template<class _Yp>
-inline
-typename enable_if
-<
-    is_convertible<_Yp*, _Tp*>::value,
-    weak_ptr<_Tp>&
->::type
-weak_ptr<_Tp>::operator=(shared_ptr<_Yp> const& __r) _NOEXCEPT
-{
-    weak_ptr(__r).swap(*this);
-    return *this;
-}
-
-template<class _Tp>
-inline
-void
-weak_ptr<_Tp>::swap(weak_ptr& __r) _NOEXCEPT
-{
-    _VSTD::swap(__ptr_, __r.__ptr_);
-    _VSTD::swap(__cntrl_, __r.__cntrl_);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-void
-swap(weak_ptr<_Tp>& __x, weak_ptr<_Tp>& __y) _NOEXCEPT
-{
-    __x.swap(__y);
-}
-
-template<class _Tp>
-inline
-void
-weak_ptr<_Tp>::reset() _NOEXCEPT
-{
-    weak_ptr().swap(*this);
-}
-
-template<class _Tp>
-template<class _Yp>
-shared_ptr<_Tp>::shared_ptr(const weak_ptr<_Yp>& __r,
-                            typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type)
-    : __ptr_(__r.__ptr_),
-      __cntrl_(__r.__cntrl_ ? __r.__cntrl_->lock() : __r.__cntrl_)
-{
-    if (__cntrl_ == nullptr)
-        __throw_bad_weak_ptr();
-}
-
-template<class _Tp>
-shared_ptr<_Tp>
-weak_ptr<_Tp>::lock() const _NOEXCEPT
-{
-    shared_ptr<_Tp> __r;
-    __r.__cntrl_ = __cntrl_ ? __cntrl_->lock() : __cntrl_;
-    if (__r.__cntrl_)
-        __r.__ptr_ = __ptr_;
-    return __r;
-}
-
-#if _LIBCPP_STD_VER > 14
-template <class _Tp = void> struct owner_less;
-#else
-template <class _Tp> struct owner_less;
-#endif
-
-template <class _Tp>
-struct _LIBCPP_TEMPLATE_VIS owner_less<shared_ptr<_Tp> >
-    : binary_function<shared_ptr<_Tp>, shared_ptr<_Tp>, bool>
-{
-    typedef bool result_type;
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(shared_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(shared_ptr<_Tp> const& __x,   weak_ptr<_Tp> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(  weak_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-};
-
-template <class _Tp>
-struct _LIBCPP_TEMPLATE_VIS owner_less<weak_ptr<_Tp> >
-    : binary_function<weak_ptr<_Tp>, weak_ptr<_Tp>, bool>
-{
-    typedef bool result_type;
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(  weak_ptr<_Tp> const& __x,   weak_ptr<_Tp> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(shared_ptr<_Tp> const& __x,   weak_ptr<_Tp> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(  weak_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-};
-
-#if _LIBCPP_STD_VER > 14
-template <>
-struct _LIBCPP_TEMPLATE_VIS owner_less<void>
-{
-    template <class _Tp, class _Up>
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()( shared_ptr<_Tp> const& __x, shared_ptr<_Up> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-    template <class _Tp, class _Up>
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()( shared_ptr<_Tp> const& __x,   weak_ptr<_Up> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-    template <class _Tp, class _Up>
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(   weak_ptr<_Tp> const& __x, shared_ptr<_Up> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-    template <class _Tp, class _Up>
-    _LIBCPP_INLINE_VISIBILITY
-    bool operator()(   weak_ptr<_Tp> const& __x,   weak_ptr<_Up> const& __y) const _NOEXCEPT
-        {return __x.owner_before(__y);}
-    typedef void is_transparent;
-};
-#endif
-
-template<class _Tp>
-class _LIBCPP_TEMPLATE_VIS enable_shared_from_this
-{
-    mutable weak_ptr<_Tp> __weak_this_;
-protected:
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-    enable_shared_from_this() _NOEXCEPT {}
-    _LIBCPP_INLINE_VISIBILITY
-    enable_shared_from_this(enable_shared_from_this const&) _NOEXCEPT {}
-    _LIBCPP_INLINE_VISIBILITY
-    enable_shared_from_this& operator=(enable_shared_from_this const&) _NOEXCEPT
-        {return *this;}
-    _LIBCPP_INLINE_VISIBILITY
-    ~enable_shared_from_this() {}
-public:
-    _LIBCPP_INLINE_VISIBILITY
-    shared_ptr<_Tp> shared_from_this()
-        {return shared_ptr<_Tp>(__weak_this_);}
-    _LIBCPP_INLINE_VISIBILITY
-    shared_ptr<_Tp const> shared_from_this() const
-        {return shared_ptr<const _Tp>(__weak_this_);}
-
-#if _LIBCPP_STD_VER > 14
-    _LIBCPP_INLINE_VISIBILITY
-    weak_ptr<_Tp> weak_from_this() _NOEXCEPT
-       { return __weak_this_; }
-
-    _LIBCPP_INLINE_VISIBILITY
-    weak_ptr<const _Tp> weak_from_this() const _NOEXCEPT
-        { return __weak_this_; }
-#endif // _LIBCPP_STD_VER > 14
-
-    template <class _Up> friend class shared_ptr;
-};
-
-template <class _Tp>
-struct _LIBCPP_TEMPLATE_VIS hash<shared_ptr<_Tp> >
-{
-    typedef shared_ptr<_Tp>      argument_type;
-    typedef size_t               result_type;
-
-    _LIBCPP_INLINE_VISIBILITY
-    result_type operator()(const argument_type& __ptr) const _NOEXCEPT
-    {
-        return hash<typename shared_ptr<_Tp>::element_type*>()(__ptr.get());
-    }
-};
-
-template<class _CharT, class _Traits, class _Yp>
-inline _LIBCPP_INLINE_VISIBILITY
-basic_ostream<_CharT, _Traits>&
-operator<<(basic_ostream<_CharT, _Traits>& __os, shared_ptr<_Yp> const& __p);
-
-
-#if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
-
-class _LIBCPP_TYPE_VIS __sp_mut
-{
-    void* __lx;
-public:
-    void lock() _NOEXCEPT;
-    void unlock() _NOEXCEPT;
-
-private:
-    _LIBCPP_CONSTEXPR __sp_mut(void*) _NOEXCEPT;
-    __sp_mut(const __sp_mut&);
-    __sp_mut& operator=(const __sp_mut&);
-
-    friend _LIBCPP_FUNC_VIS __sp_mut& __get_sp_mut(const void*);
-};
-
-_LIBCPP_FUNC_VIS _LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-__sp_mut& __get_sp_mut(const void*);
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-atomic_is_lock_free(const shared_ptr<_Tp>*)
-{
-    return false;
-}
-
-template <class _Tp>
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-shared_ptr<_Tp>
-atomic_load(const shared_ptr<_Tp>* __p)
-{
-    __sp_mut& __m = __get_sp_mut(__p);
-    __m.lock();
-    shared_ptr<_Tp> __q = *__p;
-    __m.unlock();
-    return __q;
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-shared_ptr<_Tp>
-atomic_load_explicit(const shared_ptr<_Tp>* __p, memory_order)
-{
-    return atomic_load(__p);
-}
-
-template <class _Tp>
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-void
-atomic_store(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r)
-{
-    __sp_mut& __m = __get_sp_mut(__p);
-    __m.lock();
-    __p->swap(__r);
-    __m.unlock();
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-void
-atomic_store_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order)
-{
-    atomic_store(__p, __r);
-}
-
-template <class _Tp>
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-shared_ptr<_Tp>
-atomic_exchange(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r)
-{
-    __sp_mut& __m = __get_sp_mut(__p);
-    __m.lock();
-    __p->swap(__r);
-    __m.unlock();
-    return __r;
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-shared_ptr<_Tp>
-atomic_exchange_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order)
-{
-    return atomic_exchange(__p, __r);
-}
-
-template <class _Tp>
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-bool
-atomic_compare_exchange_strong(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w)
-{
-    shared_ptr<_Tp> __temp;
-    __sp_mut& __m = __get_sp_mut(__p);
-    __m.lock();
-    if (__p->__owner_equivalent(*__v))
-    {
-        _VSTD::swap(__temp, *__p);
-        *__p = __w;
-        __m.unlock();
-        return true;
-    }
-    _VSTD::swap(__temp, *__v);
-    *__v = *__p;
-    __m.unlock();
-    return false;
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-bool
-atomic_compare_exchange_weak(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w)
-{
-    return atomic_compare_exchange_strong(__p, __v, __w);
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-bool
-atomic_compare_exchange_strong_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v,
-                                        shared_ptr<_Tp> __w, memory_order, memory_order)
-{
-    return atomic_compare_exchange_strong(__p, __v, __w);
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
-bool
-atomic_compare_exchange_weak_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v,
-                                      shared_ptr<_Tp> __w, memory_order, memory_order)
-{
-    return atomic_compare_exchange_weak(__p, __v, __w);
-}
-
-#endif  // !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
-
-//enum class
-#if defined(_LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE)
-# ifndef _LIBCPP_CXX03_LANG
-enum class pointer_safety : unsigned char {
-  relaxed,
-  preferred,
-  strict
-};
-# endif
-#else
-struct _LIBCPP_TYPE_VIS pointer_safety
-{
-    enum __lx
-    {
-        relaxed,
-        preferred,
-        strict
-    };
-
-    __lx __v_;
-
-    _LIBCPP_INLINE_VISIBILITY
-    pointer_safety() : __v_() {}
-
-    _LIBCPP_INLINE_VISIBILITY
-    pointer_safety(__lx __v) : __v_(__v) {}
-    _LIBCPP_INLINE_VISIBILITY
-    operator int() const {return __v_;}
-};
-#endif
-
-#if !defined(_LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE) && \
-    defined(_LIBCPP_BUILDING_LIBRARY)
-_LIBCPP_FUNC_VIS pointer_safety get_pointer_safety() _NOEXCEPT;
-#else
-// This function is only offered in C++03 under ABI v1.
-# if !defined(_LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE) || !defined(_LIBCPP_CXX03_LANG)
-inline _LIBCPP_INLINE_VISIBILITY
-pointer_safety get_pointer_safety() _NOEXCEPT {
-  return pointer_safety::relaxed;
-}
-# endif
-#endif
-
-
-_LIBCPP_FUNC_VIS void declare_reachable(void* __p);
-_LIBCPP_FUNC_VIS void declare_no_pointers(char* __p, size_t __n);
-_LIBCPP_FUNC_VIS void undeclare_no_pointers(char* __p, size_t __n);
-_LIBCPP_FUNC_VIS void* __undeclare_reachable(void* __p);
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-_Tp*
-undeclare_reachable(_Tp* __p)
-{
-    return static_cast<_Tp*>(__undeclare_reachable(__p));
-}
-
 _LIBCPP_FUNC_VIS void* align(size_t __align, size_t __sz, void*& __ptr, size_t& __space);
 
 // --- Helper for container swap --
@@ -4193,7 +868,7 @@ void __swap_allocator(_Alloc & __a1, _Alloc & __a2)
 #endif
 {
     _VSTD::__swap_allocator(__a1, __a2,
-      integral_constant<bool, _VSTD::allocator_traits<_Alloc>::propagate_on_container_swap::value>());
+      integral_constant<bool, allocator_traits<_Alloc>::propagate_on_container_swap::value>());
 }
 
 template <typename _Alloc, typename _Traits=allocator_traits<_Alloc> >
@@ -4233,7 +908,7 @@ struct __is_allocator : false_type {};
 template<typename _Alloc>
 struct __is_allocator<_Alloc,
        typename __void_t<typename _Alloc::value_type>::type,
-       typename __void_t<decltype(_VSTD::declval<_Alloc&>().allocate(size_t(0)))>::type
+       typename __void_t<decltype(declval<_Alloc&>().allocate(size_t(0)))>::type
      >
    : true_type {};
 
@@ -4291,4 +966,4 @@ _LIBCPP_POP_MACROS
 #   include <__pstl_memory>
 #endif
 
-#endif  // _LIBCPP_MEMORY
+#endif // _LIBCPP_MEMORY
lib/libcxx/include/module.modulemap
@@ -217,6 +217,102 @@ module std [system] {
     header "algorithm"
     export initializer_list
     export *
+
+    module __algorithm {
+      module adjacent_find            { private header "__algorithm/adjacent_find.h" }
+      module all_of                   { private header "__algorithm/all_of.h" }
+      module any_of                   { private header "__algorithm/any_of.h" }
+      module binary_search            { private header "__algorithm/binary_search.h" }
+      module clamp                    { private header "__algorithm/clamp.h" }
+      module comp                     { private header "__algorithm/comp.h" }
+      module comp_ref_type            { private header "__algorithm/comp_ref_type.h" }
+      module copy                     { private header "__algorithm/copy.h" }
+      module copy_backward            { private header "__algorithm/copy_backward.h" }
+      module copy_if                  { private header "__algorithm/copy_if.h" }
+      module copy_n                   { private header "__algorithm/copy_n.h" }
+      module count                    { private header "__algorithm/count.h" }
+      module count_if                 { private header "__algorithm/count_if.h" }
+      module equal                    { private header "__algorithm/equal.h" }
+      module equal_range              { private header "__algorithm/equal_range.h" }
+      module fill                     { private header "__algorithm/fill.h" }
+      module fill_n                   { private header "__algorithm/fill_n.h" }
+      module find                     { private header "__algorithm/find.h" }
+      module find_end                 { private header "__algorithm/find_end.h" }
+      module find_first_of            { private header "__algorithm/find_first_of.h" }
+      module find_if                  { private header "__algorithm/find_if.h" }
+      module find_if_not              { private header "__algorithm/find_if_not.h" }
+      module for_each                 { private header "__algorithm/for_each.h" }
+      module for_each_n               { private header "__algorithm/for_each_n.h" }
+      module generate                 { private header "__algorithm/generate.h" }
+      module generate_n               { private header "__algorithm/generate_n.h" }
+      module half_positive            { private header "__algorithm/half_positive.h" }
+      module includes                 { private header "__algorithm/includes.h" }
+      module inplace_merge            { private header "__algorithm/inplace_merge.h" }
+      module is_heap                  { private header "__algorithm/is_heap.h" }
+      module is_heap_until            { private header "__algorithm/is_heap_until.h" }
+      module is_partitioned           { private header "__algorithm/is_partitioned.h" }
+      module is_permutation           { private header "__algorithm/is_permutation.h" }
+      module is_sorted                { private header "__algorithm/is_sorted.h" }
+      module is_sorted_until          { private header "__algorithm/is_sorted_until.h" }
+      module iter_swap                { private header "__algorithm/iter_swap.h" }
+      module lexicographical_compare  { private header "__algorithm/lexicographical_compare.h" }
+      module lower_bound              { private header "__algorithm/lower_bound.h" }
+      module make_heap                { private header "__algorithm/make_heap.h" }
+      module max                      { private header "__algorithm/max.h" }
+      module max_element              { private header "__algorithm/max_element.h" }
+      module merge                    { private header "__algorithm/merge.h" }
+      module min                      { private header "__algorithm/min.h" }
+      module min_element              { private header "__algorithm/min_element.h" }
+      module minmax                   { private header "__algorithm/minmax.h" }
+      module minmax_element           { private header "__algorithm/minmax_element.h" }
+      module mismatch                 { private header "__algorithm/mismatch.h" }
+      module move                     { private header "__algorithm/move.h" }
+      module move_backward            { private header "__algorithm/move_backward.h" }
+      module next_permutation         { private header "__algorithm/next_permutation.h" }
+      module none_of                  { private header "__algorithm/none_of.h" }
+      module nth_element              { private header "__algorithm/nth_element.h" }
+      module partial_sort             { private header "__algorithm/partial_sort.h" }
+      module partial_sort_copy        { private header "__algorithm/partial_sort_copy.h" }
+      module partition                { private header "__algorithm/partition.h" }
+      module partition_copy           { private header "__algorithm/partition_copy.h" }
+      module partition_point          { private header "__algorithm/partition_point.h" }
+      module pop_heap                 { private header "__algorithm/pop_heap.h" }
+      module prev_permutation         { private header "__algorithm/prev_permutation.h" }
+      module push_heap                { private header "__algorithm/push_heap.h" }
+      module remove                   { private header "__algorithm/remove.h" }
+      module remove_copy              { private header "__algorithm/remove_copy.h" }
+      module remove_copy_if           { private header "__algorithm/remove_copy_if.h" }
+      module remove_if                { private header "__algorithm/remove_if.h" }
+      module replace                  { private header "__algorithm/replace.h" }
+      module replace_copy             { private header "__algorithm/replace_copy.h" }
+      module replace_copy_if          { private header "__algorithm/replace_copy_if.h" }
+      module replace_if               { private header "__algorithm/replace_if.h" }
+      module reverse                  { private header "__algorithm/reverse.h" }
+      module reverse_copy             { private header "__algorithm/reverse_copy.h" }
+      module rotate                   { private header "__algorithm/rotate.h" }
+      module rotate_copy              { private header "__algorithm/rotate_copy.h" }
+      module sample                   { private header "__algorithm/sample.h" }
+      module search                   { private header "__algorithm/search.h" }
+      module search_n                 { private header "__algorithm/search_n.h" }
+      module set_difference           { private header "__algorithm/set_difference.h" }
+      module set_intersection         { private header "__algorithm/set_intersection.h" }
+      module set_symmetric_difference { private header "__algorithm/set_symmetric_difference.h" }
+      module set_union                { private header "__algorithm/set_union.h" }
+      module shift_left               { private header "__algorithm/shift_left.h" }
+      module shift_right              { private header "__algorithm/shift_right.h" }
+      module shuffle                  { private header "__algorithm/shuffle.h" }
+      module sift_down                { private header "__algorithm/sift_down.h" }
+      module sort                     { private header "__algorithm/sort.h" }
+      module sort_heap                { private header "__algorithm/sort_heap.h" }
+      module stable_partition         { private header "__algorithm/stable_partition.h" }
+      module stable_sort              { private header "__algorithm/stable_sort.h" }
+      module swap_ranges              { private header "__algorithm/swap_ranges.h" }
+      module transform                { private header "__algorithm/transform.h" }
+      module unique                   { private header "__algorithm/unique.h" }
+      module unique_copy              { private header "__algorithm/unique_copy.h" }
+      module unwrap_iter              { private header "__algorithm/unwrap_iter.h" }
+      module upper_bound              { private header "__algorithm/upper_bound.h" }
+    }
   }
   module any {
     header "any"
@@ -292,6 +388,15 @@ module std [system] {
     header "filesystem"
     export *
   }
+  module format {
+    header "format"
+    export *
+
+    module __format {
+      module format_error         { private header "__format/format_error.h"         }
+      module format_parse_context { private header "__format/format_parse_context.h" }
+    }
+  }
   module forward_list {
     header "forward_list"
     export initializer_list
@@ -304,6 +409,34 @@ module std [system] {
   module functional {
     header "functional"
     export *
+
+    module __functional {
+      module binary_function            { private header "__functional/binary_function.h" }
+      module binary_negate              { private header "__functional/binary_negate.h" }
+      module bind                       { private header "__functional/bind.h" }
+      module bind_front                 { private header "__functional/bind_front.h" }
+      module binder1st                  { private header "__functional/binder1st.h" }
+      module binder2nd                  { private header "__functional/binder2nd.h" }
+      module default_searcher           { private header "__functional/default_searcher.h" }
+      module function                   { private header "__functional/function.h" }
+      module hash                       { private header "__functional/hash.h" }
+      module identity                   { private header "__functional/identity.h" }
+      module is_transparent             { private header "__functional/is_transparent.h" }
+      module invoke                     { private header "__functional/invoke.h" }
+      module mem_fn                     { private header "__functional/mem_fn.h"  }
+      module mem_fun_ref                { private header "__functional/mem_fun_ref.h"  }
+      module not_fn                     { private header "__functional/not_fn.h" }
+      module operations                 { private header "__functional/operations.h" }
+      module perfect_forward            { private header "__functional/perfect_forward.h" }
+      module pointer_to_binary_function { private header "__functional/pointer_to_binary_function.h" }
+      module pointer_to_unary_function  { private header "__functional/pointer_to_unary_function.h" }
+      module ranges_operations          { private header "__functional/ranges_operations.h" }
+      module reference_wrapper          { private header "__functional/reference_wrapper.h" }
+      module unary_function             { private header "__functional/unary_function.h" }
+      module unary_negate               { private header "__functional/unary_negate.h" }
+      module unwrap_ref                 { private header "__functional/unwrap_ref.h" }
+      module weak_result_type           { private header "__functional/weak_result_type.h" }
+    }
   }
   module future {
     header "future"
@@ -342,6 +475,49 @@ module std [system] {
   module iterator {
     header "iterator"
     export *
+
+    module __iterator {
+      module access                { private header "__iterator/access.h" }
+      module advance               {
+        private header "__iterator/advance.h"
+        export __function_like
+      }
+      module back_insert_iterator  { private header "__iterator/back_insert_iterator.h" }
+      module common_iterator       { private header "__iterator/common_iterator.h" }
+      module concepts              { private header "__iterator/concepts.h" }
+      module counted_iterator      { private header "__iterator/counted_iterator.h" }
+      module data                  { private header "__iterator/data.h" }
+      module default_sentinel      { private header "__iterator/default_sentinel.h" }
+      module distance              { private header "__iterator/distance.h" }
+      module empty                 { private header "__iterator/empty.h" }
+      module erase_if_container    { private header "__iterator/erase_if_container.h" }
+      module front_insert_iterator { private header "__iterator/front_insert_iterator.h" }
+      module incrementable_traits  { private header "__iterator/incrementable_traits.h" }
+      module insert_iterator       { private header "__iterator/insert_iterator.h" }
+      module istream_iterator      { private header "__iterator/istream_iterator.h" }
+      module istreambuf_iterator   { private header "__iterator/istreambuf_iterator.h" }
+      module iter_move             { private header "__iterator/iter_move.h" }
+      module iter_swap             { private header "__iterator/iter_swap.h" }
+      module iterator              { private header "__iterator/iterator.h" }
+      module iterator_traits       { private header "__iterator/iterator_traits.h" }
+      module move_iterator         { private header "__iterator/move_iterator.h" }
+      module next                  {
+        private header "__iterator/next.h"
+        export __function_like
+      }
+      module ostream_iterator      { private header "__iterator/ostream_iterator.h" }
+      module ostreambuf_iterator   { private header "__iterator/ostreambuf_iterator.h" }
+      module prev                  {
+        private header "__iterator/prev.h"
+        export __function_like
+      }
+      module projected             { private header "__iterator/projected.h" }
+      module readable_traits       { private header "__iterator/readable_traits.h" }
+      module reverse_access        { private header "__iterator/reverse_access.h" }
+      module reverse_iterator      { private header "__iterator/reverse_iterator.h" }
+      module size                  { private header "__iterator/size.h" }
+      module wrap_iter             { private header "__iterator/wrap_iter.h" }
+    }
   }
   module latch {
     requires cplusplus14
@@ -369,6 +545,25 @@ module std [system] {
   module memory {
     header "memory"
     export *
+
+    module __memory {
+      module addressof                { private header "__memory/addressof.h"                }
+      module allocation_guard         { private header "__memory/allocation_guard.h"         }
+      module allocator                { private header "__memory/allocator.h"                }
+      module allocator_arg_t          { private header "__memory/allocator_arg_t.h"          }
+      module allocator_traits         { private header "__memory/allocator_traits.h"         }
+      module auto_ptr                 { private header "__memory/auto_ptr.h"                 }
+      module compressed_pair          { private header "__memory/compressed_pair.h"          }
+      module construct_at             { private header "__memory/construct_at.h"             }
+      module pointer_safety           { private header "__memory/pointer_safety.h"           }
+      module pointer_traits           { private header "__memory/pointer_traits.h"           }
+      module raw_storage_iterator     { private header "__memory/raw_storage_iterator.h"     }
+      module shared_ptr               { private header "__memory/shared_ptr.h"               }
+      module temporary_buffer         { private header "__memory/temporary_buffer.h"         }
+      module uninitialized_algorithms { private header "__memory/uninitialized_algorithms.h" }
+      module unique_ptr               { private header "__memory/unique_ptr.h"               }
+      module uses_allocator           { private header "__memory/uses_allocator.h"           }
+    }
   }
   module mutex {
     header "mutex"
@@ -404,6 +599,38 @@ module std [system] {
     header "random"
     export initializer_list
     export *
+
+    module __random {
+      module uniform_int_distribution { private header "__random/uniform_int_distribution.h" }
+    }
+  }
+  module ranges {
+    header "ranges"
+    export compare
+    export initializer_list
+    export iterator
+    export *
+
+    module __ranges {
+      module access                 { private header "__ranges/access.h"                }
+      module all                    { private header "__ranges/all.h"                   }
+      module common_view            { private header "__ranges/common_view.h"           }
+      module concepts               { private header "__ranges/concepts.h"              }
+      module copyable_box           { private header "__ranges/copyable_box.h"          }
+      module dangling               { private header "__ranges/dangling.h"              }
+      module data                   { private header "__ranges/data.h"                  }
+      module drop_view              { private header "__ranges/drop_view.h"             }
+      module empty                  { private header "__ranges/empty.h"                 }
+      module empty_view             { private header "__ranges/empty_view.h"            }
+      module enable_borrowed_range  { private header "__ranges/enable_borrowed_range.h" }
+      module enable_view            { private header "__ranges/enable_view.h"           }
+      module non_propagating_cache  { private header "__ranges/non_propagating_cache.h" }
+      module ref_view               { private header "__ranges/ref_view.h"              }
+      module size                   { private header "__ranges/size.h"                  }
+      module subrange               { private header "__ranges/subrange.h"              }
+      module transform_view         { private header "__ranges/transform_view.h"        }
+      module view_interface         { private header "__ranges/view_interface.h"        }
+    }
   }
   module ratio {
     header "ratio"
@@ -428,6 +655,15 @@ module std [system] {
     export initializer_list
     export *
   }
+  module shared_mutex {
+    header "shared_mutex"
+    export version
+  }
+  module span {
+    header "span"
+    export ranges.__ranges.enable_borrowed_range
+    export version
+  }
   module sstream {
     header "sstream"
     // FIXME: should re-export istream, ostream, ios, streambuf, string?
@@ -477,6 +713,7 @@ module std [system] {
   }
   module type_traits {
     header "type_traits"
+    export functional.__functional.unwrap_ref
     export *
   }
   module typeindex {
@@ -501,6 +738,23 @@ module std [system] {
     header "utility"
     export initializer_list
     export *
+
+    module __utility {
+      module __decay_copy        { private header "__utility/__decay_copy.h"        }
+      module as_const            { private header "__utility/as_const.h"            }
+      module cmp                 { private header "__utility/cmp.h"                 }
+      module declval             { private header "__utility/declval.h"             }
+      module exchange            { private header "__utility/exchange.h"            }
+      module forward             { private header "__utility/forward.h"             }
+      module in_place            { private header "__utility/in_place.h"            }
+      module integer_sequence    { private header "__utility/integer_sequence.h"    }
+      module move                { private header "__utility/move.h"                }
+      module pair                { private header "__utility/pair.h"                }
+      module piecewise_construct { private header "__utility/piecewise_construct.h" }
+      module rel_ops             { private header "__utility/rel_ops.h"             }
+      module swap                { private header "__utility/swap.h"                }
+      module to_underlying       { private header "__utility/to_underlying.h"       }
+    }
   }
   module valarray {
     header "valarray"
@@ -510,6 +764,10 @@ module std [system] {
   module variant {
     header "variant"
     export *
+
+    module __variant {
+      module monostate { private header "__variant/monostate.h" }
+    }
   }
   module vector {
     header "vector"
@@ -521,23 +779,26 @@ module std [system] {
     export *
   }
 
+  // __config not modularised due to a bug in Clang
   // FIXME: These should be private.
-  module __bits { header "__bits" export * }
-  module __bit_reference { header "__bit_reference" export * }
-  module __debug { header "__debug" export * }
-  module __errc { header "__errc" export * }
-  module __functional_base { header "__functional_base" export * }
-  module __hash_table { header "__hash_table" export * }
-  module __locale { header "__locale" export * }
-  module __mutex_base { header "__mutex_base" export * }
-  module __split_buffer { header "__split_buffer" export * }
-  module __sso_allocator { header "__sso_allocator" export * }
-  module __std_stream { header "__std_stream" export * }
-  module __string { header "__string" export * }
-  module __tree { header "__tree" export * }
-  module __tuple { header "__tuple" export * }
-  module __undef_macros { header "__undef_macros" export * }
-  module __node_handle { header "__node_handle" export * }
+  module __availability      { private header "__availability"      export * }
+  module __bit_reference     { private header "__bit_reference"     export * }
+  module __bits              { private header "__bits"              export * }
+  module __debug             { header "__debug"             export * }
+  module __errc              { private header "__errc"              export * }
+  module __function_like     { private header "__function_like.h"   export * }
+  module __hash_table        { header "__hash_table"        export * }
+  module __locale            { private header "__locale"            export * }
+  module __mutex_base        { private header "__mutex_base"        export * }
+  module __node_handle       { private header "__node_handle"       export * }
+  module __nullptr           { header "__nullptr"           export * }
+  module __split_buffer      { private header "__split_buffer"      export * }
+  module __std_stream        { private header "__std_stream"        export * }
+  module __string            { private header "__string"            export * }
+  module __threading_support { header "__threading_support" export * }
+  module __tree              { header "__tree"              export * }
+  module __tuple             { private header "__tuple"             export * }
+  module __undef_macros      { header "__undef_macros"      export * }
 
   module experimental {
     requires cplusplus11
lib/libcxx/include/mutex
@@ -188,14 +188,15 @@ template<class Callable, class ...Args>
 
 #include <__config>
 #include <__mutex_base>
+#include <__threading_support>
+#include <__utility/forward.h>
 #include <cstdint>
 #include <functional>
 #include <memory>
 #ifndef _LIBCPP_CXX03_LANG
-#include <tuple>
+# include <tuple>
 #endif
 #include <version>
-#include <__threading_support>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -365,7 +366,7 @@ try_lock(_L0& __l0, _L1& __l1, _L2& __l2, _L3&... __l3)
     return __r;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _L0, class _L1>
 void
@@ -469,7 +470,7 @@ void __unlock(_L0& __l0, _L1& __l1, _L2& __l2, _L3&... __l3) {
     _VSTD::__unlock(__l2, __l3...);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 #if _LIBCPP_STD_VER > 14
 template <class ..._Mutexes>
@@ -568,7 +569,7 @@ template<class _Callable>
 _LIBCPP_INLINE_VISIBILITY
 void call_once(once_flag&, const _Callable&);
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 struct _LIBCPP_TEMPLATE_VIS once_flag
 {
@@ -601,7 +602,7 @@ private:
     template<class _Callable>
     friend
     void call_once(once_flag&, const _Callable&);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 };
 
 #ifndef _LIBCPP_CXX03_LANG
@@ -702,10 +703,10 @@ call_once(once_flag& __flag, const _Callable& __func)
     }
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_MUTEX
+#endif // _LIBCPP_MUTEX
lib/libcxx/include/new
@@ -86,8 +86,8 @@ void  operator delete[](void* ptr, void*) noexcept;
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <cstddef>
 #include <cstdlib>
 #include <exception>
@@ -314,7 +314,7 @@ void* __libcpp_aligned_alloc(std::size_t __alignment, std::size_t __size) {
   return ::_aligned_malloc(__size, __alignment);
 #else
   void* __result = nullptr;
-  ::posix_memalign(&__result, __alignment, __size);
+  (void)::posix_memalign(&__result, __alignment, __size);
   // If posix_memalign fails, __result is unmodified so we still return `nullptr`.
   return __result;
 #endif
@@ -356,4 +356,4 @@ constexpr _Tp* launder(_Tp* __p) noexcept
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_NEW
+#endif // _LIBCPP_NEW
lib/libcxx/include/numbers
@@ -59,12 +59,12 @@ namespace std::numbers {
 */
 
 #include <__config>
-
-#if _LIBCPP_STD_VER > 17 && defined(__cpp_concepts) && __cpp_concepts >= 201811L
-
+#include <concepts>
 #include <type_traits>
 #include <version>
 
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CONCEPTS)
+
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
@@ -99,22 +99,19 @@ template <class T> inline constexpr T inv_sqrt3_v =  __illformed<T>{};
 template <class T> inline constexpr T egamma_v =     __illformed<T>{};
 template <class T> inline constexpr T phi_v =        __illformed<T>{};
 
-template <class T>
-concept __floating_point = is_floating_point_v<T>;
-
-template <__floating_point T> inline constexpr T e_v<T>          = 2.718281828459045235360287471352662;
-template <__floating_point T> inline constexpr T log2e_v<T>      = 1.442695040888963407359924681001892;
-template <__floating_point T> inline constexpr T log10e_v<T>     = 0.434294481903251827651128918916605;
-template <__floating_point T> inline constexpr T pi_v<T>         = 3.141592653589793238462643383279502;
-template <__floating_point T> inline constexpr T inv_pi_v<T>     = 0.318309886183790671537767526745028;
-template <__floating_point T> inline constexpr T inv_sqrtpi_v<T> = 0.564189583547756286948079451560772;
-template <__floating_point T> inline constexpr T ln2_v<T>        = 0.693147180559945309417232121458176;
-template <__floating_point T> inline constexpr T ln10_v<T>       = 2.302585092994045684017991454684364;
-template <__floating_point T> inline constexpr T sqrt2_v<T>      = 1.414213562373095048801688724209698;
-template <__floating_point T> inline constexpr T sqrt3_v<T>      = 1.732050807568877293527446341505872;
-template <__floating_point T> inline constexpr T inv_sqrt3_v<T>  = 0.577350269189625764509148780501957;
-template <__floating_point T> inline constexpr T egamma_v<T>     = 0.577215664901532860606512090082402;
-template <__floating_point T> inline constexpr T phi_v<T>        = 1.618033988749894848204586834365638;
+template <floating_point T> inline constexpr T e_v<T>          = 2.718281828459045235360287471352662;
+template <floating_point T> inline constexpr T log2e_v<T>      = 1.442695040888963407359924681001892;
+template <floating_point T> inline constexpr T log10e_v<T>     = 0.434294481903251827651128918916605;
+template <floating_point T> inline constexpr T pi_v<T>         = 3.141592653589793238462643383279502;
+template <floating_point T> inline constexpr T inv_pi_v<T>     = 0.318309886183790671537767526745028;
+template <floating_point T> inline constexpr T inv_sqrtpi_v<T> = 0.564189583547756286948079451560772;
+template <floating_point T> inline constexpr T ln2_v<T>        = 0.693147180559945309417232121458176;
+template <floating_point T> inline constexpr T ln10_v<T>       = 2.302585092994045684017991454684364;
+template <floating_point T> inline constexpr T sqrt2_v<T>      = 1.414213562373095048801688724209698;
+template <floating_point T> inline constexpr T sqrt3_v<T>      = 1.732050807568877293527446341505872;
+template <floating_point T> inline constexpr T inv_sqrt3_v<T>  = 0.577350269189625764509148780501957;
+template <floating_point T> inline constexpr T egamma_v<T>     = 0.577215664901532860606512090082402;
+template <floating_point T> inline constexpr T phi_v<T>        = 1.618033988749894848204586834365638;
 
 inline constexpr double e          = e_v<double>;
 inline constexpr double log2e      = log2e_v<double>;
@@ -136,6 +133,6 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif //_LIBCPP_STD_VER > 17 && defined(__cpp_concepts) && __cpp_concepts >= 201811L
+#endif //_LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CONCEPTS)
 
 #endif // _LIBCPP_NUMBERS
lib/libcxx/include/numeric
@@ -145,10 +145,11 @@ template<class T>
 */
 
 #include <__config>
+#include <__debug>
+#include <cmath> // for isnormal
+#include <functional>
 #include <iterator>
 #include <limits> // for numeric_limits
-#include <functional>
-#include <cmath> // for isnormal
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -613,8 +614,8 @@ _LIBCPP_INLINE_VISIBILITY constexpr
 enable_if_t<is_floating_point_v<_Fp>, _Fp>
 midpoint(_Fp __a, _Fp __b) noexcept
 {
-	constexpr _Fp __lo = numeric_limits<_Fp>::min()*2;
-	constexpr _Fp __hi = numeric_limits<_Fp>::max()/2;
+    constexpr _Fp __lo = numeric_limits<_Fp>::min()*2;
+    constexpr _Fp __hi = numeric_limits<_Fp>::max()/2;
     return __fp_abs(__a) <= __hi && __fp_abs(__b) <= __hi ?  // typical case: overflow is impossible
       (__a + __b)/2 :                                        // always correctly rounded
       __fp_abs(__a) < __lo ? __a + __b/2 :                   // not safe to halve a
@@ -632,4 +633,4 @@ _LIBCPP_POP_MACROS
 #   include <__pstl_numeric>
 #endif
 
-#endif  // _LIBCPP_NUMERIC
+#endif // _LIBCPP_NUMERIC
lib/libcxx/include/optional
@@ -69,7 +69,7 @@ namespace std {
   template <class T, class U> constexpr bool operator>=(const T&, const optional<U>&);
 
   // 23.6.9, specialized algorithms
-  template <class T> void swap(optional<T>&, optional<T>&) noexcept(see below );
+  template <class T> void swap(optional<T>&, optional<T>&) noexcept(see below ); // constexpr in C++20
   template <class T> constexpr optional<see below > make_optional(T&&);
   template <class T, class... Args>
     constexpr optional<T> make_optional(Args&&... args);
@@ -95,26 +95,26 @@ namespace std {
     template <class U = T>
       constexpr EXPLICIT optional(U &&);
     template <class U>
-      constexpr EXPLICIT optional(const optional<U> &);
+      EXPLICIT optional(const optional<U> &);   // constexpr in C++20
     template <class U>
-      constexpr EXPLICIT optional(optional<U> &&);
+      EXPLICIT optional(optional<U> &&);        // constexpr in C++20
 
     // 23.6.3.2, destructor
-    ~optional();
+    ~optional(); // constexpr in C++20
 
     // 23.6.3.3, assignment
-    optional &operator=(nullopt_t) noexcept;
-    optional &operator=(const optional &);                // constexpr in C++20
-    optional &operator=(optional &&) noexcept(see below); // constexpr in C++20
-    template <class U = T> optional &operator=(U &&);
-    template <class U> optional &operator=(const optional<U> &);
-    template <class U> optional &operator=(optional<U> &&);
-    template <class... Args> T& emplace(Args &&...);
+    optional &operator=(nullopt_t) noexcept;                     // constexpr in C++20
+    optional &operator=(const optional &);                       // constexpr in C++20
+    optional &operator=(optional &&) noexcept(see below);        // constexpr in C++20
+    template <class U = T> optional &operator=(U &&);            // constexpr in C++20
+    template <class U> optional &operator=(const optional<U> &); // constexpr in C++20
+    template <class U> optional &operator=(optional<U> &&);      // constexpr in C++20
+    template <class... Args> T& emplace(Args &&...);             // constexpr in C++20
     template <class U, class... Args>
-      T& emplace(initializer_list<U>, Args &&...);
+      T& emplace(initializer_list<U>, Args &&...);               // constexpr in C++20
 
     // 23.6.3.4, swap
-    void swap(optional &) noexcept(see below );
+    void swap(optional &) noexcept(see below ); // constexpr in C++20
 
     // 23.6.3.5, observers
     constexpr T const *operator->() const;
@@ -133,7 +133,7 @@ namespace std {
     template <class U> constexpr T value_or(U &&) &&;
 
     // 23.6.3.6, modifiers
-    void reset() noexcept;
+    void reset() noexcept; // constexpr in C++20
 
   private:
     T *val; // exposition only
@@ -146,10 +146,11 @@ template<class T>
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <__debug>
 #include <__functional_base>
+#include <compare>
 #include <functional>
 #include <initializer_list>
 #include <new>
@@ -220,7 +221,7 @@ struct __optional_destruct_base<_Tp, false>
     bool __engaged_;
 
     _LIBCPP_INLINE_VISIBILITY
-    ~__optional_destruct_base()
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 ~__optional_destruct_base()
     {
         if (__engaged_)
             __val_.~value_type();
@@ -238,7 +239,7 @@ struct __optional_destruct_base<_Tp, false>
            __engaged_(true) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    void reset() noexcept
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void reset() noexcept
     {
         if (__engaged_)
         {
@@ -273,7 +274,7 @@ struct __optional_destruct_base<_Tp, true>
            __engaged_(true) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    void reset() noexcept
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void reset() noexcept
     {
         if (__engaged_)
         {
@@ -318,16 +319,20 @@ struct __optional_storage_base : __optional_destruct_base<_Tp>
 
     template <class... _Args>
     _LIBCPP_INLINE_VISIBILITY
-    void __construct(_Args&&... __args)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void __construct(_Args&&... __args)
     {
         _LIBCPP_ASSERT(!has_value(), "__construct called for engaged __optional_storage");
+#if _LIBCPP_STD_VER > 17
+        _VSTD::construct_at(_VSTD::addressof(this->__val_), _VSTD::forward<_Args>(__args)...);
+#else
         ::new ((void*)_VSTD::addressof(this->__val_)) value_type(_VSTD::forward<_Args>(__args)...);
+#endif
         this->__engaged_ = true;
     }
 
     template <class _That>
     _LIBCPP_INLINE_VISIBILITY
-    void __construct_from(_That&& __opt)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void __construct_from(_That&& __opt)
     {
         if (__opt.has_value())
             __construct(_VSTD::forward<_That>(__opt).__get());
@@ -335,7 +340,7 @@ struct __optional_storage_base : __optional_destruct_base<_Tp>
 
     template <class _That>
     _LIBCPP_INLINE_VISIBILITY
-    void __assign_from(_That&& __opt)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void __assign_from(_That&& __opt)
     {
         if (this->__engaged_ == __opt.has_value())
         {
@@ -393,7 +398,7 @@ struct __optional_storage_base<_Tp, true>
     }
 
     _LIBCPP_INLINE_VISIBILITY
-    void reset() noexcept { __value_ = nullptr; }
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void reset() noexcept { __value_ = nullptr; }
 
     _LIBCPP_INLINE_VISIBILITY
     constexpr bool has_value() const noexcept
@@ -409,7 +414,7 @@ struct __optional_storage_base<_Tp, true>
 
     template <class _UArg>
     _LIBCPP_INLINE_VISIBILITY
-    void __construct(_UArg&& __val)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void __construct(_UArg&& __val)
     {
         _LIBCPP_ASSERT(!has_value(), "__construct called for engaged __optional_storage");
         static_assert(__can_bind_reference<_UArg>(),
@@ -420,7 +425,7 @@ struct __optional_storage_base<_Tp, true>
 
     template <class _That>
     _LIBCPP_INLINE_VISIBILITY
-    void __construct_from(_That&& __opt)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void __construct_from(_That&& __opt)
     {
         if (__opt.has_value())
             __construct(_VSTD::forward<_That>(__opt).__get());
@@ -428,7 +433,7 @@ struct __optional_storage_base<_Tp, true>
 
     template <class _That>
     _LIBCPP_INLINE_VISIBILITY
-    void __assign_from(_That&& __opt)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void __assign_from(_That&& __opt)
     {
         if (has_value() == __opt.has_value())
         {
@@ -460,7 +465,7 @@ struct __optional_copy_base<_Tp, false> : __optional_storage_base<_Tp>
     __optional_copy_base() = default;
 
     _LIBCPP_INLINE_VISIBILITY
-    __optional_copy_base(const __optional_copy_base& __opt)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 __optional_copy_base(const __optional_copy_base& __opt)
     {
         this->__construct_from(__opt);
     }
@@ -491,7 +496,7 @@ struct __optional_move_base<_Tp, false> : __optional_copy_base<_Tp>
     __optional_move_base(const __optional_move_base&) = default;
 
     _LIBCPP_INLINE_VISIBILITY
-    __optional_move_base(__optional_move_base&& __opt)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 __optional_move_base(__optional_move_base&& __opt)
         noexcept(is_nothrow_move_constructible_v<value_type>)
     {
         this->__construct_from(_VSTD::move(__opt));
@@ -525,7 +530,7 @@ struct __optional_copy_assign_base<_Tp, false> : __optional_move_base<_Tp>
     __optional_copy_assign_base(__optional_copy_assign_base&&) = default;
 
     _LIBCPP_INLINE_VISIBILITY
-    __optional_copy_assign_base& operator=(const __optional_copy_assign_base& __opt)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 __optional_copy_assign_base& operator=(const __optional_copy_assign_base& __opt)
     {
         this->__assign_from(__opt);
         return *this;
@@ -560,7 +565,7 @@ struct __optional_move_assign_base<_Tp, false> : __optional_copy_assign_base<_Tp
     __optional_move_assign_base& operator=(const __optional_move_assign_base&) = default;
 
     _LIBCPP_INLINE_VISIBILITY
-    __optional_move_assign_base& operator=(__optional_move_assign_base&& __opt)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 __optional_move_assign_base& operator=(__optional_move_assign_base&& __opt)
         noexcept(is_nothrow_move_assignable_v<value_type> &&
                  is_nothrow_move_constructible_v<value_type>)
     {
@@ -727,7 +732,7 @@ public:
         _CheckOptionalLikeCtor<_Up, _Up const&>::template __enable_implicit<_Up>()
     , int> = 0>
     _LIBCPP_INLINE_VISIBILITY
-    optional(const optional<_Up>& __v)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 optional(const optional<_Up>& __v)
     {
         this->__construct_from(__v);
     }
@@ -735,7 +740,7 @@ public:
         _CheckOptionalLikeCtor<_Up, _Up const&>::template __enable_explicit<_Up>()
     , int> = 0>
     _LIBCPP_INLINE_VISIBILITY
-    explicit optional(const optional<_Up>& __v)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 explicit optional(const optional<_Up>& __v)
     {
         this->__construct_from(__v);
     }
@@ -745,7 +750,7 @@ public:
         _CheckOptionalLikeCtor<_Up, _Up &&>::template __enable_implicit<_Up>()
     , int> = 0>
     _LIBCPP_INLINE_VISIBILITY
-    optional(optional<_Up>&& __v)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 optional(optional<_Up>&& __v)
     {
         this->__construct_from(_VSTD::move(__v));
     }
@@ -753,13 +758,13 @@ public:
         _CheckOptionalLikeCtor<_Up, _Up &&>::template __enable_explicit<_Up>()
     , int> = 0>
     _LIBCPP_INLINE_VISIBILITY
-    explicit optional(optional<_Up>&& __v)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 explicit optional(optional<_Up>&& __v)
     {
         this->__construct_from(_VSTD::move(__v));
     }
 
     _LIBCPP_INLINE_VISIBILITY
-    optional& operator=(nullopt_t) noexcept
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 optional& operator=(nullopt_t) noexcept
     {
         reset();
         return *this;
@@ -782,7 +787,7 @@ public:
                       >::value>
              >
     _LIBCPP_INLINE_VISIBILITY
-    optional&
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 optional&
     operator=(_Up&& __v)
     {
         if (this->has_value())
@@ -797,7 +802,7 @@ public:
         _CheckOptionalLikeAssign<_Up, _Up const&>::template __enable_assign<_Up>()
     , int> = 0>
     _LIBCPP_INLINE_VISIBILITY
-    optional&
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 optional&
     operator=(const optional<_Up>& __v)
     {
         this->__assign_from(__v);
@@ -809,7 +814,7 @@ public:
         _CheckOptionalLikeCtor<_Up, _Up &&>::template __enable_assign<_Up>()
     , int> = 0>
     _LIBCPP_INLINE_VISIBILITY
-    optional&
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 optional&
     operator=(optional<_Up>&& __v)
     {
         this->__assign_from(_VSTD::move(__v));
@@ -823,7 +828,7 @@ public:
                       >
              >
     _LIBCPP_INLINE_VISIBILITY
-    _Tp &
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 _Tp &
     emplace(_Args&&... __args)
     {
         reset();
@@ -838,7 +843,7 @@ public:
                       >
              >
     _LIBCPP_INLINE_VISIBILITY
-    _Tp &
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 _Tp &
     emplace(initializer_list<_Up> __il, _Args&&... __args)
     {
         reset();
@@ -847,7 +852,7 @@ public:
     }
 
     _LIBCPP_INLINE_VISIBILITY
-    void swap(optional& __opt)
+    _LIBCPP_CONSTEXPR_AFTER_CXX17 void swap(optional& __opt)
         noexcept(is_nothrow_move_constructible_v<value_type> &&
                  is_nothrow_swappable_v<value_type>)
     {
@@ -877,7 +882,7 @@ public:
     add_pointer_t<value_type const>
     operator->() const
     {
-        _LIBCPP_ASSERT(this->has_value(), "optional operator-> called for disengaged value");
+        _LIBCPP_ASSERT(this->has_value(), "optional operator-> called on a disengaged value");
 #ifndef _LIBCPP_HAS_NO_BUILTIN_ADDRESSOF
         return _VSTD::addressof(this->__get());
 #else
@@ -890,7 +895,7 @@ public:
     add_pointer_t<value_type>
     operator->()
     {
-        _LIBCPP_ASSERT(this->has_value(), "optional operator-> called for disengaged value");
+        _LIBCPP_ASSERT(this->has_value(), "optional operator-> called on a disengaged value");
 #ifndef _LIBCPP_HAS_NO_BUILTIN_ADDRESSOF
         return _VSTD::addressof(this->__get());
 #else
@@ -901,36 +906,36 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     constexpr
     const value_type&
-    operator*() const&
+    operator*() const& noexcept
     {
-        _LIBCPP_ASSERT(this->has_value(), "optional operator* called for disengaged value");
+        _LIBCPP_ASSERT(this->has_value(), "optional operator* called on a disengaged value");
         return this->__get();
     }
 
     _LIBCPP_INLINE_VISIBILITY
     constexpr
     value_type&
-    operator*() &
+    operator*() & noexcept
     {
-        _LIBCPP_ASSERT(this->has_value(), "optional operator* called for disengaged value");
+        _LIBCPP_ASSERT(this->has_value(), "optional operator* called on a disengaged value");
         return this->__get();
     }
 
     _LIBCPP_INLINE_VISIBILITY
     constexpr
     value_type&&
-    operator*() &&
+    operator*() && noexcept
     {
-        _LIBCPP_ASSERT(this->has_value(), "optional operator* called for disengaged value");
+        _LIBCPP_ASSERT(this->has_value(), "optional operator* called on a disengaged value");
         return _VSTD::move(this->__get());
     }
 
     _LIBCPP_INLINE_VISIBILITY
     constexpr
     const value_type&&
-    operator*() const&&
+    operator*() const&& noexcept
     {
-        _LIBCPP_ASSERT(this->has_value(), "optional operator* called for disengaged value");
+        _LIBCPP_ASSERT(this->has_value(), "optional operator* called on a disengaged value");
         return _VSTD::move(this->__get());
     }
 
@@ -1005,7 +1010,7 @@ public:
 private:
     template <class _Up>
     _LIBCPP_INLINE_VISIBILITY
-    static _Up*
+    static _LIBCPP_CONSTEXPR_AFTER_CXX17 _Up*
     __operator_arrow(true_type, _Up& __x)
     {
         return _VSTD::addressof(__x);
@@ -1029,8 +1034,8 @@ template<class T>
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() ==
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() ==
+        declval<const _Up&>()), bool>,
     bool
 >
 operator==(const optional<_Tp>& __x, const optional<_Up>& __y)
@@ -1045,8 +1050,8 @@ operator==(const optional<_Tp>& __x, const optional<_Up>& __y)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() !=
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() !=
+        declval<const _Up&>()), bool>,
     bool
 >
 operator!=(const optional<_Tp>& __x, const optional<_Up>& __y)
@@ -1061,8 +1066,8 @@ operator!=(const optional<_Tp>& __x, const optional<_Up>& __y)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() <
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() <
+        declval<const _Up&>()), bool>,
     bool
 >
 operator<(const optional<_Tp>& __x, const optional<_Up>& __y)
@@ -1077,8 +1082,8 @@ operator<(const optional<_Tp>& __x, const optional<_Up>& __y)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() >
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() >
+        declval<const _Up&>()), bool>,
     bool
 >
 operator>(const optional<_Tp>& __x, const optional<_Up>& __y)
@@ -1093,8 +1098,8 @@ operator>(const optional<_Tp>& __x, const optional<_Up>& __y)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() <=
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() <=
+        declval<const _Up&>()), bool>,
     bool
 >
 operator<=(const optional<_Tp>& __x, const optional<_Up>& __y)
@@ -1109,8 +1114,8 @@ operator<=(const optional<_Tp>& __x, const optional<_Up>& __y)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() >=
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() >=
+        declval<const _Up&>()), bool>,
     bool
 >
 operator>=(const optional<_Tp>& __x, const optional<_Up>& __y)
@@ -1223,8 +1228,8 @@ operator>=(nullopt_t, const optional<_Tp>& __x) noexcept
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() ==
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() ==
+        declval<const _Up&>()), bool>,
     bool
 >
 operator==(const optional<_Tp>& __x, const _Up& __v)
@@ -1235,8 +1240,8 @@ operator==(const optional<_Tp>& __x, const _Up& __v)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() ==
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() ==
+        declval<const _Up&>()), bool>,
     bool
 >
 operator==(const _Tp& __v, const optional<_Up>& __x)
@@ -1247,8 +1252,8 @@ operator==(const _Tp& __v, const optional<_Up>& __x)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() !=
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() !=
+        declval<const _Up&>()), bool>,
     bool
 >
 operator!=(const optional<_Tp>& __x, const _Up& __v)
@@ -1259,8 +1264,8 @@ operator!=(const optional<_Tp>& __x, const _Up& __v)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() !=
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() !=
+        declval<const _Up&>()), bool>,
     bool
 >
 operator!=(const _Tp& __v, const optional<_Up>& __x)
@@ -1271,8 +1276,8 @@ operator!=(const _Tp& __v, const optional<_Up>& __x)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() <
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() <
+        declval<const _Up&>()), bool>,
     bool
 >
 operator<(const optional<_Tp>& __x, const _Up& __v)
@@ -1283,8 +1288,8 @@ operator<(const optional<_Tp>& __x, const _Up& __v)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() <
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() <
+        declval<const _Up&>()), bool>,
     bool
 >
 operator<(const _Tp& __v, const optional<_Up>& __x)
@@ -1295,8 +1300,8 @@ operator<(const _Tp& __v, const optional<_Up>& __x)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() <=
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() <=
+        declval<const _Up&>()), bool>,
     bool
 >
 operator<=(const optional<_Tp>& __x, const _Up& __v)
@@ -1307,8 +1312,8 @@ operator<=(const optional<_Tp>& __x, const _Up& __v)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() <=
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() <=
+        declval<const _Up&>()), bool>,
     bool
 >
 operator<=(const _Tp& __v, const optional<_Up>& __x)
@@ -1319,8 +1324,8 @@ operator<=(const _Tp& __v, const optional<_Up>& __x)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() >
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() >
+        declval<const _Up&>()), bool>,
     bool
 >
 operator>(const optional<_Tp>& __x, const _Up& __v)
@@ -1331,8 +1336,8 @@ operator>(const optional<_Tp>& __x, const _Up& __v)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() >
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() >
+        declval<const _Up&>()), bool>,
     bool
 >
 operator>(const _Tp& __v, const optional<_Up>& __x)
@@ -1343,8 +1348,8 @@ operator>(const _Tp& __v, const optional<_Up>& __x)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() >=
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() >=
+        declval<const _Up&>()), bool>,
     bool
 >
 operator>=(const optional<_Tp>& __x, const _Up& __v)
@@ -1355,8 +1360,8 @@ operator>=(const optional<_Tp>& __x, const _Up& __v)
 template <class _Tp, class _Up>
 _LIBCPP_INLINE_VISIBILITY constexpr
 _EnableIf<
-    is_convertible_v<decltype(_VSTD::declval<const _Tp&>() >=
-        _VSTD::declval<const _Up&>()), bool>,
+    is_convertible_v<decltype(declval<const _Tp&>() >=
+        declval<const _Up&>()), bool>,
     bool
 >
 operator>=(const _Tp& __v, const optional<_Up>& __x)
@@ -1366,7 +1371,7 @@ operator>=(const _Tp& __v, const optional<_Up>& __x)
 
 
 template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
 _EnableIf<
     is_move_constructible_v<_Tp> && is_swappable_v<_Tp>,
     void
@@ -1402,11 +1407,13 @@ struct _LIBCPP_TEMPLATE_VIS hash<
     __enable_hash_helper<optional<_Tp>, remove_const_t<_Tp>>
 >
 {
-    typedef optional<_Tp> argument_type;
-    typedef size_t        result_type;
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef optional<_Tp> argument_type;
+    _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t        result_type;
+#endif
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator()(const argument_type& __opt) const
+    size_t operator()(const optional<_Tp>& __opt) const
     {
         return static_cast<bool>(__opt) ? hash<remove_const_t<_Tp>>()(*__opt) : 0;
     }
@@ -1414,8 +1421,8 @@ struct _LIBCPP_TEMPLATE_VIS hash<
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_STD_VER > 14
+#endif // _LIBCPP_STD_VER > 14
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_OPTIONAL
+#endif // _LIBCPP_OPTIONAL
lib/libcxx/include/ostream
@@ -134,11 +134,11 @@ template <class Stream, class T>
 */
 
 #include <__config>
+#include <bitset>
 #include <ios>
-#include <streambuf>
-#include <locale>
 #include <iterator>
-#include <bitset>
+#include <locale>
+#include <streambuf>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -165,27 +165,21 @@ public:
     { this->init(__sb); }
     virtual ~basic_ostream();
 protected:
-#ifndef _LIBCPP_CXX03_LANG
     inline _LIBCPP_INLINE_VISIBILITY
     basic_ostream(basic_ostream&& __rhs);
 
     // 27.7.2.3 Assign/swap
     inline _LIBCPP_INLINE_VISIBILITY
     basic_ostream& operator=(basic_ostream&& __rhs);
-#endif
+
     inline _LIBCPP_HIDE_FROM_ABI_AFTER_V1
     void swap(basic_ostream& __rhs)
     { basic_ios<char_type, traits_type>::swap(__rhs); }
 
-#ifndef _LIBCPP_CXX03_LANG
     basic_ostream           (const basic_ostream& __rhs) = delete;
     basic_ostream& operator=(const basic_ostream& __rhs) = delete;
-#else
-    basic_ostream           (const basic_ostream& __rhs); // not defined
-    basic_ostream& operator=(const basic_ostream& __rhs); // not defined
-#endif
-public:
 
+public:
     // 27.7.2.4 Prefix/suffix:
     class _LIBCPP_TEMPLATE_VIS sentry;
 
@@ -254,8 +248,7 @@ public:
     ~sentry();
 
     _LIBCPP_INLINE_VISIBILITY
-        _LIBCPP_EXPLICIT
-        operator bool() const {return __ok_;}
+    explicit operator bool() const {return __ok_;}
 };
 
 template <class _CharT, class _Traits>
@@ -280,7 +273,7 @@ basic_ostream<_CharT, _Traits>::sentry::~sentry()
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             if (__os_.rdbuf()->pubsync() == -1)
                 __os_.setstate(ios_base::badbit);
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -288,12 +281,10 @@ basic_ostream<_CharT, _Traits>::sentry::~sentry()
         catch (...)
         {
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 basic_ostream<_CharT, _Traits>::basic_ostream(basic_ostream&& __rhs)
 {
@@ -308,8 +299,6 @@ basic_ostream<_CharT, _Traits>::operator=(basic_ostream&& __rhs)
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template <class _CharT, class _Traits>
 basic_ostream<_CharT, _Traits>::~basic_ostream()
 {
@@ -322,7 +311,7 @@ basic_ostream<_CharT, _Traits>::operator<<(basic_streambuf<char_type, traits_typ
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -331,7 +320,7 @@ basic_ostream<_CharT, _Traits>::operator<<(basic_streambuf<char_type, traits_typ
 #ifndef _LIBCPP_NO_EXCEPTIONS
                 try
                 {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
                     typedef istreambuf_iterator<_CharT, _Traits> _Ip;
                     typedef ostreambuf_iterator<_CharT, _Traits> _Op;
                     _Ip __i(__sb);
@@ -352,7 +341,7 @@ basic_ostream<_CharT, _Traits>::operator<<(basic_streambuf<char_type, traits_typ
                 {
                     this->__set_failbit_and_consider_rethrow();
                 }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             }
             else
                 this->setstate(ios_base::badbit);
@@ -363,7 +352,7 @@ basic_ostream<_CharT, _Traits>::operator<<(basic_streambuf<char_type, traits_typ
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -374,7 +363,7 @@ basic_ostream<_CharT, _Traits>::operator<<(bool __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -389,7 +378,7 @@ basic_ostream<_CharT, _Traits>::operator<<(bool __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -400,7 +389,7 @@ basic_ostream<_CharT, _Traits>::operator<<(short __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -419,7 +408,7 @@ basic_ostream<_CharT, _Traits>::operator<<(short __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -430,7 +419,7 @@ basic_ostream<_CharT, _Traits>::operator<<(unsigned short __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -445,7 +434,7 @@ basic_ostream<_CharT, _Traits>::operator<<(unsigned short __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -456,7 +445,7 @@ basic_ostream<_CharT, _Traits>::operator<<(int __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -475,7 +464,7 @@ basic_ostream<_CharT, _Traits>::operator<<(int __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -486,7 +475,7 @@ basic_ostream<_CharT, _Traits>::operator<<(unsigned int __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -501,7 +490,7 @@ basic_ostream<_CharT, _Traits>::operator<<(unsigned int __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -512,7 +501,7 @@ basic_ostream<_CharT, _Traits>::operator<<(long __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -527,7 +516,7 @@ basic_ostream<_CharT, _Traits>::operator<<(long __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -538,7 +527,7 @@ basic_ostream<_CharT, _Traits>::operator<<(unsigned long __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -553,7 +542,7 @@ basic_ostream<_CharT, _Traits>::operator<<(unsigned long __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -564,7 +553,7 @@ basic_ostream<_CharT, _Traits>::operator<<(long long __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -579,7 +568,7 @@ basic_ostream<_CharT, _Traits>::operator<<(long long __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -590,7 +579,7 @@ basic_ostream<_CharT, _Traits>::operator<<(unsigned long long __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -605,7 +594,7 @@ basic_ostream<_CharT, _Traits>::operator<<(unsigned long long __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -616,7 +605,7 @@ basic_ostream<_CharT, _Traits>::operator<<(float __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -631,7 +620,7 @@ basic_ostream<_CharT, _Traits>::operator<<(float __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -642,7 +631,7 @@ basic_ostream<_CharT, _Traits>::operator<<(double __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -657,7 +646,7 @@ basic_ostream<_CharT, _Traits>::operator<<(double __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -668,7 +657,7 @@ basic_ostream<_CharT, _Traits>::operator<<(long double __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -683,7 +672,7 @@ basic_ostream<_CharT, _Traits>::operator<<(long double __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -694,7 +683,7 @@ basic_ostream<_CharT, _Traits>::operator<<(const void* __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -709,7 +698,7 @@ basic_ostream<_CharT, _Traits>::operator<<(const void* __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -721,7 +710,7 @@ __put_character_sequence(basic_ostream<_CharT, _Traits>& __os,
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         typename basic_ostream<_CharT, _Traits>::sentry __s(__os);
         if (__s)
         {
@@ -742,7 +731,7 @@ __put_character_sequence(basic_ostream<_CharT, _Traits>& __os,
     {
         __os.__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return __os;
 }
 
@@ -761,7 +750,7 @@ operator<<(basic_ostream<_CharT, _Traits>& __os, char __cn)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         typename basic_ostream<_CharT, _Traits>::sentry __s(__os);
         if (__s)
         {
@@ -783,7 +772,7 @@ operator<<(basic_ostream<_CharT, _Traits>& __os, char __cn)
     {
         __os.__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return __os;
 }
 
@@ -822,7 +811,7 @@ operator<<(basic_ostream<_CharT, _Traits>& __os, const char* __strn)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         typename basic_ostream<_CharT, _Traits>::sentry __s(__os);
         if (__s)
         {
@@ -857,7 +846,7 @@ operator<<(basic_ostream<_CharT, _Traits>& __os, const char* __strn)
     {
         __os.__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return __os;
 }
 
@@ -891,7 +880,7 @@ basic_ostream<_CharT, _Traits>::put(char_type __c)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __s(*this);
         if (__s)
         {
@@ -907,7 +896,7 @@ basic_ostream<_CharT, _Traits>::put(char_type __c)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -918,7 +907,7 @@ basic_ostream<_CharT, _Traits>::write(const char_type* __s, streamsize __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         sentry __sen(*this);
         if (__sen && __n)
         {
@@ -931,7 +920,7 @@ basic_ostream<_CharT, _Traits>::write(const char_type* __s, streamsize __n)
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -942,7 +931,7 @@ basic_ostream<_CharT, _Traits>::flush()
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         if (this->rdbuf())
         {
             sentry __s(*this);
@@ -958,7 +947,7 @@ basic_ostream<_CharT, _Traits>::flush()
     {
         this->__set_badbit_and_consider_rethrow();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return *this;
 }
 
@@ -1025,19 +1014,17 @@ flush(basic_ostream<_CharT, _Traits>& __os)
     return __os;
 }
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template <class _Stream, class _Tp, class = void>
 struct __is_ostreamable : false_type { };
 
 template <class _Stream, class _Tp>
 struct __is_ostreamable<_Stream, _Tp, decltype(
-    _VSTD::declval<_Stream>() << _VSTD::declval<_Tp>(), void()
+    declval<_Stream>() << declval<_Tp>(), void()
 )> : true_type { };
 
 template <class _Stream, class _Tp, class = typename enable_if<
     _And<is_base_of<ios_base, _Stream>,
-         __is_ostreamable<_Stream&, const _Tp&>>::value
+         __is_ostreamable<_Stream&, const _Tp&> >::value
 >::type>
 _LIBCPP_INLINE_VISIBILITY
 _Stream&& operator<<(_Stream&& __os, const _Tp& __x)
@@ -1046,8 +1033,6 @@ _Stream&& operator<<(_Stream&& __os, const _Tp& __x)
     return _VSTD::move(__os);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
-
 template<class _CharT, class _Traits, class _Allocator>
 basic_ostream<_CharT, _Traits>&
 operator<<(basic_ostream<_CharT, _Traits>& __os,
@@ -1106,4 +1091,4 @@ _LIBCPP_EXTERN_TEMPLATE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS basic_ostream<wch
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_OSTREAM
+#endif // _LIBCPP_OSTREAM
lib/libcxx/include/queue
@@ -179,10 +179,13 @@ template <class T, class Container, class Compare>
 */
 
 #include <__config>
+#include <__memory/uses_allocator.h>
+#include <__utility/forward.h>
+#include <algorithm>
+#include <compare>
 #include <deque>
-#include <vector>
 #include <functional>
-#include <algorithm>
+#include <vector>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -238,47 +241,42 @@ public:
     queue& operator=(queue&& __q)
         _NOEXCEPT_(is_nothrow_move_assignable<container_type>::value)
         {c = _VSTD::move(__q.c); return *this;}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     explicit queue(const container_type& __c)  : c(__c) {}
 #ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     explicit queue(container_type&& __c) : c(_VSTD::move(__c)) {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         explicit queue(const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(__a) {}
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         queue(const queue& __q, const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(__q.c, __a) {}
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         queue(const container_type& __c, const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(__c, __a) {}
 #ifndef _LIBCPP_CXX03_LANG
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         queue(container_type&& __c, const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(_VSTD::move(__c), __a) {}
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         queue(queue&& __q, const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(_VSTD::move(__q.c), __a) {}
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
     bool      empty() const {return c.empty();}
@@ -308,7 +306,7 @@ public:
         void     emplace(_Args&&... __args)
             {        c.emplace_back(_VSTD::forward<_Args>(__args)...);}
 #endif
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     void pop() {c.pop_front();}
 
@@ -335,15 +333,15 @@ public:
 
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template<class _Container,
-         class = typename enable_if<!__is_allocator<_Container>::value, nullptr_t>::type
+         class = _EnableIf<!__is_allocator<_Container>::value>
 >
 queue(_Container)
     -> queue<typename _Container::value_type, _Container>;
 
 template<class _Container,
          class _Alloc,
-         class = typename enable_if<!__is_allocator<_Container>::value, nullptr_t>::type,
-         class = typename enable_if< __is_allocator<_Alloc>::value, nullptr_t>::type
+         class = _EnableIf<!__is_allocator<_Container>::value>,
+         class = _EnableIf<uses_allocator<_Container, _Alloc>::value>
 >
 queue(_Container, _Alloc)
     -> queue<typename _Container::value_type, _Container>;
@@ -399,10 +397,7 @@ operator<=(const queue<_Tp, _Container>& __x,const queue<_Tp, _Container>& __y)
 
 template <class _Tp, class _Container>
 inline _LIBCPP_INLINE_VISIBILITY
-typename enable_if<
-    __is_swappable<_Container>::value,
-    void
->::type
+_EnableIf<__is_swappable<_Container>::value, void>
 swap(queue<_Tp, _Container>& __x, queue<_Tp, _Container>& __y)
     _NOEXCEPT_(_NOEXCEPT_(__x.swap(__y)))
 {
@@ -458,7 +453,7 @@ public:
         _NOEXCEPT_(is_nothrow_move_assignable<container_type>::value &&
                    is_nothrow_move_assignable<value_compare>::value)
         {c = _VSTD::move(__q.c); comp = _VSTD::move(__q.comp); return *this;}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     explicit priority_queue(const value_compare& __comp)
@@ -482,41 +477,35 @@ public:
         _LIBCPP_INLINE_VISIBILITY
         priority_queue(_InputIter __f, _InputIter __l,
                        const value_compare& __comp, container_type&& __c);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         explicit priority_queue(const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0);
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0);
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         priority_queue(const value_compare& __comp, const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0);
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0);
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         priority_queue(const value_compare& __comp, const container_type& __c,
                        const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0);
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0);
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         priority_queue(const priority_queue& __q, const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0);
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0);
 #ifndef _LIBCPP_CXX03_LANG
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         priority_queue(const value_compare& __comp, container_type&& __c,
                        const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0);
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0);
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         priority_queue(priority_queue&& __q, const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0);
-#endif  // _LIBCPP_CXX03_LANG
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0);
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
     bool            empty() const {return c.empty();}
@@ -533,7 +522,7 @@ public:
     template <class... _Args>
     _LIBCPP_INLINE_VISIBILITY
     void emplace(_Args&&... __args);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     void pop();
 
@@ -546,28 +535,28 @@ public:
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template <class _Compare,
           class _Container,
-          class = typename enable_if<!__is_allocator<_Compare>::value, nullptr_t>::type,
-          class = typename enable_if<!__is_allocator<_Container>::value, nullptr_t>::type
+          class = _EnableIf<!__is_allocator<_Compare>::value>,
+          class = _EnableIf<!__is_allocator<_Container>::value>
 >
 priority_queue(_Compare, _Container)
     -> priority_queue<typename _Container::value_type, _Container, _Compare>;
 
 template<class _InputIterator,
-         class _Compare   = less<typename iterator_traits<_InputIterator>::value_type>,
-         class _Container = vector<typename iterator_traits<_InputIterator>::value_type>,
-         class = typename enable_if< __is_cpp17_input_iterator<_InputIterator>::value, nullptr_t>::type,
-         class = typename enable_if<!__is_allocator<_Compare>::value, nullptr_t>::type,
-         class = typename enable_if<!__is_allocator<_Container>::value, nullptr_t>::type
+         class _Compare = less<__iter_value_type<_InputIterator>>,
+         class _Container = vector<__iter_value_type<_InputIterator>>,
+         class = _EnableIf<__is_cpp17_input_iterator<_InputIterator>::value>,
+         class = _EnableIf<!__is_allocator<_Compare>::value>,
+         class = _EnableIf<!__is_allocator<_Container>::value>
 >
 priority_queue(_InputIterator, _InputIterator, _Compare = _Compare(), _Container = _Container())
-    -> priority_queue<typename iterator_traits<_InputIterator>::value_type, _Container, _Compare>;
+    -> priority_queue<__iter_value_type<_InputIterator>, _Container, _Compare>;
 
 template<class _Compare,
          class _Container,
          class _Alloc,
-         class = typename enable_if<!__is_allocator<_Compare>::value, nullptr_t>::type,
-         class = typename enable_if<!__is_allocator<_Container>::value, nullptr_t>::type,
-         class = typename enable_if< __is_allocator<_Alloc>::value, nullptr_t>::type
+         class = _EnableIf<!__is_allocator<_Compare>::value>,
+         class = _EnableIf<!__is_allocator<_Container>::value>,
+         class = _EnableIf<uses_allocator<_Container, _Alloc>::value>
 >
 priority_queue(_Compare, _Container, _Alloc)
     -> priority_queue<typename _Container::value_type, _Container, _Compare>;
@@ -595,7 +584,7 @@ priority_queue<_Tp, _Container, _Compare>::priority_queue(const value_compare& _
     _VSTD::make_heap(c.begin(), c.end(), comp);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Container, class _Compare>
 template <class _InputIter>
@@ -636,14 +625,13 @@ priority_queue<_Tp, _Container, _Compare>::priority_queue(_InputIter __f, _Input
     _VSTD::make_heap(c.begin(), c.end(), comp);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Container, class _Compare>
 template <class _Alloc>
 inline
 priority_queue<_Tp, _Container, _Compare>::priority_queue(const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type*)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>*)
     : c(__a)
 {
 }
@@ -653,8 +641,7 @@ template <class _Alloc>
 inline
 priority_queue<_Tp, _Container, _Compare>::priority_queue(const value_compare& __comp,
                                                           const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type*)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>*)
     : c(__a),
       comp(__comp)
 {
@@ -666,8 +653,7 @@ inline
 priority_queue<_Tp, _Container, _Compare>::priority_queue(const value_compare& __comp,
                                                           const container_type& __c,
                                                           const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type*)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>*)
     : c(__c, __a),
       comp(__comp)
 {
@@ -679,8 +665,7 @@ template <class _Alloc>
 inline
 priority_queue<_Tp, _Container, _Compare>::priority_queue(const priority_queue& __q,
                                                           const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type*)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>*)
     : c(__q.c, __a),
       comp(__q.comp)
 {
@@ -695,8 +680,7 @@ inline
 priority_queue<_Tp, _Container, _Compare>::priority_queue(const value_compare& __comp,
                                                           container_type&& __c,
                                                           const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type*)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>*)
     : c(_VSTD::move(__c), __a),
       comp(__comp)
 {
@@ -708,15 +692,14 @@ template <class _Alloc>
 inline
 priority_queue<_Tp, _Container, _Compare>::priority_queue(priority_queue&& __q,
                                                           const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type*)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>*)
     : c(_VSTD::move(__q.c), __a),
       comp(_VSTD::move(__q.comp))
 {
     _VSTD::make_heap(c.begin(), c.end(), comp);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Container, class _Compare>
 inline
@@ -748,7 +731,7 @@ priority_queue<_Tp, _Container, _Compare>::emplace(_Args&&... __args)
     _VSTD::push_heap(c.begin(), c.end(), comp);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Container, class _Compare>
 inline
@@ -773,11 +756,10 @@ priority_queue<_Tp, _Container, _Compare>::swap(priority_queue& __q)
 
 template <class _Tp, class _Container, class _Compare>
 inline _LIBCPP_INLINE_VISIBILITY
-typename enable_if<
-    __is_swappable<_Container>::value
-    && __is_swappable<_Compare>::value,
+_EnableIf<
+    __is_swappable<_Container>::value && __is_swappable<_Compare>::value,
     void
->::type
+>
 swap(priority_queue<_Tp, _Container, _Compare>& __x,
      priority_queue<_Tp, _Container, _Compare>& __y)
     _NOEXCEPT_(_NOEXCEPT_(__x.swap(__y)))
@@ -793,4 +775,4 @@ struct _LIBCPP_TEMPLATE_VIS uses_allocator<priority_queue<_Tp, _Container, _Comp
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_QUEUE
+#endif // _LIBCPP_QUEUE
lib/libcxx/include/random
@@ -17,6 +17,9 @@
 
 namespace std
 {
+// [rand.req.urng], uniform random bit generator requirements
+template<class G>
+concept uniform_random_bit_generator = see below; // C++20
 
 // Engines
 
@@ -1675,17 +1678,19 @@ class piecewise_linear_distribution
 */
 
 #include <__config>
+#include <__random/uniform_int_distribution.h>
+#include <algorithm>
+#include <cmath>
+#include <concepts>
 #include <cstddef>
 #include <cstdint>
-#include <cmath>
-#include <type_traits>
 #include <initializer_list>
+#include <iosfwd>
 #include <limits>
-#include <algorithm>
 #include <numeric>
-#include <vector>
 #include <string>
-#include <iosfwd>
+#include <type_traits>
+#include <vector>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -1697,6 +1702,20 @@ _LIBCPP_PUSH_MACROS
 
 _LIBCPP_BEGIN_NAMESPACE_STD
 
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CONCEPTS)
+
+// [rand.req.urng]
+template<class _Gen>
+concept uniform_random_bit_generator =
+  invocable<_Gen&> && unsigned_integral<invoke_result_t<_Gen&>> &&
+  requires {
+    { _Gen::min() } -> same_as<invoke_result_t<_Gen&>>;
+    { _Gen::max() } -> same_as<invoke_result_t<_Gen&>>;
+    requires bool_constant<(_Gen::min() < _Gen::max())>::value;
+  };
+
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CONCEPTS)
+
 // __is_seed_sequence
 
 template <class _Sseq, class _Engine>
@@ -1712,7 +1731,7 @@ struct __is_seed_sequence
 template <unsigned long long __a, unsigned long long __c,
           unsigned long long __m, unsigned long long _Mp,
           bool _MightOverflow = (__a != 0 && __m != 0 && __m-1 > (_Mp-__c)/__a),
-          bool _OverflowOK = ((__m|__m-1) > __m), // m = 2^n
+          bool _OverflowOK = ((__m | (__m-1)) > __m), // m = 2^n
           bool _SchrageOK = (__a != 0 && __m != 0 && __m % __a <= __m / __a)> // r <= q
 struct __lce_alg_picker
 {
@@ -1901,7 +1920,7 @@ private:
 
     static_assert(__m == 0 || __a < __m, "linear_congruential_engine invalid parameters");
     static_assert(__m == 0 || __c < __m, "linear_congruential_engine invalid parameters");
-    static_assert(_VSTD::is_unsigned<_UIntType>::value, "_UIntType must be unsigned type");
+    static_assert(is_unsigned<_UIntType>::value, "_UIntType must be unsigned type");
 public:
     static _LIBCPP_CONSTEXPR const result_type _Min = __c == 0u ? 1u: 0u;
     static _LIBCPP_CONSTEXPR const result_type _Max = __m - 1u;
@@ -2940,7 +2959,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     explicit discard_block_engine(_Engine&& __e)
         : __e_(_VSTD::move(__e)), __n_(0) {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     explicit discard_block_engine(result_type __sd) : __e_(__sd), __n_(0) {}
     template<class _Sseq>
@@ -3152,7 +3171,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     explicit independent_bits_engine(_Engine&& __e)
         : __e_(_VSTD::move(__e)) {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     explicit independent_bits_engine(result_type __sd) : __e_(__sd) {}
     template<class _Sseq>
@@ -3382,7 +3401,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     explicit shuffle_order_engine(_Engine&& __e)
         : __e_(_VSTD::move(__e)) {__init();}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     explicit shuffle_order_engine(result_type __sd) : __e_(__sd) {__init();}
     template<class _Sseq>
@@ -3634,7 +3653,7 @@ public:
     template<class _Tp>
         _LIBCPP_INLINE_VISIBILITY
         seed_seq(initializer_list<_Tp> __il) {init(__il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     template<class _InputIterator>
         _LIBCPP_INLINE_VISIBILITY
@@ -3755,42 +3774,6 @@ generate_canonical(_URNG& __g)
     return _Sp / __base;
 }
 
-// uniform_int_distribution
-
-// in <algorithm>
-
-template <class _CharT, class _Traits, class _IT>
-basic_ostream<_CharT, _Traits>&
-operator<<(basic_ostream<_CharT, _Traits>& __os,
-           const uniform_int_distribution<_IT>& __x)
-{
-    __save_flags<_CharT, _Traits> __lx(__os);
-    typedef basic_ostream<_CharT, _Traits> _Ostream;
-    __os.flags(_Ostream::dec | _Ostream::left);
-    _CharT __sp = __os.widen(' ');
-    __os.fill(__sp);
-    return __os << __x.a() << __sp << __x.b();
-}
-
-template <class _CharT, class _Traits, class _IT>
-basic_istream<_CharT, _Traits>&
-operator>>(basic_istream<_CharT, _Traits>& __is,
-           uniform_int_distribution<_IT>& __x)
-{
-    typedef uniform_int_distribution<_IT> _Eng;
-    typedef typename _Eng::result_type result_type;
-    typedef typename _Eng::param_type param_type;
-    __save_flags<_CharT, _Traits> __lx(__is);
-    typedef basic_istream<_CharT, _Traits> _Istream;
-    __is.flags(_Istream::dec | _Istream::skipws);
-    result_type __a;
-    result_type __b;
-    __is >> __a >> __b;
-    if (!__is.fail())
-        __x.param(param_type(__a, __b));
-    return __is;
-}
-
 // uniform_real_distribution
 
 template<class _RealType = double>
@@ -4142,7 +4125,7 @@ inline _LIBCPP_INLINE_VISIBILITY double __libcpp_lgamma(double __d) {
 }
 
 template<class _IntType>
-binomial_distribution<_IntType>::param_type::param_type(const result_type __t, const double __p)
+binomial_distribution<_IntType>::param_type::param_type(result_type __t, double __p)
     : __t_(__t), __p_(__p)
 {
     if (0 < __p_ && __p_ < 1)
@@ -6145,7 +6128,7 @@ public:
         _LIBCPP_INLINE_VISIBILITY
         param_type(initializer_list<double> __wl)
             : __p_(__wl.begin(), __wl.end()) {__init();}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
         template<class _UnaryOperation>
             param_type(size_t __nw, double __xmin, double __xmax,
                        _UnaryOperation __fw);
@@ -6192,7 +6175,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     discrete_distribution(initializer_list<double> __wl)
         : __p_(__wl) {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     template<class _UnaryOperation>
         _LIBCPP_INLINE_VISIBILITY
         discrete_distribution(size_t __nw, double __xmin, double __xmax,
@@ -6274,8 +6257,7 @@ discrete_distribution<_IntType>::param_type::__init()
         if (__p_.size() > 1)
         {
             double __s = _VSTD::accumulate(__p_.begin(), __p_.end(), 0.0);
-            for (_VSTD::vector<double>::iterator __i = __p_.begin(), __e = __p_.end();
-                                                                       __i < __e; ++__i)
+            for (vector<double>::iterator __i = __p_.begin(), __e = __p_.end(); __i < __e; ++__i)
                 *__i /= __s;
             vector<double> __t(__p_.size() - 1);
             _VSTD::partial_sum(__p_.begin(), __p_.end() - 1, __t.begin());
@@ -6294,7 +6276,7 @@ vector<double>
 discrete_distribution<_IntType>::param_type::probabilities() const
 {
     size_t __n = __p_.size();
-    _VSTD::vector<double> __p(__n+1);
+    vector<double> __p(__n+1);
     _VSTD::adjacent_difference(__p_.begin(), __p_.end(), __p.begin());
     if (__n > 0)
         __p[__n] = 1 - __p_[__n-1];
@@ -6374,7 +6356,7 @@ public:
 #ifndef _LIBCPP_CXX03_LANG
         template<class _UnaryOperation>
             param_type(initializer_list<result_type> __bl, _UnaryOperation __fw);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
         template<class _UnaryOperation>
             param_type(size_t __nw, result_type __xmin, result_type __xmax,
                        _UnaryOperation __fw);
@@ -6431,7 +6413,7 @@ public:
         piecewise_constant_distribution(initializer_list<result_type> __bl,
                                         _UnaryOperation __fw)
         : __p_(__bl, __fw) {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     template<class _UnaryOperation>
         _LIBCPP_INLINE_VISIBILITY
@@ -6586,7 +6568,7 @@ piecewise_constant_distribution<_RealType>::param_type::param_type(
     }
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template<class _RealType>
 template<class _UnaryOperation>
@@ -6700,7 +6682,7 @@ public:
 #ifndef _LIBCPP_CXX03_LANG
         template<class _UnaryOperation>
             param_type(initializer_list<result_type> __bl, _UnaryOperation __fw);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
         template<class _UnaryOperation>
             param_type(size_t __nw, result_type __xmin, result_type __xmax,
                        _UnaryOperation __fw);
@@ -6757,7 +6739,7 @@ public:
         piecewise_linear_distribution(initializer_list<result_type> __bl,
                                       _UnaryOperation __fw)
         : __p_(__bl, __fw) {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     template<class _UnaryOperation>
         _LIBCPP_INLINE_VISIBILITY
@@ -6916,7 +6898,7 @@ piecewise_linear_distribution<_RealType>::param_type::param_type(
     }
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template<class _RealType>
 template<class _UnaryOperation>
@@ -7022,4 +7004,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_RANDOM
+#endif // _LIBCPP_RANDOM
lib/libcxx/include/ranges
@@ -0,0 +1,209 @@
+// -*- C++ -*-
+//===--------------------------- ranges -----------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef _LIBCPP_RANGES
+#define _LIBCPP_RANGES
+
+/*
+
+#include <compare>              // see [compare.syn]
+#include <initializer_list>     // see [initializer.list.syn]
+#include <iterator>             // see [iterator.synopsis]
+
+namespace std::ranges {
+  inline namespace unspecified {
+    // [range.access], range access
+    inline constexpr unspecified begin = unspecified;
+    inline constexpr unspecified end = unspecified;
+    inline constexpr unspecified cbegin = unspecified;
+    inline constexpr unspecified cend = unspecified;
+
+    inline constexpr unspecified size = unspecified;
+    inline constexpr unspecified ssize = unspecified;
+  }
+
+  // [range.range], ranges
+  template<class T>
+    concept range = see below;
+
+  template<class T>
+    inline constexpr bool enable_borrowed_range = false;
+
+  template<class T>
+    using iterator_t = decltype(ranges::begin(declval<R&>()));
+  template<range R>
+    using sentinel_t = decltype(ranges::end(declval<R&>()));
+  template<range R>
+    using range_difference_t = iter_difference_t<iterator_t<R>>;
+  template<sized_range R>
+    using range_size_t = decltype(ranges::size(declval<R&>()));
+  template<range R>
+    using range_value_t = iter_value_t<iterator_t<R>>;
+  template<range R>
+    using range_reference_t = iter_reference_t<iterator_t<R>>;
+  template<range R>
+    using range_rvalue_reference_t = iter_rvalue_reference_t<iterator_t<R>>;
+
+  // [range.sized], sized ranges
+  template<class>
+    inline constexpr bool disable_sized_range = false;
+
+  template<class T>
+    concept sized_range = ...;
+
+  // [range.view], views
+  template<class T>
+    inline constexpr bool enable_view = ...;
+
+  struct view_base { };
+
+  template<class T>
+    concept view = ...;
+
+  // [range.refinements], other range refinements
+  template<class R, class T>
+    concept output_range = see below;
+
+  template<class T>
+    concept input_range = see below;
+
+  template<class T>
+    concept forward_range = see below;
+
+  template<class T>
+  concept bidirectional_range = see below;
+
+  template<class T>
+  concept random_access_range = see below;
+
+  template<class T>
+  concept contiguous_range = see below;
+
+  template <class _Tp>
+    concept common_range = see below;
+
+  template<class T>
+  concept viewable_range = see below;
+
+  // [view.interface], class template view_interface
+  template<class D>
+    requires is_class_v<D> && same_as<D, remove_cv_t<D>>
+  class view_interface;
+
+  // [range.subrange], sub-ranges
+  enum class subrange_kind : bool { unsized, sized };
+
+  template<input_or_output_iterator I, sentinel_for<I> S = I, subrange_kind K = see below>
+    requires (K == subrange_kind::sized || !sized_sentinel_for<S, I>)
+  class subrange;
+
+  template<class I, class S, subrange_kind K>
+    inline constexpr bool enable_borrowed_range<subrange<I, S, K>> = true;
+
+  // [range.dangling], dangling iterator handling
+  struct dangling;
+
+  template<range R>
+    using borrowed_iterator_t = see below;
+
+  template<range R>
+    using borrowed_subrange_t = see below;
+
+  // [range.empty], empty view
+  template<class T>
+    requires is_object_v<T>
+  class empty_view;
+
+  // [range.all], all view
+  namespace views {
+    inline constexpr unspecified all = unspecified;
+
+    template<viewable_range R>
+      using all_t = decltype(all(declval<R>()));
+  }
+
+  template<range R>
+    requires is_object_v<R>
+  class ref_view;
+
+  template<class T>
+    inline constexpr bool enable_borrowed_range<ref_view<T>> = true;
+
+  // [range.drop], drop view
+  template<view V>
+    class drop_view;
+
+  template<class T>
+    inline constexpr bool enable_borrowed_range<drop_view<T>> = enable_borrowed_range<T>;
+
+  // [range.transform], transform view
+  template<input_range V, copy_constructible F>
+    requires view<V> && is_object_v<F> &&
+             regular_invocable<F&, range_reference_t<V>> &&
+             can-reference<invoke_result_t<F&, range_reference_t<V>>>
+  class transform_view;
+
+  // [range.common], common view
+  template<view V>
+    requires (!common_range<V> && copyable<iterator_t<V>>)
+  class common_view;
+
+  template<class T>
+  inline constexpr bool enable_borrowed_range<common_view<T>> = enable_borrowed_range<T>;
+}
+
+*/
+
+// Make sure all feature tests macros are always available.
+#include <version>
+// Only enable the contents of the header when libc++ was build with LIBCXX_ENABLE_INCOMPLETE_FEATURES enabled
+#if !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
+
+#include <__config>
+#include <__ranges/access.h>
+#include <__ranges/all.h>
+#include <__ranges/common_view.h>
+#include <__ranges/concepts.h>
+#include <__ranges/dangling.h>
+#include <__ranges/data.h>
+#include <__ranges/drop_view.h>
+#include <__ranges/empty.h>
+#include <__ranges/empty_view.h>
+#include <__ranges/enable_borrowed_range.h>
+#include <__ranges/enable_view.h>
+#include <__ranges/ref_view.h>
+#include <__ranges/size.h>
+#include <__ranges/subrange.h>
+#include <__ranges/transform_view.h>
+#include <__ranges/view_interface.h>
+#include <compare>          // Required by the standard.
+#include <initializer_list> // Required by the standard.
+#include <iterator>         // Required by the standard.
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_RANGES)
+
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // !defined(_LIBCPP_HAS_NO_INCOMPLETE_RANGES)
+
+#endif // _LIBCPP_RANGES
lib/libcxx/include/ratio
@@ -78,8 +78,8 @@ typedef ratio<1000000000000000000000000, 1> yotta;  // not supported
 */
 
 #include <__config>
-#include <cstdint>
 #include <climits>
+#include <cstdint>
 #include <type_traits>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -312,7 +312,7 @@ template <class _R1, class _R2>
 struct _LIBCPP_TEMPLATE_VIS ratio_multiply
     : public __ratio_multiply<_R1, _R2>::type {};
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _R1, class _R2>
 struct __ratio_divide
@@ -339,7 +339,7 @@ template <class _R1, class _R2>
 struct _LIBCPP_TEMPLATE_VIS ratio_divide
     : public __ratio_divide<_R1, _R2>::type {};
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _R1, class _R2>
 struct __ratio_add
@@ -374,7 +374,7 @@ template <class _R1, class _R2>
 struct _LIBCPP_TEMPLATE_VIS ratio_add
     : public __ratio_add<_R1, _R2>::type {};
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _R1, class _R2>
 struct __ratio_subtract
@@ -409,7 +409,7 @@ template <class _R1, class _R2>
 struct _LIBCPP_TEMPLATE_VIS ratio_subtract
     : public __ratio_subtract<_R1, _R2>::type {};
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 // ratio_equal
 
@@ -529,4 +529,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_RATIO
+#endif // _LIBCPP_RATIO
lib/libcxx/include/regex
@@ -763,15 +763,18 @@ typedef regex_token_iterator<wstring::const_iterator> wsregex_token_iterator;
 */
 
 #include <__config>
-#include <stdexcept>
+#include <__debug>
+#include <__iterator/wrap_iter.h>
 #include <__locale>
+#include <compare>
+#include <deque>
 #include <initializer_list>
-#include <utility>
 #include <iterator>
-#include <string>
 #include <memory>
+#include <stdexcept>
+#include <string>
+#include <utility>
 #include <vector>
-#include <deque>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -2000,14 +2003,14 @@ class __l_anchor_multiline
 {
     typedef __owns_one_state<_CharT> base;
 
-    bool __multiline;
+    bool __multiline_;
 
 public:
     typedef _VSTD::__state<_CharT> __state;
 
     _LIBCPP_INLINE_VISIBILITY
     __l_anchor_multiline(bool __multiline, __node<_CharT>* __s)
-        : base(__s), __multiline(__multiline) {}
+        : base(__s), __multiline_(__multiline) {}
 
     virtual void __exec(__state&) const;
 };
@@ -2022,7 +2025,7 @@ __l_anchor_multiline<_CharT>::__exec(__state& __s) const
         __s.__do_ = __state::__accept_but_not_consume;
         __s.__node_ = this->first();
     }
-    else if (__multiline &&
+    else if (__multiline_ &&
              !__s.__at_first_ &&
              __is_eol(*_VSTD::prev(__s.__current_)))
     {
@@ -2634,7 +2637,7 @@ public:
         {
         __init(__il.begin(), __il.end());
         }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 //    ~basic_regex() = default;
 
@@ -2647,7 +2650,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     basic_regex& operator=(initializer_list<value_type> __il)
         {return assign(__il);}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     template <class _ST, class _SA>
         _LIBCPP_INLINE_VISIBILITY
         basic_regex& operator=(const basic_string<value_type, _ST, _SA>& __p)
@@ -2721,7 +2724,7 @@ public:
                         flag_type __f = regex_constants::ECMAScript)
         {return assign(__il.begin(), __il.end(), __f);}
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     // const operations:
     _LIBCPP_INLINE_VISIBILITY
@@ -4571,7 +4574,7 @@ basic_regex<_CharT, _Traits>::__parse_character_escape(_ForwardIterator __first,
             if (__hd == -1)
                 __throw_regex_error<regex_constants::error_escape>();
             __sum = 16 * __sum + static_cast<unsigned>(__hd);
-            // drop through
+            // fallthrough
         case 'x':
             ++__first;
             if (__first == __last)
@@ -5882,7 +5885,6 @@ basic_regex<_CharT, _Traits>::__match_at_start_posix_subs(
 {
     vector<__state> __states;
     __state __best_state;
-    ptrdiff_t __j = 0;
     ptrdiff_t __highest_j = 0;
     ptrdiff_t _Np = _VSTD::distance(__first, __last);
     __node* __st = __start_.get();
@@ -5903,7 +5905,6 @@ basic_regex<_CharT, _Traits>::__match_at_start_posix_subs(
         __states.back().__node_ = __st;
         __states.back().__flags_ = __flags;
         __states.back().__at_first_ = __at_first;
-        const _CharT* __current = __first;
         bool __matched = false;
         int __counter = 0;
         int __length = __last - __first;
@@ -5943,9 +5944,6 @@ basic_regex<_CharT, _Traits>::__match_at_start_posix_subs(
                     __states.pop_back();
                 break;
             case __state::__accept_and_consume:
-                __j += __s.__current_ - __current;
-                __current = __s.__current_;
-                break;
             case __state::__repeat:
             case __state::__accept_but_not_consume:
                 break;
@@ -6442,7 +6440,7 @@ public:
                          regex_constants::match_flag_type __m =
                                        regex_constants::match_default) = delete;
 #endif
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     template <size_t _Np>
         regex_token_iterator(_BidirectionalIterator __a,
                              _BidirectionalIterator __b,
@@ -6557,7 +6555,7 @@ regex_token_iterator<_BidirectionalIterator, _CharT, _Traits>::
     __init(__a, __b);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _BidirectionalIterator, class _CharT, class _Traits>
 template <size_t _Np>
@@ -6774,4 +6772,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_REGEX
+#endif // _LIBCPP_REGEX
lib/libcxx/include/scoped_allocator
@@ -106,6 +106,7 @@ template <class OuterA1, class OuterA2, class... InnerAllocs>
 */
 
 #include <__config>
+#include <__utility/forward.h>
 #include <memory>
 #include <version>
 
@@ -375,7 +376,7 @@ struct __outermost<_Alloc, true>
 {
     typedef typename remove_reference
                      <
-                        decltype(_VSTD::declval<_Alloc>().outer_allocator())
+                        decltype(declval<_Alloc>().outer_allocator())
                      >::type                                    _OuterAlloc;
     typedef typename __outermost<_OuterAlloc>::type             type;
     _LIBCPP_INLINE_VISIBILITY
@@ -676,8 +677,8 @@ operator!=(const scoped_allocator_adaptor<_OuterA1, _InnerAllocs...>& __a,
     return !(__a == __b);
 }
 
-#endif  // !defined(_LIBCPP_CXX03_LANG)
+#endif // !defined(_LIBCPP_CXX03_LANG)
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_SCOPED_ALLOCATOR
+#endif // _LIBCPP_SCOPED_ALLOCATOR
lib/libcxx/include/semaphore
@@ -45,8 +45,8 @@ using binary_semaphore = counting_semaphore<1>;
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <__threading_support>
 #include <atomic>
 
@@ -98,7 +98,7 @@ public:
     _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
     void acquire()
     {
-        auto const __test_fn = [=]() -> bool {
+        auto const __test_fn = [this]() -> bool {
             auto __old = __a.load(memory_order_relaxed);
             return (__old != 0) && __a.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed);
         };
@@ -108,7 +108,7 @@ public:
     _LIBCPP_AVAILABILITY_SYNC _LIBCPP_INLINE_VISIBILITY
     bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time)
     {
-        auto const __test_fn = [=]() -> bool {
+        auto const __test_fn = [this]() -> bool {
             auto __old = __a.load(memory_order_acquire);
             while(1) {
                 if (__old == 0)
lib/libcxx/include/set
@@ -154,10 +154,14 @@ public:
         iterator find(const K& x);
     template<typename K>
         const_iterator find(const K& x) const;  // C++14
+
     template<typename K>
         size_type count(const K& x) const;        // C++14
     size_type      count(const key_type& k) const;
-        bool contains(const key_type& x) const; // C++20
+
+    bool           contains(const key_type& x) const;  // C++20
+    template<class K> bool contains(const K& x) const; // C++20
+
           iterator lower_bound(const key_type& k);
     const_iterator lower_bound(const key_type& k) const;
     template<typename K>
@@ -355,10 +359,14 @@ public:
         iterator find(const K& x);
     template<typename K>
         const_iterator find(const K& x) const;  // C++14
+
     template<typename K>
         size_type count(const K& x) const;      // C++14
     size_type      count(const key_type& k) const;
-        bool contains(const key_type& x) const; // C++20
+
+    bool           contains(const key_type& x) const;  // C++20
+    template<class K> bool contains(const K& x) const; // C++20
+
           iterator lower_bound(const key_type& k);
     const_iterator lower_bound(const key_type& k) const;
     template<typename K>
@@ -426,9 +434,15 @@ erase_if(multiset<Key, Compare, Allocator>& c, Predicate pred);  // C++20
 */
 
 #include <__config>
-#include <__tree>
+#include <__debug>
+#include <__functional/is_transparent.h>
 #include <__node_handle>
+#include <__tree>
+#include <__utility/forward.h>
+#include <compare>
 #include <functional>
+#include <initializer_list>
+#include <iterator> // __libcpp_erase_if_container
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -450,7 +464,7 @@ public:
     typedef key_type                                 value_type;
     typedef _Compare                                 key_compare;
     typedef key_compare                              value_compare;
-    typedef typename __identity<_Allocator>::type    allocator_type;
+    typedef __identity_t<_Allocator>                 allocator_type;
     typedef value_type&                              reference;
     typedef const value_type&                        const_reference;
 
@@ -546,7 +560,7 @@ public:
     set(set&& __s)
         _NOEXCEPT_(is_nothrow_move_constructible<__base>::value)
         : __tree_(_VSTD::move(__s.__tree_)) {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     explicit set(const allocator_type& __a)
@@ -597,7 +611,7 @@ public:
             __tree_ = _VSTD::move(__s.__tree_);
             return *this;
         }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     ~set() {
@@ -652,7 +666,7 @@ public:
         _LIBCPP_INLINE_VISIBILITY
         iterator emplace_hint(const_iterator __p, _Args&&... __args)
             {return __tree_.__emplace_hint_unique(__p, _VSTD::forward<_Args>(__args)...);}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     pair<iterator,bool> insert(const value_type& __v)
@@ -681,7 +695,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     void insert(initializer_list<value_type> __il)
         {insert(__il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     iterator  erase(const_iterator __p) {return __tree_.erase(__p);}
@@ -795,6 +809,10 @@ public:
 #if _LIBCPP_STD_VER > 17
     _LIBCPP_INLINE_VISIBILITY
     bool contains(const key_type& __k) const {return find(__k) != end();}
+    template <typename _K2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename enable_if<__is_transparent<_Compare, _K2>::value, bool>::type
+    contains(const _K2& __k) const { return find(__k) != end(); }
 #endif // _LIBCPP_STD_VER > 17
 
     _LIBCPP_INLINE_VISIBILITY
@@ -852,12 +870,12 @@ public:
 
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template<class _InputIterator,
-         class _Compare = less<typename iterator_traits<_InputIterator>::value_type>,
-         class _Allocator = allocator<typename iterator_traits<_InputIterator>::value_type>,
+         class _Compare = less<__iter_value_type<_InputIterator>>,
+         class _Allocator = allocator<__iter_value_type<_InputIterator>>,
          class = _EnableIf<__is_allocator<_Allocator>::value, void>,
          class = _EnableIf<!__is_allocator<_Compare>::value, void>>
 set(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator())
-  -> set<typename iterator_traits<_InputIterator>::value_type, _Compare, _Allocator>;
+  -> set<__iter_value_type<_InputIterator>, _Compare, _Allocator>;
 
 template<class _Key, class _Compare = less<_Key>,
          class _Allocator = allocator<_Key>,
@@ -869,8 +887,8 @@ set(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator())
 template<class _InputIterator, class _Allocator,
          class = _EnableIf<__is_allocator<_Allocator>::value, void>>
 set(_InputIterator, _InputIterator, _Allocator)
-  -> set<typename iterator_traits<_InputIterator>::value_type,
-         less<typename iterator_traits<_InputIterator>::value_type>, _Allocator>;
+  -> set<__iter_value_type<_InputIterator>,
+         less<__iter_value_type<_InputIterator>>, _Allocator>;
 
 template<class _Key, class _Allocator,
          class = _EnableIf<__is_allocator<_Allocator>::value, void>>
@@ -892,7 +910,7 @@ set<_Key, _Compare, _Allocator>::set(set&& __s, const allocator_type& __a)
     }
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Key, class _Compare, class _Allocator>
 inline _LIBCPP_INLINE_VISIBILITY
@@ -964,7 +982,7 @@ template <class _Key, class _Compare, class _Allocator, class _Predicate>
 inline _LIBCPP_INLINE_VISIBILITY
     typename set<_Key, _Compare, _Allocator>::size_type
     erase_if(set<_Key, _Compare, _Allocator>& __c, _Predicate __pred) {
-  return __libcpp_erase_if_container(__c, __pred);
+  return _VSTD::__libcpp_erase_if_container(__c, __pred);
 }
 #endif
 
@@ -974,11 +992,11 @@ class _LIBCPP_TEMPLATE_VIS multiset
 {
 public:
     // types:
-    typedef _Key                                      key_type;
+    typedef _Key                                     key_type;
     typedef key_type                                 value_type;
-    typedef _Compare                                  key_compare;
+    typedef _Compare                                 key_compare;
     typedef key_compare                              value_compare;
-    typedef typename __identity<_Allocator>::type    allocator_type;
+    typedef __identity_t<_Allocator>                 allocator_type;
     typedef value_type&                              reference;
     typedef const value_type&                        const_reference;
 
@@ -1077,7 +1095,7 @@ public:
         : __tree_(_VSTD::move(__s.__tree_)) {}
 
     multiset(multiset&& __s, const allocator_type& __a);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     explicit multiset(const allocator_type& __a)
         : __tree_(__a) {}
@@ -1124,7 +1142,7 @@ public:
             __tree_ = _VSTD::move(__s.__tree_);
             return *this;
         }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     ~multiset() {
@@ -1179,7 +1197,7 @@ public:
         _LIBCPP_INLINE_VISIBILITY
         iterator emplace_hint(const_iterator __p, _Args&&... __args)
             {return __tree_.__emplace_hint_multi(__p, _VSTD::forward<_Args>(__args)...);}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     iterator insert(const value_type& __v)
@@ -1208,7 +1226,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     void insert(initializer_list<value_type> __il)
         {insert(__il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     iterator  erase(const_iterator __p) {return __tree_.erase(__p);}
@@ -1301,11 +1319,11 @@ public:
 #if _LIBCPP_STD_VER > 11
     template <typename _K2>
     _LIBCPP_INLINE_VISIBILITY
-    typename _VSTD::enable_if<_VSTD::__is_transparent<_Compare, _K2>::value,iterator>::type
+    typename enable_if<__is_transparent<_Compare, _K2>::value,iterator>::type
     find(const _K2& __k)                           {return __tree_.find(__k);}
     template <typename _K2>
     _LIBCPP_INLINE_VISIBILITY
-    typename _VSTD::enable_if<_VSTD::__is_transparent<_Compare, _K2>::value,const_iterator>::type
+    typename enable_if<__is_transparent<_Compare, _K2>::value,const_iterator>::type
     find(const _K2& __k) const                     {return __tree_.find(__k);}
 #endif
 
@@ -1322,6 +1340,10 @@ public:
 #if _LIBCPP_STD_VER > 17
     _LIBCPP_INLINE_VISIBILITY
     bool contains(const key_type& __k) const {return find(__k) != end();}
+    template <typename _K2>
+    _LIBCPP_INLINE_VISIBILITY
+    typename enable_if<__is_transparent<_Compare, _K2>::value, bool>::type
+    contains(const _K2& __k) const { return find(__k) != end(); }
 #endif // _LIBCPP_STD_VER > 17
 
     _LIBCPP_INLINE_VISIBILITY
@@ -1333,12 +1355,12 @@ public:
 #if _LIBCPP_STD_VER > 11
     template <typename _K2>
     _LIBCPP_INLINE_VISIBILITY
-    typename _VSTD::enable_if<_VSTD::__is_transparent<_Compare, _K2>::value,iterator>::type
+    typename enable_if<__is_transparent<_Compare, _K2>::value,iterator>::type
     lower_bound(const _K2& __k)       {return __tree_.lower_bound(__k);}
 
     template <typename _K2>
     _LIBCPP_INLINE_VISIBILITY
-    typename _VSTD::enable_if<_VSTD::__is_transparent<_Compare, _K2>::value,const_iterator>::type
+    typename enable_if<__is_transparent<_Compare, _K2>::value,const_iterator>::type
     lower_bound(const _K2& __k) const {return __tree_.lower_bound(__k);}
 #endif
 
@@ -1351,11 +1373,11 @@ public:
 #if _LIBCPP_STD_VER > 11
     template <typename _K2>
     _LIBCPP_INLINE_VISIBILITY
-    typename _VSTD::enable_if<_VSTD::__is_transparent<_Compare, _K2>::value,iterator>::type
+    typename enable_if<__is_transparent<_Compare, _K2>::value,iterator>::type
     upper_bound(const _K2& __k)       {return __tree_.upper_bound(__k);}
     template <typename _K2>
     _LIBCPP_INLINE_VISIBILITY
-    typename _VSTD::enable_if<_VSTD::__is_transparent<_Compare, _K2>::value,const_iterator>::type
+    typename enable_if<__is_transparent<_Compare, _K2>::value,const_iterator>::type
     upper_bound(const _K2& __k) const {return __tree_.upper_bound(__k);}
 #endif
 
@@ -1368,23 +1390,23 @@ public:
 #if _LIBCPP_STD_VER > 11
     template <typename _K2>
     _LIBCPP_INLINE_VISIBILITY
-    typename _VSTD::enable_if<_VSTD::__is_transparent<_Compare, _K2>::value,pair<iterator,iterator>>::type
+    typename enable_if<__is_transparent<_Compare, _K2>::value,pair<iterator,iterator>>::type
     equal_range(const _K2& __k)       {return __tree_.__equal_range_multi(__k);}
     template <typename _K2>
     _LIBCPP_INLINE_VISIBILITY
-    typename _VSTD::enable_if<_VSTD::__is_transparent<_Compare, _K2>::value,pair<const_iterator,const_iterator>>::type
+    typename enable_if<__is_transparent<_Compare, _K2>::value,pair<const_iterator,const_iterator>>::type
     equal_range(const _K2& __k) const {return __tree_.__equal_range_multi(__k);}
 #endif
 };
 
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template<class _InputIterator,
-         class _Compare = less<typename iterator_traits<_InputIterator>::value_type>,
-         class _Allocator = allocator<typename iterator_traits<_InputIterator>::value_type>,
+         class _Compare = less<__iter_value_type<_InputIterator>>,
+         class _Allocator = allocator<__iter_value_type<_InputIterator>>,
          class = _EnableIf<__is_allocator<_Allocator>::value, void>,
          class = _EnableIf<!__is_allocator<_Compare>::value, void>>
 multiset(_InputIterator, _InputIterator, _Compare = _Compare(), _Allocator = _Allocator())
-  -> multiset<typename iterator_traits<_InputIterator>::value_type, _Compare, _Allocator>;
+  -> multiset<__iter_value_type<_InputIterator>, _Compare, _Allocator>;
 
 template<class _Key, class _Compare = less<_Key>,
          class _Allocator = allocator<_Key>,
@@ -1396,8 +1418,8 @@ multiset(initializer_list<_Key>, _Compare = _Compare(), _Allocator = _Allocator(
 template<class _InputIterator, class _Allocator,
          class = _EnableIf<__is_allocator<_Allocator>::value, void>>
 multiset(_InputIterator, _InputIterator, _Allocator)
-  -> multiset<typename iterator_traits<_InputIterator>::value_type,
-         less<typename iterator_traits<_InputIterator>::value_type>, _Allocator>;
+  -> multiset<__iter_value_type<_InputIterator>,
+         less<__iter_value_type<_InputIterator>>, _Allocator>;
 
 template<class _Key, class _Allocator,
          class = _EnableIf<__is_allocator<_Allocator>::value, void>>
@@ -1419,7 +1441,7 @@ multiset<_Key, _Compare, _Allocator>::multiset(multiset&& __s, const allocator_t
     }
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Key, class _Compare, class _Allocator>
 inline _LIBCPP_INLINE_VISIBILITY
@@ -1490,10 +1512,10 @@ template <class _Key, class _Compare, class _Allocator, class _Predicate>
 inline _LIBCPP_INLINE_VISIBILITY
     typename multiset<_Key, _Compare, _Allocator>::size_type
     erase_if(multiset<_Key, _Compare, _Allocator>& __c, _Predicate __pred) {
-  return __libcpp_erase_if_container(__c, __pred);
+  return _VSTD::__libcpp_erase_if_container(__c, __pred);
 }
 #endif
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_SET
+#endif // _LIBCPP_SET
lib/libcxx/include/setjmp.h
@@ -41,4 +41,4 @@ void longjmp(jmp_buf env, int val);
 
 #endif // __cplusplus
 
-#endif  // _LIBCPP_SETJMP_H
+#endif // _LIBCPP_SETJMP_H
lib/libcxx/include/shared_mutex
@@ -122,8 +122,8 @@ template <class Mutex>
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
 #include <version>
 
 _LIBCPP_PUSH_MACROS
@@ -500,10 +500,10 @@ swap(shared_lock<_Mutex>& __x, shared_lock<_Mutex>& __y) _NOEXCEPT
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // !_LIBCPP_HAS_NO_THREADS
+#endif // !_LIBCPP_HAS_NO_THREADS
 
-#endif  // _LIBCPP_STD_VER > 11
+#endif // _LIBCPP_STD_VER > 11
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_SHARED_MUTEX
+#endif // _LIBCPP_SHARED_MUTEX
lib/libcxx/include/span
@@ -22,6 +22,12 @@ inline constexpr size_t dynamic_extent = numeric_limits<size_t>::max();
 template <class ElementType, size_t Extent = dynamic_extent>
     class span;
 
+template<class ElementType, size_t Extent>
+  inline constexpr bool ranges::enable_view<span<ElementType, Extent>> = true;
+
+template<class ElementType, size_t Extent>
+    inline constexpr bool ranges::enable_borrowed_range<span<ElementType, Extent>> = true;
+
 // [span.objectrep], views of object representation
 template <class ElementType, size_t Extent>
     span<const byte, ((Extent == dynamic_extent) ? dynamic_extent :
@@ -32,7 +38,6 @@ template <class ElementType, size_t Extent>
         (sizeof(ElementType) * Extent))> as_writable_bytes(span<ElementType, Extent> s) noexcept;
 
 
-namespace std {
 template <class ElementType, size_t Extent = dynamic_extent>
 class span {
 public:
@@ -123,10 +128,16 @@ template<class Container>
 */
 
 #include <__config>
+#include <__debug>
+#include <__iterator/wrap_iter.h>
+#include <__ranges/enable_borrowed_range.h>
+#include <__ranges/enable_view.h>
 #include <array>        // for array
 #include <cstddef>      // for byte
 #include <iterator>     // for iterators
+#include <limits>
 #include <type_traits>  // for remove_cv, etc
+#include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -197,7 +208,11 @@ public:
     using const_pointer          = const _Tp *;
     using reference              = _Tp &;
     using const_reference        = const _Tp &;
-    using iterator               =  __wrap_iter<pointer>;
+#if (_LIBCPP_DEBUG_LEVEL == 2) || defined(_LIBCPP_ABI_SPAN_POINTER_ITERATORS)
+    using iterator               = pointer;
+#else
+    using iterator               = __wrap_iter<pointer>;
+#endif
     using reverse_iterator       = _VSTD::reverse_iterator<iterator>;
 
     static constexpr size_type extent = _Extent;
@@ -372,7 +387,11 @@ public:
     using const_pointer          = const _Tp *;
     using reference              = _Tp &;
     using const_reference        = const _Tp &;
-    using iterator               =  __wrap_iter<pointer>;
+#if (_LIBCPP_DEBUG_LEVEL == 2) || defined(_LIBCPP_ABI_SPAN_POINTER_ITERATORS)
+    using iterator               = pointer;
+#else
+    using iterator               = __wrap_iter<pointer>;
+#endif
     using reverse_iterator       = _VSTD::reverse_iterator<iterator>;
 
     static constexpr size_type extent = dynamic_extent;
@@ -516,6 +535,14 @@ private:
     size_type __size;
 };
 
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+template <class _Tp, size_t _Extent>
+inline constexpr bool ranges::enable_borrowed_range<span<_Tp, _Extent> > = true;
+
+template <class _ElementType, size_t _Extent>
+inline constexpr bool ranges::enable_view<span<_ElementType, _Extent>> = true;
+#endif // !defined(_LIBCPP_HAS_NO_RANGES)
+
 //  as_bytes & as_writable_bytes
 template <class _Tp, size_t _Extent>
 _LIBCPP_INLINE_VISIBILITY
lib/libcxx/include/sstream
@@ -181,8 +181,8 @@ typedef basic_stringstream<wchar_t> wstringstream;
 */
 
 #include <__config>
-#include <ostream>
 #include <istream>
+#include <ostream>
 #include <string>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -219,19 +219,13 @@ private:
 
 public:
     // 30.8.2.1 [stringbuf.cons], constructors
-#ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
-    basic_stringbuf() : basic_stringbuf(ios_base::in | ios_base::out) {}
+    basic_stringbuf()
+        : __hm_(nullptr), __mode_(ios_base::in | ios_base::out) {}
 
     _LIBCPP_INLINE_VISIBILITY
     explicit basic_stringbuf(ios_base::openmode __wch)
         : __hm_(nullptr), __mode_(__wch) {}
-#else
-    _LIBCPP_INLINE_VISIBILITY
-    explicit basic_stringbuf(ios_base::openmode __wch = ios_base::in |
-                                                        ios_base::out)
-        : __hm_(nullptr), __mode_(__wch) {}
-#endif
 
     _LIBCPP_INLINE_VISIBILITY
     explicit basic_stringbuf(const string_type& __s,
@@ -542,7 +536,7 @@ basic_stringbuf<_CharT, _Traits, _Allocator>::overflow(int_type __c)
 #ifndef _LIBCPP_NO_EXCEPTIONS
             try
             {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
                 ptrdiff_t __nout = this->pptr()  - this->pbase();
                 ptrdiff_t __hm = __hm_ - this->pbase();
                 __str_.push_back(char_type());
@@ -557,7 +551,7 @@ basic_stringbuf<_CharT, _Traits, _Allocator>::overflow(int_type __c)
             {
                 return traits_type::eof();
             }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         }
         __hm_ = _VSTD::max(this->pptr() + 1, __hm_);
         if (__mode_ & ios_base::in)
@@ -643,18 +637,13 @@ private:
 
 public:
     // 30.8.3.1 [istringstream.cons], constructors
-#ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
-    basic_istringstream() : basic_istringstream(ios_base::in) {}
+    basic_istringstream()
+        : basic_istream<_CharT, _Traits>(&__sb_), __sb_(ios_base::in) {}
 
     _LIBCPP_INLINE_VISIBILITY
     explicit basic_istringstream(ios_base::openmode __wch)
         : basic_istream<_CharT, _Traits>(&__sb_), __sb_(__wch | ios_base::in) {}
-#else
-    _LIBCPP_INLINE_VISIBILITY
-    explicit basic_istringstream(ios_base::openmode __wch = ios_base::in)
-        : basic_istream<_CharT, _Traits>(&__sb_), __sb_(__wch | ios_base::in) {}
-#endif
 
     _LIBCPP_INLINE_VISIBILITY
     explicit basic_istringstream(const string_type& __s,
@@ -728,20 +717,13 @@ private:
 
 public:
     // 30.8.4.1 [ostringstream.cons], constructors
-#ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
-    basic_ostringstream() : basic_ostringstream(ios_base::out) {}
+    basic_ostringstream()
+        : basic_ostream<_CharT, _Traits>(&__sb_), __sb_(ios_base::out) {}
 
     _LIBCPP_INLINE_VISIBILITY
     explicit basic_ostringstream(ios_base::openmode __wch)
-        : basic_ostream<_CharT, _Traits>(&__sb_),
-          __sb_(__wch | ios_base::out) {}
-#else
-    _LIBCPP_INLINE_VISIBILITY
-    explicit basic_ostringstream(ios_base::openmode __wch = ios_base::out)
-        : basic_ostream<_CharT, _Traits>(&__sb_),
-          __sb_(__wch | ios_base::out) {}
-#endif
+        : basic_ostream<_CharT, _Traits>(&__sb_), __sb_(__wch | ios_base::out) {}
 
     _LIBCPP_INLINE_VISIBILITY
     explicit basic_ostringstream(const string_type& __s,
@@ -816,19 +798,13 @@ private:
 
 public:
     // 30.8.5.1 [stringstream.cons], constructors
-#ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
-    basic_stringstream() : basic_stringstream(ios_base::in | ios_base::out) {}
+    basic_stringstream()
+        : basic_iostream<_CharT, _Traits>(&__sb_), __sb_(ios_base::in | ios_base::out) {}
 
     _LIBCPP_INLINE_VISIBILITY
     explicit basic_stringstream(ios_base::openmode __wch)
         : basic_iostream<_CharT, _Traits>(&__sb_), __sb_(__wch) {}
-#else
-    _LIBCPP_INLINE_VISIBILITY
-    explicit basic_stringstream(ios_base::openmode __wch = ios_base::in |
-                                                           ios_base::out)
-        : basic_iostream<_CharT, _Traits>(&__sb_), __sb_(__wch) {}
-#endif
 
     _LIBCPP_INLINE_VISIBILITY
     explicit basic_stringstream(const string_type& __s,
@@ -892,4 +868,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_SSTREAM
+#endif // _LIBCPP_SSTREAM
lib/libcxx/include/stack
@@ -88,6 +88,8 @@ template <class T, class Container>
 */
 
 #include <__config>
+#include <__memory/uses_allocator.h>
+#include <__utility/forward.h>
 #include <deque>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -148,7 +150,7 @@ public:
 
     _LIBCPP_INLINE_VISIBILITY
     explicit stack(container_type&& __c) : c(_VSTD::move(__c)) {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     explicit stack(const container_type& __c) : c(__c) {}
@@ -156,35 +158,30 @@ public:
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         explicit stack(const _Alloc& __a,
-                       typename enable_if<uses_allocator<container_type,
-                                                         _Alloc>::value>::type* = 0)
+                       _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(__a) {}
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         stack(const container_type& __c, const _Alloc& __a,
-              typename enable_if<uses_allocator<container_type,
-                                                _Alloc>::value>::type* = 0)
+              _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(__c, __a) {}
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         stack(const stack& __s, const _Alloc& __a,
-              typename enable_if<uses_allocator<container_type,
-                                                _Alloc>::value>::type* = 0)
+              _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(__s.c, __a) {}
 #ifndef _LIBCPP_CXX03_LANG
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         stack(container_type&& __c, const _Alloc& __a,
-              typename enable_if<uses_allocator<container_type,
-                                                _Alloc>::value>::type* = 0)
+              _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(_VSTD::move(__c), __a) {}
     template <class _Alloc>
         _LIBCPP_INLINE_VISIBILITY
         stack(stack&& __s, const _Alloc& __a,
-              typename enable_if<uses_allocator<container_type,
-                                                _Alloc>::value>::type* = 0)
+              _EnableIf<uses_allocator<container_type, _Alloc>::value>* = 0)
             : c(_VSTD::move(__s.c), __a) {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_NODISCARD_AFTER_CXX17 _LIBCPP_INLINE_VISIBILITY
     bool empty()     const      {return c.empty();}
@@ -210,7 +207,7 @@ public:
         void      emplace(_Args&&... __args)
         {        c.emplace_back(_VSTD::forward<_Args>(__args)...);}
 #endif
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     void pop() {c.pop_back();}
@@ -236,15 +233,15 @@ public:
 
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template<class _Container,
-         class = typename enable_if<!__is_allocator<_Container>::value, nullptr_t>::type
+         class = _EnableIf<!__is_allocator<_Container>::value>
 >
 stack(_Container)
     -> stack<typename _Container::value_type, _Container>;
 
 template<class _Container,
          class _Alloc,
-         class = typename enable_if<!__is_allocator<_Container>::value, nullptr_t>::type,
-         class = typename enable_if< __is_allocator<_Alloc>::value, nullptr_t>::type
+         class = _EnableIf<!__is_allocator<_Container>::value>,
+         class = _EnableIf<uses_allocator<_Container, _Alloc>::value>
          >
 stack(_Container, _Alloc)
     -> stack<typename _Container::value_type, _Container>;
@@ -300,10 +297,7 @@ operator<=(const stack<_Tp, _Container>& __x, const stack<_Tp, _Container>& __y)
 
 template <class _Tp, class _Container>
 inline _LIBCPP_INLINE_VISIBILITY
-typename enable_if<
-    __is_swappable<_Container>::value,
-    void
->::type
+_EnableIf<__is_swappable<_Container>::value, void>
 swap(stack<_Tp, _Container>& __x, stack<_Tp, _Container>& __y)
     _NOEXCEPT_(_NOEXCEPT_(__x.swap(__y)))
 {
@@ -318,4 +312,4 @@ struct _LIBCPP_TEMPLATE_VIS uses_allocator<stack<_Tp, _Container>, _Alloc>
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_STACK
+#endif // _LIBCPP_STACK
lib/libcxx/include/stdbool.h
@@ -35,4 +35,4 @@ Macros:
 #define __bool_true_false_are_defined 1
 #endif
 
-#endif  // _LIBCPP_STDBOOL_H
+#endif // _LIBCPP_STDBOOL_H
lib/libcxx/include/stddef.h
@@ -53,4 +53,4 @@ using std::nullptr_t;
 
 #endif
 
-#endif  // _LIBCPP_STDDEF_H
+#endif // _LIBCPP_STDDEF_H
lib/libcxx/include/stdexcept
@@ -42,9 +42,9 @@ public:
 */
 
 #include <__config>
-#include <cstdlib>
 #include <exception>
 #include <iosfwd>  // for string forward decl
+#include <cstdlib>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -306,4 +306,4 @@ void __throw_underflow_error(const char*__msg)
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_STDEXCEPT
+#endif // _LIBCPP_STDEXCEPT
lib/libcxx/include/stdint.h
@@ -122,4 +122,4 @@ Macros:
 
 #include_next <stdint.h>
 
-#endif  // _LIBCPP_STDINT_H
+#endif // _LIBCPP_STDINT_H
lib/libcxx/include/stdio.h
@@ -116,4 +116,4 @@ void perror(const char* s);
 
 #endif
 
-#endif  // _LIBCPP_STDIO_H
+#endif // _LIBCPP_STDIO_H
lib/libcxx/include/stdlib.h
@@ -103,7 +103,7 @@ extern "C++" {
 #endif
 
 // MSVCRT already has the correct prototype in <stdlib.h> if __cplusplus is defined
-#if !defined(_LIBCPP_MSVCRT) && !defined(__sun__) && !defined(_AIX)
+#if !defined(_LIBCPP_MSVCRT) && !defined(__sun__)
 inline _LIBCPP_INLINE_VISIBILITY long abs(long __x) _NOEXCEPT {
   return __builtin_labs(__x);
 }
@@ -112,9 +112,9 @@ inline _LIBCPP_INLINE_VISIBILITY long long abs(long long __x) _NOEXCEPT {
   return __builtin_llabs(__x);
 }
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-#endif // !defined(_LIBCPP_MSVCRT) && !defined(__sun__) && !defined(_AIX)
+#endif // !defined(_LIBCPP_MSVCRT) && !defined(__sun__)
 
-#if !(defined(_AIX) || defined(__sun__))
+#if !defined(__sun__)
 inline _LIBCPP_INLINE_VISIBILITY float abs(float __lcpp_x) _NOEXCEPT {
   return __builtin_fabsf(__lcpp_x); // Use builtins to prevent needing math.h
 }
@@ -127,7 +127,7 @@ inline _LIBCPP_INLINE_VISIBILITY long double
 abs(long double __lcpp_x) _NOEXCEPT {
   return __builtin_fabsl(__lcpp_x);
 }
-#endif // !(defined(_AIX) || defined(__sun__))
+#endif // !defined(__sun__)
 
 // div
 
@@ -138,7 +138,7 @@ abs(long double __lcpp_x) _NOEXCEPT {
 #endif
 
 // MSVCRT already has the correct prototype in <stdlib.h> if __cplusplus is defined
-#if !defined(_LIBCPP_MSVCRT) && !defined(__sun__) && !defined(_AIX)
+#if !defined(_LIBCPP_MSVCRT) && !defined(__sun__)
 inline _LIBCPP_INLINE_VISIBILITY ldiv_t div(long __x, long __y) _NOEXCEPT {
   return ::ldiv(__x, __y);
 }
@@ -148,8 +148,8 @@ inline _LIBCPP_INLINE_VISIBILITY lldiv_t div(long long __x,
   return ::lldiv(__x, __y);
 }
 #endif // _LIBCPP_HAS_NO_LONG_LONG
-#endif // _LIBCPP_MSVCRT / __sun__ / _AIX
+#endif // _LIBCPP_MSVCRT / __sun__
 } // extern "C++"
-#endif  // __cplusplus
+#endif // __cplusplus
 
-#endif  // _LIBCPP_STDLIB_H
+#endif // _LIBCPP_STDLIB_H
lib/libcxx/include/streambuf
@@ -7,8 +7,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef _LIBCPP_STEAMBUF
-#define _LIBCPP_STEAMBUF
+#ifndef _LIBCPP_STREAMBUF
+#define _LIBCPP_STREAMBUF
 
 /*
     streambuf synopsis
@@ -108,8 +108,8 @@ protected:
 */
 
 #include <__config>
-#include <iosfwd>
 #include <ios>
+#include <iosfwd>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -495,4 +495,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_STEAMBUF
+#endif // _LIBCPP_STREAMBUF
lib/libcxx/include/string
@@ -69,6 +69,9 @@ struct char_traits
 
 template <> struct char_traits<char>;
 template <> struct char_traits<wchar_t>;
+template <> struct char_traits<char8_t>;  // C++20
+template <> struct char_traits<char16_t>;
+template <> struct char_traits<char32_t>;
 
 template<class charT, class traits = char_traits<charT>, class Allocator = allocator<charT> >
 class basic_string
@@ -107,6 +110,7 @@ public:
         explicit basic_string(const T& t, const Allocator& a = Allocator()); // C++17
     basic_string(const value_type* s, const allocator_type& a = allocator_type());
     basic_string(const value_type* s, size_type n, const allocator_type& a = allocator_type());
+    basic_string(nullptr_t) = delete; // C++2b
     basic_string(size_type n, value_type c, const allocator_type& a = allocator_type());
     template<class InputIterator>
         basic_string(InputIterator begin, InputIterator end,
@@ -127,6 +131,7 @@ public:
              allocator_type::propagate_on_container_move_assignment::value ||
              allocator_type::is_always_equal::value ); // C++17
     basic_string& operator=(const value_type* s);
+    basic_string& operator=(nullptr_t) = delete; // C++2b
     basic_string& operator=(value_type c);
     basic_string& operator=(initializer_list<value_type>);
 
@@ -262,49 +267,49 @@ public:
 
     size_type find(const basic_string& str, size_type pos = 0) const noexcept;
     template <class T>
-        size_type find(const T& t, size_type pos = 0) const;  // C++17
+        size_type find(const T& t, size_type pos = 0) const noexcept; // C++17, noexcept as an extension
     size_type find(const value_type* s, size_type pos, size_type n) const noexcept;
     size_type find(const value_type* s, size_type pos = 0) const noexcept;
     size_type find(value_type c, size_type pos = 0) const noexcept;
 
     size_type rfind(const basic_string& str, size_type pos = npos) const noexcept;
     template <class T>
-        size_type rfind(const T& t, size_type pos = npos) const;  // C++17
+        size_type rfind(const T& t, size_type pos = npos) const noexcept; // C++17, noexcept as an extension
     size_type rfind(const value_type* s, size_type pos, size_type n) const noexcept;
     size_type rfind(const value_type* s, size_type pos = npos) const noexcept;
     size_type rfind(value_type c, size_type pos = npos) const noexcept;
 
     size_type find_first_of(const basic_string& str, size_type pos = 0) const noexcept;
     template <class T>
-        size_type find_first_of(const T& t, size_type pos = 0) const; // C++17
+        size_type find_first_of(const T& t, size_type pos = 0) const noexcept; // C++17, noexcept as an extension
     size_type find_first_of(const value_type* s, size_type pos, size_type n) const noexcept;
     size_type find_first_of(const value_type* s, size_type pos = 0) const noexcept;
     size_type find_first_of(value_type c, size_type pos = 0) const noexcept;
 
     size_type find_last_of(const basic_string& str, size_type pos = npos) const noexcept;
     template <class T>
-        size_type find_last_of(const T& t, size_type pos = npos) const noexcept;  // C++17
+        size_type find_last_of(const T& t, size_type pos = npos) const noexcept noexcept; // C++17, noexcept as an extension
     size_type find_last_of(const value_type* s, size_type pos, size_type n) const noexcept;
     size_type find_last_of(const value_type* s, size_type pos = npos) const noexcept;
     size_type find_last_of(value_type c, size_type pos = npos) const noexcept;
 
     size_type find_first_not_of(const basic_string& str, size_type pos = 0) const noexcept;
     template <class T>
-        size_type find_first_not_of(const T& t, size_type pos = 0) const; // C++17
+        size_type find_first_not_of(const T& t, size_type pos = 0) const noexcept; // C++17, noexcept as an extension
     size_type find_first_not_of(const value_type* s, size_type pos, size_type n) const noexcept;
     size_type find_first_not_of(const value_type* s, size_type pos = 0) const noexcept;
     size_type find_first_not_of(value_type c, size_type pos = 0) const noexcept;
 
     size_type find_last_not_of(const basic_string& str, size_type pos = npos) const noexcept;
     template <class T>
-        size_type find_last_not_of(const T& t, size_type pos = npos) const; // C++17
+        size_type find_last_not_of(const T& t, size_type pos = npos) const noexcept; // C++17, noexcept as an extension
     size_type find_last_not_of(const value_type* s, size_type pos, size_type n) const noexcept;
     size_type find_last_not_of(const value_type* s, size_type pos = npos) const noexcept;
     size_type find_last_not_of(value_type c, size_type pos = npos) const noexcept;
 
     int compare(const basic_string& str) const noexcept;
     template <class T>
-        int compare(const T& t) const noexcept;  // C++17
+        int compare(const T& t) const noexcept;  // C++17, noexcept as an extension
     int compare(size_type pos1, size_type n1, const basic_string& str) const;
     template <class T>
         int compare(size_type pos1, size_type n1, const T& t) const;  // C++17
@@ -450,6 +455,7 @@ erase_if(basic_string<charT, traits, Allocator>& c, Predicate pred); // C++20
 
 typedef basic_string<char>    string;
 typedef basic_string<wchar_t> wstring;
+typedef basic_string<char8_t> u8string; // C++20
 typedef basic_string<char16_t> u16string;
 typedef basic_string<char32_t> u32string;
 
@@ -494,12 +500,14 @@ wstring to_wstring(double val);
 wstring to_wstring(long double val);
 
 template <> struct hash<string>;
+template <> struct hash<u8string>; // C++20
 template <> struct hash<u16string>;
 template <> struct hash<u32string>;
 template <> struct hash<wstring>;
 
 basic_string<char>     operator "" s( const char *str,     size_t len ); // C++14
 basic_string<wchar_t>  operator "" s( const wchar_t *str,  size_t len ); // C++14
+basic_string<char8_t>  operator "" s( const char8_t *str,  size_t len ); // C++20
 basic_string<char16_t> operator "" s( const char16_t *str, size_t len ); // C++14
 basic_string<char32_t> operator "" s( const char32_t *str, size_t len ); // C++14
 
@@ -508,26 +516,28 @@ basic_string<char32_t> operator "" s( const char32_t *str, size_t len ); // C++1
 */
 
 #include <__config>
-#include <string_view>
-#include <iosfwd>
+#include <__debug>
+#include <__functional_base>
+#include <__iterator/wrap_iter.h>
+#include <algorithm>
+#include <compare>
+#include <cstdio>  // EOF
 #include <cstring>
-#include <cstdio>  // For EOF.
 #include <cwchar>
-#include <algorithm>
+#include <initializer_list>
+#include <iosfwd>
 #include <iterator>
-#include <utility>
 #include <memory>
 #include <stdexcept>
+#include <string_view>
 #include <type_traits>
-#include <initializer_list>
-#include <__functional_base>
+#include <utility>
 #include <version>
+
 #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
-#include <cstdint>
+# include <cstdint>
 #endif
 
-#include <__debug>
-
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
@@ -625,29 +635,16 @@ __basic_string_common<__b>::__throw_out_of_range() const
 
 _LIBCPP_EXTERN_TEMPLATE(class _LIBCPP_EXTERN_TEMPLATE_TYPE_VIS __basic_string_common<true>)
 
-#ifdef _LIBCPP_NO_EXCEPTIONS
-template <class _Iter>
-struct __libcpp_string_gets_noexcept_iterator_impl : public true_type {};
-#elif defined(_LIBCPP_HAS_NO_NOEXCEPT)
 template <class _Iter>
-struct __libcpp_string_gets_noexcept_iterator_impl : public false_type {};
-#else
-template <class _Iter, bool = __is_cpp17_forward_iterator<_Iter>::value>
-struct __libcpp_string_gets_noexcept_iterator_impl : public _LIBCPP_BOOL_CONSTANT((
-    noexcept(++(declval<_Iter&>())) &&
-    is_nothrow_assignable<_Iter&, _Iter>::value &&
-    noexcept(declval<_Iter>() == declval<_Iter>()) &&
-    noexcept(*declval<_Iter>())
-)) {};
-
-template <class _Iter>
-struct __libcpp_string_gets_noexcept_iterator_impl<_Iter, false> : public false_type {};
-#endif
+struct __string_is_trivial_iterator : public false_type {};
 
+template <class _Tp>
+struct __string_is_trivial_iterator<_Tp*>
+    : public is_arithmetic<_Tp> {};
 
 template <class _Iter>
-struct __libcpp_string_gets_noexcept_iterator
-    : public _LIBCPP_BOOL_CONSTANT(__libcpp_is_trivial_iterator<_Iter>::value || __libcpp_string_gets_noexcept_iterator_impl<_Iter>::value) {};
+struct __string_is_trivial_iterator<__wrap_iter<_Iter> >
+    : public __string_is_trivial_iterator<_Iter> {};
 
 template <class _CharT, class _Traits, class _Tp>
 struct __can_be_converted_to_string_view : public _BoolConstant<
@@ -668,21 +665,21 @@ struct __padding<_CharT, 1>
 {
 };
 
-#endif  // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
+#endif // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 typedef basic_string<char8_t> u8string;
 #endif
 
 #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
 typedef basic_string<char16_t> u16string;
 typedef basic_string<char32_t> u32string;
-#endif  // _LIBCPP_HAS_NO_UNICODE_CHARS
+#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
 
 template<class _CharT, class _Traits, class _Allocator>
 class
     _LIBCPP_TEMPLATE_VIS
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
     _LIBCPP_PREFERRED_NAME(u8string)
 #endif
 #ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
@@ -736,7 +733,7 @@ private:
 #else  // _LIBCPP_BIG_ENDIAN
     static const size_type __short_mask = 0x80;
     static const size_type __long_mask  = ~(size_type(~0) >> 1);
-#endif  // _LIBCPP_BIG_ENDIAN
+#endif // _LIBCPP_BIG_ENDIAN
 
     enum {__min_cap = (sizeof(__long) - 1)/sizeof(value_type) > 2 ?
                       (sizeof(__long) - 1)/sizeof(value_type) : 2};
@@ -766,7 +763,7 @@ private:
 #else  // _LIBCPP_BIG_ENDIAN
     static const size_type __short_mask = 0x01;
     static const size_type __long_mask  = 0x1ul;
-#endif  // _LIBCPP_BIG_ENDIAN
+#endif // _LIBCPP_BIG_ENDIAN
 
     enum {__min_cap = (sizeof(__long) - 1)/sizeof(value_type) > 2 ?
                       (sizeof(__long) - 1)/sizeof(value_type) : 2};
@@ -781,7 +778,7 @@ private:
         value_type __data_[__min_cap];
     };
 
-#endif  // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
+#endif // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
 
     union __ulx{__long __lx; __short __lxx;};
 
@@ -805,7 +802,7 @@ private:
     __compressed_pair<__rep, allocator_type> __r_;
 
 public:
-    _LIBCPP_FUNC_VIS
+    _LIBCPP_TEMPLATE_DATA_VIS
     static const size_type npos = -1;
 
     _LIBCPP_INLINE_VISIBILITY basic_string()
@@ -832,7 +829,7 @@ public:
 
     _LIBCPP_INLINE_VISIBILITY
     basic_string(basic_string&& __str, const allocator_type& __a);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     template <class = _EnableIf<__is_allocator<_Allocator>::value, nullptr_t> >
     _LIBCPP_INLINE_VISIBILITY
@@ -848,6 +845,10 @@ public:
         _LIBCPP_INLINE_VISIBILITY
         basic_string(const _CharT* __s, const _Allocator& __a);
 
+#if _LIBCPP_STD_VER > 20
+    basic_string(nullptr_t) = delete;
+#endif
+
     _LIBCPP_INLINE_VISIBILITY
     basic_string(const _CharT* __s, size_type __n);
     _LIBCPP_INLINE_VISIBILITY
@@ -890,7 +891,7 @@ public:
     basic_string(initializer_list<_CharT> __il);
     _LIBCPP_INLINE_VISIBILITY
     basic_string(initializer_list<_CharT> __il, const _Allocator& __a);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     inline ~basic_string();
 
@@ -911,6 +912,9 @@ public:
     basic_string& operator=(initializer_list<value_type> __il) {return assign(__il.begin(), __il.size());}
 #endif
     _LIBCPP_INLINE_VISIBILITY basic_string& operator=(const value_type* __s) {return assign(__s);}
+#if _LIBCPP_STD_VER > 20
+    basic_string& operator=(nullptr_t) = delete;
+#endif
     basic_string& operator=(value_type __c);
 
 #if _LIBCPP_DEBUG_LEVEL == 2
@@ -939,7 +943,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     const_iterator end() const _NOEXCEPT
         {return const_iterator(__get_pointer() + size());}
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
     _LIBCPP_INLINE_VISIBILITY
     reverse_iterator rbegin() _NOEXCEPT
         {return reverse_iterator(end());}
@@ -1010,7 +1014,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY basic_string& operator+=(value_type __c)            {push_back(__c); return *this;}
 #ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY basic_string& operator+=(initializer_list<value_type> __il) {return append(__il);}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     basic_string& append(const basic_string& __str);
@@ -1041,20 +1045,16 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     void __append_default_init(size_type __n);
 
-    template <class _ForwardIterator>
-    _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
-    basic_string& __append_forward_unsafe(_ForwardIterator, _ForwardIterator);
     template<class _InputIterator>
     _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
     _EnableIf
         <
-            __is_exactly_cpp17_input_iterator<_InputIterator>::value
-                || !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
+            __is_exactly_cpp17_input_iterator<_InputIterator>::value,
             basic_string&
         >
     _LIBCPP_INLINE_VISIBILITY
     append(_InputIterator __first, _InputIterator __last) {
-      const basic_string __temp (__first, __last, __alloc());
+      const basic_string __temp(__first, __last, __alloc());
       append(__temp.data(), __temp.size());
       return *this;
     }
@@ -1062,19 +1062,16 @@ public:
     _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
     _EnableIf
         <
-            __is_cpp17_forward_iterator<_ForwardIterator>::value
-                && __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
+            __is_cpp17_forward_iterator<_ForwardIterator>::value,
             basic_string&
         >
     _LIBCPP_INLINE_VISIBILITY
-    append(_ForwardIterator __first, _ForwardIterator __last) {
-      return __append_forward_unsafe(__first, __last);
-    }
+    append(_ForwardIterator __first, _ForwardIterator __last);
 
 #ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     basic_string& append(initializer_list<value_type> __il) {return append(__il.begin(), __il.size());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     void push_back(value_type __c);
     _LIBCPP_INLINE_VISIBILITY
@@ -1117,8 +1114,7 @@ public:
     _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
     _EnableIf
         <
-           __is_exactly_cpp17_input_iterator<_InputIterator>::value
-                || !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
+            __is_exactly_cpp17_input_iterator<_InputIterator>::value,
             basic_string&
         >
         assign(_InputIterator __first, _InputIterator __last);
@@ -1126,15 +1122,14 @@ public:
     _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
     _EnableIf
         <
-            __is_cpp17_forward_iterator<_ForwardIterator>::value
-                 && __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
+            __is_cpp17_forward_iterator<_ForwardIterator>::value,
             basic_string&
         >
         assign(_ForwardIterator __first, _ForwardIterator __last);
 #ifndef _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     basic_string& assign(initializer_list<value_type> __il) {return assign(__il.begin(), __il.size());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     basic_string& insert(size_type __pos1, const basic_string& __str);
@@ -1168,8 +1163,7 @@ public:
     _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
     _EnableIf
         <
-           __is_exactly_cpp17_input_iterator<_InputIterator>::value
-                || !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
+            __is_exactly_cpp17_input_iterator<_InputIterator>::value,
             iterator
         >
         insert(const_iterator __pos, _InputIterator __first, _InputIterator __last);
@@ -1177,8 +1171,7 @@ public:
     _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
     _EnableIf
         <
-            __is_cpp17_forward_iterator<_ForwardIterator>::value
-                 && __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
+            __is_cpp17_forward_iterator<_ForwardIterator>::value,
             iterator
         >
         insert(const_iterator __pos, _ForwardIterator __first, _ForwardIterator __last);
@@ -1186,7 +1179,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     iterator insert(const_iterator __pos, initializer_list<value_type> __il)
                     {return insert(__pos, __il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     basic_string& erase(size_type __pos = 0, size_type __n = npos);
     _LIBCPP_INLINE_VISIBILITY
@@ -1247,7 +1240,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     basic_string& replace(const_iterator __i1, const_iterator __i2, initializer_list<value_type> __il)
         {return replace(__i1, __i2, __il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     size_type copy(value_type* __s, size_type __n, size_type __pos = 0) const;
     _LIBCPP_INLINE_VISIBILITY
@@ -1284,7 +1277,7 @@ public:
             __can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
             size_type
         >
-              find(const _Tp& __t, size_type __pos = 0) const;
+              find(const _Tp& __t, size_type __pos = 0) const _NOEXCEPT;
     size_type find(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
     _LIBCPP_INLINE_VISIBILITY
     size_type find(const value_type* __s, size_type __pos = 0) const _NOEXCEPT;
@@ -1300,7 +1293,7 @@ public:
             __can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
             size_type
         >
-              rfind(const _Tp& __t, size_type __pos = npos) const;
+              rfind(const _Tp& __t, size_type __pos = npos) const _NOEXCEPT;
     size_type rfind(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
     _LIBCPP_INLINE_VISIBILITY
     size_type rfind(const value_type* __s, size_type __pos = npos) const _NOEXCEPT;
@@ -1316,7 +1309,7 @@ public:
             __can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
             size_type
         >
-              find_first_of(const _Tp& __t, size_type __pos = 0) const;
+              find_first_of(const _Tp& __t, size_type __pos = 0) const _NOEXCEPT;
     size_type find_first_of(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
     _LIBCPP_INLINE_VISIBILITY
     size_type find_first_of(const value_type* __s, size_type __pos = 0) const _NOEXCEPT;
@@ -1333,7 +1326,7 @@ public:
             __can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
             size_type
         >
-              find_last_of(const _Tp& __t, size_type __pos = npos) const;
+              find_last_of(const _Tp& __t, size_type __pos = npos) const _NOEXCEPT;
     size_type find_last_of(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
     _LIBCPP_INLINE_VISIBILITY
     size_type find_last_of(const value_type* __s, size_type __pos = npos) const _NOEXCEPT;
@@ -1350,7 +1343,7 @@ public:
             __can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
             size_type
         >
-              find_first_not_of(const _Tp &__t, size_type __pos = 0) const;
+              find_first_not_of(const _Tp &__t, size_type __pos = 0) const _NOEXCEPT;
     size_type find_first_not_of(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
     _LIBCPP_INLINE_VISIBILITY
     size_type find_first_not_of(const value_type* __s, size_type __pos = 0) const _NOEXCEPT;
@@ -1367,7 +1360,7 @@ public:
             __can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
             size_type
         >
-              find_last_not_of(const _Tp& __t, size_type __pos = npos) const;
+              find_last_not_of(const _Tp& __t, size_type __pos = npos) const _NOEXCEPT;
     size_type find_last_not_of(const value_type* __s, size_type __pos, size_type __n) const _NOEXCEPT;
     _LIBCPP_INLINE_VISIBILITY
     size_type find_last_not_of(const value_type* __s, size_type __pos = npos) const _NOEXCEPT;
@@ -1384,7 +1377,7 @@ public:
             __can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
             int
         >
-        compare(const _Tp &__t) const;
+        compare(const _Tp &__t) const _NOEXCEPT;
 
     template <class _Tp>
     _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
@@ -1468,7 +1461,7 @@ public:
     bool __addable(const const_iterator* __i, ptrdiff_t __n) const;
     bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const;
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 private:
     _LIBCPP_INLINE_VISIBILITY
@@ -1514,7 +1507,7 @@ private:
         {return __r_.first().__s.__size_ >> 1;}
 #   endif
 
-#endif  // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
+#endif // _LIBCPP_ABI_ALTERNATE_STRING_LAYOUT
 
     _LIBCPP_INLINE_VISIBILITY
     void __set_long_size(size_type __s) _NOEXCEPT
@@ -1714,6 +1707,13 @@ private:
     _LIBCPP_INLINE_VISIBILITY void __invalidate_all_iterators();
     _LIBCPP_INLINE_VISIBILITY void __invalidate_iterators_past(size_type);
 
+    template<class _Tp>
+    _LIBCPP_INLINE_VISIBILITY
+    bool __addr_in_range(_Tp&& __t) const {
+        const volatile void *__p = _VSTD::addressof(__t);
+        return data() <= __p && __p <= data() + size();
+    }
+
     friend basic_string operator+<>(const basic_string&, const basic_string&);
     friend basic_string operator+<>(const value_type*, const basic_string&);
     friend basic_string operator+<>(value_type, const basic_string&);
@@ -1734,7 +1734,7 @@ _LIBCPP_STRING_V1_EXTERN_TEMPLATE_LIST(_LIBCPP_EXTERN_TEMPLATE, wchar_t)
 
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template<class _InputIterator,
-         class _CharT = typename iterator_traits<_InputIterator>::value_type,
+         class _CharT = __iter_value_type<_InputIterator>,
          class _Allocator = allocator<_CharT>,
          class = _EnableIf<__is_cpp17_input_iterator<_InputIterator>::value>,
          class = _EnableIf<__is_allocator<_Allocator>::value>
@@ -1773,11 +1773,7 @@ basic_string<_CharT, _Traits, _Allocator>::__invalidate_all_iterators()
 template <class _CharT, class _Traits, class _Allocator>
 inline
 void
-basic_string<_CharT, _Traits, _Allocator>::__invalidate_iterators_past(size_type
-#if _LIBCPP_DEBUG_LEVEL == 2
-                                                                        __pos
-#endif
-                                                                      )
+basic_string<_CharT, _Traits, _Allocator>::__invalidate_iterators_past(size_type __pos)
 {
 #if _LIBCPP_DEBUG_LEVEL == 2
     __c_node* __c = __get_db()->__find_c_and_lock(this);
@@ -1797,7 +1793,9 @@ basic_string<_CharT, _Traits, _Allocator>::__invalidate_iterators_past(size_type
         }
         __get_db()->unlock();
     }
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#else
+    (void)__pos;
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 }
 
 template <class _CharT, class _Traits, class _Allocator>
@@ -2001,7 +1999,7 @@ basic_string<_CharT, _Traits, _Allocator>::basic_string(basic_string&& __str, co
 #endif
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _CharT, class _Traits, class _Allocator>
 void
@@ -2129,7 +2127,7 @@ basic_string<_CharT, _Traits, _Allocator>::__init(_InputIterator __first, _Input
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     for (; __first != __last; ++__first)
         push_back(*__first);
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2140,7 +2138,7 @@ basic_string<_CharT, _Traits, _Allocator>::__init(_InputIterator __first, _Input
             __alloc_traits::deallocate(__alloc(), __get_long_pointer(), __get_long_cap());
         throw;
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template <class _CharT, class _Traits, class _Allocator>
@@ -2168,9 +2166,23 @@ basic_string<_CharT, _Traits, _Allocator>::__init(_ForwardIterator __first, _For
         __set_long_cap(__cap+1);
         __set_long_size(__sz);
     }
+
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try
+    {
+#endif  // _LIBCPP_NO_EXCEPTIONS
     for (; __first != __last; ++__first, (void) ++__p)
         traits_type::assign(*__p, *__first);
     traits_type::assign(*__p, value_type());
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    }
+    catch (...)
+    {
+        if (__is_long())
+            __alloc_traits::deallocate(__alloc(), __get_long_pointer(), __get_long_cap());
+        throw;
+    }
+#endif  // _LIBCPP_NO_EXCEPTIONS
 }
 
 template <class _CharT, class _Traits, class _Allocator>
@@ -2225,7 +2237,7 @@ basic_string<_CharT, _Traits, _Allocator>::basic_string(
 #endif
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _CharT, class _Traits, class _Allocator>
 basic_string<_CharT, _Traits, _Allocator>::~basic_string()
@@ -2357,12 +2369,11 @@ basic_string<_CharT, _Traits, _Allocator>::assign(size_type __n, value_type __c)
         size_type __sz = size();
         __grow_by(__cap, __n - __cap, __sz, 0, __sz);
     }
-    else
-        __invalidate_iterators_past(__n);
     value_type* __p = _VSTD::__to_address(__get_pointer());
     traits_type::assign(__p, __n, __c);
     traits_type::assign(__p[__n], value_type());
     __set_size(__n);
+    __invalidate_iterators_past(__n);
     return *this;
 }
 
@@ -2463,8 +2474,7 @@ template <class _CharT, class _Traits, class _Allocator>
 template<class _InputIterator>
 _EnableIf
 <
-     __is_exactly_cpp17_input_iterator <_InputIterator>::value
-          || !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
+     __is_exactly_cpp17_input_iterator<_InputIterator>::value,
     basic_string<_CharT, _Traits, _Allocator>&
 >
 basic_string<_CharT, _Traits, _Allocator>::assign(_InputIterator __first, _InputIterator __last)
@@ -2478,26 +2488,35 @@ template <class _CharT, class _Traits, class _Allocator>
 template<class _ForwardIterator>
 _EnableIf
 <
-    __is_cpp17_forward_iterator<_ForwardIterator>::value
-         && __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
+    __is_cpp17_forward_iterator<_ForwardIterator>::value,
     basic_string<_CharT, _Traits, _Allocator>&
 >
 basic_string<_CharT, _Traits, _Allocator>::assign(_ForwardIterator __first, _ForwardIterator __last)
 {
-    size_type __n = static_cast<size_type>(_VSTD::distance(__first, __last));
     size_type __cap = capacity();
-    if (__cap < __n)
+    size_type __n = __string_is_trivial_iterator<_ForwardIterator>::value ?
+        static_cast<size_type>(_VSTD::distance(__first, __last)) : 0;
+
+    if (__string_is_trivial_iterator<_ForwardIterator>::value &&
+        (__cap >= __n || !__addr_in_range(*__first)))
     {
-        size_type __sz = size();
-        __grow_by(__cap, __n - __cap, __sz, 0, __sz);
+        if (__cap < __n)
+        {
+            size_type __sz = size();
+            __grow_by(__cap, __n - __cap, __sz, 0, __sz);
+        }
+        pointer __p = __get_pointer();
+        for (; __first != __last; ++__first, ++__p)
+            traits_type::assign(*__p, *__first);
+        traits_type::assign(*__p, value_type());
+        __set_size(__n);
+        __invalidate_iterators_past(__n);
     }
     else
-        __invalidate_iterators_past(__n);
-    pointer __p = __get_pointer();
-    for (; __first != __last; ++__first, ++__p)
-        traits_type::assign(*__p, *__first);
-    traits_type::assign(*__p, value_type());
-    __set_size(__n);
+    {
+        const basic_string __temp(__first, __last, __alloc());
+        assign(__temp.data(), __temp.size());
+    }
     return *this;
 }
 
@@ -2644,39 +2663,23 @@ basic_string<_CharT, _Traits, _Allocator>::push_back(value_type __c)
     traits_type::assign(*++__p, value_type());
 }
 
-template <class _Tp>
-bool __ptr_in_range (const _Tp* __p, const _Tp* __first, const _Tp* __last)
-{
-    return __first <= __p && __p < __last;
-}
-
-template <class _Tp1, class _Tp2>
-bool __ptr_in_range (const _Tp1*, const _Tp2*, const _Tp2*)
-{
-    return false;
-}
-
 template <class _CharT, class _Traits, class _Allocator>
 template<class _ForwardIterator>
-basic_string<_CharT, _Traits, _Allocator>&
-basic_string<_CharT, _Traits, _Allocator>::__append_forward_unsafe(
+_EnableIf
+<
+    __is_cpp17_forward_iterator<_ForwardIterator>::value,
+    basic_string<_CharT, _Traits, _Allocator>&
+>
+basic_string<_CharT, _Traits, _Allocator>::append(
     _ForwardIterator __first, _ForwardIterator __last)
 {
-    static_assert(__is_cpp17_forward_iterator<_ForwardIterator>::value,
-                  "function requires a ForwardIterator");
     size_type __sz = size();
     size_type __cap = capacity();
     size_type __n = static_cast<size_type>(_VSTD::distance(__first, __last));
     if (__n)
     {
-        typedef typename iterator_traits<_ForwardIterator>::reference _CharRef;
-        _CharRef __tmp_ref = *__first;
-        if (__ptr_in_range(_VSTD::addressof(__tmp_ref), data(), data() + size()))
-        {
-            const basic_string __temp (__first, __last, __alloc());
-            append(__temp.data(), __temp.size());
-        }
-        else
+        if (__string_is_trivial_iterator<_ForwardIterator>::value &&
+            !__addr_in_range(*__first))
         {
             if (__cap - __sz < __n)
                 __grow_by(__cap, __sz + __n - __cap, __sz, __sz, 0);
@@ -2686,6 +2689,11 @@ basic_string<_CharT, _Traits, _Allocator>::__append_forward_unsafe(
             traits_type::assign(*__p, value_type());
             __set_size(__sz + __n);
         }
+        else
+        {
+            const basic_string __temp(__first, __last, __alloc());
+            append(__temp.data(), __temp.size());
+        }
     }
     return *this;
 }
@@ -2801,8 +2809,7 @@ template <class _CharT, class _Traits, class _Allocator>
 template<class _InputIterator>
 _EnableIf
 <
-   __is_exactly_cpp17_input_iterator<_InputIterator>::value
-        || !__libcpp_string_gets_noexcept_iterator<_InputIterator>::value,
+   __is_exactly_cpp17_input_iterator<_InputIterator>::value,
    typename basic_string<_CharT, _Traits, _Allocator>::iterator
 >
 basic_string<_CharT, _Traits, _Allocator>::insert(const_iterator __pos, _InputIterator __first, _InputIterator __last)
@@ -2820,8 +2827,7 @@ template <class _CharT, class _Traits, class _Allocator>
 template<class _ForwardIterator>
 _EnableIf
 <
-    __is_cpp17_forward_iterator<_ForwardIterator>::value
-        && __libcpp_string_gets_noexcept_iterator<_ForwardIterator>::value,
+    __is_cpp17_forward_iterator<_ForwardIterator>::value,
     typename basic_string<_CharT, _Traits, _Allocator>::iterator
 >
 basic_string<_CharT, _Traits, _Allocator>::insert(const_iterator __pos, _ForwardIterator __first, _ForwardIterator __last)
@@ -2835,34 +2841,35 @@ basic_string<_CharT, _Traits, _Allocator>::insert(const_iterator __pos, _Forward
     size_type __n = static_cast<size_type>(_VSTD::distance(__first, __last));
     if (__n)
     {
-        typedef typename iterator_traits<_ForwardIterator>::reference _CharRef;
-        _CharRef __tmp_char = *__first;
-        if (__ptr_in_range(_VSTD::addressof(__tmp_char), data(), data() + size()))
+        if (__string_is_trivial_iterator<_ForwardIterator>::value &&
+            !__addr_in_range(*__first))
         {
-            const basic_string __temp(__first, __last, __alloc());
-            return insert(__pos, __temp.data(), __temp.data() + __temp.size());
-        }
-
-        size_type __sz = size();
-        size_type __cap = capacity();
-        value_type* __p;
-        if (__cap - __sz >= __n)
-        {
-            __p = _VSTD::__to_address(__get_pointer());
-            size_type __n_move = __sz - __ip;
-            if (__n_move != 0)
-                traits_type::move(__p + __ip + __n, __p + __ip, __n_move);
+            size_type __sz = size();
+            size_type __cap = capacity();
+            value_type* __p;
+            if (__cap - __sz >= __n)
+            {
+                __p = _VSTD::__to_address(__get_pointer());
+                size_type __n_move = __sz - __ip;
+                if (__n_move != 0)
+                    traits_type::move(__p + __ip + __n, __p + __ip, __n_move);
+            }
+            else
+            {
+                __grow_by(__cap, __sz + __n - __cap, __sz, __ip, 0, __n);
+                __p = _VSTD::__to_address(__get_long_pointer());
+            }
+            __sz += __n;
+            __set_size(__sz);
+            traits_type::assign(__p[__sz], value_type());
+            for (__p += __ip; __first != __last; ++__p, ++__first)
+                traits_type::assign(*__p, *__first);
         }
         else
         {
-            __grow_by(__cap, __sz + __n - __cap, __sz, __ip, 0, __n);
-            __p = _VSTD::__to_address(__get_long_pointer());
+            const basic_string __temp(__first, __last, __alloc());
+            return insert(__pos, __temp.data(), __temp.data() + __temp.size());
         }
-        __sz += __n;
-        __set_size(__sz);
-        traits_type::assign(__p[__sz], value_type());
-        for (__p += __ip; __first != __last; ++__p, ++__first)
-            traits_type::assign(*__p, *__first);
     }
     return begin() + __ip;
 }
@@ -3353,7 +3360,7 @@ basic_string<_CharT, _Traits, _Allocator>::__shrink_or_extend(size_type __target
         #ifndef _LIBCPP_NO_EXCEPTIONS
             try
             {
-        #endif  // _LIBCPP_NO_EXCEPTIONS
+        #endif // _LIBCPP_NO_EXCEPTIONS
                 __new_data = __alloc_traits::allocate(__alloc(), __target_capacity+1);
         #ifndef _LIBCPP_NO_EXCEPTIONS
             }
@@ -3364,7 +3371,7 @@ basic_string<_CharT, _Traits, _Allocator>::__shrink_or_extend(size_type __target
         #else  // _LIBCPP_NO_EXCEPTIONS
             if (__new_data == nullptr)
                 return;
-        #endif  // _LIBCPP_NO_EXCEPTIONS
+        #endif // _LIBCPP_NO_EXCEPTIONS
         }
         __now_long = true;
         __was_long = __is_long();
@@ -3543,7 +3550,7 @@ _EnableIf
     typename basic_string<_CharT, _Traits, _Allocator>::size_type
 >
 basic_string<_CharT, _Traits, _Allocator>::find(const _Tp &__t,
-                                                size_type __pos) const
+                                                size_type __pos) const _NOEXCEPT
 {
     __self_view __sv = __t;
     return __str_find<value_type, size_type, traits_type, npos>
@@ -3601,7 +3608,7 @@ _EnableIf
     typename basic_string<_CharT, _Traits, _Allocator>::size_type
 >
 basic_string<_CharT, _Traits, _Allocator>::rfind(const _Tp& __t,
-                                                size_type __pos) const
+                                                size_type __pos) const _NOEXCEPT
 {
     __self_view __sv = __t;
     return __str_rfind<value_type, size_type, traits_type, npos>
@@ -3659,7 +3666,7 @@ _EnableIf
     typename basic_string<_CharT, _Traits, _Allocator>::size_type
 >
 basic_string<_CharT, _Traits, _Allocator>::find_first_of(const _Tp& __t,
-                                                size_type __pos) const
+                                                size_type __pos) const _NOEXCEPT
 {
     __self_view __sv = __t;
     return __str_find_first_of<value_type, size_type, traits_type, npos>
@@ -3717,7 +3724,7 @@ _EnableIf
     typename basic_string<_CharT, _Traits, _Allocator>::size_type
 >
 basic_string<_CharT, _Traits, _Allocator>::find_last_of(const _Tp& __t,
-                                                size_type __pos) const
+                                                size_type __pos) const _NOEXCEPT
 {
     __self_view __sv = __t;
     return __str_find_last_of<value_type, size_type, traits_type, npos>
@@ -3775,7 +3782,7 @@ _EnableIf
     typename basic_string<_CharT, _Traits, _Allocator>::size_type
 >
 basic_string<_CharT, _Traits, _Allocator>::find_first_not_of(const _Tp& __t,
-                                                size_type __pos) const
+                                                size_type __pos) const _NOEXCEPT
 {
     __self_view __sv = __t;
     return __str_find_first_not_of<value_type, size_type, traits_type, npos>
@@ -3834,7 +3841,7 @@ _EnableIf
     typename basic_string<_CharT, _Traits, _Allocator>::size_type
 >
 basic_string<_CharT, _Traits, _Allocator>::find_last_not_of(const _Tp& __t,
-                                                size_type __pos) const
+                                                size_type __pos) const _NOEXCEPT
 {
     __self_view __sv = __t;
     return __str_find_last_not_of<value_type, size_type, traits_type, npos>
@@ -3871,7 +3878,7 @@ _EnableIf
     __can_be_converted_to_string_view<_CharT, _Traits, _Tp>::value,
     int
 >
-basic_string<_CharT, _Traits, _Allocator>::compare(const _Tp& __t) const
+basic_string<_CharT, _Traits, _Allocator>::compare(const _Tp& __t) const _NOEXCEPT
 {
     __self_view __sv = __t;
     size_t __lhs_sz = size();
@@ -4349,7 +4356,7 @@ operator+(basic_string<_CharT, _Traits, _Allocator>&& __lhs, _CharT __rhs)
     return _VSTD::move(__lhs);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 // swap
 
@@ -4404,7 +4411,7 @@ _LIBCPP_FUNC_VIS wstring to_wstring(double __val);
 _LIBCPP_FUNC_VIS wstring to_wstring(long double __val);
 
 template<class _CharT, class _Traits, class _Allocator>
-_LIBCPP_FUNC_VIS
+_LIBCPP_TEMPLATE_DATA_VIS
 const typename basic_string<_CharT, _Traits, _Allocator>::size_type
                basic_string<_CharT, _Traits, _Allocator>::npos;
 
@@ -4441,8 +4448,6 @@ basic_istream<_CharT, _Traits>&
 getline(basic_istream<_CharT, _Traits>& __is,
         basic_string<_CharT, _Traits, _Allocator>& __str);
 
-#ifndef _LIBCPP_CXX03_LANG
-
 template<class _CharT, class _Traits, class _Allocator>
 inline _LIBCPP_INLINE_VISIBILITY
 basic_istream<_CharT, _Traits>&
@@ -4455,8 +4460,6 @@ basic_istream<_CharT, _Traits>&
 getline(basic_istream<_CharT, _Traits>&& __is,
         basic_string<_CharT, _Traits, _Allocator>& __str);
 
-#endif  // _LIBCPP_CXX03_LANG
-
 #if _LIBCPP_STD_VER > 17
 template <class _CharT, class _Traits, class _Allocator, class _Up>
 inline _LIBCPP_INLINE_VISIBILITY
@@ -4513,7 +4516,7 @@ basic_string<_CharT, _Traits, _Allocator>::__subscriptable(const const_iterator*
     return this->data() <= __p && __p < this->data() + this->size();
 }
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 #if _LIBCPP_STD_VER > 11
 // Literal suffixes for basic_string [basic.string.literals]
@@ -4533,7 +4536,7 @@ inline namespace literals
         return basic_string<wchar_t> (__str, __len);
     }
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
     inline _LIBCPP_INLINE_VISIBILITY
     basic_string<char8_t> operator "" s(const char8_t *__str, size_t __len) _NOEXCEPT
     {
@@ -4560,4 +4563,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_STRING
+#endif // _LIBCPP_STRING
lib/libcxx/include/string.h
@@ -106,4 +106,4 @@ inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_PREFERRED_OVERLOAD
 }
 #endif
 
-#endif  // _LIBCPP_STRING_H
+#endif // _LIBCPP_STRING_H
lib/libcxx/include/string_view
@@ -19,6 +19,12 @@ namespace std {
     template<class charT, class traits = char_traits<charT>>
         class basic_string_view;
 
+    template<class charT, class traits>
+    inline constexpr bool ranges::enable_view<basic_string_view<charT, traits>> = true;
+
+    template<class charT, class traits>
+    inline constexpr bool ranges::enable_borrowed_range<basic_string_view<charT, traits>> = true;  // C++20
+
     // 7.9, basic_string_view non-member comparison functions
     template<class charT, class traits>
     constexpr bool operator==(basic_string_view<charT, traits> x,
@@ -48,6 +54,7 @@ namespace std {
 
     // basic_string_view typedef names
     typedef basic_string_view<char> string_view;
+    typedef basic_string_view<char8_t> u8string_view; // C++20
     typedef basic_string_view<char16_t> u16string_view;
     typedef basic_string_view<char32_t> u32string_view;
     typedef basic_string_view<wchar_t> wstring_view;
@@ -76,6 +83,7 @@ namespace std {
       basic_string_view& operator=(const basic_string_view&) noexcept = default;
       template<class Allocator>
       constexpr basic_string_view(const charT* str);
+      basic_string_view(nullptr_t) = delete; // C++2b
       constexpr basic_string_view(const charT* str, size_type len);
 
       // 7.4, basic_string_view iterator support
@@ -106,7 +114,7 @@ namespace std {
       constexpr void remove_suffix(size_type n);
       constexpr void swap(basic_string_view& s) noexcept;
 
-      size_type copy(charT* s, size_type n, size_type pos = 0) const;
+      size_type copy(charT* s, size_type n, size_type pos = 0) const;  // constexpr in C++20
 
       constexpr basic_string_view substr(size_type pos = 0, size_type n = npos) const;
       constexpr int compare(basic_string_view s) const noexcept;
@@ -119,28 +127,28 @@ namespace std {
                             const charT* s, size_type n2) const;
       constexpr size_type find(basic_string_view s, size_type pos = 0) const noexcept;
       constexpr size_type find(charT c, size_type pos = 0) const noexcept;
-      constexpr size_type find(const charT* s, size_type pos, size_type n) const;
-      constexpr size_type find(const charT* s, size_type pos = 0) const;
+      constexpr size_type find(const charT* s, size_type pos, size_type n) const noexcept; // noexcept as an extension
+      constexpr size_type find(const charT* s, size_type pos = 0) const noexcept; // noexcept as an extension
       constexpr size_type rfind(basic_string_view s, size_type pos = npos) const noexcept;
       constexpr size_type rfind(charT c, size_type pos = npos) const noexcept;
-      constexpr size_type rfind(const charT* s, size_type pos, size_type n) const;
-      constexpr size_type rfind(const charT* s, size_type pos = npos) const;
+      constexpr size_type rfind(const charT* s, size_type pos, size_type n) const noexcept; // noexcept as an extension
+      constexpr size_type rfind(const charT* s, size_type pos = npos) const noexcept; // noexcept as an extension
       constexpr size_type find_first_of(basic_string_view s, size_type pos = 0) const noexcept;
       constexpr size_type find_first_of(charT c, size_type pos = 0) const noexcept;
-      constexpr size_type find_first_of(const charT* s, size_type pos, size_type n) const;
-      constexpr size_type find_first_of(const charT* s, size_type pos = 0) const;
+      constexpr size_type find_first_of(const charT* s, size_type pos, size_type n) const noexcept; // noexcept as an extension
+      constexpr size_type find_first_of(const charT* s, size_type pos = 0) const noexcept; // noexcept as an extension
       constexpr size_type find_last_of(basic_string_view s, size_type pos = npos) const noexcept;
       constexpr size_type find_last_of(charT c, size_type pos = npos) const noexcept;
-      constexpr size_type find_last_of(const charT* s, size_type pos, size_type n) const;
-      constexpr size_type find_last_of(const charT* s, size_type pos = npos) const;
+      constexpr size_type find_last_of(const charT* s, size_type pos, size_type n) const noexcept; // noexcept as an extension
+      constexpr size_type find_last_of(const charT* s, size_type pos = npos) const noexcept; // noexcept as an extension
       constexpr size_type find_first_not_of(basic_string_view s, size_type pos = 0) const noexcept;
       constexpr size_type find_first_not_of(charT c, size_type pos = 0) const noexcept;
-      constexpr size_type find_first_not_of(const charT* s, size_type pos, size_type n) const;
-      constexpr size_type find_first_not_of(const charT* s, size_type pos = 0) const;
+      constexpr size_type find_first_not_of(const charT* s, size_type pos, size_type n) const noexcept; // noexcept as an extension
+      constexpr size_type find_first_not_of(const charT* s, size_type pos = 0) const noexcept; // noexcept as an extension
       constexpr size_type find_last_not_of(basic_string_view s, size_type pos = npos) const noexcept;
       constexpr size_type find_last_not_of(charT c, size_type pos = npos) const noexcept;
-      constexpr size_type find_last_not_of(const charT* s, size_type pos, size_type n) const;
-      constexpr size_type find_last_not_of(const charT* s, size_type pos = npos) const;
+      constexpr size_type find_last_not_of(const charT* s, size_type pos, size_type n) const noexcept; // noexcept as an extension
+      constexpr size_type find_last_not_of(const charT* s, size_type pos = npos) const noexcept; // noexcept as an extension
 
       constexpr bool starts_with(basic_string_view s) const noexcept; // C++20
       constexpr bool starts_with(charT c) const noexcept;             // C++20
@@ -161,12 +169,14 @@ namespace std {
   // 7.11, Hash support
   template <class T> struct hash;
   template <> struct hash<string_view>;
+  template <> struct hash<u8string_view>; // C++20
   template <> struct hash<u16string_view>;
   template <> struct hash<u32string_view>;
   template <> struct hash<wstring_view>;
 
   constexpr basic_string_view<char>     operator "" sv( const char *str,     size_t len ) noexcept;
   constexpr basic_string_view<wchar_t>  operator "" sv( const wchar_t *str,  size_t len ) noexcept;
+  constexpr basic_string_view<char8_t>  operator "" sv( const char8_t *str,  size_t len ) noexcept; // C++20
   constexpr basic_string_view<char16_t> operator "" sv( const char16_t *str, size_t len ) noexcept;
   constexpr basic_string_view<char32_t> operator "" sv( const char32_t *str, size_t len ) noexcept;
 
@@ -176,14 +186,17 @@ namespace std {
 */
 
 #include <__config>
+#include <__debug>
+#include <__ranges/enable_borrowed_range.h>
+#include <__ranges/enable_view.h>
 #include <__string>
-#include <iosfwd>
 #include <algorithm>
+#include <compare>
+#include <iosfwd>
 #include <iterator>
 #include <limits>
 #include <stdexcept>
 #include <version>
-#include <__debug>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -199,7 +212,7 @@ template<class _CharT, class _Traits = char_traits<_CharT> >
     class _LIBCPP_TEMPLATE_VIS basic_string_view;
 
 typedef basic_string_view<char>     string_view;
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 typedef basic_string_view<char8_t>  u8string_view;
 #endif
 typedef basic_string_view<char16_t> u16string_view;
@@ -209,7 +222,7 @@ typedef basic_string_view<wchar_t>  wstring_view;
 template<class _CharT, class _Traits>
 class
     _LIBCPP_PREFERRED_NAME(string_view)
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
     _LIBCPP_PREFERRED_NAME(u8string_view)
 #endif
     _LIBCPP_PREFERRED_NAME(u16string_view)
@@ -261,6 +274,10 @@ public:
     basic_string_view(const _CharT* __s)
         : __data(__s), __size(_VSTD::__char_traits_length_checked<_Traits>(__s)) {}
 
+#if _LIBCPP_STD_VER > 20
+    basic_string_view(nullptr_t) = delete;
+#endif
+
     // [string.view.iterators], iterators
     _LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
     const_iterator begin()  const _NOEXCEPT { return cbegin(); }
@@ -356,7 +373,7 @@ public:
         __other.__size = __sz;
     }
 
-    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
     size_type copy(_CharT* __s, size_type __n, size_type __pos = 0) const
     {
         if (__pos > size())
@@ -431,7 +448,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find(const _CharT* __s, size_type __pos, size_type __n) const
+    size_type find(const _CharT* __s, size_type __pos, size_type __n) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string_view::find(): received nullptr");
         return __str_find<value_type, size_type, traits_type, npos>
@@ -439,7 +456,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find(const _CharT* __s, size_type __pos = 0) const
+    size_type find(const _CharT* __s, size_type __pos = 0) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__s != nullptr, "string_view::find(): received nullptr");
         return __str_find<value_type, size_type, traits_type, npos>
@@ -463,7 +480,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const
+    size_type rfind(const _CharT* __s, size_type __pos, size_type __n) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string_view::rfind(): received nullptr");
         return __str_rfind<value_type, size_type, traits_type, npos>
@@ -471,7 +488,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type rfind(const _CharT* __s, size_type __pos=npos) const
+    size_type rfind(const _CharT* __s, size_type __pos=npos) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__s != nullptr, "string_view::rfind(): received nullptr");
         return __str_rfind<value_type, size_type, traits_type, npos>
@@ -492,7 +509,7 @@ public:
     { return find(__c, __pos); }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find_first_of(const _CharT* __s, size_type __pos, size_type __n) const
+    size_type find_first_of(const _CharT* __s, size_type __pos, size_type __n) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string_view::find_first_of(): received nullptr");
         return __str_find_first_of<value_type, size_type, traits_type, npos>
@@ -500,7 +517,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find_first_of(const _CharT* __s, size_type __pos=0) const
+    size_type find_first_of(const _CharT* __s, size_type __pos=0) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__s != nullptr, "string_view::find_first_of(): received nullptr");
         return __str_find_first_of<value_type, size_type, traits_type, npos>
@@ -521,7 +538,7 @@ public:
     { return rfind(__c, __pos); }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find_last_of(const _CharT* __s, size_type __pos, size_type __n) const
+    size_type find_last_of(const _CharT* __s, size_type __pos, size_type __n) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string_view::find_last_of(): received nullptr");
         return __str_find_last_of<value_type, size_type, traits_type, npos>
@@ -529,7 +546,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find_last_of(const _CharT* __s, size_type __pos=npos) const
+    size_type find_last_of(const _CharT* __s, size_type __pos=npos) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__s != nullptr, "string_view::find_last_of(): received nullptr");
         return __str_find_last_of<value_type, size_type, traits_type, npos>
@@ -553,7 +570,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const
+    size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string_view::find_first_not_of(): received nullptr");
         return __str_find_first_not_of<value_type, size_type, traits_type, npos>
@@ -561,7 +578,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find_first_not_of(const _CharT* __s, size_type __pos=0) const
+    size_type find_first_not_of(const _CharT* __s, size_type __pos=0) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__s != nullptr, "string_view::find_first_not_of(): received nullptr");
         return __str_find_first_not_of<value_type, size_type, traits_type, npos>
@@ -585,7 +602,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const
+    size_type find_last_not_of(const _CharT* __s, size_type __pos, size_type __n) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__n == 0 || __s != nullptr, "string_view::find_last_not_of(): received nullptr");
         return __str_find_last_not_of<value_type, size_type, traits_type, npos>
@@ -593,7 +610,7 @@ public:
     }
 
     _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-    size_type find_last_not_of(const _CharT* __s, size_type __pos=npos) const
+    size_type find_last_not_of(const _CharT* __s, size_type __pos=npos) const _NOEXCEPT
     {
         _LIBCPP_ASSERT(__s != nullptr, "string_view::find_last_not_of(): received nullptr");
         return __str_find_last_not_of<value_type, size_type, traits_type, npos>
@@ -645,6 +662,13 @@ private:
     size_type           __size;
 };
 
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_RANGES)
+template <class _CharT, class _Traits>
+inline constexpr bool ranges::enable_view<basic_string_view<_CharT, _Traits>> = true;
+
+template <class _CharT, class _Traits>
+inline constexpr bool ranges::enable_borrowed_range<basic_string_view<_CharT, _Traits> > = true;
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_RANGES)
 
 // [string.view.comparison]
 // operator ==
@@ -842,7 +866,7 @@ inline namespace literals
         return basic_string_view<wchar_t> (__str, __len);
     }
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
     inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
     basic_string_view<char8_t> operator "" sv(const char8_t *__str, size_t __len) _NOEXCEPT
     {
lib/libcxx/include/strstream
@@ -130,8 +130,8 @@ private:
 */
 
 #include <__config>
-#include <ostream>
 #include <istream>
+#include <ostream>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -163,7 +163,7 @@ public:
     strstreambuf(strstreambuf&& __rhs);
     _LIBCPP_INLINE_VISIBILITY
     strstreambuf& operator=(strstreambuf&& __rhs);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     virtual ~strstreambuf();
 
@@ -233,7 +233,7 @@ strstreambuf::operator=(strstreambuf&& __rhs)
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 class _LIBCPP_TYPE_VIS istrstream
     : public istream
@@ -268,7 +268,7 @@ public:
         __sb_ = _VSTD::move(__rhs.__sb_);
         return *this;
     }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     virtual ~istrstream();
 
@@ -317,7 +317,7 @@ public:
         __sb_ = _VSTD::move(__rhs.__sb_);
         return *this;
     }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     virtual ~ostrstream();
 
@@ -377,7 +377,7 @@ public:
         __sb_ = _VSTD::move(__rhs.__sb_);
         return *this;
     }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     virtual ~strstream();
 
@@ -404,4 +404,4 @@ private:
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_STRSTREAM
+#endif // _LIBCPP_STRSTREAM
lib/libcxx/include/system_error
@@ -142,11 +142,14 @@ template <> struct hash<std::error_condition>;
 
 */
 
+#include <__config>
 #include <__errc>
-#include <type_traits>
-#include <stdexcept>
+#include <__functional/unary_function.h>
 #include <__functional_base>
+#include <compare>
+#include <stdexcept>
 #include <string>
+#include <type_traits>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -289,8 +292,7 @@ public:
     string message() const;
 
     _LIBCPP_INLINE_VISIBILITY
-        _LIBCPP_EXPLICIT
-        operator bool() const _NOEXCEPT {return __val_ != 0;}
+    explicit operator bool() const _NOEXCEPT {return __val_ != 0;}
 };
 
 inline _LIBCPP_INLINE_VISIBILITY
@@ -366,8 +368,7 @@ public:
     string message() const;
 
     _LIBCPP_INLINE_VISIBILITY
-        _LIBCPP_EXPLICIT
-        operator bool() const _NOEXCEPT {return __val_ != 0;}
+    explicit operator bool() const _NOEXCEPT {return __val_ != 0;}
 };
 
 inline _LIBCPP_INLINE_VISIBILITY
@@ -484,4 +485,4 @@ void __throw_system_error(int ev, const char* what_arg);
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_SYSTEM_ERROR
+#endif // _LIBCPP_SYSTEM_ERROR
lib/libcxx/include/tgmath.h
@@ -31,6 +31,6 @@
 
 #include_next <tgmath.h>
 
-#endif  // __cplusplus
+#endif // __cplusplus
 
-#endif  // _LIBCPP_TGMATH_H
+#endif // _LIBCPP_TGMATH_H
lib/libcxx/include/thread
@@ -83,20 +83,20 @@ void sleep_for(const chrono::duration<Rep, Period>& rel_time);
 */
 
 #include <__config>
-#include <iosfwd>
+#include <__debug>
 #include <__functional_base>
-#include <type_traits>
+#include <__mutex_base>
+#include <__threading_support>
+#include <__utility/__decay_copy.h>
+#include <__utility/forward.h>
+#include <chrono>
 #include <cstddef>
 #include <functional>
+#include <iosfwd>
 #include <memory>
 #include <system_error>
-#include <chrono>
-#include <__mutex_base>
-#ifndef _LIBCPP_CXX03_LANG
 #include <tuple>
-#endif
-#include <__threading_support>
-#include <__debug>
+#include <type_traits>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -346,7 +346,7 @@ thread::thread(_Fp __f)
         __throw_system_error(__ec, "thread constructor failed");
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 inline _LIBCPP_INLINE_VISIBILITY
 void swap(thread& __x, thread& __y) _NOEXCEPT {__x.swap(__y);}
@@ -362,12 +362,11 @@ sleep_for(const chrono::duration<_Rep, _Period>& __d)
 {
     if (__d > chrono::duration<_Rep, _Period>::zero())
     {
-#if defined(_LIBCPP_COMPILER_GCC) && (__powerpc__ || __POWERPC__)
-    //  GCC's long double const folding is incomplete for IBM128 long doubles.
-        _LIBCPP_CONSTEXPR chrono::duration<long double> _Max = chrono::duration<long double>(ULLONG_MAX/1000000000ULL) ;
-#else
-        _LIBCPP_CONSTEXPR chrono::duration<long double> _Max = chrono::nanoseconds::max();
-#endif
+        // The standard guarantees a 64bit signed integer resolution for nanoseconds,
+        // so use INT64_MAX / 1e9 as cut-off point. Use a constant to avoid <climits>
+        // and issues with long double folding on PowerPC with GCC.
+        _LIBCPP_CONSTEXPR chrono::duration<long double> _Max =
+            chrono::duration<long double>(9223372036.0L);
         chrono::nanoseconds __ns;
         if (__d < _Max)
         {
@@ -411,4 +410,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_THREAD
+#endif // _LIBCPP_THREAD
lib/libcxx/include/tuple
@@ -38,35 +38,39 @@ public:
     template <class Alloc>
         tuple(allocator_arg_t, const Alloc& a);
     template <class Alloc>
-        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, const T&...);
+        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, const T&...);          // constexpr in C++20
     template <class Alloc, class... U>
-        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, U&&...);
+        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, U&&...);               // constexpr in C++20
     template <class Alloc>
-        tuple(allocator_arg_t, const Alloc& a, const tuple&);
+        tuple(allocator_arg_t, const Alloc& a, const tuple&);                             // constexpr in C++20
     template <class Alloc>
-        tuple(allocator_arg_t, const Alloc& a, tuple&&);
+        tuple(allocator_arg_t, const Alloc& a, tuple&&);                                  // constexpr in C++20
     template <class Alloc, class... U>
-        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, const tuple<U...>&);
+        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, const tuple<U...>&);   // constexpr in C++20
     template <class Alloc, class... U>
-        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, tuple<U...>&&);
+        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, tuple<U...>&&);        // constexpr in C++20
     template <class Alloc, class U1, class U2>
-        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, const pair<U1, U2>&);
+        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, const pair<U1, U2>&);  // constexpr in C++20
     template <class Alloc, class U1, class U2>
-        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, pair<U1, U2>&&);
+        explicit(see-below) tuple(allocator_arg_t, const Alloc& a, pair<U1, U2>&&);       // constexpr in C++20
 
-    tuple& operator=(const tuple&);
-    tuple&
-        operator=(tuple&&) noexcept(AND(is_nothrow_move_assignable<T>::value ...));
+    tuple& operator=(const tuple&);                                                       // constexpr in C++20
+    tuple& operator=(tuple&&) noexcept(is_nothrow_move_assignable_v<T> && ...);           // constexpr in C++20
     template <class... U>
-        tuple& operator=(const tuple<U...>&);
+        tuple& operator=(const tuple<U...>&);                                             // constexpr in C++20
     template <class... U>
-        tuple& operator=(tuple<U...>&&);
+        tuple& operator=(tuple<U...>&&);                                                  // constexpr in C++20
     template <class U1, class U2>
-        tuple& operator=(const pair<U1, U2>&); // iff sizeof...(T) == 2
+        tuple& operator=(const pair<U1, U2>&); // iff sizeof...(T) == 2                   // constexpr in C++20
     template <class U1, class U2>
-        tuple& operator=(pair<U1, U2>&&); // iff sizeof...(T) == 2
+        tuple& operator=(pair<U1, U2>&&); // iff sizeof...(T) == 2                        // constexpr in C++20
 
-    void swap(tuple&) noexcept(AND(swap(declval<T&>(), declval<T&>())...));
+    template<class U, size_t N>
+        tuple& operator=(array<U, N> const&) // iff sizeof...(T) == N, EXTENSION
+    template<class U, size_t N>
+        tuple& operator=(array<U, N>&&) // iff sizeof...(T) == N, EXTENSION
+
+    void swap(tuple&) noexcept(AND(swap(declval<T&>(), declval<T&>())...));               // constexpr in C++20
 };
 
 template <class ...T>
@@ -146,10 +150,16 @@ template <class... Types>
 */
 
 #include <__config>
+#include <__functional/unwrap_ref.h>
+#include <__functional_base>
+#include <__memory/allocator_arg_t.h>
+#include <__memory/uses_allocator.h>
 #include <__tuple>
+#include <__utility/forward.h>
+#include <__utility/move.h>
+#include <compare>
 #include <cstddef>
 #include <type_traits>
-#include <__functional_base>
 #include <utility>
 #include <version>
 
@@ -170,7 +180,7 @@ template <size_t _Ip, class _Hp,
 class __tuple_leaf;
 
 template <size_t _Ip, class _Hp, bool _Ep>
-inline _LIBCPP_INLINE_VISIBILITY
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 void swap(__tuple_leaf<_Ip, _Hp, _Ep>& __x, __tuple_leaf<_Ip, _Hp, _Ep>& __y)
     _NOEXCEPT_(__is_nothrow_swappable<_Hp>::value)
 {
@@ -191,29 +201,30 @@ class __tuple_leaf
 #endif
     }
 
+    _LIBCPP_CONSTEXPR_AFTER_CXX11
     __tuple_leaf& operator=(const __tuple_leaf&);
 public:
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR __tuple_leaf()
+    _LIBCPP_INLINE_VISIBILITY constexpr __tuple_leaf()
              _NOEXCEPT_(is_nothrow_default_constructible<_Hp>::value) : __value_()
        {static_assert(!is_reference<_Hp>::value,
               "Attempted to default construct a reference element in a tuple");}
 
     template <class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY constexpr
         __tuple_leaf(integral_constant<int, 0>, const _Alloc&)
             : __value_()
         {static_assert(!is_reference<_Hp>::value,
               "Attempted to default construct a reference element in a tuple");}
 
     template <class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY constexpr
         __tuple_leaf(integral_constant<int, 1>, const _Alloc& __a)
             : __value_(allocator_arg_t(), __a)
         {static_assert(!is_reference<_Hp>::value,
               "Attempted to default construct a reference element in a tuple");}
 
     template <class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY constexpr
         __tuple_leaf(integral_constant<int, 2>, const _Alloc& __a)
             : __value_(__a)
         {static_assert(!is_reference<_Hp>::value,
@@ -234,21 +245,21 @@ public:
        "Attempted construction of reference element binds to a temporary whose lifetime has ended");}
 
     template <class _Tp, class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
         explicit __tuple_leaf(integral_constant<int, 0>, const _Alloc&, _Tp&& __t)
             : __value_(_VSTD::forward<_Tp>(__t))
         {static_assert(__can_bind_reference<_Tp&&>(),
        "Attempted construction of reference element binds to a temporary whose lifetime has ended");}
 
     template <class _Tp, class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
         explicit __tuple_leaf(integral_constant<int, 1>, const _Alloc& __a, _Tp&& __t)
             : __value_(allocator_arg_t(), __a, _VSTD::forward<_Tp>(__t))
         {static_assert(!is_reference<_Hp>::value,
             "Attempted to uses-allocator construct a reference element in a tuple");}
 
     template <class _Tp, class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
         explicit __tuple_leaf(integral_constant<int, 2>, const _Alloc& __a, _Tp&& __t)
             : __value_(_VSTD::forward<_Tp>(__t), __a)
         {static_assert(!is_reference<_Hp>::value,
@@ -257,16 +268,7 @@ public:
     __tuple_leaf(const __tuple_leaf& __t) = default;
     __tuple_leaf(__tuple_leaf&& __t) = default;
 
-    template <class _Tp>
-        _LIBCPP_INLINE_VISIBILITY
-        __tuple_leaf&
-        operator=(_Tp&& __t) _NOEXCEPT_((is_nothrow_assignable<_Hp&, _Tp>::value))
-        {
-            __value_ = _VSTD::forward<_Tp>(__t);
-            return *this;
-        }
-
-    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
     int swap(__tuple_leaf& __t) _NOEXCEPT_(__is_nothrow_swappable<__tuple_leaf>::value)
     {
         _VSTD::swap(*this, __t);
@@ -281,23 +283,23 @@ template <size_t _Ip, class _Hp>
 class __tuple_leaf<_Ip, _Hp, true>
     : private _Hp
 {
-
+    _LIBCPP_CONSTEXPR_AFTER_CXX11
     __tuple_leaf& operator=(const __tuple_leaf&);
 public:
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR __tuple_leaf()
+    _LIBCPP_INLINE_VISIBILITY constexpr __tuple_leaf()
              _NOEXCEPT_(is_nothrow_default_constructible<_Hp>::value) {}
 
     template <class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY constexpr
         __tuple_leaf(integral_constant<int, 0>, const _Alloc&) {}
 
     template <class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY constexpr
         __tuple_leaf(integral_constant<int, 1>, const _Alloc& __a)
             : _Hp(allocator_arg_t(), __a) {}
 
     template <class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY constexpr
         __tuple_leaf(integral_constant<int, 2>, const _Alloc& __a)
             : _Hp(__a) {}
 
@@ -314,33 +316,24 @@ public:
             : _Hp(_VSTD::forward<_Tp>(__t)) {}
 
     template <class _Tp, class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY constexpr
         explicit __tuple_leaf(integral_constant<int, 0>, const _Alloc&, _Tp&& __t)
             : _Hp(_VSTD::forward<_Tp>(__t)) {}
 
     template <class _Tp, class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY constexpr
         explicit __tuple_leaf(integral_constant<int, 1>, const _Alloc& __a, _Tp&& __t)
             : _Hp(allocator_arg_t(), __a, _VSTD::forward<_Tp>(__t)) {}
 
     template <class _Tp, class _Alloc>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY constexpr
         explicit __tuple_leaf(integral_constant<int, 2>, const _Alloc& __a, _Tp&& __t)
             : _Hp(_VSTD::forward<_Tp>(__t), __a) {}
 
     __tuple_leaf(__tuple_leaf const &) = default;
     __tuple_leaf(__tuple_leaf &&) = default;
 
-    template <class _Tp>
-        _LIBCPP_INLINE_VISIBILITY
-        __tuple_leaf&
-        operator=(_Tp&& __t) _NOEXCEPT_((is_nothrow_assignable<_Hp&, _Tp>::value))
-        {
-            _Hp::operator=(_VSTD::forward<_Tp>(__t));
-            return *this;
-        }
-
-    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
     int
     swap(__tuple_leaf& __t) _NOEXCEPT_(__is_nothrow_swappable<__tuple_leaf>::value)
     {
@@ -353,7 +346,7 @@ public:
 };
 
 template <class ..._Tp>
-_LIBCPP_INLINE_VISIBILITY
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
 void __swallow(_Tp&&...) _NOEXCEPT {}
 
 template <class _Tp>
@@ -373,7 +366,7 @@ struct _LIBCPP_DECLSPEC_EMPTY_BASES __tuple_impl<__tuple_indices<_Indx...>, _Tp.
     : public __tuple_leaf<_Indx, _Tp>...
 {
     _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_CONSTEXPR __tuple_impl()
+    constexpr __tuple_impl()
         _NOEXCEPT_(__all<is_nothrow_default_constructible<_Tp>::value...>::value) {}
 
     template <size_t ..._Uf, class ..._Tf,
@@ -391,7 +384,7 @@ struct _LIBCPP_DECLSPEC_EMPTY_BASES __tuple_impl<__tuple_indices<_Indx...>, _Tp.
 
     template <class _Alloc, size_t ..._Uf, class ..._Tf,
               size_t ..._Ul, class ..._Tl, class ..._Up>
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
         explicit
         __tuple_impl(allocator_arg_t, const _Alloc& __a,
                      __tuple_indices<_Uf...>, __tuple_types<_Tf...>,
@@ -421,7 +414,7 @@ struct _LIBCPP_DECLSPEC_EMPTY_BASES __tuple_impl<__tuple_indices<_Indx...>, _Tp.
                          __tuple_constructible<_Tuple, tuple<_Tp...> >::value
                       >::type
              >
-        _LIBCPP_INLINE_VISIBILITY
+        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
         __tuple_impl(allocator_arg_t, const _Alloc& __a, _Tuple&& __t)
             : __tuple_leaf<_Indx, _Tp>(__uses_alloc_ctor<_Tp, _Alloc, typename tuple_element<_Indx,
                                        typename __make_tuple_types<_Tuple>::type>::type>(), __a,
@@ -429,49 +422,30 @@ struct _LIBCPP_DECLSPEC_EMPTY_BASES __tuple_impl<__tuple_indices<_Indx...>, _Tp.
                                        typename __make_tuple_types<_Tuple>::type>::type>(_VSTD::get<_Indx>(__t)))...
             {}
 
-    template <class _Tuple>
-        _LIBCPP_INLINE_VISIBILITY
-        typename enable_if
-        <
-            __tuple_assignable<_Tuple, tuple<_Tp...> >::value,
-            __tuple_impl&
-        >::type
-        operator=(_Tuple&& __t) _NOEXCEPT_((__all<is_nothrow_assignable<_Tp&, typename tuple_element<_Indx,
-                                       typename __make_tuple_types<_Tuple>::type>::type>::value...>::value))
-        {
-            __swallow(__tuple_leaf<_Indx, _Tp>::operator=(_VSTD::forward<typename tuple_element<_Indx,
-                                       typename __make_tuple_types<_Tuple>::type>::type>(_VSTD::get<_Indx>(__t)))...);
-            return *this;
-        }
-
     __tuple_impl(const __tuple_impl&) = default;
     __tuple_impl(__tuple_impl&&) = default;
 
-    _LIBCPP_INLINE_VISIBILITY
-    __tuple_impl&
-    operator=(const __tuple_impl& __t) _NOEXCEPT_((__all<is_nothrow_copy_assignable<_Tp>::value...>::value))
-    {
-        __swallow(__tuple_leaf<_Indx, _Tp>::operator=(static_cast<const __tuple_leaf<_Indx, _Tp>&>(__t).get())...);
-        return *this;
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
-    __tuple_impl&
-    operator=(__tuple_impl&& __t) _NOEXCEPT_((__all<is_nothrow_move_assignable<_Tp>::value...>::value))
-    {
-        __swallow(__tuple_leaf<_Indx, _Tp>::operator=(_VSTD::forward<_Tp>(static_cast<__tuple_leaf<_Indx, _Tp>&>(__t).get()))...);
-        return *this;
-    }
-
-    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
     void swap(__tuple_impl& __t)
         _NOEXCEPT_(__all<__is_nothrow_swappable<_Tp>::value...>::value)
     {
-        __swallow(__tuple_leaf<_Indx, _Tp>::swap(static_cast<__tuple_leaf<_Indx, _Tp>&>(__t))...);
+        _VSTD::__swallow(__tuple_leaf<_Indx, _Tp>::swap(static_cast<__tuple_leaf<_Indx, _Tp>&>(__t))...);
     }
 };
 
+template<class _Dest, class _Source, size_t ..._Np>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+void __memberwise_copy_assign(_Dest& __dest, _Source const& __source, __tuple_indices<_Np...>) {
+    _VSTD::__swallow(((_VSTD::get<_Np>(__dest) = _VSTD::get<_Np>(__source)), void(), 0)...);
+}
 
+template<class _Dest, class _Source, class ..._Up, size_t ..._Np>
+_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+void __memberwise_forward_assign(_Dest& __dest, _Source&& __source, __tuple_types<_Up...>, __tuple_indices<_Np...>) {
+    _VSTD::__swallow(((
+        _VSTD::get<_Np>(__dest) = _VSTD::forward<_Up>(_VSTD::get<_Np>(__source))
+    ), void(), 0)...);
+}
 
 template <class ..._Tp>
 class _LIBCPP_TEMPLATE_VIS tuple
@@ -480,165 +454,6 @@ class _LIBCPP_TEMPLATE_VIS tuple
 
     _BaseT __base_;
 
-#if defined(_LIBCPP_ENABLE_TUPLE_IMPLICIT_REDUCED_ARITY_EXTENSION)
-    static constexpr bool _EnableImplicitReducedArityExtension = true;
-#else
-    static constexpr bool _EnableImplicitReducedArityExtension = false;
-#endif
-
-    template <class ..._Args>
-    struct _PackExpandsToThisTuple : false_type {};
-
-    template <class _Arg>
-    struct _PackExpandsToThisTuple<_Arg>
-        : is_same<typename __uncvref<_Arg>::type, tuple> {};
-
-    template <bool _MaybeEnable, class _Dummy = void>
-    struct _CheckArgsConstructor : __check_tuple_constructor_fail {};
-
-    template <class _Dummy>
-    struct _CheckArgsConstructor<true, _Dummy>
-    {
-        template <int&...>
-        static constexpr bool __enable_implicit_default() {
-           return __all<__is_implicitly_default_constructible<_Tp>::value... >::value;
-        }
-
-        template <int&...>
-        static constexpr bool __enable_explicit_default() {
-            return
-                __all<is_default_constructible<_Tp>::value...>::value &&
-                !__enable_implicit_default< >();
-        }
-
-
-        template <class ..._Args>
-        static constexpr bool __enable_explicit() {
-            return
-                __tuple_constructible<
-                    tuple<_Args...>,
-                    typename __make_tuple_types<tuple,
-                             sizeof...(_Args) < sizeof...(_Tp) ?
-                                 sizeof...(_Args) :
-                                 sizeof...(_Tp)>::type
-                >::value &&
-                !__tuple_convertible<
-                    tuple<_Args...>,
-                    typename __make_tuple_types<tuple,
-                             sizeof...(_Args) < sizeof...(_Tp) ?
-                                 sizeof...(_Args) :
-                                 sizeof...(_Tp)>::type
-                >::value &&
-                __all_default_constructible<
-                    typename __make_tuple_types<tuple, sizeof...(_Tp),
-                             sizeof...(_Args) < sizeof...(_Tp) ?
-                                 sizeof...(_Args) :
-                                 sizeof...(_Tp)>::type
-                >::value;
-        }
-
-        template <class ..._Args>
-        static constexpr bool __enable_implicit() {
-            return
-               __tuple_constructible<
-                    tuple<_Args...>,
-                    typename __make_tuple_types<tuple,
-                             sizeof...(_Args) < sizeof...(_Tp) ?
-                                 sizeof...(_Args) :
-                                 sizeof...(_Tp)>::type
-                >::value &&
-                __tuple_convertible<
-                    tuple<_Args...>,
-                    typename __make_tuple_types<tuple,
-                             sizeof...(_Args) < sizeof...(_Tp) ?
-                                 sizeof...(_Args) :
-                                 sizeof...(_Tp)>::type
-                >::value &&
-                __all_default_constructible<
-                    typename __make_tuple_types<tuple, sizeof...(_Tp),
-                             sizeof...(_Args) < sizeof...(_Tp) ?
-                                 sizeof...(_Args) :
-                                 sizeof...(_Tp)>::type
-                >::value;
-        }
-    };
-
-    template <bool _MaybeEnable,
-              bool = sizeof...(_Tp) == 1,
-              class _Dummy = void>
-    struct _CheckTupleLikeConstructor : __check_tuple_constructor_fail {};
-
-    template <class _Dummy>
-    struct _CheckTupleLikeConstructor<true, false, _Dummy>
-    {
-        template <class _Tuple>
-        static constexpr bool __enable_implicit() {
-            return __tuple_constructible<_Tuple, tuple>::value
-                && __tuple_convertible<_Tuple, tuple>::value;
-        }
-
-        template <class _Tuple>
-        static constexpr bool __enable_explicit() {
-            return __tuple_constructible<_Tuple, tuple>::value
-               && !__tuple_convertible<_Tuple, tuple>::value;
-        }
-    };
-
-    template <class _Dummy>
-    struct _CheckTupleLikeConstructor<true, true, _Dummy>
-    {
-        // This trait is used to disable the tuple-like constructor when
-        // the UTypes... constructor should be selected instead.
-        // See LWG issue #2549.
-        template <class _Tuple>
-        using _PreferTupleLikeConstructor = _Or<
-            // Don't attempt the two checks below if the tuple we are given
-            // has the same type as this tuple.
-            _IsSame<__uncvref_t<_Tuple>, tuple>,
-            _Lazy<_And,
-                _Not<is_constructible<_Tp..., _Tuple>>,
-                _Not<is_convertible<_Tuple, _Tp...>>
-            >
-        >;
-
-        template <class _Tuple>
-        static constexpr bool __enable_implicit() {
-            return _And<
-                __tuple_constructible<_Tuple, tuple>,
-                __tuple_convertible<_Tuple, tuple>,
-                _PreferTupleLikeConstructor<_Tuple>
-            >::value;
-        }
-
-        template <class _Tuple>
-        static constexpr bool __enable_explicit() {
-            return _And<
-                __tuple_constructible<_Tuple, tuple>,
-                _PreferTupleLikeConstructor<_Tuple>,
-                _Not<__tuple_convertible<_Tuple, tuple>>
-            >::value;
-        }
-    };
-
-    template <class _Tuple, bool _DisableIfLValue>
-    using _EnableImplicitTupleLikeConstructor = _EnableIf<
-                         _CheckTupleLikeConstructor<
-                             __tuple_like_with_size<_Tuple, sizeof...(_Tp)>::value
-                             && !_PackExpandsToThisTuple<_Tuple>::value
-                             && (!is_lvalue_reference<_Tuple>::value || !_DisableIfLValue)
-                         >::template __enable_implicit<_Tuple>(),
-                         bool
-                      >;
-
-    template <class _Tuple, bool _DisableIfLValue>
-    using _EnableExplicitTupleLikeConstructor = _EnableIf<
-                         _CheckTupleLikeConstructor<
-                             __tuple_like_with_size<_Tuple, sizeof...(_Tp)>::value
-                             && !_PackExpandsToThisTuple<_Tuple>::value
-                             && (!is_lvalue_reference<_Tuple>::value || !_DisableIfLValue)
-                         >::template __enable_explicit<_Tuple>(),
-                         bool
-                      >;
     template <size_t _Jp, class ..._Up> friend _LIBCPP_CONSTEXPR_AFTER_CXX11
         typename tuple_element<_Jp, tuple<_Up...> >::type& get(tuple<_Up...>&) _NOEXCEPT;
     template <size_t _Jp, class ..._Up> friend _LIBCPP_CONSTEXPR_AFTER_CXX11
@@ -648,57 +463,69 @@ class _LIBCPP_TEMPLATE_VIS tuple
     template <size_t _Jp, class ..._Up> friend _LIBCPP_CONSTEXPR_AFTER_CXX11
         const typename tuple_element<_Jp, tuple<_Up...> >::type&& get(const tuple<_Up...>&&) _NOEXCEPT;
 public:
-
-    template <bool _Dummy = true, _EnableIf<
-        _CheckArgsConstructor<_Dummy>::__enable_implicit_default()
-    , void*> = nullptr>
+    // [tuple.cnstr]
+
+    // tuple() constructors (including allocator_arg_t variants)
+    template <template<class...> class _IsImpDefault = __is_implicitly_default_constructible, _EnableIf<
+        _And<
+            _IsImpDefault<_Tp>... // explicit check
+        >::value
+    , int> = 0>
     _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
     tuple()
-        _NOEXCEPT_(__all<is_nothrow_default_constructible<_Tp>::value...>::value) {}
-
-    template <bool _Dummy = true, _EnableIf<
-        _CheckArgsConstructor<_Dummy>::__enable_explicit_default()
-    , void*> = nullptr>
-    explicit _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-    tuple()
-        _NOEXCEPT_(__all<is_nothrow_default_constructible<_Tp>::value...>::value) {}
-
-    tuple(tuple const&) = default;
-    tuple(tuple&&) = default;
-
-    template <class _AllocArgT, class _Alloc, _EnableIf<
-             _CheckArgsConstructor<_IsSame<allocator_arg_t, _AllocArgT>::value >::__enable_implicit_default()
-      , void*> = nullptr
-    >
-    _LIBCPP_INLINE_VISIBILITY
-    tuple(_AllocArgT, _Alloc const& __a)
+        _NOEXCEPT_(_And<is_nothrow_default_constructible<_Tp>...>::value)
+    { }
+
+    template <template<class...> class _IsImpDefault = __is_implicitly_default_constructible,
+              template<class...> class _IsDefault = is_default_constructible, _EnableIf<
+        _And<
+            _IsDefault<_Tp>...,
+            _Not<_Lazy<_And, _IsImpDefault<_Tp>...> > // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
+    explicit tuple()
+        _NOEXCEPT_(_And<is_nothrow_default_constructible<_Tp>...>::value)
+    { }
+
+    template <class _Alloc, template<class...> class _IsImpDefault = __is_implicitly_default_constructible, _EnableIf<
+        _And<
+            _IsImpDefault<_Tp>... // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple(allocator_arg_t, _Alloc const& __a)
       : __base_(allocator_arg_t(), __a,
                     __tuple_indices<>(), __tuple_types<>(),
                     typename __make_tuple_indices<sizeof...(_Tp), 0>::type(),
                     __tuple_types<_Tp...>()) {}
 
-    template <class _AllocArgT, class _Alloc, _EnableIf<
-             _CheckArgsConstructor<_IsSame<allocator_arg_t, _AllocArgT>::value>::__enable_explicit_default()
-      , void*> = nullptr
-    >
-    explicit _LIBCPP_INLINE_VISIBILITY
-    tuple(_AllocArgT, _Alloc const& __a)
+    template <class _Alloc,
+              template<class...> class _IsImpDefault = __is_implicitly_default_constructible,
+              template<class...> class _IsDefault = is_default_constructible, _EnableIf<
+        _And<
+            _IsDefault<_Tp>...,
+            _Not<_Lazy<_And, _IsImpDefault<_Tp>...> > // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    explicit tuple(allocator_arg_t, _Alloc const& __a)
       : __base_(allocator_arg_t(), __a,
                     __tuple_indices<>(), __tuple_types<>(),
                     typename __make_tuple_indices<sizeof...(_Tp), 0>::type(),
                     __tuple_types<_Tp...>()) {}
 
-    template <bool _Dummy = true,
-              typename enable_if
-                      <
-                         _CheckArgsConstructor<
-                            _Dummy
-                         >::template __enable_implicit<_Tp const&...>(),
-                         bool
-                      >::type = false
-        >
+    // tuple(const T&...) constructors (including allocator_arg_t variants)
+    template <template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) >= 1>,
+            is_copy_constructible<_Tp>...,
+            is_convertible<const _Tp&, _Tp>... // explicit check
+        >::value
+    , int> = 0>
     _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    tuple(const _Tp& ... __t) _NOEXCEPT_((__all<is_nothrow_copy_constructible<_Tp>::value...>::value))
+    tuple(const _Tp& ... __t)
+        _NOEXCEPT_(_And<is_nothrow_copy_constructible<_Tp>...>::value)
         : __base_(typename __make_tuple_indices<sizeof...(_Tp)>::type(),
                 typename __make_tuple_types<tuple, sizeof...(_Tp)>::type(),
                 typename __make_tuple_indices<0>::type(),
@@ -706,17 +533,16 @@ public:
                 __t...
                ) {}
 
-    template <bool _Dummy = true,
-              typename enable_if
-                      <
-                         _CheckArgsConstructor<
-                            _Dummy
-                         >::template __enable_explicit<_Tp const&...>(),
-                         bool
-                      >::type = false
-        >
+    template <template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) >= 1>,
+            is_copy_constructible<_Tp>...,
+            _Not<_Lazy<_And, is_convertible<const _Tp&, _Tp>...> > // explicit check
+        >::value
+    , int> = 0>
     _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    explicit tuple(const _Tp& ... __t) _NOEXCEPT_((__all<is_nothrow_copy_constructible<_Tp>::value...>::value))
+    explicit tuple(const _Tp& ... __t)
+        _NOEXCEPT_(_And<is_nothrow_copy_constructible<_Tp>...>::value)
         : __base_(typename __make_tuple_indices<sizeof...(_Tp)>::type(),
                 typename __make_tuple_types<tuple, sizeof...(_Tp)>::type(),
                 typename __make_tuple_indices<0>::type(),
@@ -724,17 +550,15 @@ public:
                 __t...
                ) {}
 
-    template <class _Alloc, bool _Dummy = true,
-              typename enable_if
-                      <
-                         _CheckArgsConstructor<
-                            _Dummy
-                         >::template __enable_implicit<_Tp const&...>(),
-                         bool
-                      >::type = false
-        >
-      _LIBCPP_INLINE_VISIBILITY
-      tuple(allocator_arg_t, const _Alloc& __a, const _Tp& ... __t)
+    template <class _Alloc, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) >= 1>,
+            is_copy_constructible<_Tp>...,
+            is_convertible<const _Tp&, _Tp>... // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple(allocator_arg_t, const _Alloc& __a, const _Tp& ... __t)
         : __base_(allocator_arg_t(), __a,
                 typename __make_tuple_indices<sizeof...(_Tp)>::type(),
                 typename __make_tuple_types<tuple, sizeof...(_Tp)>::type(),
@@ -743,18 +567,15 @@ public:
                 __t...
                ) {}
 
-    template <class _Alloc, bool _Dummy = true,
-              typename enable_if
-                      <
-                         _CheckArgsConstructor<
-                            _Dummy
-                         >::template __enable_explicit<_Tp const&...>(),
-                         bool
-                      >::type = false
-        >
-      _LIBCPP_INLINE_VISIBILITY
-      explicit
-      tuple(allocator_arg_t, const _Alloc& __a, const _Tp& ... __t)
+    template <class _Alloc, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) >= 1>,
+            is_copy_constructible<_Tp>...,
+            _Not<_Lazy<_And, is_convertible<const _Tp&, _Tp>...> > // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    explicit tuple(allocator_arg_t, const _Alloc& __a, const _Tp& ... __t)
         : __base_(allocator_arg_t(), __a,
                 typename __make_tuple_indices<sizeof...(_Tp)>::type(),
                 typename __make_tuple_types<tuple, sizeof...(_Tp)>::type(),
@@ -763,193 +584,493 @@ public:
                 __t...
                ) {}
 
-    template <class ..._Up,
-              bool _PackIsTuple = _PackExpandsToThisTuple<_Up...>::value,
-              typename enable_if
-                      <
-                         _CheckArgsConstructor<
-                             sizeof...(_Up) == sizeof...(_Tp)
-                             && !_PackIsTuple
-                         >::template __enable_implicit<_Up...>() ||
-                        _CheckArgsConstructor<
-                            _EnableImplicitReducedArityExtension
-                            && sizeof...(_Up) < sizeof...(_Tp)
-                            && !_PackIsTuple
-                         >::template __enable_implicit<_Up...>(),
-                         bool
-                      >::type = false
-             >
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-        tuple(_Up&&... __u)
-            _NOEXCEPT_((
-                is_nothrow_constructible<_BaseT,
-                    typename __make_tuple_indices<sizeof...(_Up)>::type,
-                    typename __make_tuple_types<tuple, sizeof...(_Up)>::type,
-                    typename __make_tuple_indices<sizeof...(_Tp), sizeof...(_Up)>::type,
-                    typename __make_tuple_types<tuple, sizeof...(_Tp), sizeof...(_Up)>::type,
-                    _Up...
-                >::value
-            ))
-            : __base_(typename __make_tuple_indices<sizeof...(_Up)>::type(),
+    // tuple(U&& ...) constructors (including allocator_arg_t variants)
+    template <class ..._Up> struct _IsThisTuple : false_type { };
+    template <class _Up> struct _IsThisTuple<_Up> : is_same<__uncvref_t<_Up>, tuple> { };
+
+    template <class ..._Up>
+    struct _EnableUTypesCtor : _And<
+        _BoolConstant<sizeof...(_Tp) >= 1>,
+        _Not<_IsThisTuple<_Up...> >, // extension to allow mis-behaved user constructors
+        is_constructible<_Tp, _Up>...
+    > { };
+
+    template <class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableUTypesCtor<_Up...>,
+            is_convertible<_Up, _Tp>... // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    tuple(_Up&&... __u)
+        _NOEXCEPT_((_And<is_nothrow_constructible<_Tp, _Up>...>::value))
+        : __base_(typename __make_tuple_indices<sizeof...(_Up)>::type(),
                     typename __make_tuple_types<tuple, sizeof...(_Up)>::type(),
                     typename __make_tuple_indices<sizeof...(_Tp), sizeof...(_Up)>::type(),
                     typename __make_tuple_types<tuple, sizeof...(_Tp), sizeof...(_Up)>::type(),
                     _VSTD::forward<_Up>(__u)...) {}
 
-    template <class ..._Up,
-              typename enable_if
-                      <
-                         _CheckArgsConstructor<
-                             sizeof...(_Up) <= sizeof...(_Tp)
-                             && !_PackExpandsToThisTuple<_Up...>::value
-                         >::template __enable_explicit<_Up...>() ||
-                         _CheckArgsConstructor<
-                            !_EnableImplicitReducedArityExtension
-                            && sizeof...(_Up) < sizeof...(_Tp)
-                            && !_PackExpandsToThisTuple<_Up...>::value
-                         >::template __enable_implicit<_Up...>(),
-                         bool
-                      >::type = false
-             >
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-        explicit
-        tuple(_Up&&... __u)
-            _NOEXCEPT_((
-                is_nothrow_constructible<_BaseT,
-                    typename __make_tuple_indices<sizeof...(_Up)>::type,
-                    typename __make_tuple_types<tuple, sizeof...(_Up)>::type,
-                    typename __make_tuple_indices<sizeof...(_Tp), sizeof...(_Up)>::type,
-                    typename __make_tuple_types<tuple, sizeof...(_Tp), sizeof...(_Up)>::type,
-                    _Up...
-                >::value
-            ))
-            : __base_(typename __make_tuple_indices<sizeof...(_Up)>::type(),
+    template <class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableUTypesCtor<_Up...>,
+            _Not<_Lazy<_And, is_convertible<_Up, _Tp>...> > // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit tuple(_Up&&... __u)
+        _NOEXCEPT_((_And<is_nothrow_constructible<_Tp, _Up>...>::value))
+        : __base_(typename __make_tuple_indices<sizeof...(_Up)>::type(),
                     typename __make_tuple_types<tuple, sizeof...(_Up)>::type(),
                     typename __make_tuple_indices<sizeof...(_Tp), sizeof...(_Up)>::type(),
                     typename __make_tuple_types<tuple, sizeof...(_Tp), sizeof...(_Up)>::type(),
                     _VSTD::forward<_Up>(__u)...) {}
 
-    template <class _Alloc, class ..._Up,
-              typename enable_if
-                      <
-                         _CheckArgsConstructor<
-                             sizeof...(_Up) == sizeof...(_Tp) &&
-                             !_PackExpandsToThisTuple<_Up...>::value
-                         >::template __enable_implicit<_Up...>(),
-                         bool
-                      >::type = false
-             >
-        _LIBCPP_INLINE_VISIBILITY
-        tuple(allocator_arg_t, const _Alloc& __a, _Up&&... __u)
-            : __base_(allocator_arg_t(), __a,
+    template <class _Alloc, class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableUTypesCtor<_Up...>,
+            is_convertible<_Up, _Tp>... // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple(allocator_arg_t, const _Alloc& __a, _Up&&... __u)
+        : __base_(allocator_arg_t(), __a,
                     typename __make_tuple_indices<sizeof...(_Up)>::type(),
                     typename __make_tuple_types<tuple, sizeof...(_Up)>::type(),
                     typename __make_tuple_indices<sizeof...(_Tp), sizeof...(_Up)>::type(),
                     typename __make_tuple_types<tuple, sizeof...(_Tp), sizeof...(_Up)>::type(),
                     _VSTD::forward<_Up>(__u)...) {}
 
-    template <class _Alloc, class ..._Up,
-              typename enable_if
-                      <
-                         _CheckArgsConstructor<
-                             sizeof...(_Up) == sizeof...(_Tp) &&
-                             !_PackExpandsToThisTuple<_Up...>::value
-                         >::template __enable_explicit<_Up...>(),
-                         bool
-                      >::type = false
-             >
-        _LIBCPP_INLINE_VISIBILITY
-        explicit
-        tuple(allocator_arg_t, const _Alloc& __a, _Up&&... __u)
-            : __base_(allocator_arg_t(), __a,
+    template <class _Alloc, class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableUTypesCtor<_Up...>,
+            _Not<_Lazy<_And, is_convertible<_Up, _Tp>...> > // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    explicit tuple(allocator_arg_t, const _Alloc& __a, _Up&&... __u)
+        : __base_(allocator_arg_t(), __a,
                     typename __make_tuple_indices<sizeof...(_Up)>::type(),
                     typename __make_tuple_types<tuple, sizeof...(_Up)>::type(),
                     typename __make_tuple_indices<sizeof...(_Tp), sizeof...(_Up)>::type(),
                     typename __make_tuple_types<tuple, sizeof...(_Tp), sizeof...(_Up)>::type(),
                     _VSTD::forward<_Up>(__u)...) {}
 
-    template <class _Tuple, _EnableImplicitTupleLikeConstructor<_Tuple, true> = false>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-        tuple(_Tuple&& __t) _NOEXCEPT_((is_nothrow_constructible<_BaseT, _Tuple>::value))
-            : __base_(_VSTD::forward<_Tuple>(__t)) {}
+    // Copy and move constructors (including the allocator_arg_t variants)
+    tuple(const tuple&) = default;
+    tuple(tuple&&) = default;
 
-    template <class _Tuple, _EnableImplicitTupleLikeConstructor<const _Tuple&, false> = false>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-        tuple(const _Tuple& __t) _NOEXCEPT_((is_nothrow_constructible<_BaseT, const _Tuple&>::value))
-            : __base_(__t) {}
-    template <class _Tuple, _EnableExplicitTupleLikeConstructor<_Tuple, true> = false>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-        explicit
-        tuple(_Tuple&& __t) _NOEXCEPT_((is_nothrow_constructible<_BaseT, _Tuple>::value))
-            : __base_(_VSTD::forward<_Tuple>(__t)) {}
+    template <class _Alloc, template<class...> class _And = _And, _EnableIf<
+        _And<is_copy_constructible<_Tp>...>::value
+    , int> = 0>
+    tuple(allocator_arg_t, const _Alloc& __alloc, const tuple& __t)
+        : __base_(allocator_arg_t(), __alloc, __t)
+    { }
+
+    template <class _Alloc, template<class...> class _And = _And, _EnableIf<
+        _And<is_move_constructible<_Tp>...>::value
+    , int> = 0>
+    tuple(allocator_arg_t, const _Alloc& __alloc, tuple&& __t)
+        : __base_(allocator_arg_t(), __alloc, _VSTD::move(__t))
+    { }
+
+    // tuple(const tuple<U...>&) constructors (including allocator_arg_t variants)
+    template <class ..._Up>
+    struct _EnableCopyFromOtherTuple : _And<
+        _Not<is_same<tuple<_Tp...>, tuple<_Up...> > >,
+        _Lazy<_Or,
+            _BoolConstant<sizeof...(_Tp) != 1>,
+            // _Tp and _Up are 1-element packs - the pack expansions look
+            // weird to avoid tripping up the type traits in degenerate cases
+            _Lazy<_And,
+                _Not<is_convertible<const tuple<_Up>&, _Tp> >...,
+                _Not<is_constructible<_Tp, const tuple<_Up>&> >...
+            >
+        >,
+        is_constructible<_Tp, const _Up&>...
+    > { };
+
+    template <class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableCopyFromOtherTuple<_Up...>,
+            is_convertible<const _Up&, _Tp>... // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    tuple(const tuple<_Up...>& __t)
+        _NOEXCEPT_((_And<is_nothrow_constructible<_Tp, const _Up&>...>::value))
+        : __base_(__t)
+    { }
+
+    template <class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableCopyFromOtherTuple<_Up...>,
+            _Not<_Lazy<_And, is_convertible<const _Up&, _Tp>...> > // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit tuple(const tuple<_Up...>& __t)
+        _NOEXCEPT_((_And<is_nothrow_constructible<_Tp, const _Up&>...>::value))
+        : __base_(__t)
+    { }
+
+    template <class ..._Up, class _Alloc, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableCopyFromOtherTuple<_Up...>,
+            is_convertible<const _Up&, _Tp>... // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple(allocator_arg_t, const _Alloc& __a, const tuple<_Up...>& __t)
+        : __base_(allocator_arg_t(), __a, __t)
+    { }
+
+    template <class ..._Up, class _Alloc, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableCopyFromOtherTuple<_Up...>,
+            _Not<_Lazy<_And, is_convertible<const _Up&, _Tp>...> > // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    explicit tuple(allocator_arg_t, const _Alloc& __a, const tuple<_Up...>& __t)
+        : __base_(allocator_arg_t(), __a, __t)
+    { }
+
+    // tuple(tuple<U...>&&) constructors (including allocator_arg_t variants)
+    template <class ..._Up>
+    struct _EnableMoveFromOtherTuple : _And<
+        _Not<is_same<tuple<_Tp...>, tuple<_Up...> > >,
+        _Lazy<_Or,
+            _BoolConstant<sizeof...(_Tp) != 1>,
+            // _Tp and _Up are 1-element packs - the pack expansions look
+            // weird to avoid tripping up the type traits in degenerate cases
+            _Lazy<_And,
+                _Not<is_convertible<tuple<_Up>, _Tp> >...,
+                _Not<is_constructible<_Tp, tuple<_Up> > >...
+            >
+        >,
+        is_constructible<_Tp, _Up>...
+    > { };
+
+    template <class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableMoveFromOtherTuple<_Up...>,
+            is_convertible<_Up, _Tp>... // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    tuple(tuple<_Up...>&& __t)
+        _NOEXCEPT_((_And<is_nothrow_constructible<_Tp, _Up>...>::value))
+        : __base_(_VSTD::move(__t))
+    { }
+
+    template <class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableMoveFromOtherTuple<_Up...>,
+            _Not<_Lazy<_And, is_convertible<_Up, _Tp>...> > // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit tuple(tuple<_Up...>&& __t)
+        _NOEXCEPT_((_And<is_nothrow_constructible<_Tp, _Up>...>::value))
+        : __base_(_VSTD::move(__t))
+    { }
+
+    template <class _Alloc, class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableMoveFromOtherTuple<_Up...>,
+            is_convertible<_Up, _Tp>... // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple(allocator_arg_t, const _Alloc& __a, tuple<_Up...>&& __t)
+        : __base_(allocator_arg_t(), __a, _VSTD::move(__t))
+    { }
+
+    template <class _Alloc, class ..._Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Up) == sizeof...(_Tp)>,
+            _EnableMoveFromOtherTuple<_Up...>,
+            _Not<_Lazy<_And, is_convertible<_Up, _Tp>...> > // explicit check
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    explicit tuple(allocator_arg_t, const _Alloc& __a, tuple<_Up...>&& __t)
+        : __base_(allocator_arg_t(), __a, _VSTD::move(__t))
+    { }
+
+    // tuple(const pair<U1, U2>&) constructors (including allocator_arg_t variants)
+    template <class _Up1, class _Up2, class ..._DependentTp>
+    struct _EnableImplicitCopyFromPair : _And<
+        is_constructible<_FirstType<_DependentTp...>, const _Up1&>,
+        is_constructible<_SecondType<_DependentTp...>, const _Up2&>,
+        is_convertible<const _Up1&, _FirstType<_DependentTp...> >, // explicit check
+        is_convertible<const _Up2&, _SecondType<_DependentTp...> >
+    > { };
+
+    template <class _Up1, class _Up2, class ..._DependentTp>
+    struct _EnableExplicitCopyFromPair : _And<
+        is_constructible<_FirstType<_DependentTp...>, const _Up1&>,
+        is_constructible<_SecondType<_DependentTp...>, const _Up2&>,
+        _Not<is_convertible<const _Up1&, _FirstType<_DependentTp...> > >, // explicit check
+        _Not<is_convertible<const _Up2&, _SecondType<_DependentTp...> > >
+    > { };
+
+    template <class _Up1, class _Up2, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            _EnableImplicitCopyFromPair<_Up1, _Up2, _Tp...>
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    tuple(const pair<_Up1, _Up2>& __p)
+        _NOEXCEPT_((_And<
+            is_nothrow_constructible<_FirstType<_Tp...>, const _Up1&>,
+            is_nothrow_constructible<_SecondType<_Tp...>, const _Up2&>
+        >::value))
+        : __base_(__p)
+    { }
+
+    template <class _Up1, class _Up2, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            _EnableExplicitCopyFromPair<_Up1, _Up2, _Tp...>
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit tuple(const pair<_Up1, _Up2>& __p)
+        _NOEXCEPT_((_And<
+            is_nothrow_constructible<_FirstType<_Tp...>, const _Up1&>,
+            is_nothrow_constructible<_SecondType<_Tp...>, const _Up2&>
+        >::value))
+        : __base_(__p)
+    { }
+
+    template <class _Alloc, class _Up1, class _Up2, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            _EnableImplicitCopyFromPair<_Up1, _Up2, _Tp...>
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple(allocator_arg_t, const _Alloc& __a, const pair<_Up1, _Up2>& __p)
+        : __base_(allocator_arg_t(), __a, __p)
+    { }
+
+    template <class _Alloc, class _Up1, class _Up2, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            _EnableExplicitCopyFromPair<_Up1, _Up2, _Tp...>
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    explicit tuple(allocator_arg_t, const _Alloc& __a, const pair<_Up1, _Up2>& __p)
+        : __base_(allocator_arg_t(), __a, __p)
+    { }
+
+    // tuple(pair<U1, U2>&&) constructors (including allocator_arg_t variants)
+    template <class _Up1, class _Up2, class ..._DependentTp>
+    struct _EnableImplicitMoveFromPair : _And<
+        is_constructible<_FirstType<_DependentTp...>, _Up1>,
+        is_constructible<_SecondType<_DependentTp...>, _Up2>,
+        is_convertible<_Up1, _FirstType<_DependentTp...> >, // explicit check
+        is_convertible<_Up2, _SecondType<_DependentTp...> >
+    > { };
+
+    template <class _Up1, class _Up2, class ..._DependentTp>
+    struct _EnableExplicitMoveFromPair : _And<
+        is_constructible<_FirstType<_DependentTp...>, _Up1>,
+        is_constructible<_SecondType<_DependentTp...>, _Up2>,
+        _Not<is_convertible<_Up1, _FirstType<_DependentTp...> > >, // explicit check
+        _Not<is_convertible<_Up2, _SecondType<_DependentTp...> > >
+    > { };
+
+    template <class _Up1, class _Up2, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            _EnableImplicitMoveFromPair<_Up1, _Up2, _Tp...>
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    tuple(pair<_Up1, _Up2>&& __p)
+        _NOEXCEPT_((_And<
+            is_nothrow_constructible<_FirstType<_Tp...>, _Up1>,
+            is_nothrow_constructible<_SecondType<_Tp...>, _Up2>
+        >::value))
+        : __base_(_VSTD::move(__p))
+    { }
+
+    template <class _Up1, class _Up2, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            _EnableExplicitMoveFromPair<_Up1, _Up2, _Tp...>
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
+    explicit tuple(pair<_Up1, _Up2>&& __p)
+        _NOEXCEPT_((_And<
+            is_nothrow_constructible<_FirstType<_Tp...>, _Up1>,
+            is_nothrow_constructible<_SecondType<_Tp...>, _Up2>
+        >::value))
+        : __base_(_VSTD::move(__p))
+    { }
+
+    template <class _Alloc, class _Up1, class _Up2, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            _EnableImplicitMoveFromPair<_Up1, _Up2, _Tp...>
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple(allocator_arg_t, const _Alloc& __a, pair<_Up1, _Up2>&& __p)
+        : __base_(allocator_arg_t(), __a, _VSTD::move(__p))
+    { }
+
+    template <class _Alloc, class _Up1, class _Up2, template<class...> class _And = _And, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            _EnableExplicitMoveFromPair<_Up1, _Up2, _Tp...>
+        >::value
+    , int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    explicit tuple(allocator_arg_t, const _Alloc& __a, pair<_Up1, _Up2>&& __p)
+        : __base_(allocator_arg_t(), __a, _VSTD::move(__p))
+    { }
+
+    // [tuple.assign]
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple& operator=(_If<_And<is_copy_assignable<_Tp>...>::value, tuple, __nat> const& __tuple)
+        _NOEXCEPT_((_And<is_nothrow_copy_assignable<_Tp>...>::value))
+    {
+        _VSTD::__memberwise_copy_assign(*this, __tuple,
+            typename __make_tuple_indices<sizeof...(_Tp)>::type());
+        return *this;
+    }
 
-    template <class _Tuple, _EnableExplicitTupleLikeConstructor<const _Tuple&, false> = false>
-        _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-        explicit
-        tuple(const _Tuple& __t) _NOEXCEPT_((is_nothrow_constructible<_BaseT, const _Tuple&>::value))
-            : __base_(__t) {}
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple& operator=(_If<_And<is_move_assignable<_Tp>...>::value, tuple, __nat>&& __tuple)
+        _NOEXCEPT_((_And<is_nothrow_move_assignable<_Tp>...>::value))
+    {
+        _VSTD::__memberwise_forward_assign(*this, _VSTD::move(__tuple),
+            __tuple_types<_Tp...>(),
+            typename __make_tuple_indices<sizeof...(_Tp)>::type());
+        return *this;
+    }
 
-    template <class _Alloc, class _Tuple,
-              typename enable_if
-                      <
-                         _CheckTupleLikeConstructor<
-                             __tuple_like_with_size<_Tuple, sizeof...(_Tp)>::value
-                         >::template __enable_implicit<_Tuple>(),
-                         bool
-                      >::type = false
-             >
-        _LIBCPP_INLINE_VISIBILITY
-        tuple(allocator_arg_t, const _Alloc& __a, _Tuple&& __t)
-            : __base_(allocator_arg_t(), __a, _VSTD::forward<_Tuple>(__t)) {}
+    template<class... _Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == sizeof...(_Up)>,
+            is_assignable<_Tp&, _Up const&>...
+        >::value
+    ,int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple& operator=(tuple<_Up...> const& __tuple)
+        _NOEXCEPT_((_And<is_nothrow_assignable<_Tp&, _Up const&>...>::value))
+    {
+        _VSTD::__memberwise_copy_assign(*this, __tuple,
+            typename __make_tuple_indices<sizeof...(_Tp)>::type());
+        return *this;
+    }
 
-    template <class _Alloc, class _Tuple,
-              typename enable_if
-                      <
-                         _CheckTupleLikeConstructor<
-                             __tuple_like_with_size<_Tuple, sizeof...(_Tp)>::value
-                         >::template __enable_explicit<_Tuple>(),
-                         bool
-                      >::type = false
-             >
-        _LIBCPP_INLINE_VISIBILITY
-        explicit
-        tuple(allocator_arg_t, const _Alloc& __a, _Tuple&& __t)
-            : __base_(allocator_arg_t(), __a, _VSTD::forward<_Tuple>(__t)) {}
+    template<class... _Up, _EnableIf<
+        _And<
+            _BoolConstant<sizeof...(_Tp) == sizeof...(_Up)>,
+            is_assignable<_Tp&, _Up>...
+        >::value
+    ,int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple& operator=(tuple<_Up...>&& __tuple)
+        _NOEXCEPT_((_And<is_nothrow_assignable<_Tp&, _Up>...>::value))
+    {
+        _VSTD::__memberwise_forward_assign(*this, _VSTD::move(__tuple),
+            __tuple_types<_Up...>(),
+            typename __make_tuple_indices<sizeof...(_Tp)>::type());
+        return *this;
+    }
 
-    using _CanCopyAssign = __all<is_copy_assignable<_Tp>::value...>;
-    using _CanMoveAssign = __all<is_move_assignable<_Tp>::value...>;
+    template<class _Up1, class _Up2, class _Dep = true_type, _EnableIf<
+        _And<_Dep,
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            is_assignable<_FirstType<_Tp..., _Dep>&, _Up1 const&>,
+            is_assignable<_SecondType<_Tp..., _Dep>&, _Up2 const&>
+        >::value
+    ,int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple& operator=(pair<_Up1, _Up2> const& __pair)
+        _NOEXCEPT_((_And<
+            is_nothrow_assignable<_FirstType<_Tp...>&, _Up1 const&>,
+            is_nothrow_assignable<_SecondType<_Tp...>&, _Up2 const&>
+        >::value))
+    {
+        _VSTD::get<0>(*this) = __pair.first;
+        _VSTD::get<1>(*this) = __pair.second;
+        return *this;
+    }
 
-    _LIBCPP_INLINE_VISIBILITY
-    tuple& operator=(typename conditional<_CanCopyAssign::value, tuple, __nat>::type const& __t)
-        _NOEXCEPT_((__all<is_nothrow_copy_assignable<_Tp>::value...>::value))
+    template<class _Up1, class _Up2, class _Dep = true_type, _EnableIf<
+        _And<_Dep,
+            _BoolConstant<sizeof...(_Tp) == 2>,
+            is_assignable<_FirstType<_Tp..., _Dep>&, _Up1>,
+            is_assignable<_SecondType<_Tp..., _Dep>&, _Up2>
+        >::value
+    ,int> = 0>
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple& operator=(pair<_Up1, _Up2>&& __pair)
+        _NOEXCEPT_((_And<
+            is_nothrow_assignable<_FirstType<_Tp...>&, _Up1>,
+            is_nothrow_assignable<_SecondType<_Tp...>&, _Up2>
+        >::value))
     {
-        __base_.operator=(__t.__base_);
+        _VSTD::get<0>(*this) = _VSTD::forward<_Up1>(__pair.first);
+        _VSTD::get<1>(*this) = _VSTD::forward<_Up2>(__pair.second);
         return *this;
     }
 
-    _LIBCPP_INLINE_VISIBILITY
-    tuple& operator=(typename conditional<_CanMoveAssign::value, tuple, __nat>::type&& __t)
-        _NOEXCEPT_((__all<is_nothrow_move_assignable<_Tp>::value...>::value))
+    // EXTENSION
+    template<class _Up, size_t _Np, class = _EnableIf<
+        _And<
+            _BoolConstant<_Np == sizeof...(_Tp)>,
+            is_assignable<_Tp&, _Up const&>...
+        >::value
+    > >
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple& operator=(array<_Up, _Np> const& __array)
+        _NOEXCEPT_((_And<is_nothrow_assignable<_Tp&, _Up const&>...>::value))
     {
-        __base_.operator=(static_cast<_BaseT&&>(__t.__base_));
+        _VSTD::__memberwise_copy_assign(*this, __array,
+            typename __make_tuple_indices<sizeof...(_Tp)>::type());
         return *this;
     }
 
-    template <class _Tuple,
-              class = typename enable_if
-                      <
-                         __tuple_assignable<_Tuple, tuple>::value
-                      >::type
-             >
-        _LIBCPP_INLINE_VISIBILITY
-        tuple&
-        operator=(_Tuple&& __t) _NOEXCEPT_((is_nothrow_assignable<_BaseT&, _Tuple>::value))
-        {
-            __base_.operator=(_VSTD::forward<_Tuple>(__t));
-            return *this;
-        }
+    // EXTENSION
+    template<class _Up, size_t _Np, class = void, class = _EnableIf<
+        _And<
+            _BoolConstant<_Np == sizeof...(_Tp)>,
+            is_assignable<_Tp&, _Up>...
+        >::value
+    > >
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
+    tuple& operator=(array<_Up, _Np>&& __array)
+        _NOEXCEPT_((_And<is_nothrow_assignable<_Tp&, _Up>...>::value))
+    {
+        _VSTD::__memberwise_forward_assign(*this, _VSTD::move(__array),
+            __tuple_types<_If<true, _Up, _Tp>...>(),
+            typename __make_tuple_indices<sizeof...(_Tp)>::type());
+        return *this;
+    }
 
-    _LIBCPP_INLINE_VISIBILITY
+    // [tuple.swap]
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
     void swap(tuple& __t) _NOEXCEPT_(__all<__is_nothrow_swappable<_Tp>::value...>::value)
         {__base_.swap(__t.__base_);}
 };
@@ -958,21 +1079,21 @@ template <>
 class _LIBCPP_TEMPLATE_VIS tuple<>
 {
 public:
-    _LIBCPP_INLINE_VISIBILITY
-    _LIBCPP_CONSTEXPR tuple() _NOEXCEPT = default;
+    _LIBCPP_INLINE_VISIBILITY constexpr
+        tuple() _NOEXCEPT = default;
     template <class _Alloc>
-    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
         tuple(allocator_arg_t, const _Alloc&) _NOEXCEPT {}
     template <class _Alloc>
-    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
         tuple(allocator_arg_t, const _Alloc&, const tuple&) _NOEXCEPT {}
     template <class _Up>
-    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
         tuple(array<_Up, 0>) _NOEXCEPT {}
     template <class _Alloc, class _Up>
-    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
         tuple(allocator_arg_t, const _Alloc&, array<_Up, 0>) _NOEXCEPT {}
-    _LIBCPP_INLINE_VISIBILITY
+    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
     void swap(tuple&) _NOEXCEPT {}
 };
 
@@ -990,7 +1111,7 @@ tuple(allocator_arg_t, _Alloc, tuple<_Tp...>) -> tuple<_Tp...>;
 #endif
 
 template <class ..._Tp>
-inline _LIBCPP_INLINE_VISIBILITY
+inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
 typename enable_if
 <
     __all<__is_swappable<_Tp>::value...>::value,
@@ -1044,7 +1165,7 @@ get(const tuple<_Tp...>&& __t) _NOEXCEPT
 
 namespace __find_detail {
 
-static constexpr size_t __not_found = -1;
+static constexpr size_t __not_found = static_cast<size_t>(-1);
 static constexpr size_t __ambiguous = __not_found - 1;
 
 inline _LIBCPP_INLINE_VISIBILITY
@@ -1450,4 +1571,4 @@ _LIBCPP_NOEXCEPT_RETURN(
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_TUPLE
+#endif // _LIBCPP_TUPLE
lib/libcxx/include/type_traits
@@ -99,7 +99,7 @@ namespace std
     template <class T> struct is_trivial;
     template <class T> struct is_trivially_copyable;
     template <class T> struct is_standard_layout;
-    template <class T> struct is_literal_type;
+    template <class T> struct is_literal_type; // Deprecated in C++17; removed in C++20
     template <class T> struct is_empty;
     template <class T> struct is_polymorphic;
     template <class T> struct is_abstract;
@@ -165,8 +165,8 @@ namespace std
     template <class T> struct decay;
     template <class... T> struct common_type;
     template <class T> struct underlying_type;
-    template <class> class result_of; // undefined
-    template <class Fn, class... ArgTypes> class result_of<Fn(ArgTypes...)>;
+    template <class> class result_of; // undefined; deprecated in C++17; removed in C++20
+    template <class Fn, class... ArgTypes> class result_of<Fn(ArgTypes...)>; // deprecated in C++17; removed in C++20
     template <class Fn, class... ArgTypes> struct invoke_result;  // C++17
 
     // const-volatile modifications:
@@ -216,9 +216,9 @@ namespace std
       using add_pointer_t    = typename add_pointer<T>::type;  // C++14
 
     // other transformations:
-    template <size_t Len, std::size_t Align=default-alignment>
+    template <size_t Len, size_t Align=default-alignment>
       using aligned_storage_t = typename aligned_storage<Len,Align>::type;  // C++14
-    template <std::size_t Len, class... Types>
+    template <size_t Len, class... Types>
       using aligned_union_t   = typename aligned_union<Len,Types...>::type;  // C++14
     template <class T>
       using remove_cvref_t    = typename remove_cvref<T>::type;  // C++20
@@ -233,7 +233,7 @@ namespace std
     template <class T>
       using underlying_type_t = typename underlying_type<T>::type;  // C++14
     template <class T>
-      using result_of_t       = typename result_of<T>::type;  // C++14
+      using result_of_t       = typename result_of<T>::type;  // C++14; deprecated in C++17; removed in C++20
     template <class Fn, class... ArgTypes>
       using invoke_result_t   = typename invoke_result<Fn, ArgTypes...>::type;  // C++17
 
@@ -302,7 +302,7 @@ namespace std
       template <class T> inline constexpr bool is_pod_v
         = is_pod<T>::value;                                              // C++17
       template <class T> inline constexpr bool is_literal_type_v
-        = is_literal_type<T>::value;                                     // C++17
+        = is_literal_type<T>::value;                                     // C++17; deprecated in C++17; removed in C++20
       template <class T> inline constexpr bool is_empty_v
         = is_empty<T>::value;                                            // C++17
       template <class T> inline constexpr bool is_polymorphic_v
@@ -476,8 +476,6 @@ struct _MetaBase<true> {
   using _EnableIfImpl _LIBCPP_NODEBUG_TYPE = _Tp;
   template <class _Result, class _First, class ..._Rest>
   using _OrImpl _LIBCPP_NODEBUG_TYPE = typename _MetaBase<_First::value != true && sizeof...(_Rest) != 0>::template _OrImpl<_First, _Rest...>;
-  template <class _Result, class _First, class ..._Rest>
-  using _AndImpl _LIBCPP_NODEBUG_TYPE = typename _MetaBase<_First::value == true && sizeof...(_Rest) != 0>::template _AndImpl<_First, _Rest...>;
 };
 
 template <>
@@ -488,8 +486,6 @@ struct _MetaBase<false> {
   using _SelectApplyImpl _LIBCPP_NODEBUG_TYPE = _SecondFn<_Args...>;
   template <class _Result, class ...>
   using _OrImpl _LIBCPP_NODEBUG_TYPE = _Result;
-  template <class _Result, class ...>
-  using _AndImpl _LIBCPP_NODEBUG_TYPE = _Result;
 };
 template <bool _Cond, class _Ret = void>
 using _EnableIf _LIBCPP_NODEBUG_TYPE = typename _MetaBase<_Cond>::template _EnableIfImpl<_Ret>;
@@ -497,8 +493,6 @@ template <bool _Cond, class _IfRes, class _ElseRes>
 using _If _LIBCPP_NODEBUG_TYPE = typename _MetaBase<_Cond>::template _SelectImpl<_IfRes, _ElseRes>;
 template <class ..._Rest>
 using _Or _LIBCPP_NODEBUG_TYPE = typename _MetaBase< sizeof...(_Rest) != 0 >::template _OrImpl<false_type, _Rest...>;
-template <class ..._Rest>
-using _And _LIBCPP_NODEBUG_TYPE = typename _MetaBase< sizeof...(_Rest) != 0 >::template _AndImpl<true_type, _Rest...>;
 template <class _Pred>
 struct _Not : _BoolConstant<!_Pred::value> {};
 template <class ..._Args>
@@ -506,6 +500,14 @@ using _FirstType _LIBCPP_NODEBUG_TYPE = typename _MetaBase<(sizeof...(_Args) >=
 template <class ..._Args>
 using _SecondType _LIBCPP_NODEBUG_TYPE = typename _MetaBase<(sizeof...(_Args) >= 2)>::template _SecondImpl<_Args...>;
 
+template <class ...> using __expand_to_true = true_type;
+template <class ..._Pred>
+__expand_to_true<_EnableIf<_Pred::value>...> __and_helper(int);
+template <class ...>
+false_type __and_helper(...);
+template <class ..._Pred>
+using _And _LIBCPP_NODEBUG_TYPE = decltype(__and_helper<_Pred...>(0));
+
 template <template <class...> class _Func, class ..._Args>
 struct _Lazy : _Func<_Args...> {};
 
@@ -525,6 +527,9 @@ struct __void_t { typedef void type; };
 template <class _Tp>
 struct __identity { typedef _Tp type; };
 
+template <class _Tp>
+using __identity_t _LIBCPP_NODEBUG_TYPE = typename __identity<_Tp>::type;
+
 template <class _Tp, bool>
 struct _LIBCPP_TEMPLATE_VIS __dependent_type : public _Tp {};
 
@@ -575,7 +580,7 @@ using _IsSame = _BoolConstant<
 #ifdef __clang__
     __is_same(_Tp, _Up)
 #else
-    _VSTD::is_same<_Tp, _Up>::value
+    is_same<_Tp, _Up>::value
 #endif
 >;
 
@@ -584,7 +589,7 @@ using _IsNotSame = _BoolConstant<
 #ifdef __clang__
     !__is_same(_Tp, _Up)
 #else
-    !_VSTD::is_same<_Tp, _Up>::value
+    !is_same<_Tp, _Up>::value
 #endif
 >;
 
@@ -784,6 +789,33 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_integral_v
 
 #endif // __has_keyword(__is_integral)
 
+// __libcpp_is_signed_integer, __libcpp_is_unsigned_integer
+
+// [basic.fundamental] defines five standard signed integer types;
+// __int128_t is an extended signed integer type.
+// The signed and unsigned integer types, plus bool and the
+// five types with "char" in their name, compose the "integral" types.
+
+template <class _Tp> struct __libcpp_is_signed_integer : public false_type {};
+template <> struct __libcpp_is_signed_integer<signed char>      : public true_type {};
+template <> struct __libcpp_is_signed_integer<signed short>     : public true_type {};
+template <> struct __libcpp_is_signed_integer<signed int>       : public true_type {};
+template <> struct __libcpp_is_signed_integer<signed long>      : public true_type {};
+template <> struct __libcpp_is_signed_integer<signed long long> : public true_type {};
+#ifndef _LIBCPP_HAS_NO_INT128
+template <> struct __libcpp_is_signed_integer<__int128_t>       : public true_type {};
+#endif
+
+template <class _Tp> struct __libcpp_is_unsigned_integer : public false_type {};
+template <> struct __libcpp_is_unsigned_integer<unsigned char>      : public true_type {};
+template <> struct __libcpp_is_unsigned_integer<unsigned short>     : public true_type {};
+template <> struct __libcpp_is_unsigned_integer<unsigned int>       : public true_type {};
+template <> struct __libcpp_is_unsigned_integer<unsigned long>      : public true_type {};
+template <> struct __libcpp_is_unsigned_integer<unsigned long long> : public true_type {};
+#ifndef _LIBCPP_HAS_NO_INT128
+template <> struct __libcpp_is_unsigned_integer<__uint128_t>        : public true_type {};
+#endif
+
 // is_floating_point
 
 template <class _Tp> struct __libcpp_is_floating_point              : public false_type {};
@@ -831,8 +863,10 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_array_v
 
 // is_pointer
 
-// In clang 10.0.0 and earlier __is_pointer didn't work with Objective-C types.
-#if __has_keyword(__is_pointer) && _LIBCPP_CLANG_VER > 1000
+// Before Clang 11 / AppleClang 12.0.5, __is_pointer didn't work for Objective-C types.
+#if __has_keyword(__is_pointer) &&                                             \
+    !(defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER < 1100) &&               \
+    !(defined(_LIBCPP_APPLE_CLANG_VER) && _LIBCPP_APPLE_CLANG_VER < 1205)
 
 template<class _Tp>
 struct _LIBCPP_TEMPLATE_VIS is_pointer : _BoolConstant<__is_pointer(_Tp)> { };
@@ -1126,9 +1160,11 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_arithmetic_v
 
 // is_fundamental
 
-// In clang 9 and lower, this builtin did not work for nullptr_t. Additionally, in C++03 mode,
-// nullptr isn't defined by the compiler so, this builtin won't work.
-#if __has_keyword(__is_fundamental) && _LIBCPP_CLANG_VER > 900 && !defined(_LIBCPP_CXX03_LANG)
+// Before Clang 10, __is_fundamental didn't work for nullptr_t.
+// In C++03 nullptr_t is library-provided but must still count as "fundamental."
+#if __has_keyword(__is_fundamental) &&                                         \
+    !(defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER < 1000) &&               \
+    !defined(_LIBCPP_CXX03_LANG)
 
 template<class _Tp>
 struct _LIBCPP_TEMPLATE_VIS is_fundamental : _BoolConstant<__is_fundamental(_Tp)> { };
@@ -1155,7 +1191,7 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_fundamental_v
 
 // is_scalar
 
-// >= 11 because in C++03 nullptr isn't actually nullptr
+// In C++03 nullptr_t is library-provided but must still count as "scalar."
 #if __has_keyword(__is_scalar) && !defined(_LIBCPP_CXX03_LANG)
 
 template<class _Tp>
@@ -1335,7 +1371,7 @@ template <class _Tp> _Tp   __declval(long);
 _LIBCPP_SUPPRESS_DEPRECATED_POP
 
 template <class _Tp>
-decltype(_VSTD::__declval<_Tp>(0))
+decltype(__declval<_Tp>(0))
 declval() _NOEXCEPT;
 
 // __uncvref
@@ -1412,8 +1448,9 @@ template<class _Tp> using type_identity_t = typename type_identity<_Tp>::type;
 
 // is_signed
 
-// In clang 9 and earlier, this builtin did not work for floating points or enums
-#if __has_keyword(__is_signed) && _LIBCPP_CLANG_VER > 900
+// Before Clang 10, __is_signed didn't work for floating-point types or enums.
+#if __has_keyword(__is_signed) &&                                              \
+    !(defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER < 1000)
 
 template<class _Tp>
 struct _LIBCPP_TEMPLATE_VIS is_signed : _BoolConstant<__is_signed(_Tp)> { };
@@ -1448,7 +1485,11 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_signed_v
 
 // is_unsigned
 
-#if __has_keyword(__is_unsigned)
+// Before Clang 13, __is_unsigned returned true for enums with signed underlying type.
+// No currently-released version of AppleClang contains the fixed intrinsic.
+#if __has_keyword(__is_unsigned) &&                                            \
+    !(defined(_LIBCPP_CLANG_VER) && _LIBCPP_CLANG_VER < 1300) &&               \
+    !defined(_LIBCPP_APPLE_CLANG_VER)
 
 template<class _Tp>
 struct _LIBCPP_TEMPLATE_VIS is_unsigned : _BoolConstant<__is_unsigned(_Tp)> { };
@@ -1698,7 +1739,7 @@ struct __is_convertible_test : public false_type {};
 
 template <class _From, class _To>
 struct __is_convertible_test<_From, _To,
-    decltype(_VSTD::__is_convertible_imp::__test_convert<_To>(_VSTD::declval<_From>()))> : public true_type
+    decltype(__is_convertible_imp::__test_convert<_To>(declval<_From>()))> : public true_type
 {};
 
 template <class _Tp, bool _IsArray =    is_array<_Tp>::value,
@@ -1754,7 +1795,7 @@ template <class _T1, class _T2> struct _LIBCPP_TEMPLATE_VIS is_convertible
     static const size_t __complete_check2 = __is_convertible_check<_T2>::__v;
 };
 
-#endif  // __has_feature(is_convertible_to)
+#endif // __has_feature(is_convertible_to)
 
 #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES)
 template <class _From, class _To>
@@ -1817,7 +1858,7 @@ template <class _Tp> struct __libcpp_empty<_Tp, false> : public false_type {};
 
 template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_empty : public __libcpp_empty<_Tp> {};
 
-#endif  // __has_feature(is_empty)
+#endif // __has_feature(is_empty)
 
 #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES)
 template <class _Tp>
@@ -2297,6 +2338,14 @@ struct _LIBCPP_TEMPLATE_VIS make_unsigned
 template <class _Tp> using make_unsigned_t = typename make_unsigned<_Tp>::type;
 #endif
 
+#ifndef _LIBCPP_CXX03_LANG
+template <class _Tp>
+_LIBCPP_NODISCARD_ATTRIBUTE _LIBCPP_INLINE_VISIBILITY constexpr
+typename make_unsigned<_Tp>::type __to_unsigned_like(_Tp __x) noexcept {
+    return static_cast<typename make_unsigned<_Tp>::type>(__x);
+}
+#endif
+
 #if _LIBCPP_STD_VER > 14
 template <class...> using void_t = void;
 #endif
@@ -2304,7 +2353,7 @@ template <class...> using void_t = void;
 #if _LIBCPP_STD_VER > 17
 // Let COND_RES(X, Y) be:
 template <class _Tp, class _Up>
-using __cond_type = decltype(false ? _VSTD::declval<_Tp>() : _VSTD::declval<_Up>());
+using __cond_type = decltype(false ? declval<_Tp>() : declval<_Up>());
 
 template <class _Tp, class _Up, class = void>
 struct __common_type3 {};
@@ -2327,11 +2376,11 @@ struct __common_type2_imp {};
 template <class _Tp, class _Up>
 struct __common_type2_imp<_Tp, _Up,
                           typename __void_t<decltype(
-                                            true ? _VSTD::declval<_Tp>() : _VSTD::declval<_Up>()
+                                            true ? declval<_Tp>() : declval<_Up>()
                                             )>::type>
 {
   typedef _LIBCPP_NODEBUG_TYPE typename decay<decltype(
-                         true ? _VSTD::declval<_Tp>() : _VSTD::declval<_Up>()
+                         true ? declval<_Tp>() : declval<_Up>()
                          )>::type type;
 };
 
@@ -2411,6 +2460,216 @@ struct _LIBCPP_TEMPLATE_VIS
 template <class ..._Tp> using common_type_t = typename common_type<_Tp...>::type;
 #endif
 
+#if _LIBCPP_STD_VER > 11
+// Let COPYCV(FROM, TO) be an alias for type TO with the addition of FROM's
+// top-level cv-qualifiers.
+template <class _From, class _To>
+struct __copy_cv
+{
+    using type = _To;
+};
+
+template <class _From, class _To>
+struct __copy_cv<const _From, _To>
+{
+    using type = add_const_t<_To>;
+};
+
+template <class _From, class _To>
+struct __copy_cv<volatile _From, _To>
+{
+    using type = add_volatile_t<_To>;
+};
+
+template <class _From, class _To>
+struct __copy_cv<const volatile _From, _To>
+{
+    using type = add_cv_t<_To>;
+};
+
+template <class _From, class _To>
+using __copy_cv_t = typename __copy_cv<_From, _To>::type;
+
+template <class _From, class _To>
+struct __copy_cvref
+{
+    using type = __copy_cv_t<_From, _To>;
+};
+
+template <class _From, class _To>
+struct __copy_cvref<_From&, _To>
+{
+    using type = add_lvalue_reference_t<__copy_cv_t<_From, _To>>;
+};
+
+template <class _From, class _To>
+struct __copy_cvref<_From&&, _To>
+{
+    using type = add_rvalue_reference_t<__copy_cv_t<_From, _To>>;
+};
+
+template <class _From, class _To>
+using __copy_cvref_t = typename __copy_cvref<_From, _To>::type;
+
+#endif // _LIBCPP_STD_VER > 11
+
+// common_reference
+#if _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CONCEPTS)
+// Let COND_RES(X, Y) be:
+template <class _Xp, class _Yp>
+using __cond_res =
+    decltype(false ? declval<_Xp(&)()>()() : declval<_Yp(&)()>()());
+
+// Let `XREF(A)` denote a unary alias template `T` such that `T<U>` denotes the same type as `U`
+// with the addition of `A`'s cv and reference qualifiers, for a non-reference cv-unqualified type
+// `U`.
+// [Note: `XREF(A)` is `__xref<A>::template __apply`]
+template <class _Tp>
+struct __xref {
+  template<class _Up>
+  using __apply = __copy_cvref_t<_Tp, _Up>;
+};
+
+// Given types A and B, let X be remove_reference_t<A>, let Y be remove_reference_t<B>,
+// and let COMMON-REF(A, B) be:
+template<class _Ap, class _Bp, class _Xp = remove_reference_t<_Ap>, class _Yp = remove_reference_t<_Bp>>
+struct __common_ref;
+
+template<class _Xp, class _Yp>
+using __common_ref_t = typename __common_ref<_Xp, _Yp>::__type;
+
+template<class _Xp, class _Yp>
+using __cv_cond_res = __cond_res<__copy_cv_t<_Xp, _Yp>&, __copy_cv_t<_Yp, _Xp>&>;
+
+
+//    If A and B are both lvalue reference types, COMMON-REF(A, B) is
+//    COND-RES(COPYCV(X, Y)&, COPYCV(Y, X)&) if that type exists and is a reference type.
+template<class _Ap, class _Bp, class _Xp, class _Yp>
+requires requires { typename __cv_cond_res<_Xp, _Yp>; } && is_reference_v<__cv_cond_res<_Xp, _Yp>>
+struct __common_ref<_Ap&, _Bp&, _Xp, _Yp>
+{
+    using __type = __cv_cond_res<_Xp, _Yp>;
+};
+
+//    Otherwise, let C be remove_reference_t<COMMON-REF(X&, Y&)>&&. ...
+template <class _Xp, class _Yp>
+using __common_ref_C = remove_reference_t<__common_ref_t<_Xp&, _Yp&>>&&;
+
+
+//    .... If A and B are both rvalue reference types, C is well-formed, and
+//    is_convertible_v<A, C> && is_convertible_v<B, C> is true, then COMMON-REF(A, B) is C.
+template<class _Ap, class _Bp, class _Xp, class _Yp>
+requires
+  requires { typename __common_ref_C<_Xp, _Yp>; } &&
+  is_convertible_v<_Ap&&, __common_ref_C<_Xp, _Yp>> &&
+  is_convertible_v<_Bp&&, __common_ref_C<_Xp, _Yp>>
+struct __common_ref<_Ap&&, _Bp&&, _Xp, _Yp>
+{
+    using __type = __common_ref_C<_Xp, _Yp>;
+};
+
+//    Otherwise, let D be COMMON-REF(const X&, Y&). ...
+template <class _Tp, class _Up>
+using __common_ref_D = __common_ref_t<const _Tp&, _Up&>;
+
+//    ... If A is an rvalue reference and B is an lvalue reference and D is well-formed and
+//    is_convertible_v<A, D> is true, then COMMON-REF(A, B) is D.
+template<class _Ap, class _Bp, class _Xp, class _Yp>
+requires requires { typename __common_ref_D<_Xp, _Yp>; } &&
+         is_convertible_v<_Ap&&, __common_ref_D<_Xp, _Yp>>
+struct __common_ref<_Ap&&, _Bp&, _Xp, _Yp>
+{
+    using __type = __common_ref_D<_Xp, _Yp>;
+};
+
+//    Otherwise, if A is an lvalue reference and B is an rvalue reference, then
+//    COMMON-REF(A, B) is COMMON-REF(B, A).
+template<class _Ap, class _Bp, class _Xp, class _Yp>
+struct __common_ref<_Ap&, _Bp&&, _Xp, _Yp> : __common_ref<_Bp&&, _Ap&> {};
+
+//    Otherwise, COMMON-REF(A, B) is ill-formed.
+template<class _Ap, class _Bp, class _Xp, class _Yp>
+struct __common_ref {};
+
+// Note C: For the common_reference trait applied to a parameter pack [...]
+
+template <class...>
+struct common_reference;
+
+template <class... _Types>
+using common_reference_t = typename common_reference<_Types...>::type;
+
+// bullet 1 - sizeof...(T) == 0
+template<>
+struct common_reference<> {};
+
+// bullet 2 - sizeof...(T) == 1
+template <class _Tp>
+struct common_reference<_Tp>
+{
+    using type = _Tp;
+};
+
+// bullet 3 - sizeof...(T) == 2
+template <class _Tp, class _Up> struct __common_reference_sub_bullet3;
+template <class _Tp, class _Up> struct __common_reference_sub_bullet2 : __common_reference_sub_bullet3<_Tp, _Up> {};
+template <class _Tp, class _Up> struct __common_reference_sub_bullet1 : __common_reference_sub_bullet2<_Tp, _Up> {};
+
+// sub-bullet 1 - If T1 and T2 are reference types and COMMON-REF(T1, T2) is well-formed, then
+// the member typedef `type` denotes that type.
+template <class _Tp, class _Up> struct common_reference<_Tp, _Up> : __common_reference_sub_bullet1<_Tp, _Up> {};
+
+template <class _Tp, class _Up>
+requires is_reference_v<_Tp> && is_reference_v<_Up> && requires { typename __common_ref_t<_Tp, _Up>; }
+struct __common_reference_sub_bullet1<_Tp, _Up>
+{
+    using type = __common_ref_t<_Tp, _Up>;
+};
+
+// sub-bullet 2 - Otherwise, if basic_common_reference<remove_cvref_t<T1>, remove_cvref_t<T2>, XREF(T1), XREF(T2)>::type
+// is well-formed, then the member typedef `type` denotes that type.
+template <class, class, template <class> class, template <class> class> struct basic_common_reference {};
+
+template <class _Tp, class _Up>
+using __basic_common_reference_t = typename basic_common_reference<
+    remove_cvref_t<_Tp>, remove_cvref_t<_Up>,
+    __xref<_Tp>::template __apply, __xref<_Up>::template __apply>::type;
+
+template <class _Tp, class _Up>
+requires requires { typename __basic_common_reference_t<_Tp, _Up>; }
+struct __common_reference_sub_bullet2<_Tp, _Up>
+{
+    using type = __basic_common_reference_t<_Tp, _Up>;
+};
+
+// sub-bullet 3 - Otherwise, if COND-RES(T1, T2) is well-formed,
+// then the member typedef `type` denotes that type.
+template <class _Tp, class _Up>
+requires requires { typename __cond_res<_Tp, _Up>; }
+struct __common_reference_sub_bullet3<_Tp, _Up>
+{
+    using type = __cond_res<_Tp, _Up>;
+};
+
+
+// sub-bullet 4 & 5 - Otherwise, if common_type_t<T1, T2> is well-formed,
+//                    then the member typedef `type` denotes that type.
+//                  - Otherwise, there shall be no member `type`.
+template <class _Tp, class _Up> struct __common_reference_sub_bullet3 : common_type<_Tp, _Up> {};
+
+// bullet 4 - If there is such a type `C`, the member typedef type shall denote the same type, if
+//            any, as `common_reference_t<C, Rest...>`.
+template <class _Tp, class _Up, class _Vp, class... _Rest>
+requires requires { typename common_reference_t<_Tp, _Up>; }
+struct common_reference<_Tp, _Up, _Vp, _Rest...>
+    : common_reference<common_reference_t<_Tp, _Up>, _Vp, _Rest...>
+{};
+
+// bullet 5 - Otherwise, there shall be no member `type`.
+template <class...> struct common_reference {};
+
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_CONCEPTS)
+
 // is_assignable
 
 template<typename, typename _Tp> struct __select_2nd { typedef _LIBCPP_NODEBUG_TYPE _Tp type; };
@@ -2428,7 +2687,7 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_assignable_v = __is_assignable(_Tp,
 #else // __has_keyword(__is_assignable)
 
 template <class _Tp, class _Arg>
-typename __select_2nd<decltype((_VSTD::declval<_Tp>() = _VSTD::declval<_Arg>())), true_type>::type
+typename __select_2nd<decltype((declval<_Tp>() = declval<_Arg>())), true_type>::type
 __is_assignable_test(int);
 
 template <class, class>
@@ -2455,7 +2714,7 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_assignable_v
     = is_assignable<_Tp, _Arg>::value;
 #endif
 
-#endif  // __has_keyword(__is_assignable)
+#endif // __has_keyword(__is_assignable)
 
 // is_copy_assignable
 
@@ -2509,7 +2768,7 @@ template <typename _Tp>
 struct __is_destructor_wellformed {
     template <typename _Tp1>
     static char  __test (
-        typename __is_destructible_apply<decltype(_VSTD::declval<_Tp1&>().~_Tp1())>::type
+        typename __is_destructible_apply<decltype(declval<_Tp1&>().~_Tp1())>::type
     );
 
     template <typename _Tp1>
@@ -2523,33 +2782,33 @@ struct __destructible_imp;
 
 template <class _Tp>
 struct __destructible_imp<_Tp, false>
-   : public _VSTD::integral_constant<bool,
-        __is_destructor_wellformed<typename _VSTD::remove_all_extents<_Tp>::type>::value> {};
+   : public integral_constant<bool,
+        __is_destructor_wellformed<typename remove_all_extents<_Tp>::type>::value> {};
 
 template <class _Tp>
 struct __destructible_imp<_Tp, true>
-    : public _VSTD::true_type {};
+    : public true_type {};
 
 template <class _Tp, bool>
 struct __destructible_false;
 
 template <class _Tp>
-struct __destructible_false<_Tp, false> : public __destructible_imp<_Tp, _VSTD::is_reference<_Tp>::value> {};
+struct __destructible_false<_Tp, false> : public __destructible_imp<_Tp, is_reference<_Tp>::value> {};
 
 template <class _Tp>
-struct __destructible_false<_Tp, true> : public _VSTD::false_type {};
+struct __destructible_false<_Tp, true> : public false_type {};
 
 template <class _Tp>
 struct is_destructible
-    : public __destructible_false<_Tp, _VSTD::is_function<_Tp>::value> {};
+    : public __destructible_false<_Tp, is_function<_Tp>::value> {};
 
 template <class _Tp>
 struct is_destructible<_Tp[]>
-    : public _VSTD::false_type {};
+    : public false_type {};
 
 template <>
 struct is_destructible<void>
-    : public _VSTD::false_type {};
+    : public false_type {};
 
 #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES)
 template <class _Tp>
@@ -2559,43 +2818,6 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_destructible_v
 
 #endif // __has_keyword(__is_destructible)
 
-// move
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-typename remove_reference<_Tp>::type&&
-move(_Tp&& __t) _NOEXCEPT
-{
-    typedef _LIBCPP_NODEBUG_TYPE typename remove_reference<_Tp>::type _Up;
-    return static_cast<_Up&&>(__t);
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-_Tp&&
-forward(typename remove_reference<_Tp>::type& __t) _NOEXCEPT
-{
-    return static_cast<_Tp&&>(__t);
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-_Tp&&
-forward(typename remove_reference<_Tp>::type&& __t) _NOEXCEPT
-{
-    static_assert(!is_lvalue_reference<_Tp>::value,
-                  "can not forward an rvalue as an lvalue");
-    return static_cast<_Tp&&>(__t);
-}
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-typename decay<_Tp>::type
-__decay_copy(_Tp&& __t)
-{
-    return _VSTD::forward<_Tp>(__t);
-}
-
 template <class _MP, bool _IsMemberFunctionPtr, bool _IsMemberObjectPtr>
 struct __member_pointer_traits_imp
 {
@@ -2795,7 +3017,7 @@ struct __member_pointer_traits_imp<_Rp (_Class::*)(_Param..., ...) const volatil
     typedef _Rp (_FnType) (_Param..., ...);
 };
 
-#endif  // __has_feature(cxx_reference_qualified_functions) || defined(_LIBCPP_COMPILER_GCC)
+#endif // __has_feature(cxx_reference_qualified_functions) || defined(_LIBCPP_COMPILER_GCC)
 
 
 template <class _Rp, class _Class>
@@ -2876,11 +3098,11 @@ struct __is_constructible_helper
     // NOTE: The static_cast implementation below is required to support
     //  classes with explicit conversion operators.
     template <class _To, class _From,
-              class = decltype(__eat<_To>(_VSTD::declval<_From>()))>
+              class = decltype(__eat<_To>(declval<_From>()))>
     static true_type __test_cast(int);
 
     template <class _To, class _From,
-              class = decltype(static_cast<_To>(_VSTD::declval<_From>()))>
+              class = decltype(static_cast<_To>(declval<_From>()))>
     static integral_constant<bool,
         !__is_invalid_base_to_derived_cast<_To, _From>::value &&
         !__is_invalid_lvalue_to_rvalue_cast<_To, _From>::value
@@ -2890,12 +3112,12 @@ struct __is_constructible_helper
     static false_type __test_cast(...);
 
     template <class _Tp, class ..._Args,
-        class = decltype(_Tp(_VSTD::declval<_Args>()...))>
+        class = decltype(_Tp(declval<_Args>()...))>
     static true_type __test_nary(int);
     template <class _Tp, class...>
     static false_type __test_nary(...);
 
-    template <class _Tp, class _A0, class = decltype(::new _Tp(_VSTD::declval<_A0>()))>
+    template <class _Tp, class _A0, class = decltype(::new _Tp(declval<_A0>()))>
     static is_destructible<_Tp> __test_unary(int);
     template <class, class>
     static false_type __test_unary(...);
@@ -2984,18 +3206,18 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_default_constructible_v
 template <class _Tp>
 void __test_implicit_default_constructible(_Tp);
 
-template <class _Tp, class = void, bool = is_default_constructible<_Tp>::value>
+template <class _Tp, class = void, class = typename is_default_constructible<_Tp>::type>
 struct __is_implicitly_default_constructible
     : false_type
 { };
 
 template <class _Tp>
-struct __is_implicitly_default_constructible<_Tp, decltype(__test_implicit_default_constructible<_Tp const&>({})), true>
+struct __is_implicitly_default_constructible<_Tp, decltype(__test_implicit_default_constructible<_Tp const&>({})), true_type>
     : true_type
 { };
 
 template <class _Tp>
-struct __is_implicitly_default_constructible<_Tp, decltype(__test_implicit_default_constructible<_Tp const&>({})), false>
+struct __is_implicitly_default_constructible<_Tp, decltype(__test_implicit_default_constructible<_Tp const&>({})), false_type>
     : false_type
 { };
 #endif // !C++03
@@ -3072,7 +3294,7 @@ struct _LIBCPP_TEMPLATE_VIS is_trivially_constructible<_Tp, _Tp&>
 {
 };
 
-#endif  // !__has_feature(is_trivially_constructible)
+#endif // !__has_feature(is_trivially_constructible)
 
 
 #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES)
@@ -3149,7 +3371,7 @@ template <class _Tp>
 struct is_trivially_assignable<_Tp&, _Tp&&>
     : integral_constant<bool, is_scalar<_Tp>::value> {};
 
-#endif  // !__has_feature(is_trivially_assignable)
+#endif // !__has_feature(is_trivially_assignable)
 
 #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES)
 template <class _Tp, class _Arg>
@@ -3259,7 +3481,7 @@ struct _LIBCPP_TEMPLATE_VIS is_nothrow_constructible<_Tp[_Ns]>
 {
 };
 
-#endif  // _LIBCPP_HAS_NO_NOEXCEPT
+#endif // _LIBCPP_HAS_NO_NOEXCEPT
 
 
 #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES)
@@ -3324,7 +3546,7 @@ struct __libcpp_is_nothrow_assignable<false, _Tp, _Arg>
 
 template <class _Tp, class _Arg>
 struct __libcpp_is_nothrow_assignable<true, _Tp, _Arg>
-    : public integral_constant<bool, noexcept(_VSTD::declval<_Tp>() = _VSTD::declval<_Arg>()) >
+    : public integral_constant<bool, noexcept(declval<_Tp>() = declval<_Arg>()) >
 {
 };
 
@@ -3334,7 +3556,7 @@ struct _LIBCPP_TEMPLATE_VIS is_nothrow_assignable
 {
 };
 
-#endif  // _LIBCPP_HAS_NO_NOEXCEPT
+#endif // _LIBCPP_HAS_NO_NOEXCEPT
 
 #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES)
 template <class _Tp, class _Arg>
@@ -3381,7 +3603,7 @@ struct __libcpp_is_nothrow_destructible<false, _Tp>
 
 template <class _Tp>
 struct __libcpp_is_nothrow_destructible<true, _Tp>
-    : public integral_constant<bool, noexcept(_VSTD::declval<_Tp>().~_Tp()) >
+    : public integral_constant<bool, noexcept(declval<_Tp>().~_Tp()) >
 {
 };
 
@@ -3455,15 +3677,17 @@ _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_pod_v
 
 // is_literal_type;
 
-template <class _Tp> struct _LIBCPP_TEMPLATE_VIS is_literal_type
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS)
+template <class _Tp> struct _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX17 is_literal_type
     : public integral_constant<bool, __is_literal_type(_Tp)>
     {};
 
 #if _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES)
 template <class _Tp>
-_LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_literal_type_v
+_LIBCPP_DEPRECATED_IN_CXX17 _LIBCPP_INLINE_VAR _LIBCPP_CONSTEXPR bool is_literal_type_v
     = is_literal_type<_Tp>::value;
-#endif
+#endif // _LIBCPP_STD_VER > 14 && !defined(_LIBCPP_HAS_NO_VARIABLE_TEMPLATES)
+#endif // _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS)
 
 // is_standard_layout;
 
@@ -3604,42 +3828,42 @@ template <class _Fp, class _A0, class ..._Args,
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR_AFTER_CXX17 auto
 __invoke(_Fp&& __f, _A0&& __a0, _Args&& ...__args)
-_LIBCPP_INVOKE_RETURN((_VSTD::forward<_A0>(__a0).*__f)(_VSTD::forward<_Args>(__args)...))
+_LIBCPP_INVOKE_RETURN((static_cast<_A0&&>(__a0).*__f)(static_cast<_Args&&>(__args)...))
 
 template <class _Fp, class _A0, class ..._Args,
           class = __enable_if_bullet1<_Fp, _A0>>
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR auto
 __invoke_constexpr(_Fp&& __f, _A0&& __a0, _Args&& ...__args)
-_LIBCPP_INVOKE_RETURN((_VSTD::forward<_A0>(__a0).*__f)(_VSTD::forward<_Args>(__args)...))
+_LIBCPP_INVOKE_RETURN((static_cast<_A0&&>(__a0).*__f)(static_cast<_Args&&>(__args)...))
 
 template <class _Fp, class _A0, class ..._Args,
           class = __enable_if_bullet2<_Fp, _A0>>
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR_AFTER_CXX17 auto
 __invoke(_Fp&& __f, _A0&& __a0, _Args&& ...__args)
-_LIBCPP_INVOKE_RETURN((__a0.get().*__f)(_VSTD::forward<_Args>(__args)...))
+_LIBCPP_INVOKE_RETURN((__a0.get().*__f)(static_cast<_Args&&>(__args)...))
 
 template <class _Fp, class _A0, class ..._Args,
           class = __enable_if_bullet2<_Fp, _A0>>
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR auto
 __invoke_constexpr(_Fp&& __f, _A0&& __a0, _Args&& ...__args)
-_LIBCPP_INVOKE_RETURN((__a0.get().*__f)(_VSTD::forward<_Args>(__args)...))
+_LIBCPP_INVOKE_RETURN((__a0.get().*__f)(static_cast<_Args&&>(__args)...))
 
 template <class _Fp, class _A0, class ..._Args,
           class = __enable_if_bullet3<_Fp, _A0>>
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR_AFTER_CXX17 auto
 __invoke(_Fp&& __f, _A0&& __a0, _Args&& ...__args)
-_LIBCPP_INVOKE_RETURN(((*_VSTD::forward<_A0>(__a0)).*__f)(_VSTD::forward<_Args>(__args)...))
+_LIBCPP_INVOKE_RETURN(((*static_cast<_A0&&>(__a0)).*__f)(static_cast<_Args&&>(__args)...))
 
 template <class _Fp, class _A0, class ..._Args,
           class = __enable_if_bullet3<_Fp, _A0>>
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR auto
 __invoke_constexpr(_Fp&& __f, _A0&& __a0, _Args&& ...__args)
-_LIBCPP_INVOKE_RETURN(((*_VSTD::forward<_A0>(__a0)).*__f)(_VSTD::forward<_Args>(__args)...))
+_LIBCPP_INVOKE_RETURN(((*static_cast<_A0&&>(__a0)).*__f)(static_cast<_Args&&>(__args)...))
 
 // bullets 4, 5 and 6
 
@@ -3648,14 +3872,14 @@ template <class _Fp, class _A0,
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR_AFTER_CXX17 auto
 __invoke(_Fp&& __f, _A0&& __a0)
-_LIBCPP_INVOKE_RETURN(_VSTD::forward<_A0>(__a0).*__f)
+_LIBCPP_INVOKE_RETURN(static_cast<_A0&&>(__a0).*__f)
 
 template <class _Fp, class _A0,
           class = __enable_if_bullet4<_Fp, _A0>>
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR auto
 __invoke_constexpr(_Fp&& __f, _A0&& __a0)
-_LIBCPP_INVOKE_RETURN(_VSTD::forward<_A0>(__a0).*__f)
+_LIBCPP_INVOKE_RETURN(static_cast<_A0&&>(__a0).*__f)
 
 template <class _Fp, class _A0,
           class = __enable_if_bullet5<_Fp, _A0>>
@@ -3676,14 +3900,14 @@ template <class _Fp, class _A0,
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR_AFTER_CXX17 auto
 __invoke(_Fp&& __f, _A0&& __a0)
-_LIBCPP_INVOKE_RETURN((*_VSTD::forward<_A0>(__a0)).*__f)
+_LIBCPP_INVOKE_RETURN((*static_cast<_A0&&>(__a0)).*__f)
 
 template <class _Fp, class _A0,
           class = __enable_if_bullet6<_Fp, _A0>>
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR auto
 __invoke_constexpr(_Fp&& __f, _A0&& __a0)
-_LIBCPP_INVOKE_RETURN((*_VSTD::forward<_A0>(__a0)).*__f)
+_LIBCPP_INVOKE_RETURN((*static_cast<_A0&&>(__a0)).*__f)
 
 // bullet 7
 
@@ -3691,13 +3915,13 @@ template <class _Fp, class ..._Args>
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR_AFTER_CXX17 auto
 __invoke(_Fp&& __f, _Args&& ...__args)
-_LIBCPP_INVOKE_RETURN(_VSTD::forward<_Fp>(__f)(_VSTD::forward<_Args>(__args)...))
+_LIBCPP_INVOKE_RETURN(static_cast<_Fp&&>(__f)(static_cast<_Args&&>(__args)...))
 
 template <class _Fp, class ..._Args>
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_CONSTEXPR auto
 __invoke_constexpr(_Fp&& __f, _Args&& ...__args)
-_LIBCPP_INVOKE_RETURN(_VSTD::forward<_Fp>(__f)(_VSTD::forward<_Args>(__args)...))
+_LIBCPP_INVOKE_RETURN(static_cast<_Fp&&>(__f)(static_cast<_Args&&>(__args)...))
 
 #undef _LIBCPP_INVOKE_RETURN
 
@@ -3707,7 +3931,7 @@ struct __invokable_r
 {
   template <class _XFp, class ..._XArgs>
   static auto __try_call(int) -> decltype(
-    _VSTD::__invoke(_VSTD::declval<_XFp>(), _VSTD::declval<_XArgs>()...));
+    _VSTD::__invoke(declval<_XFp>(), declval<_XArgs>()...));
   template <class _XFp, class ..._XArgs>
   static __nat __try_call(...);
 
@@ -3744,14 +3968,14 @@ struct __nothrow_invokable_r_imp<true, false, _Ret, _Fp, _Args...>
     static void __test_noexcept(_Tp) noexcept;
 
     static const bool value = noexcept(_ThisT::__test_noexcept<_Ret>(
-        _VSTD::__invoke(_VSTD::declval<_Fp>(), _VSTD::declval<_Args>()...)));
+        _VSTD::__invoke(declval<_Fp>(), declval<_Args>()...)));
 };
 
 template <class _Ret, class _Fp, class ..._Args>
 struct __nothrow_invokable_r_imp<true, true, _Ret, _Fp, _Args...>
 {
     static const bool value = noexcept(
-        _VSTD::__invoke(_VSTD::declval<_Fp>(), _VSTD::declval<_Args>()...));
+        _VSTD::__invoke(declval<_Fp>(), declval<_Args>()...));
 };
 
 template <class _Ret, class _Fp, class ..._Args>
@@ -3781,7 +4005,8 @@ struct __invoke_of
 
 // result_of
 
-template <class _Callable> class result_of;
+#if _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS)
+template <class _Callable> class _LIBCPP_DEPRECATED_IN_CXX17 result_of;
 
 #ifndef _LIBCPP_CXX03_LANG
 
@@ -3812,8 +4037,8 @@ struct __result_of_mp;
 
 template <class _MP, class _Tp>
 struct __result_of_mp<_MP, _Tp, true>
-    : public __identity<typename __member_pointer_traits<_MP>::_ReturnType>
 {
+    using type = typename __member_pointer_traits<_MP>::_ReturnType;
 };
 
 // member data pointer
@@ -3824,13 +4049,13 @@ struct __result_of_mdp;
 template <class _Rp, class _Class, class _Tp>
 struct __result_of_mdp<_Rp _Class::*, _Tp, false>
 {
-    typedef typename __apply_cv<decltype(*_VSTD::declval<_Tp>()), _Rp>::type& type;
+    using type = typename __apply_cv<decltype(*declval<_Tp>()), _Rp>::type&;
 };
 
 template <class _Rp, class _Class, class _Tp>
 struct __result_of_mdp<_Rp _Class::*, _Tp, true>
 {
-    typedef typename __apply_cv<_Tp, _Rp>::type& type;
+    using type = typename __apply_cv<_Tp, _Rp>::type&;
 };
 
 template <class _Rp, class _Class, class _Tp>
@@ -3866,11 +4091,12 @@ class _LIBCPP_TEMPLATE_VIS result_of<_Fn(_Args...)>
 {
 };
 
-#endif  // C++03
+#endif // C++03
 
 #if _LIBCPP_STD_VER > 11
-template <class _Tp> using result_of_t = typename result_of<_Tp>::type;
-#endif
+template <class _Tp> using result_of_t _LIBCPP_DEPRECATED_IN_CXX17 = typename result_of<_Tp>::type;
+#endif // _LIBCPP_STD_VER > 11
+#endif // _LIBCPP_STD_VER <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_TYPE_TRAITS)
 
 #if _LIBCPP_STD_VER > 14
 
@@ -3923,70 +4149,32 @@ _LIBCPP_INLINE_VAR constexpr bool is_nothrow_invocable_r_v
 
 #endif // _LIBCPP_STD_VER > 14
 
+// __swappable
+
 template <class _Tp> struct __is_swappable;
 template <class _Tp> struct __is_nothrow_swappable;
 
-// swap, swap_ranges
 
-template <class _ForwardIterator1, class _ForwardIterator2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator2
-swap_ranges(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2);
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
 #ifndef _LIBCPP_CXX03_LANG
-typename enable_if
-<
-    is_move_constructible<_Tp>::value &&
-    is_move_assignable<_Tp>::value
->::type
+template <class _Tp>
+using __swap_result_t = typename enable_if<is_move_constructible<_Tp>::value && is_move_assignable<_Tp>::value>::type;
 #else
-void
+template <class>
+using __swap_result_t = void;
 #endif
-_LIBCPP_CONSTEXPR_AFTER_CXX17
+
+template <class _Tp>
+inline _LIBCPP_INLINE_VISIBILITY
+_LIBCPP_CONSTEXPR_AFTER_CXX17 __swap_result_t<_Tp>
 swap(_Tp& __x, _Tp& __y) _NOEXCEPT_(is_nothrow_move_constructible<_Tp>::value &&
-                                    is_nothrow_move_assignable<_Tp>::value)
-{
-    _Tp __t(_VSTD::move(__x));
-    __x = _VSTD::move(__y);
-    __y = _VSTD::move(__t);
-}
+                                    is_nothrow_move_assignable<_Tp>::value);
 
 template<class _Tp, size_t _Np>
 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
 typename enable_if<
     __is_swappable<_Tp>::value
 >::type
-swap(_Tp (&__a)[_Np], _Tp (&__b)[_Np]) _NOEXCEPT_(__is_nothrow_swappable<_Tp>::value)
-{
-    _VSTD::swap_ranges(__a, __a + _Np, __b);
-}
-
-template <class _ForwardIterator1, class _ForwardIterator2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_ForwardIterator2
-swap_ranges(_ForwardIterator1 __first1, _ForwardIterator1 __last1, _ForwardIterator2 __first2)
-{
-    for(; __first1 != __last1; ++__first1, (void) ++__first2)
-        swap(*__first1, *__first2);
-    return __first2;
-}
-
-// iter_swap
-
-template <class _ForwardIterator1, class _ForwardIterator2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-void
-iter_swap(_ForwardIterator1 __a, _ForwardIterator2 __b)
-    //                                  _NOEXCEPT_(_NOEXCEPT_(swap(*__a, *__b)))
-               _NOEXCEPT_(_NOEXCEPT_(swap(*_VSTD::declval<_ForwardIterator1>(),
-                                          *_VSTD::declval<_ForwardIterator2>())))
-{
-    swap(*__a, *__b);
-}
-
-// __swappable
+swap(_Tp (&__a)[_Np], _Tp (&__b)[_Np]) _NOEXCEPT_(__is_nothrow_swappable<_Tp>::value);
 
 namespace __detail
 {
@@ -3997,7 +4185,7 @@ template <class _Tp, class _Up = _Tp,
 struct __swappable_with
 {
     template <class _LHS, class _RHS>
-    static decltype(swap(_VSTD::declval<_LHS>(), _VSTD::declval<_RHS>()))
+    static decltype(swap(declval<_LHS>(), declval<_RHS>()))
     __test_swap(int);
     template <class, class>
     static __nat __test_swap(long);
@@ -4017,8 +4205,8 @@ template <class _Tp, class _Up = _Tp, bool _Swappable = __swappable_with<_Tp, _U
 struct __nothrow_swappable_with {
   static const bool value =
 #ifndef _LIBCPP_HAS_NO_NOEXCEPT
-      noexcept(swap(_VSTD::declval<_Tp>(), _VSTD::declval<_Up>()))
-  &&  noexcept(swap(_VSTD::declval<_Up>(), _VSTD::declval<_Tp>()));
+      noexcept(swap(declval<_Tp>(), declval<_Up>()))
+  &&  noexcept(swap(declval<_Up>(), declval<_Tp>()));
 #else
       false;
 #endif
@@ -4168,7 +4356,7 @@ struct __has_operator_addressof_member_imp
 {
     template <class _Up>
         static auto __test(int)
-            -> typename __select_2nd<decltype(_VSTD::declval<_Up>().operator&()), true_type>::type;
+            -> typename __select_2nd<decltype(declval<_Up>().operator&()), true_type>::type;
     template <class>
         static auto __test(long) -> false_type;
 
@@ -4180,7 +4368,7 @@ struct __has_operator_addressof_free_imp
 {
     template <class _Up>
         static auto __test(int)
-            -> typename __select_2nd<decltype(operator&(_VSTD::declval<_Up>())), true_type>::type;
+            -> typename __select_2nd<decltype(operator&(declval<_Up>())), true_type>::type;
     template <class>
         static auto __test(long) -> false_type;
 
@@ -4193,7 +4381,7 @@ struct __has_operator_addressof
                                   || __has_operator_addressof_free_imp<_Tp>::value>
 {};
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 // is_scoped_enum [meta.unary.prop]
 
@@ -4233,7 +4421,7 @@ struct negation : _Not<_Tp> {};
 template<class _Tp>
 _LIBCPP_INLINE_VAR constexpr bool negation_v
     = negation<_Tp>::value;
-#endif  // _LIBCPP_STD_VER > 14
+#endif // _LIBCPP_STD_VER > 14
 
 // These traits are used in __tree and __hash_table
 struct __extract_key_fail_tag {};
@@ -4283,6 +4471,14 @@ bool __libcpp_is_constant_evaluated() _NOEXCEPT { return false; }
 template <class _CharT>
 using _IsCharLikeType = _And<is_standard_layout<_CharT>, is_trivial<_CharT> >;
 
+template<class _Tp>
+using __make_const_lvalue_ref = const typename remove_reference<_Tp>::type&;
+
+#if _LIBCPP_STD_VER > 17
+template<bool _Const, class _Tp>
+using __maybe_const = conditional_t<_Const, const _Tp, _Tp>;
+#endif // _LIBCPP_STD_VER > 17
+
 _LIBCPP_END_NAMESPACE_STD
 
 #if _LIBCPP_STD_VER > 14
@@ -4294,4 +4490,4 @@ namespace std  // purposefully not versioned
 }
 #endif
 
-#endif  // _LIBCPP_TYPE_TRAITS
+#endif // _LIBCPP_TYPE_TRAITS
lib/libcxx/include/typeindex
@@ -45,8 +45,10 @@ struct hash<type_index>
 */
 
 #include <__config>
-#include <typeinfo>
+#include <__functional/unary_function.h>
 #include <__functional_base>
+#include <compare>
+#include <typeinfo>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -99,4 +101,4 @@ struct _LIBCPP_TEMPLATE_VIS hash<type_index>
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_TYPEINDEX
+#endif // _LIBCPP_TYPEINDEX
lib/libcxx/include/typeinfo
@@ -56,12 +56,13 @@ public:
 
 */
 
-#include <__config>
 #include <__availability>
-#include <exception>
+#include <__config>
 #include <cstddef>
 #include <cstdint>
+#include <exception>
 #include <type_traits>
+
 #ifdef _LIBCPP_NO_EXCEPTIONS
 #include <cstdlib>
 #endif
@@ -125,7 +126,7 @@ public:
 //               (_LIBCPP_TYPEINFO_COMPARISON_IMPLEMENTATION = 1)
 // ------------------------------------------------------------------------- //
 // This implementation of type_info assumes a unique copy of the RTTI for a
-// given type inside a program. This is a valid assumption when abiding to
+// given type inside a program. This is a valid assumption when abiding to the
 // Itanium ABI (http://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-components).
 // Under this assumption, we can always compare the addresses of the type names
 // to implement equality-comparison of type_infos instead of having to perform
@@ -144,22 +145,29 @@ public:
 //                          NonUniqueARMRTTIBit
 //               (_LIBCPP_TYPEINFO_COMPARISON_IMPLEMENTATION = 3)
 // -------------------------------------------------------------------------- //
+// This implementation is specific to ARM64 on Apple platforms.
+//
 // This implementation of type_info does not assume always a unique copy of
-// the RTTI for a given type inside a program. It packs the pointer to the
-// type name into a uintptr_t and reserves the high bit of that pointer (which
-// is assumed to be free for use under the ABI in use) to represent whether
-// that specific copy of the RTTI can be assumed unique inside the program.
-// To implement equality-comparison of type_infos, we check whether BOTH
-// type_infos are guaranteed unique, and if so, we simply compare the addresses
-// of their type names instead of doing a deep string comparison, which is
-// faster. If at least one of the type_infos can't guarantee uniqueness, we
-// have no choice but to fall back to a deep string comparison.
+// the RTTI for a given type inside a program. When constructing the type_info,
+// the compiler packs the pointer to the type name into a uintptr_t and reserves
+// the high bit of that pointer, which is assumed to be free for use under that
+// ABI. If that high bit is set, that specific copy of the RTTI can't be assumed
+// to be unique within the program. If the high bit is unset, then the RTTI can
+// be assumed to be unique within the program.
 //
-// This implementation is specific to ARM64 on Apple platforms.
+// When comparing type_infos, if both RTTIs can be assumed to be unique, it
+// suffices to compare their addresses. If both the RTTIs can't be assumed to
+// be unique, we must perform a deep string comparison of the type names.
+// However, if one of the RTTIs is guaranteed unique and the other one isn't,
+// then both RTTIs are necessarily not to be considered equal.
 //
-// Note that the compiler is the one setting (or unsetting) the high bit of
-// the pointer when it constructs the type_info, depending on whether it can
-// guarantee uniqueness for that specific type_info.
+// The intent of this design is to remove the need for weak symbols. Specifically,
+// if a type would normally have a default-visibility RTTI emitted as a weak
+// symbol, it is given hidden visibility instead and the non-unique bit is set.
+// Otherwise, types declared with hidden visibility are always considered to have
+// a unique RTTI: the RTTI is emitted with linkonce_odr linkage and is assumed
+// to be deduplicated by the linker within the linked image. Across linked image
+// boundaries, such types are thus considered different types.
 
 // This value can be overriden in the __config_site. When it's not overriden,
 // we pick a default implementation based on the platform here.
@@ -241,20 +249,22 @@ struct __type_info_implementations {
     _LIBCPP_INLINE_VISIBILITY _LIBCPP_ALWAYS_INLINE
     static size_t __hash(__type_name_t __v) _NOEXCEPT {
       if (__is_type_name_unique(__v))
-        return reinterpret_cast<size_t>(__v);
+        return __v;
       return __non_unique_impl::__hash(__type_name_to_string(__v));
     }
     _LIBCPP_INLINE_VISIBILITY _LIBCPP_ALWAYS_INLINE
     static bool __eq(__type_name_t __lhs, __type_name_t __rhs) _NOEXCEPT {
       if (__lhs == __rhs)
         return true;
-      if (__is_type_name_unique(__lhs, __rhs))
+      if (__is_type_name_unique(__lhs) || __is_type_name_unique(__rhs))
+        // Either both are unique and have a different address, or one of them
+        // is unique and the other one isn't. In both cases they are unequal.
         return false;
       return __builtin_strcmp(__type_name_to_string(__lhs), __type_name_to_string(__rhs)) == 0;
     }
     _LIBCPP_INLINE_VISIBILITY _LIBCPP_ALWAYS_INLINE
     static bool __lt(__type_name_t __lhs, __type_name_t __rhs) _NOEXCEPT {
-      if (__is_type_name_unique(__lhs, __rhs))
+      if (__is_type_name_unique(__lhs) || __is_type_name_unique(__rhs))
         return __lhs < __rhs;
       return __builtin_strcmp(__type_name_to_string(__lhs), __type_name_to_string(__rhs)) < 0;
     }
@@ -269,10 +279,6 @@ struct __type_info_implementations {
     static bool __is_type_name_unique(__type_name_t __lhs) _NOEXCEPT {
       return !(__lhs & __non_unique_rtti_bit::value);
     }
-    _LIBCPP_INLINE_VISIBILITY
-    static bool __is_type_name_unique(__type_name_t __lhs, __type_name_t __rhs) _NOEXCEPT {
-      return !((__lhs & __rhs) & __non_unique_rtti_bit::value);
-    }
   };
 
   typedef
@@ -371,4 +377,4 @@ void __throw_bad_cast()
 }
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // __LIBCPP_TYPEINFO
+#endif // __LIBCPP_TYPEINFO
lib/libcxx/include/unordered_map
@@ -432,15 +432,18 @@ template <class Key, class T, class Hash, class Pred, class Alloc>
 */
 
 #include <__config>
+#include <__debug>
+#include <__functional/is_transparent.h>
 #include <__hash_table>
 #include <__node_handle>
+#include <__utility/forward.h>
+#include <compare>
 #include <functional>
+#include <iterator> // __libcpp_erase_if_container
 #include <stdexcept>
 #include <tuple>
 #include <version>
 
-#include <__debug>
-
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
@@ -684,7 +687,7 @@ public:
         {
             const_cast<bool&>(__x.__value_constructed) = false;
         }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     void operator()(pointer __p) _NOEXCEPT
@@ -700,7 +703,7 @@ public:
 
 #ifndef _LIBCPP_CXX03_LANG
 template <class _Key, class _Tp>
-struct __hash_value_type
+struct _LIBCPP_STANDALONE_DEBUG __hash_value_type
 {
     typedef _Key                                     key_type;
     typedef _Tp                                      mapped_type;
@@ -920,9 +923,9 @@ public:
     // types
     typedef _Key                                           key_type;
     typedef _Tp                                            mapped_type;
-    typedef typename __identity<_Hash>::type               hasher;
-    typedef typename __identity<_Pred>::type               key_equal;
-    typedef typename __identity<_Alloc>::type              allocator_type;
+    typedef __identity_t<_Hash>                            hasher;
+    typedef __identity_t<_Pred>                            key_equal;
+    typedef __identity_t<_Alloc>                           allocator_type;
     typedef pair<const key_type, mapped_type>              value_type;
     typedef value_type&                                    reference;
     typedef const value_type&                              const_reference;
@@ -1013,7 +1016,7 @@ public:
     unordered_map(initializer_list<value_type> __il, size_type __n,
                   const hasher& __hf, const key_equal& __eql,
                   const allocator_type& __a);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 #if _LIBCPP_STD_VER > 11
     _LIBCPP_INLINE_VISIBILITY
     unordered_map(size_type __n, const allocator_type& __a)
@@ -1066,7 +1069,7 @@ public:
         _NOEXCEPT_(is_nothrow_move_assignable<__table>::value);
     _LIBCPP_INLINE_VISIBILITY
     unordered_map& operator=(initializer_list<value_type> __il);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     allocator_type get_allocator() const _NOEXCEPT
@@ -1171,7 +1174,7 @@ public:
         return __table_.__emplace_unique(_VSTD::forward<_Args>(__args)...).first;
     }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 #if _LIBCPP_STD_VER > 14
     template <class... _Args>
@@ -1452,7 +1455,7 @@ public:
     bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const
         {return __table_.__addable(&__i->__i_, __n);}
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 private:
 
@@ -1718,7 +1721,7 @@ unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::operator=(
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Key, class _Tp, class _Hash, class _Pred, class _Alloc>
 template <class _InputIterator>
@@ -1778,7 +1781,7 @@ unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::operator[](const key_type& __k)
     return __r.first->second;
 }
 
-#endif  // _LIBCPP_CXX03_MODE
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Key, class _Tp, class _Hash, class _Pred, class _Alloc>
 _Tp&
@@ -1817,7 +1820,7 @@ inline _LIBCPP_INLINE_VISIBILITY
     typename unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type
     erase_if(unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __c,
              _Predicate __pred) {
-  return __libcpp_erase_if_container(__c, __pred);
+  return _VSTD::__libcpp_erase_if_container(__c, __pred);
 }
 #endif
 
@@ -1857,9 +1860,9 @@ public:
     // types
     typedef _Key                                           key_type;
     typedef _Tp                                            mapped_type;
-    typedef typename __identity<_Hash>::type               hasher;
-    typedef typename __identity<_Pred>::type               key_equal;
-    typedef typename __identity<_Alloc>::type              allocator_type;
+    typedef __identity_t<_Hash>                            hasher;
+    typedef __identity_t<_Pred>                            key_equal;
+    typedef __identity_t<_Alloc>                           allocator_type;
     typedef pair<const key_type, mapped_type>              value_type;
     typedef value_type&                                    reference;
     typedef const value_type&                              const_reference;
@@ -1948,7 +1951,7 @@ public:
     unordered_multimap(initializer_list<value_type> __il, size_type __n,
                        const hasher& __hf, const key_equal& __eql,
                        const allocator_type& __a);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 #if _LIBCPP_STD_VER > 11
     _LIBCPP_INLINE_VISIBILITY
     unordered_multimap(size_type __n, const allocator_type& __a)
@@ -2001,7 +2004,7 @@ public:
         _NOEXCEPT_(is_nothrow_move_assignable<__table>::value);
     _LIBCPP_INLINE_VISIBILITY
     unordered_multimap& operator=(initializer_list<value_type> __il);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     allocator_type get_allocator() const _NOEXCEPT
@@ -2070,7 +2073,7 @@ public:
     iterator emplace_hint(const_iterator __p, _Args&&... __args) {
         return __table_.__emplace_hint_multi(__p.__i_, _VSTD::forward<_Args>(__args)...);
     }
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 
     _LIBCPP_INLINE_VISIBILITY
@@ -2255,7 +2258,7 @@ public:
     bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const
         {return __table_.__addable(&__i->__i_, __n);}
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 
 };
@@ -2518,7 +2521,7 @@ unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>::operator=(
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 
 
@@ -2550,7 +2553,7 @@ inline _LIBCPP_INLINE_VISIBILITY
     typename unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>::size_type
     erase_if(unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __c,
              _Predicate __pred) {
-  return __libcpp_erase_if_container(__c, __pred);
+  return _VSTD::__libcpp_erase_if_container(__c, __pred);
 }
 #endif
 
@@ -2588,4 +2591,4 @@ operator!=(const unordered_multimap<_Key, _Tp, _Hash, _Pred, _Alloc>& __x,
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_UNORDERED_MAP
+#endif // _LIBCPP_UNORDERED_MAP
lib/libcxx/include/unordered_set
@@ -387,13 +387,16 @@ template <class Value, class Hash, class Pred, class Alloc>
 */
 
 #include <__config>
+#include <__debug>
+#include <__functional/is_transparent.h>
 #include <__hash_table>
 #include <__node_handle>
+#include <__utility/forward.h>
+#include <compare>
 #include <functional>
+#include <iterator> // __libcpp_erase_if_container
 #include <version>
 
-#include <__debug>
-
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
 #endif
@@ -411,9 +414,9 @@ public:
     // types
     typedef _Value                                                     key_type;
     typedef key_type                                                   value_type;
-    typedef typename __identity<_Hash>::type                           hasher;
-    typedef typename __identity<_Pred>::type                           key_equal;
-    typedef typename __identity<_Alloc>::type                          allocator_type;
+    typedef __identity_t<_Hash>                                        hasher;
+    typedef __identity_t<_Pred>                                        key_equal;
+    typedef __identity_t<_Alloc>                                       allocator_type;
     typedef value_type&                                                reference;
     typedef const value_type&                                          const_reference;
     static_assert((is_same<value_type, typename allocator_type::value_type>::value),
@@ -512,7 +515,7 @@ public:
                                   const hasher& __hf, const allocator_type& __a)
         : unordered_set(__il, __n, __hf, key_equal(), __a) {}
 #endif
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     ~unordered_set() {
         static_assert(sizeof(__diagnose_unordered_container_requirements<_Value, _Hash, _Pred>(0)), "");
@@ -530,7 +533,7 @@ public:
         _NOEXCEPT_(is_nothrow_move_assignable<__table>::value);
     _LIBCPP_INLINE_VISIBILITY
     unordered_set& operator=(initializer_list<value_type> __il);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     allocator_type get_allocator() const _NOEXCEPT
@@ -595,7 +598,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     void insert(initializer_list<value_type> __il)
         {insert(__il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     pair<iterator, bool> insert(const value_type& __x)
         {return __table_.__insert_unique(__x);}
@@ -792,7 +795,7 @@ public:
     bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const
         {return __table_.__addable(__i, __n);}
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 };
 
@@ -1039,7 +1042,7 @@ unordered_set<_Value, _Hash, _Pred, _Alloc>::operator=(
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Value, class _Hash, class _Pred, class _Alloc>
 template <class _InputIterator>
@@ -1069,7 +1072,7 @@ inline _LIBCPP_INLINE_VISIBILITY
     typename unordered_set<_Value, _Hash, _Pred, _Alloc>::size_type
     erase_if(unordered_set<_Value, _Hash, _Pred, _Alloc>& __c,
              _Predicate __pred) {
-  return __libcpp_erase_if_container(__c, __pred);
+  return _VSTD::__libcpp_erase_if_container(__c, __pred);
 }
 #endif
 
@@ -1109,9 +1112,9 @@ public:
     // types
     typedef _Value                                                     key_type;
     typedef key_type                                                   value_type;
-    typedef typename __identity<_Hash>::type                           hasher;
-    typedef typename __identity<_Pred>::type                           key_equal;
-    typedef typename __identity<_Alloc>::type                          allocator_type;
+    typedef __identity_t<_Hash>                                        hasher;
+    typedef __identity_t<_Pred>                                        key_equal;
+    typedef __identity_t<_Alloc>                                       allocator_type;
     typedef value_type&                                                reference;
     typedef const value_type&                                          const_reference;
     static_assert((is_same<value_type, typename allocator_type::value_type>::value),
@@ -1208,7 +1211,7 @@ public:
     unordered_multiset(initializer_list<value_type> __il, size_type __n, const hasher& __hf, const allocator_type& __a)
       : unordered_multiset(__il, __n, __hf, key_equal(), __a) {}
 #endif
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     ~unordered_multiset() {
         static_assert(sizeof(__diagnose_unordered_container_requirements<_Value, _Hash, _Pred>(0)), "");
@@ -1225,7 +1228,7 @@ public:
     unordered_multiset& operator=(unordered_multiset&& __u)
         _NOEXCEPT_(is_nothrow_move_assignable<__table>::value);
     unordered_multiset& operator=(initializer_list<value_type> __il);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     allocator_type get_allocator() const _NOEXCEPT
@@ -1269,7 +1272,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     void insert(initializer_list<value_type> __il)
         {insert(__il.begin(), __il.end());}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     iterator insert(const value_type& __x) {return __table_.__insert_multi(__x);}
@@ -1458,7 +1461,7 @@ public:
     bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const
         {return __table_.__addable(__i, __n);}
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 };
 
@@ -1705,7 +1708,7 @@ unordered_multiset<_Value, _Hash, _Pred, _Alloc>::operator=(
     return *this;
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Value, class _Hash, class _Pred, class _Alloc>
 template <class _InputIterator>
@@ -1735,7 +1738,7 @@ inline _LIBCPP_INLINE_VISIBILITY
     typename unordered_multiset<_Value, _Hash, _Pred, _Alloc>::size_type
     erase_if(unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __c,
              _Predicate __pred) {
-  return __libcpp_erase_if_container(__c, __pred);
+  return _VSTD::__libcpp_erase_if_container(__c, __pred);
 }
 #endif
 
@@ -1773,4 +1776,4 @@ operator!=(const unordered_multiset<_Value, _Hash, _Pred, _Alloc>& __x,
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_UNORDERED_SET
+#endif // _LIBCPP_UNORDERED_SET
lib/libcxx/include/utility
@@ -58,6 +58,14 @@ template <class T>                      void as_const(const T&&) = delete; // C+
 
 template <class T> typename add_rvalue_reference<T>::type declval() noexcept;
 
+template<class T, class U> constexpr bool cmp_equal(T t, U u) noexcept;         // C++20
+template<class T, class U> constexpr bool cmp_not_equal(T t, U u) noexcept;     // C++20
+template<class T, class U> constexpr bool cmp_less(T t, U u) noexcept;          // C++20
+template<class T, class U> constexpr bool cmp_greater(T t, U u) noexcept;       // C++20
+template<class T, class U> constexpr bool cmp_less_equal(T t, U u) noexcept;    // C++20
+template<class T, class U> constexpr bool cmp_greater_equal(T t, U u) noexcept; // C++20
+template<class R, class T> constexpr bool in_range(T t) noexcept;               // C++20
+
 template <class T1, class T2>
 struct pair
 {
@@ -76,15 +84,15 @@ struct pair
     template <class U, class V> explicit(see-below) pair(pair<U, V>&& p);        // constexpr in C++14
     template <class... Args1, class... Args2>
         pair(piecewise_construct_t, tuple<Args1...> first_args,
-             tuple<Args2...> second_args);
+             tuple<Args2...> second_args);                                       // constexpr in C++20
 
-    template <class U, class V> pair& operator=(const pair<U, V>& p);
+    template <class U, class V> pair& operator=(const pair<U, V>& p);            // constexpr in C++20
     pair& operator=(pair&& p) noexcept(is_nothrow_move_assignable<T1>::value &&
-                                       is_nothrow_move_assignable<T2>::value);
-    template <class U, class V> pair& operator=(pair<U, V>&& p);
+                                       is_nothrow_move_assignable<T2>::value);   // constexpr in C++20
+    template <class U, class V> pair& operator=(pair<U, V>&& p);                 // constexpr in C++20
 
     void swap(pair& p) noexcept(is_nothrow_swappable_v<T1> &&
-                                is_nothrow_swappable_v<T2>);
+                                is_nothrow_swappable_v<T2>);                     // constexpr in C++20
 };
 
 template <class T1, class T2> bool operator==(const pair<T1,T2>&, const pair<T1,T2>&); // constexpr in C++14
@@ -94,10 +102,10 @@ template <class T1, class T2> bool operator> (const pair<T1,T2>&, const pair<T1,
 template <class T1, class T2> bool operator>=(const pair<T1,T2>&, const pair<T1,T2>&); // constexpr in C++14
 template <class T1, class T2> bool operator<=(const pair<T1,T2>&, const pair<T1,T2>&); // constexpr in C++14
 
-template <class T1, class T2> pair<V1, V2> make_pair(T1&&, T2&&);   // constexpr in C++14
+template <class T1, class T2> pair<V1, V2> make_pair(T1&&, T2&&);                // constexpr in C++14
 template <class T1, class T2>
 void
-swap(pair<T1, T2>& x, pair<T1, T2>& y) noexcept(noexcept(x.swap(y)));
+swap(pair<T1, T2>& x, pair<T1, T2>& y) noexcept(noexcept(x.swap(y)));            // constexpr in C++20
 
 struct piecewise_construct_t { explicit piecewise_construct_t() = default; };
 inline constexpr piecewise_construct_t piecewise_construct = piecewise_construct_t();
@@ -191,1439 +199,32 @@ template <size_t I>
 template <size_t I>
   inline constexpr in_place_index_t<I> in_place_index{};
 
+// [utility.underlying], to_underlying
+template <class T>
+    constexpr underlying_type_t<T> to_underlying( T value ) noexcept; // C++2b
+
 }  // std
 
 */
 
 #include <__config>
+#include <__debug>
 #include <__tuple>
-#include <type_traits>
+#include <__utility/as_const.h>
+#include <__utility/cmp.h>
+#include <__utility/declval.h>
+#include <__utility/exchange.h>
+#include <__utility/forward.h>
+#include <__utility/in_place.h>
+#include <__utility/integer_sequence.h>
+#include <__utility/move.h>
+#include <__utility/pair.h>
+#include <__utility/piecewise_construct.h>
+#include <__utility/rel_ops.h>
+#include <__utility/swap.h>
+#include <__utility/to_underlying.h>
+#include <compare>
 #include <initializer_list>
-#include <cstddef>
-#include <cstring>
-#include <cstdint>
 #include <version>
-#include <__debug>
-
-#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
-#pragma GCC system_header
-#endif
-
-_LIBCPP_BEGIN_NAMESPACE_STD
-
-namespace rel_ops
-{
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator!=(const _Tp& __x, const _Tp& __y)
-{
-    return !(__x == __y);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator> (const _Tp& __x, const _Tp& __y)
-{
-    return __y < __x;
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator<=(const _Tp& __x, const _Tp& __y)
-{
-    return !(__y < __x);
-}
-
-template<class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY
-bool
-operator>=(const _Tp& __x, const _Tp& __y)
-{
-    return !(__x < __y);
-}
-
-}  // rel_ops
-
-// swap_ranges is defined in <type_traits>`
-
-// swap is defined in <type_traits>
-
-// move_if_noexcept
-
-template <class _Tp>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-#ifndef _LIBCPP_CXX03_LANG
-typename conditional
-<
-    !is_nothrow_move_constructible<_Tp>::value && is_copy_constructible<_Tp>::value,
-    const _Tp&,
-    _Tp&&
->::type
-#else  // _LIBCPP_CXX03_LANG
-const _Tp&
-#endif
-move_if_noexcept(_Tp& __x) _NOEXCEPT
-{
-    return _VSTD::move(__x);
-}
-
-#if _LIBCPP_STD_VER > 14
-template <class _Tp> constexpr add_const_t<_Tp>& as_const(_Tp& __t) noexcept { return __t; }
-template <class _Tp>                        void as_const(const _Tp&&) = delete;
-#endif
-
-struct _LIBCPP_TEMPLATE_VIS piecewise_construct_t { explicit piecewise_construct_t() = default; };
-#if defined(_LIBCPP_CXX03_LANG) || defined(_LIBCPP_BUILDING_LIBRARY)
-extern _LIBCPP_EXPORTED_FROM_ABI const piecewise_construct_t piecewise_construct;// = piecewise_construct_t();
-#else
-/* _LIBCPP_INLINE_VAR */ constexpr piecewise_construct_t piecewise_construct = piecewise_construct_t();
-#endif
-
-#if defined(_LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR)
-template <class, class>
-struct __non_trivially_copyable_base {
-  _LIBCPP_CONSTEXPR _LIBCPP_INLINE_VISIBILITY
-  __non_trivially_copyable_base() _NOEXCEPT {}
-  _LIBCPP_CONSTEXPR_AFTER_CXX11 _LIBCPP_INLINE_VISIBILITY
-  __non_trivially_copyable_base(__non_trivially_copyable_base const&) _NOEXCEPT {}
-};
-#endif
-
-template <class _T1, class _T2>
-struct _LIBCPP_TEMPLATE_VIS pair
-#if defined(_LIBCPP_DEPRECATED_ABI_DISABLE_PAIR_TRIVIAL_COPY_CTOR)
-: private __non_trivially_copyable_base<_T1, _T2>
-#endif
-{
-    typedef _T1 first_type;
-    typedef _T2 second_type;
-
-    _T1 first;
-    _T2 second;
-
-#if !defined(_LIBCPP_CXX03_LANG)
-    pair(pair const&) = default;
-    pair(pair&&) = default;
-#else
-  // Use the implicitly declared copy constructor in C++03
-#endif
-
-#ifdef _LIBCPP_CXX03_LANG
-    _LIBCPP_INLINE_VISIBILITY
-    pair() : first(), second() {}
-
-    _LIBCPP_INLINE_VISIBILITY
-    pair(_T1 const& __t1, _T2 const& __t2) : first(__t1), second(__t2) {}
-
-    template <class _U1, class _U2>
-    _LIBCPP_INLINE_VISIBILITY
-    pair(const pair<_U1, _U2>& __p) : first(__p.first), second(__p.second) {}
-
-    _LIBCPP_INLINE_VISIBILITY
-    pair& operator=(pair const& __p) {
-        first = __p.first;
-        second = __p.second;
-        return *this;
-    }
-#else
-    template <bool _Val>
-    using _EnableB _LIBCPP_NODEBUG_TYPE = typename enable_if<_Val, bool>::type;
-
-    struct _CheckArgs {
-      template <int&...>
-      static constexpr bool __enable_explicit_default() {
-          return is_default_constructible<_T1>::value
-              && is_default_constructible<_T2>::value
-              && !__enable_implicit_default<>();
-      }
-
-      template <int&...>
-      static constexpr bool __enable_implicit_default() {
-          return __is_implicitly_default_constructible<_T1>::value
-              && __is_implicitly_default_constructible<_T2>::value;
-      }
-
-      template <class _U1, class _U2>
-      static constexpr bool __enable_explicit() {
-          return is_constructible<first_type, _U1>::value
-              && is_constructible<second_type, _U2>::value
-              && (!is_convertible<_U1, first_type>::value
-                  || !is_convertible<_U2, second_type>::value);
-      }
-
-      template <class _U1, class _U2>
-      static constexpr bool __enable_implicit() {
-          return is_constructible<first_type, _U1>::value
-              && is_constructible<second_type, _U2>::value
-              && is_convertible<_U1, first_type>::value
-              && is_convertible<_U2, second_type>::value;
-      }
-    };
-
-    template <bool _MaybeEnable>
-    using _CheckArgsDep _LIBCPP_NODEBUG_TYPE = typename conditional<
-      _MaybeEnable, _CheckArgs, __check_tuple_constructor_fail>::type;
-
-    struct _CheckTupleLikeConstructor {
-        template <class _Tuple>
-        static constexpr bool __enable_implicit() {
-            return __tuple_convertible<_Tuple, pair>::value;
-        }
-
-        template <class _Tuple>
-        static constexpr bool __enable_explicit() {
-            return __tuple_constructible<_Tuple, pair>::value
-               && !__tuple_convertible<_Tuple, pair>::value;
-        }
-
-        template <class _Tuple>
-        static constexpr bool __enable_assign() {
-            return __tuple_assignable<_Tuple, pair>::value;
-        }
-    };
-
-    template <class _Tuple>
-    using _CheckTLC _LIBCPP_NODEBUG_TYPE = typename conditional<
-        __tuple_like_with_size<_Tuple, 2>::value
-            && !is_same<typename decay<_Tuple>::type, pair>::value,
-        _CheckTupleLikeConstructor,
-        __check_tuple_constructor_fail
-    >::type;
-
-    template<bool _Dummy = true, _EnableB<
-            _CheckArgsDep<_Dummy>::__enable_explicit_default()
-    > = false>
-    explicit _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-    pair() _NOEXCEPT_(is_nothrow_default_constructible<first_type>::value &&
-                      is_nothrow_default_constructible<second_type>::value)
-        : first(), second() {}
-
-    template<bool _Dummy = true, _EnableB<
-            _CheckArgsDep<_Dummy>::__enable_implicit_default()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
-    pair() _NOEXCEPT_(is_nothrow_default_constructible<first_type>::value &&
-                      is_nothrow_default_constructible<second_type>::value)
-        : first(), second() {}
-
-    template <bool _Dummy = true, _EnableB<
-             _CheckArgsDep<_Dummy>::template __enable_explicit<_T1 const&, _T2 const&>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    explicit pair(_T1 const& __t1, _T2 const& __t2)
-        _NOEXCEPT_(is_nothrow_copy_constructible<first_type>::value &&
-                   is_nothrow_copy_constructible<second_type>::value)
-        : first(__t1), second(__t2) {}
-
-    template<bool _Dummy = true, _EnableB<
-            _CheckArgsDep<_Dummy>::template __enable_implicit<_T1 const&, _T2 const&>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    pair(_T1 const& __t1, _T2 const& __t2)
-        _NOEXCEPT_(is_nothrow_copy_constructible<first_type>::value &&
-                   is_nothrow_copy_constructible<second_type>::value)
-        : first(__t1), second(__t2) {}
-
-    template<class _U1, class _U2, _EnableB<
-             _CheckArgs::template __enable_explicit<_U1, _U2>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    explicit pair(_U1&& __u1, _U2&& __u2)
-        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1>::value &&
-                    is_nothrow_constructible<second_type, _U2>::value))
-        : first(_VSTD::forward<_U1>(__u1)), second(_VSTD::forward<_U2>(__u2)) {}
-
-    template<class _U1, class _U2, _EnableB<
-            _CheckArgs::template __enable_implicit<_U1, _U2>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    pair(_U1&& __u1, _U2&& __u2)
-        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1>::value &&
-                    is_nothrow_constructible<second_type, _U2>::value))
-        : first(_VSTD::forward<_U1>(__u1)), second(_VSTD::forward<_U2>(__u2)) {}
-
-    template<class _U1, class _U2, _EnableB<
-            _CheckArgs::template __enable_explicit<_U1 const&, _U2 const&>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    explicit pair(pair<_U1, _U2> const& __p)
-        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1 const&>::value &&
-                    is_nothrow_constructible<second_type, _U2 const&>::value))
-        : first(__p.first), second(__p.second) {}
-
-    template<class _U1, class _U2, _EnableB<
-            _CheckArgs::template __enable_implicit<_U1 const&, _U2 const&>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    pair(pair<_U1, _U2> const& __p)
-        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1 const&>::value &&
-                    is_nothrow_constructible<second_type, _U2 const&>::value))
-        : first(__p.first), second(__p.second) {}
-
-    template<class _U1, class _U2, _EnableB<
-            _CheckArgs::template __enable_explicit<_U1, _U2>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    explicit pair(pair<_U1, _U2>&&__p)
-        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1&&>::value &&
-                    is_nothrow_constructible<second_type, _U2&&>::value))
-        : first(_VSTD::forward<_U1>(__p.first)), second(_VSTD::forward<_U2>(__p.second)) {}
-
-    template<class _U1, class _U2, _EnableB<
-            _CheckArgs::template __enable_implicit<_U1, _U2>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    pair(pair<_U1, _U2>&& __p)
-        _NOEXCEPT_((is_nothrow_constructible<first_type, _U1&&>::value &&
-                    is_nothrow_constructible<second_type, _U2&&>::value))
-        : first(_VSTD::forward<_U1>(__p.first)), second(_VSTD::forward<_U2>(__p.second)) {}
-
-    template<class _Tuple, _EnableB<
-            _CheckTLC<_Tuple>::template __enable_explicit<_Tuple>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    explicit pair(_Tuple&& __p)
-        : first(_VSTD::get<0>(_VSTD::forward<_Tuple>(__p))),
-          second(_VSTD::get<1>(_VSTD::forward<_Tuple>(__p))) {}
-
-    template<class _Tuple, _EnableB<
-            _CheckTLC<_Tuple>::template __enable_implicit<_Tuple>()
-    > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    pair(_Tuple&& __p)
-        : first(_VSTD::get<0>(_VSTD::forward<_Tuple>(__p))),
-          second(_VSTD::get<1>(_VSTD::forward<_Tuple>(__p))) {}
-
-    template <class... _Args1, class... _Args2>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    pair(piecewise_construct_t __pc,
-         tuple<_Args1...> __first_args, tuple<_Args2...> __second_args)
-        _NOEXCEPT_((is_nothrow_constructible<first_type, _Args1...>::value &&
-                    is_nothrow_constructible<second_type, _Args2...>::value))
-        : pair(__pc, __first_args, __second_args,
-                typename __make_tuple_indices<sizeof...(_Args1)>::type(),
-                typename __make_tuple_indices<sizeof...(_Args2) >::type()) {}
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    pair& operator=(typename conditional<
-                        is_copy_assignable<first_type>::value &&
-                        is_copy_assignable<second_type>::value,
-                    pair, __nat>::type const& __p)
-        _NOEXCEPT_(is_nothrow_copy_assignable<first_type>::value &&
-                   is_nothrow_copy_assignable<second_type>::value)
-    {
-        first = __p.first;
-        second = __p.second;
-        return *this;
-    }
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    pair& operator=(typename conditional<
-                        is_move_assignable<first_type>::value &&
-                        is_move_assignable<second_type>::value,
-                    pair, __nat>::type&& __p)
-        _NOEXCEPT_(is_nothrow_move_assignable<first_type>::value &&
-                   is_nothrow_move_assignable<second_type>::value)
-    {
-        first = _VSTD::forward<first_type>(__p.first);
-        second = _VSTD::forward<second_type>(__p.second);
-        return *this;
-    }
-
-    template <class _Tuple, _EnableB<
-            _CheckTLC<_Tuple>::template __enable_assign<_Tuple>()
-     > = false>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    pair& operator=(_Tuple&& __p) {
-        first = _VSTD::get<0>(_VSTD::forward<_Tuple>(__p));
-        second = _VSTD::get<1>(_VSTD::forward<_Tuple>(__p));
-        return *this;
-    }
-#endif
-
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    void
-    swap(pair& __p) _NOEXCEPT_(__is_nothrow_swappable<first_type>::value &&
-                               __is_nothrow_swappable<second_type>::value)
-    {
-        using _VSTD::swap;
-        swap(first,  __p.first);
-        swap(second, __p.second);
-    }
-private:
-
-#ifndef _LIBCPP_CXX03_LANG
-    template <class... _Args1, class... _Args2, size_t... _I1, size_t... _I2>
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-    pair(piecewise_construct_t,
-         tuple<_Args1...>& __first_args, tuple<_Args2...>& __second_args,
-         __tuple_indices<_I1...>, __tuple_indices<_I2...>);
-#endif
-};
-
-#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
-template<class _T1, class _T2>
-pair(_T1, _T2) -> pair<_T1, _T2>;
-#endif // _LIBCPP_HAS_NO_DEDUCTION_GUIDES
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-bool
-operator==(const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
-{
-    return __x.first == __y.first && __x.second == __y.second;
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-bool
-operator!=(const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
-{
-    return !(__x == __y);
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-bool
-operator< (const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
-{
-    return __x.first < __y.first || (!(__y.first < __x.first) && __x.second < __y.second);
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-bool
-operator> (const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
-{
-    return __y < __x;
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-bool
-operator>=(const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
-{
-    return !(__x < __y);
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-bool
-operator<=(const pair<_T1,_T2>& __x, const pair<_T1,_T2>& __y)
-{
-    return !(__y < __x);
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-typename enable_if
-<
-    __is_swappable<_T1>::value &&
-    __is_swappable<_T2>::value,
-    void
->::type
-swap(pair<_T1, _T2>& __x, pair<_T1, _T2>& __y)
-                     _NOEXCEPT_((__is_nothrow_swappable<_T1>::value &&
-                                 __is_nothrow_swappable<_T2>::value))
-{
-    __x.swap(__y);
-}
-
-template <class _Tp>
-struct __unwrap_reference { typedef _LIBCPP_NODEBUG_TYPE _Tp type; };
-
-template <class _Tp>
-struct __unwrap_reference<reference_wrapper<_Tp> > { typedef _LIBCPP_NODEBUG_TYPE _Tp& type; };
-
-#if _LIBCPP_STD_VER > 17
-template <class _Tp>
-struct unwrap_reference : __unwrap_reference<_Tp> { };
-
-template <class _Tp>
-struct unwrap_ref_decay : unwrap_reference<typename decay<_Tp>::type> { };
-#endif // > C++17
-
-template <class _Tp>
-struct __unwrap_ref_decay
-#if _LIBCPP_STD_VER > 17
-    : unwrap_ref_decay<_Tp>
-#else
-    : __unwrap_reference<typename decay<_Tp>::type>
-#endif
-{ };
-
-#ifndef _LIBCPP_CXX03_LANG
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-pair<typename __unwrap_ref_decay<_T1>::type, typename __unwrap_ref_decay<_T2>::type>
-make_pair(_T1&& __t1, _T2&& __t2)
-{
-    return pair<typename __unwrap_ref_decay<_T1>::type, typename __unwrap_ref_decay<_T2>::type>
-               (_VSTD::forward<_T1>(__t1), _VSTD::forward<_T2>(__t2));
-}
-
-#else  // _LIBCPP_CXX03_LANG
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-pair<_T1,_T2>
-make_pair(_T1 __x, _T2 __y)
-{
-    return pair<_T1, _T2>(__x, __y);
-}
-
-#endif  // _LIBCPP_CXX03_LANG
-
-template <class _T1, class _T2>
-  struct _LIBCPP_TEMPLATE_VIS tuple_size<pair<_T1, _T2> >
-    : public integral_constant<size_t, 2> {};
-
-template <size_t _Ip, class _T1, class _T2>
-struct _LIBCPP_TEMPLATE_VIS tuple_element<_Ip, pair<_T1, _T2> >
-{
-    static_assert(_Ip < 2, "Index out of bounds in std::tuple_element<std::pair<T1, T2>>");
-};
-
-template <class _T1, class _T2>
-struct _LIBCPP_TEMPLATE_VIS tuple_element<0, pair<_T1, _T2> >
-{
-    typedef _LIBCPP_NODEBUG_TYPE _T1 type;
-};
-
-template <class _T1, class _T2>
-struct _LIBCPP_TEMPLATE_VIS tuple_element<1, pair<_T1, _T2> >
-{
-    typedef _LIBCPP_NODEBUG_TYPE _T2 type;
-};
-
-template <size_t _Ip> struct __get_pair;
-
-template <>
-struct __get_pair<0>
-{
-    template <class _T1, class _T2>
-    static
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    _T1&
-    get(pair<_T1, _T2>& __p) _NOEXCEPT {return __p.first;}
-
-    template <class _T1, class _T2>
-    static
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    const _T1&
-    get(const pair<_T1, _T2>& __p) _NOEXCEPT {return __p.first;}
-
-#ifndef _LIBCPP_CXX03_LANG
-    template <class _T1, class _T2>
-    static
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    _T1&&
-    get(pair<_T1, _T2>&& __p) _NOEXCEPT {return _VSTD::forward<_T1>(__p.first);}
-
-    template <class _T1, class _T2>
-    static
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    const _T1&&
-    get(const pair<_T1, _T2>&& __p) _NOEXCEPT {return _VSTD::forward<const _T1>(__p.first);}
-#endif  // _LIBCPP_CXX03_LANG
-};
-
-template <>
-struct __get_pair<1>
-{
-    template <class _T1, class _T2>
-    static
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    _T2&
-    get(pair<_T1, _T2>& __p) _NOEXCEPT {return __p.second;}
-
-    template <class _T1, class _T2>
-    static
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    const _T2&
-    get(const pair<_T1, _T2>& __p) _NOEXCEPT {return __p.second;}
-
-#ifndef _LIBCPP_CXX03_LANG
-    template <class _T1, class _T2>
-    static
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    _T2&&
-    get(pair<_T1, _T2>&& __p) _NOEXCEPT {return _VSTD::forward<_T2>(__p.second);}
-
-    template <class _T1, class _T2>
-    static
-    _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-    const _T2&&
-    get(const pair<_T1, _T2>&& __p) _NOEXCEPT {return _VSTD::forward<const _T2>(__p.second);}
-#endif  // _LIBCPP_CXX03_LANG
-};
-
-template <size_t _Ip, class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-typename tuple_element<_Ip, pair<_T1, _T2> >::type&
-get(pair<_T1, _T2>& __p) _NOEXCEPT
-{
-    return __get_pair<_Ip>::get(__p);
-}
-
-template <size_t _Ip, class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-const typename tuple_element<_Ip, pair<_T1, _T2> >::type&
-get(const pair<_T1, _T2>& __p) _NOEXCEPT
-{
-    return __get_pair<_Ip>::get(__p);
-}
-
-#ifndef _LIBCPP_CXX03_LANG
-template <size_t _Ip, class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-typename tuple_element<_Ip, pair<_T1, _T2> >::type&&
-get(pair<_T1, _T2>&& __p) _NOEXCEPT
-{
-    return __get_pair<_Ip>::get(_VSTD::move(__p));
-}
-
-template <size_t _Ip, class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
-const typename tuple_element<_Ip, pair<_T1, _T2> >::type&&
-get(const pair<_T1, _T2>&& __p) _NOEXCEPT
-{
-    return __get_pair<_Ip>::get(_VSTD::move(__p));
-}
-#endif  // _LIBCPP_CXX03_LANG
-
-#if _LIBCPP_STD_VER > 11
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr _T1 & get(pair<_T1, _T2>& __p) _NOEXCEPT
-{
-    return __get_pair<0>::get(__p);
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr _T1 const & get(pair<_T1, _T2> const& __p) _NOEXCEPT
-{
-    return __get_pair<0>::get(__p);
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr _T1 && get(pair<_T1, _T2>&& __p) _NOEXCEPT
-{
-    return __get_pair<0>::get(_VSTD::move(__p));
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr _T1 const && get(pair<_T1, _T2> const&& __p) _NOEXCEPT
-{
-    return __get_pair<0>::get(_VSTD::move(__p));
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr _T1 & get(pair<_T2, _T1>& __p) _NOEXCEPT
-{
-    return __get_pair<1>::get(__p);
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr _T1 const & get(pair<_T2, _T1> const& __p) _NOEXCEPT
-{
-    return __get_pair<1>::get(__p);
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr _T1 && get(pair<_T2, _T1>&& __p) _NOEXCEPT
-{
-    return __get_pair<1>::get(_VSTD::move(__p));
-}
-
-template <class _T1, class _T2>
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr _T1 const && get(pair<_T2, _T1> const&& __p) _NOEXCEPT
-{
-    return __get_pair<1>::get(_VSTD::move(__p));
-}
-
-#endif
-
-#if _LIBCPP_STD_VER > 11
-
-template<class _Tp, _Tp... _Ip>
-struct _LIBCPP_TEMPLATE_VIS integer_sequence
-{
-    typedef _Tp value_type;
-    static_assert( is_integral<_Tp>::value,
-                  "std::integer_sequence can only be instantiated with an integral type" );
-    static
-    _LIBCPP_INLINE_VISIBILITY
-    constexpr
-    size_t
-    size() noexcept { return sizeof...(_Ip); }
-};
-
-template<size_t... _Ip>
-    using index_sequence = integer_sequence<size_t, _Ip...>;
-
-#if __has_builtin(__make_integer_seq) && !defined(_LIBCPP_TESTING_FALLBACK_MAKE_INTEGER_SEQUENCE)
-
-template <class _Tp, _Tp _Ep>
-using __make_integer_sequence _LIBCPP_NODEBUG_TYPE = __make_integer_seq<integer_sequence, _Tp, _Ep>;
-
-#else
-
-template<typename _Tp, _Tp _Np> using __make_integer_sequence_unchecked _LIBCPP_NODEBUG_TYPE  =
-  typename __detail::__make<_Np>::type::template __convert<integer_sequence, _Tp>;
-
-template <class _Tp, _Tp _Ep>
-struct __make_integer_sequence_checked
-{
-    static_assert(is_integral<_Tp>::value,
-                  "std::make_integer_sequence can only be instantiated with an integral type" );
-    static_assert(0 <= _Ep, "std::make_integer_sequence must have a non-negative sequence length");
-    // Workaround GCC bug by preventing bad installations when 0 <= _Ep
-    // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68929
-    typedef _LIBCPP_NODEBUG_TYPE  __make_integer_sequence_unchecked<_Tp, 0 <= _Ep ? _Ep : 0> type;
-};
-
-template <class _Tp, _Tp _Ep>
-using __make_integer_sequence _LIBCPP_NODEBUG_TYPE = typename __make_integer_sequence_checked<_Tp, _Ep>::type;
-
-#endif
-
-template<class _Tp, _Tp _Np>
-    using make_integer_sequence = __make_integer_sequence<_Tp, _Np>;
-
-template<size_t _Np>
-    using make_index_sequence = make_integer_sequence<size_t, _Np>;
-
-template<class... _Tp>
-    using index_sequence_for = make_index_sequence<sizeof...(_Tp)>;
-
-#endif  // _LIBCPP_STD_VER > 11
-
-#if _LIBCPP_STD_VER > 11
-template<class _T1, class _T2 = _T1>
-inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
-_T1 exchange(_T1& __obj, _T2 && __new_value)
-{
-    _T1 __old_value = _VSTD::move(__obj);
-    __obj = _VSTD::forward<_T2>(__new_value);
-    return __old_value;
-}
-#endif  // _LIBCPP_STD_VER > 11
-
-#if _LIBCPP_STD_VER > 14
-
-struct _LIBCPP_TYPE_VIS in_place_t {
-    explicit in_place_t() = default;
-};
-_LIBCPP_INLINE_VAR constexpr in_place_t in_place{};
-
-template <class _Tp>
-struct _LIBCPP_TEMPLATE_VIS in_place_type_t {
-    explicit in_place_type_t() = default;
-};
-template <class _Tp>
-_LIBCPP_INLINE_VAR constexpr in_place_type_t<_Tp> in_place_type{};
-
-template <size_t _Idx>
-struct _LIBCPP_TYPE_VIS in_place_index_t {
-    explicit in_place_index_t() = default;
-};
-template <size_t _Idx>
-_LIBCPP_INLINE_VAR constexpr in_place_index_t<_Idx> in_place_index{};
-
-template <class _Tp> struct __is_inplace_type_imp : false_type {};
-template <class _Tp> struct __is_inplace_type_imp<in_place_type_t<_Tp>> : true_type {};
-
-template <class _Tp>
-using __is_inplace_type = __is_inplace_type_imp<__uncvref_t<_Tp>>;
-
-template <class _Tp> struct __is_inplace_index_imp : false_type {};
-template <size_t _Idx> struct __is_inplace_index_imp<in_place_index_t<_Idx>> : true_type {};
-
-template <class _Tp>
-using __is_inplace_index = __is_inplace_index_imp<__uncvref_t<_Tp>>;
-
-#endif // _LIBCPP_STD_VER > 14
-
-template <class _Arg, class _Result>
-struct _LIBCPP_TEMPLATE_VIS unary_function
-{
-    typedef _Arg    argument_type;
-    typedef _Result result_type;
-};
-
-template <class _Size>
-inline _LIBCPP_INLINE_VISIBILITY
-_Size
-__loadword(const void* __p)
-{
-    _Size __r;
-    _VSTD::memcpy(&__r, __p, sizeof(__r));
-    return __r;
-}
-
-// We use murmur2 when size_t is 32 bits, and cityhash64 when size_t
-// is 64 bits.  This is because cityhash64 uses 64bit x 64bit
-// multiplication, which can be very slow on 32-bit systems.
-template <class _Size, size_t = sizeof(_Size)*__CHAR_BIT__>
-struct __murmur2_or_cityhash;
-
-template <class _Size>
-struct __murmur2_or_cityhash<_Size, 32>
-{
-    inline _Size operator()(const void* __key, _Size __len)
-         _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK;
-};
-
-// murmur2
-template <class _Size>
-_Size
-__murmur2_or_cityhash<_Size, 32>::operator()(const void* __key, _Size __len)
-{
-    const _Size __m = 0x5bd1e995;
-    const _Size __r = 24;
-    _Size __h = __len;
-    const unsigned char* __data = static_cast<const unsigned char*>(__key);
-    for (; __len >= 4; __data += 4, __len -= 4)
-    {
-        _Size __k = __loadword<_Size>(__data);
-        __k *= __m;
-        __k ^= __k >> __r;
-        __k *= __m;
-        __h *= __m;
-        __h ^= __k;
-    }
-    switch (__len)
-    {
-    case 3:
-        __h ^= __data[2] << 16;
-        _LIBCPP_FALLTHROUGH();
-    case 2:
-        __h ^= __data[1] << 8;
-        _LIBCPP_FALLTHROUGH();
-    case 1:
-        __h ^= __data[0];
-        __h *= __m;
-    }
-    __h ^= __h >> 13;
-    __h *= __m;
-    __h ^= __h >> 15;
-    return __h;
-}
-
-template <class _Size>
-struct __murmur2_or_cityhash<_Size, 64>
-{
-    inline _Size operator()(const void* __key, _Size __len)  _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK;
-
- private:
-  // Some primes between 2^63 and 2^64.
-  static const _Size __k0 = 0xc3a5c85c97cb3127ULL;
-  static const _Size __k1 = 0xb492b66fbe98f273ULL;
-  static const _Size __k2 = 0x9ae16a3b2f90404fULL;
-  static const _Size __k3 = 0xc949d7c7509e6557ULL;
-
-  static _Size __rotate(_Size __val, int __shift) {
-    return __shift == 0 ? __val : ((__val >> __shift) | (__val << (64 - __shift)));
-  }
-
-  static _Size __rotate_by_at_least_1(_Size __val, int __shift) {
-    return (__val >> __shift) | (__val << (64 - __shift));
-  }
-
-  static _Size __shift_mix(_Size __val) {
-    return __val ^ (__val >> 47);
-  }
-
-  static _Size __hash_len_16(_Size __u, _Size __v)
-     _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
-  {
-    const _Size __mul = 0x9ddfea08eb382d69ULL;
-    _Size __a = (__u ^ __v) * __mul;
-    __a ^= (__a >> 47);
-    _Size __b = (__v ^ __a) * __mul;
-    __b ^= (__b >> 47);
-    __b *= __mul;
-    return __b;
-  }
-
-  static _Size __hash_len_0_to_16(const char* __s, _Size __len)
-     _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
-  {
-    if (__len > 8) {
-      const _Size __a = __loadword<_Size>(__s);
-      const _Size __b = __loadword<_Size>(__s + __len - 8);
-      return __hash_len_16(__a, __rotate_by_at_least_1(__b + __len, __len)) ^ __b;
-    }
-    if (__len >= 4) {
-      const uint32_t __a = __loadword<uint32_t>(__s);
-      const uint32_t __b = __loadword<uint32_t>(__s + __len - 4);
-      return __hash_len_16(__len + (__a << 3), __b);
-    }
-    if (__len > 0) {
-      const unsigned char __a = __s[0];
-      const unsigned char __b = __s[__len >> 1];
-      const unsigned char __c = __s[__len - 1];
-      const uint32_t __y = static_cast<uint32_t>(__a) +
-                           (static_cast<uint32_t>(__b) << 8);
-      const uint32_t __z = __len + (static_cast<uint32_t>(__c) << 2);
-      return __shift_mix(__y * __k2 ^ __z * __k3) * __k2;
-    }
-    return __k2;
-  }
-
-  static _Size __hash_len_17_to_32(const char *__s, _Size __len)
-     _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
-  {
-    const _Size __a = __loadword<_Size>(__s) * __k1;
-    const _Size __b = __loadword<_Size>(__s + 8);
-    const _Size __c = __loadword<_Size>(__s + __len - 8) * __k2;
-    const _Size __d = __loadword<_Size>(__s + __len - 16) * __k0;
-    return __hash_len_16(__rotate(__a - __b, 43) + __rotate(__c, 30) + __d,
-                         __a + __rotate(__b ^ __k3, 20) - __c + __len);
-  }
-
-  // Return a 16-byte hash for 48 bytes.  Quick and dirty.
-  // Callers do best to use "random-looking" values for a and b.
-  static pair<_Size, _Size> __weak_hash_len_32_with_seeds(
-      _Size __w, _Size __x, _Size __y, _Size __z, _Size __a, _Size __b)
-        _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
-  {
-    __a += __w;
-    __b = __rotate(__b + __a + __z, 21);
-    const _Size __c = __a;
-    __a += __x;
-    __a += __y;
-    __b += __rotate(__a, 44);
-    return pair<_Size, _Size>(__a + __z, __b + __c);
-  }
-
-  // Return a 16-byte hash for s[0] ... s[31], a, and b.  Quick and dirty.
-  static pair<_Size, _Size> __weak_hash_len_32_with_seeds(
-      const char* __s, _Size __a, _Size __b)
-    _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
-  {
-    return __weak_hash_len_32_with_seeds(__loadword<_Size>(__s),
-                                         __loadword<_Size>(__s + 8),
-                                         __loadword<_Size>(__s + 16),
-                                         __loadword<_Size>(__s + 24),
-                                         __a,
-                                         __b);
-  }
-
-  // Return an 8-byte hash for 33 to 64 bytes.
-  static _Size __hash_len_33_to_64(const char *__s, size_t __len)
-    _LIBCPP_DISABLE_UBSAN_UNSIGNED_INTEGER_CHECK
-  {
-    _Size __z = __loadword<_Size>(__s + 24);
-    _Size __a = __loadword<_Size>(__s) +
-                (__len + __loadword<_Size>(__s + __len - 16)) * __k0;
-    _Size __b = __rotate(__a + __z, 52);
-    _Size __c = __rotate(__a, 37);
-    __a += __loadword<_Size>(__s + 8);
-    __c += __rotate(__a, 7);
-    __a += __loadword<_Size>(__s + 16);
-    _Size __vf = __a + __z;
-    _Size __vs = __b + __rotate(__a, 31) + __c;
-    __a = __loadword<_Size>(__s + 16) + __loadword<_Size>(__s + __len - 32);
-    __z += __loadword<_Size>(__s + __len - 8);
-    __b = __rotate(__a + __z, 52);
-    __c = __rotate(__a, 37);
-    __a += __loadword<_Size>(__s + __len - 24);
-    __c += __rotate(__a, 7);
-    __a += __loadword<_Size>(__s + __len - 16);
-    _Size __wf = __a + __z;
-    _Size __ws = __b + __rotate(__a, 31) + __c;
-    _Size __r = __shift_mix((__vf + __ws) * __k2 + (__wf + __vs) * __k0);
-    return __shift_mix(__r * __k0 + __vs) * __k2;
-  }
-};
-
-// cityhash64
-template <class _Size>
-_Size
-__murmur2_or_cityhash<_Size, 64>::operator()(const void* __key, _Size __len)
-{
-  const char* __s = static_cast<const char*>(__key);
-  if (__len <= 32) {
-    if (__len <= 16) {
-      return __hash_len_0_to_16(__s, __len);
-    } else {
-      return __hash_len_17_to_32(__s, __len);
-    }
-  } else if (__len <= 64) {
-    return __hash_len_33_to_64(__s, __len);
-  }
-
-  // For strings over 64 bytes we hash the end first, and then as we
-  // loop we keep 56 bytes of state: v, w, x, y, and z.
-  _Size __x = __loadword<_Size>(__s + __len - 40);
-  _Size __y = __loadword<_Size>(__s + __len - 16) +
-              __loadword<_Size>(__s + __len - 56);
-  _Size __z = __hash_len_16(__loadword<_Size>(__s + __len - 48) + __len,
-                          __loadword<_Size>(__s + __len - 24));
-  pair<_Size, _Size> __v = __weak_hash_len_32_with_seeds(__s + __len - 64, __len, __z);
-  pair<_Size, _Size> __w = __weak_hash_len_32_with_seeds(__s + __len - 32, __y + __k1, __x);
-  __x = __x * __k1 + __loadword<_Size>(__s);
-
-  // Decrease len to the nearest multiple of 64, and operate on 64-byte chunks.
-  __len = (__len - 1) & ~static_cast<_Size>(63);
-  do {
-    __x = __rotate(__x + __y + __v.first + __loadword<_Size>(__s + 8), 37) * __k1;
-    __y = __rotate(__y + __v.second + __loadword<_Size>(__s + 48), 42) * __k1;
-    __x ^= __w.second;
-    __y += __v.first + __loadword<_Size>(__s + 40);
-    __z = __rotate(__z + __w.first, 33) * __k1;
-    __v = __weak_hash_len_32_with_seeds(__s, __v.second * __k1, __x + __w.first);
-    __w = __weak_hash_len_32_with_seeds(__s + 32, __z + __w.second,
-                                        __y + __loadword<_Size>(__s + 16));
-    _VSTD::swap(__z, __x);
-    __s += 64;
-    __len -= 64;
-  } while (__len != 0);
-  return __hash_len_16(
-      __hash_len_16(__v.first, __w.first) + __shift_mix(__y) * __k1 + __z,
-      __hash_len_16(__v.second, __w.second) + __x);
-}
-
-template <class _Tp, size_t = sizeof(_Tp) / sizeof(size_t)>
-struct __scalar_hash;
-
-template <class _Tp>
-struct __scalar_hash<_Tp, 0>
-    : public unary_function<_Tp, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(_Tp __v) const _NOEXCEPT
-    {
-        union
-        {
-            _Tp    __t;
-            size_t __a;
-        } __u;
-        __u.__a = 0;
-        __u.__t = __v;
-        return __u.__a;
-    }
-};
-
-template <class _Tp>
-struct __scalar_hash<_Tp, 1>
-    : public unary_function<_Tp, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(_Tp __v) const _NOEXCEPT
-    {
-        union
-        {
-            _Tp    __t;
-            size_t __a;
-        } __u;
-        __u.__t = __v;
-        return __u.__a;
-    }
-};
-
-template <class _Tp>
-struct __scalar_hash<_Tp, 2>
-    : public unary_function<_Tp, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(_Tp __v) const _NOEXCEPT
-    {
-        union
-        {
-            _Tp __t;
-            struct
-            {
-                size_t __a;
-                size_t __b;
-            } __s;
-        } __u;
-        __u.__t = __v;
-        return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u));
-    }
-};
-
-template <class _Tp>
-struct __scalar_hash<_Tp, 3>
-    : public unary_function<_Tp, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(_Tp __v) const _NOEXCEPT
-    {
-        union
-        {
-            _Tp __t;
-            struct
-            {
-                size_t __a;
-                size_t __b;
-                size_t __c;
-            } __s;
-        } __u;
-        __u.__t = __v;
-        return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u));
-    }
-};
-
-template <class _Tp>
-struct __scalar_hash<_Tp, 4>
-    : public unary_function<_Tp, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(_Tp __v) const _NOEXCEPT
-    {
-        union
-        {
-            _Tp __t;
-            struct
-            {
-                size_t __a;
-                size_t __b;
-                size_t __c;
-                size_t __d;
-            } __s;
-        } __u;
-        __u.__t = __v;
-        return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u));
-    }
-};
-
-struct _PairT {
-  size_t first;
-  size_t second;
-};
-
-_LIBCPP_INLINE_VISIBILITY
-inline size_t __hash_combine(size_t __lhs, size_t __rhs) _NOEXCEPT {
-    typedef __scalar_hash<_PairT> _HashT;
-    const _PairT __p = {__lhs, __rhs};
-    return _HashT()(__p);
-}
-
-template<class _Tp>
-struct _LIBCPP_TEMPLATE_VIS hash<_Tp*>
-    : public unary_function<_Tp*, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(_Tp* __v) const _NOEXCEPT
-    {
-        union
-        {
-            _Tp* __t;
-            size_t __a;
-        } __u;
-        __u.__t = __v;
-        return __murmur2_or_cityhash<size_t>()(&__u, sizeof(__u));
-    }
-};
-
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<bool>
-    : public unary_function<bool, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(bool __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<char>
-    : public unary_function<char, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(char __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<signed char>
-    : public unary_function<signed char, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(signed char __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<unsigned char>
-    : public unary_function<unsigned char, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(unsigned char __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<char8_t>
-    : public unary_function<char8_t, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(char8_t __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-#endif // !_LIBCPP_NO_HAS_CHAR8_T
-
-#ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<char16_t>
-    : public unary_function<char16_t, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(char16_t __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<char32_t>
-    : public unary_function<char32_t, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(char32_t __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-#endif  // _LIBCPP_HAS_NO_UNICODE_CHARS
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<wchar_t>
-    : public unary_function<wchar_t, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(wchar_t __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<short>
-    : public unary_function<short, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(short __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<unsigned short>
-    : public unary_function<unsigned short, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(unsigned short __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<int>
-    : public unary_function<int, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(int __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<unsigned int>
-    : public unary_function<unsigned int, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(unsigned int __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<long>
-    : public unary_function<long, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(long __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<unsigned long>
-    : public unary_function<unsigned long, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(unsigned long __v) const _NOEXCEPT {return static_cast<size_t>(__v);}
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<long long>
-    : public __scalar_hash<long long>
-{
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<unsigned long long>
-    : public __scalar_hash<unsigned long long>
-{
-};
-
-#ifndef _LIBCPP_HAS_NO_INT128
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<__int128_t>
-    : public __scalar_hash<__int128_t>
-{
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<__uint128_t>
-    : public __scalar_hash<__uint128_t>
-{
-};
-
-#endif
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<float>
-    : public __scalar_hash<float>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(float __v) const _NOEXCEPT
-    {
-        // -0.0 and 0.0 should return same hash
-       if (__v == 0.0f)
-           return 0;
-        return __scalar_hash<float>::operator()(__v);
-    }
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<double>
-    : public __scalar_hash<double>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(double __v) const _NOEXCEPT
-    {
-        // -0.0 and 0.0 should return same hash
-       if (__v == 0.0)
-           return 0;
-        return __scalar_hash<double>::operator()(__v);
-    }
-};
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<long double>
-    : public __scalar_hash<long double>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(long double __v) const _NOEXCEPT
-    {
-        // -0.0 and 0.0 should return same hash
-        if (__v == 0.0L)
-            return 0;
-#if defined(__i386__) || (defined(__x86_64__) && defined(__ILP32__))
-        // Zero out padding bits
-        union
-        {
-            long double __t;
-            struct
-            {
-                size_t __a;
-                size_t __b;
-                size_t __c;
-                size_t __d;
-            } __s;
-        } __u;
-        __u.__s.__a = 0;
-        __u.__s.__b = 0;
-        __u.__s.__c = 0;
-        __u.__s.__d = 0;
-        __u.__t = __v;
-        return __u.__s.__a ^ __u.__s.__b ^ __u.__s.__c ^ __u.__s.__d;
-#elif defined(__x86_64__)
-        // Zero out padding bits
-        union
-        {
-            long double __t;
-            struct
-            {
-                size_t __a;
-                size_t __b;
-            } __s;
-        } __u;
-        __u.__s.__a = 0;
-        __u.__s.__b = 0;
-        __u.__t = __v;
-        return __u.__s.__a ^ __u.__s.__b;
-#else
-        return __scalar_hash<long double>::operator()(__v);
-#endif
-    }
-};
-
-#if _LIBCPP_STD_VER > 11
-
-template <class _Tp, bool = is_enum<_Tp>::value>
-struct _LIBCPP_TEMPLATE_VIS __enum_hash
-    : public unary_function<_Tp, size_t>
-{
-    _LIBCPP_INLINE_VISIBILITY
-    size_t operator()(_Tp __v) const _NOEXCEPT
-    {
-        typedef typename underlying_type<_Tp>::type type;
-        return hash<type>{}(static_cast<type>(__v));
-    }
-};
-template <class _Tp>
-struct _LIBCPP_TEMPLATE_VIS __enum_hash<_Tp, false> {
-    __enum_hash() = delete;
-    __enum_hash(__enum_hash const&) = delete;
-    __enum_hash& operator=(__enum_hash const&) = delete;
-};
-
-template <class _Tp>
-struct _LIBCPP_TEMPLATE_VIS hash : public __enum_hash<_Tp>
-{
-};
-#endif
-
-#if _LIBCPP_STD_VER > 14
-
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<nullptr_t>
-  : public unary_function<nullptr_t, size_t>
-{
-  _LIBCPP_INLINE_VISIBILITY
-  size_t operator()(nullptr_t) const _NOEXCEPT {
-    return 662607004ull;
-  }
-};
-#endif
-
-#ifndef _LIBCPP_CXX03_LANG
-template <class _Key, class _Hash>
-using __check_hash_requirements _LIBCPP_NODEBUG_TYPE  = integral_constant<bool,
-    is_copy_constructible<_Hash>::value &&
-    is_move_constructible<_Hash>::value &&
-    __invokable_r<size_t, _Hash, _Key const&>::value
->;
-
-template <class _Key, class _Hash = hash<_Key> >
-using __has_enabled_hash _LIBCPP_NODEBUG_TYPE = integral_constant<bool,
-    __check_hash_requirements<_Key, _Hash>::value &&
-    is_default_constructible<_Hash>::value
->;
-
-#if _LIBCPP_STD_VER > 14
-template <class _Type, class>
-using __enable_hash_helper_imp _LIBCPP_NODEBUG_TYPE  = _Type;
-
-template <class _Type, class ..._Keys>
-using __enable_hash_helper _LIBCPP_NODEBUG_TYPE  = __enable_hash_helper_imp<_Type,
-  typename enable_if<__all<__has_enabled_hash<_Keys>::value...>::value>::type
->;
-#else
-template <class _Type, class ...>
-using __enable_hash_helper _LIBCPP_NODEBUG_TYPE = _Type;
-#endif
-
-#endif // !_LIBCPP_CXX03_LANG
-
-_LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP_UTILITY
+#endif // _LIBCPP_UTILITY
lib/libcxx/include/valarray
@@ -340,11 +340,11 @@ template <class T> unspecified2 end(const valarray<T>& v);
 */
 
 #include <__config>
-#include <cstddef>
-#include <cmath>
-#include <initializer_list>
 #include <algorithm>
+#include <cmath>
+#include <cstddef>
 #include <functional>
+#include <initializer_list>
 #include <new>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -354,7 +354,6 @@ template <class T> unspecified2 end(const valarray<T>& v);
 _LIBCPP_PUSH_MACROS
 #include <__undef_macros>
 
-
 _LIBCPP_BEGIN_NAMESPACE_STD
 
 template<class _Tp> class _LIBCPP_TEMPLATE_VIS valarray;
@@ -413,8 +412,8 @@ end(const valarray<_Tp>& __v);
 template <class _Op, class _A0>
 struct _UnaryOp
 {
-    typedef typename _Op::result_type result_type;
-    typedef typename _A0::value_type value_type;
+    typedef typename _Op::__result_type __result_type;
+    typedef typename decay<__result_type>::type value_type;
 
     _Op __op_;
     _A0 __a0_;
@@ -423,7 +422,7 @@ struct _UnaryOp
     _UnaryOp(const _Op& __op, const _A0& __a0) : __op_(__op), __a0_(__a0) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator[](size_t __i) const {return __op_(__a0_[__i]);}
+    __result_type operator[](size_t __i) const {return __op_(__a0_[__i]);}
 
     _LIBCPP_INLINE_VISIBILITY
     size_t size() const {return __a0_.size();}
@@ -432,8 +431,8 @@ struct _UnaryOp
 template <class _Op, class _A0, class _A1>
 struct _BinaryOp
 {
-    typedef typename _Op::result_type result_type;
-    typedef typename _A0::value_type value_type;
+    typedef typename _Op::__result_type __result_type;
+    typedef typename decay<__result_type>::type value_type;
 
     _Op __op_;
     _A0 __a0_;
@@ -444,7 +443,7 @@ struct _BinaryOp
         : __op_(__op), __a0_(__a0), __a1_(__a1) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    value_type operator[](size_t __i) const {return __op_(__a0_[__i], __a1_[__i]);}
+    __result_type operator[](size_t __i) const {return __op_(__a0_[__i], __a1_[__i]);}
 
     _LIBCPP_INLINE_VISIBILITY
     size_t size() const {return __a0_.size();}
@@ -455,7 +454,7 @@ class __scalar_expr
 {
 public:
     typedef _Tp        value_type;
-    typedef const _Tp& result_type;
+    typedef const _Tp& __result_type;
 private:
     const value_type& __t_;
     size_t __s_;
@@ -464,50 +463,56 @@ public:
     explicit __scalar_expr(const value_type& __t, size_t __s) : __t_(__t), __s_(__s) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator[](size_t) const {return __t_;}
+    __result_type operator[](size_t) const {return __t_;}
 
     _LIBCPP_INLINE_VISIBILITY
     size_t size() const {return __s_;}
 };
 
 template <class _Tp>
-struct __unary_plus : unary_function<_Tp, _Tp>
+struct __unary_plus
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return +__x;}
 };
 
 template <class _Tp>
-struct __bit_not  : unary_function<_Tp, _Tp>
+struct __bit_not
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return ~__x;}
 };
 
 template <class _Tp>
-struct __bit_shift_left : binary_function<_Tp, _Tp, _Tp>
+struct __bit_shift_left
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x, const _Tp& __y) const
         {return __x << __y;}
 };
 
 template <class _Tp>
-struct __bit_shift_right : binary_function<_Tp, _Tp, _Tp>
+struct __bit_shift_right
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x, const _Tp& __y) const
         {return __x >> __y;}
 };
 
 template <class _Tp, class _Fp>
-struct __apply_expr   : unary_function<_Tp, _Tp>
+struct __apply_expr
 {
 private:
     _Fp __f_;
 public:
+    typedef _Tp __result_type;
+
     _LIBCPP_INLINE_VISIBILITY
     explicit __apply_expr(_Fp __f) : __f_(__f) {}
 
@@ -517,128 +522,144 @@ public:
 };
 
 template <class _Tp>
-struct __abs_expr : unary_function<_Tp, _Tp>
+struct __abs_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return abs(__x);}
 };
 
 template <class _Tp>
-struct __acos_expr : unary_function<_Tp, _Tp>
+struct __acos_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return acos(__x);}
 };
 
 template <class _Tp>
-struct __asin_expr : unary_function<_Tp, _Tp>
+struct __asin_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return asin(__x);}
 };
 
 template <class _Tp>
-struct __atan_expr : unary_function<_Tp, _Tp>
+struct __atan_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return atan(__x);}
 };
 
 template <class _Tp>
-struct __atan2_expr : binary_function<_Tp, _Tp, _Tp>
+struct __atan2_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x, const _Tp& __y) const
         {return atan2(__x, __y);}
 };
 
 template <class _Tp>
-struct __cos_expr : unary_function<_Tp, _Tp>
+struct __cos_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return cos(__x);}
 };
 
 template <class _Tp>
-struct __cosh_expr : unary_function<_Tp, _Tp>
+struct __cosh_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return cosh(__x);}
 };
 
 template <class _Tp>
-struct __exp_expr : unary_function<_Tp, _Tp>
+struct __exp_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return exp(__x);}
 };
 
 template <class _Tp>
-struct __log_expr : unary_function<_Tp, _Tp>
+struct __log_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return log(__x);}
 };
 
 template <class _Tp>
-struct __log10_expr : unary_function<_Tp, _Tp>
+struct __log10_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return log10(__x);}
 };
 
 template <class _Tp>
-struct __pow_expr : binary_function<_Tp, _Tp, _Tp>
+struct __pow_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x, const _Tp& __y) const
         {return pow(__x, __y);}
 };
 
 template <class _Tp>
-struct __sin_expr : unary_function<_Tp, _Tp>
+struct __sin_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return sin(__x);}
 };
 
 template <class _Tp>
-struct __sinh_expr : unary_function<_Tp, _Tp>
+struct __sinh_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return sinh(__x);}
 };
 
 template <class _Tp>
-struct __sqrt_expr : unary_function<_Tp, _Tp>
+struct __sqrt_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return sqrt(__x);}
 };
 
 template <class _Tp>
-struct __tan_expr : unary_function<_Tp, _Tp>
+struct __tan_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return tan(__x);}
 };
 
 template <class _Tp>
-struct __tanh_expr : unary_function<_Tp, _Tp>
+struct __tanh_expr
 {
+    typedef _Tp __result_type;
     _LIBCPP_INLINE_VISIBILITY
     _Tp operator()(const _Tp& __x) const
         {return tanh(__x);}
@@ -650,7 +671,7 @@ class __slice_expr
     typedef typename remove_reference<_ValExpr>::type  _RmExpr;
 public:
     typedef typename _RmExpr::value_type value_type;
-    typedef value_type result_type;
+    typedef value_type __result_type;
 
 private:
     _ValExpr __expr_;
@@ -668,7 +689,7 @@ private:
 public:
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator[](size_t __i) const
+    __result_type operator[](size_t __i) const
         {return __expr_[__start_ + __i * __stride_];}
 
     _LIBCPP_INLINE_VISIBILITY
@@ -690,7 +711,7 @@ class __shift_expr
     typedef typename remove_reference<_ValExpr>::type  _RmExpr;
 public:
     typedef typename _RmExpr::value_type value_type;
-    typedef value_type result_type;
+    typedef value_type __result_type;
 
 private:
     _ValExpr __expr_;
@@ -714,7 +735,7 @@ private:
 public:
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator[](size_t __j) const
+    __result_type operator[](size_t __j) const
         {
             ptrdiff_t __i = static_cast<ptrdiff_t>(__j);
             ptrdiff_t __m = (__sn_ * __i - __ul_) >> _Np;
@@ -733,7 +754,7 @@ class __cshift_expr
     typedef typename remove_reference<_ValExpr>::type  _RmExpr;
 public:
     typedef typename _RmExpr::value_type value_type;
-    typedef value_type result_type;
+    typedef value_type __result_type;
 
 private:
     _ValExpr __expr_;
@@ -764,7 +785,7 @@ private:
 public:
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator[](size_t __i) const
+    __result_type operator[](size_t __i) const
         {
             if (__i < __m_)
                 return __expr_[__i + __o1_];
@@ -794,7 +815,7 @@ class _LIBCPP_TEMPLATE_VIS valarray
 {
 public:
     typedef _Tp value_type;
-    typedef _Tp result_type;
+    typedef _Tp __result_type;
 
 private:
     value_type* __begin_;
@@ -814,7 +835,7 @@ public:
     _LIBCPP_INLINE_VISIBILITY
     valarray(valarray&& __v) _NOEXCEPT;
     valarray(initializer_list<value_type> __il);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     valarray(const slice_array<value_type>& __sa);
     valarray(const gslice_array<value_type>& __ga);
     valarray(const mask_array<value_type>& __ma);
@@ -829,7 +850,7 @@ public:
     valarray& operator=(valarray&& __v) _NOEXCEPT;
     _LIBCPP_INLINE_VISIBILITY
     valarray& operator=(initializer_list<value_type>);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     valarray& operator=(const value_type& __x);
     _LIBCPP_INLINE_VISIBILITY
@@ -865,7 +886,7 @@ public:
     __val_expr<__indirect_expr<const valarray&> > operator[](gslice&& __gs) const;
     _LIBCPP_INLINE_VISIBILITY
     gslice_array<value_type>                      operator[](gslice&& __gs);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     __val_expr<__mask_expr<const valarray&> >     operator[](const valarray<bool>& __vb) const;
     _LIBCPP_INLINE_VISIBILITY
@@ -875,7 +896,7 @@ public:
     __val_expr<__mask_expr<const valarray&> >     operator[](valarray<bool>&& __vb) const;
     _LIBCPP_INLINE_VISIBILITY
     mask_array<value_type>                        operator[](valarray<bool>&& __vb);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
     _LIBCPP_INLINE_VISIBILITY
     __val_expr<__indirect_expr<const valarray&> > operator[](const valarray<size_t>& __vs) const;
     _LIBCPP_INLINE_VISIBILITY
@@ -885,7 +906,7 @@ public:
     __val_expr<__indirect_expr<const valarray&> > operator[](valarray<size_t>&& __vs) const;
     _LIBCPP_INLINE_VISIBILITY
     indirect_array<value_type>                    operator[](valarray<size_t>&& __vs);
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     // unary operators:
     valarray       operator+() const;
@@ -1065,8 +1086,8 @@ _LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void valarray<size_t>::resize(size_t, s
 template <class _Op, class _Tp>
 struct _UnaryOp<_Op, valarray<_Tp> >
 {
-    typedef typename _Op::result_type result_type;
-    typedef _Tp value_type;
+    typedef typename _Op::__result_type __result_type;
+    typedef typename decay<__result_type>::type value_type;
 
     _Op __op_;
     const valarray<_Tp>& __a0_;
@@ -1075,7 +1096,7 @@ struct _UnaryOp<_Op, valarray<_Tp> >
     _UnaryOp(const _Op& __op, const valarray<_Tp>& __a0) : __op_(__op), __a0_(__a0) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator[](size_t __i) const {return __op_(__a0_[__i]);}
+    __result_type operator[](size_t __i) const {return __op_(__a0_[__i]);}
 
     _LIBCPP_INLINE_VISIBILITY
     size_t size() const {return __a0_.size();}
@@ -1084,8 +1105,8 @@ struct _UnaryOp<_Op, valarray<_Tp> >
 template <class _Op, class _Tp, class _A1>
 struct _BinaryOp<_Op, valarray<_Tp>, _A1>
 {
-    typedef typename _Op::result_type result_type;
-    typedef _Tp value_type;
+    typedef typename _Op::__result_type __result_type;
+    typedef typename decay<__result_type>::type value_type;
 
     _Op __op_;
     const valarray<_Tp>& __a0_;
@@ -1096,7 +1117,7 @@ struct _BinaryOp<_Op, valarray<_Tp>, _A1>
         : __op_(__op), __a0_(__a0), __a1_(__a1) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    value_type operator[](size_t __i) const {return __op_(__a0_[__i], __a1_[__i]);}
+    __result_type operator[](size_t __i) const {return __op_(__a0_[__i], __a1_[__i]);}
 
     _LIBCPP_INLINE_VISIBILITY
     size_t size() const {return __a0_.size();}
@@ -1105,8 +1126,8 @@ struct _BinaryOp<_Op, valarray<_Tp>, _A1>
 template <class _Op, class _A0, class _Tp>
 struct _BinaryOp<_Op, _A0, valarray<_Tp> >
 {
-    typedef typename _Op::result_type result_type;
-    typedef _Tp value_type;
+    typedef typename _Op::__result_type __result_type;
+    typedef typename decay<__result_type>::type value_type;
 
     _Op __op_;
     _A0 __a0_;
@@ -1117,7 +1138,7 @@ struct _BinaryOp<_Op, _A0, valarray<_Tp> >
         : __op_(__op), __a0_(__a0), __a1_(__a1) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    value_type operator[](size_t __i) const {return __op_(__a0_[__i], __a1_[__i]);}
+    __result_type operator[](size_t __i) const {return __op_(__a0_[__i], __a1_[__i]);}
 
     _LIBCPP_INLINE_VISIBILITY
     size_t size() const {return __a0_.size();}
@@ -1126,8 +1147,8 @@ struct _BinaryOp<_Op, _A0, valarray<_Tp> >
 template <class _Op, class _Tp>
 struct _BinaryOp<_Op, valarray<_Tp>, valarray<_Tp> >
 {
-    typedef typename _Op::result_type result_type;
-    typedef _Tp value_type;
+    typedef typename _Op::__result_type __result_type;
+    typedef typename decay<__result_type>::type value_type;
 
     _Op __op_;
     const valarray<_Tp>& __a0_;
@@ -1138,7 +1159,7 @@ struct _BinaryOp<_Op, valarray<_Tp>, valarray<_Tp> >
         : __op_(__op), __a0_(__a0), __a1_(__a1) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    value_type operator[](size_t __i) const {return __op_(__a0_[__i], __a1_[__i]);}
+    __result_type operator[](size_t __i) const {return __op_(__a0_[__i], __a1_[__i]);}
 
     _LIBCPP_INLINE_VISIBILITY
     size_t size() const {return __a0_.size();}
@@ -1518,7 +1539,7 @@ public:
           __stride_(move(__stride))
         {__init(__start);}
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     _LIBCPP_INLINE_VISIBILITY
     size_t           start()  const {return __1d_.size() ? __1d_[0] : 0;}
@@ -1668,7 +1689,7 @@ private:
         : __vp_(const_cast<value_type*>(__v.__begin_)),
           __1d_(move(__gs.__1d_))
         {}
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     template <class> friend class valarray;
 };
@@ -2199,7 +2220,7 @@ class __mask_expr
     typedef typename remove_reference<_ValExpr>::type  _RmExpr;
 public:
     typedef typename _RmExpr::value_type value_type;
-    typedef value_type result_type;
+    typedef value_type __result_type;
 
 private:
     _ValExpr __expr_;
@@ -2218,7 +2239,7 @@ private:
 
 public:
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator[](size_t __i) const
+    __result_type operator[](size_t __i) const
         {return __expr_[__1d_[__i]];}
 
     _LIBCPP_INLINE_VISIBILITY
@@ -2363,7 +2384,7 @@ private:
           __1d_(move(__ia))
         {}
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
     template <class> friend class valarray;
 };
@@ -2562,7 +2583,7 @@ class __indirect_expr
     typedef typename remove_reference<_ValExpr>::type  _RmExpr;
 public:
     typedef typename _RmExpr::value_type value_type;
-    typedef value_type result_type;
+    typedef value_type __result_type;
 
 private:
     _ValExpr __expr_;
@@ -2582,11 +2603,11 @@ private:
           __1d_(move(__ia))
           {}
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 public:
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator[](size_t __i) const
+    __result_type operator[](size_t __i) const
         {return __expr_[__1d_[__i]];}
 
     _LIBCPP_INLINE_VISIBILITY
@@ -2604,13 +2625,13 @@ class __val_expr
     _ValExpr __expr_;
 public:
     typedef typename _RmExpr::value_type value_type;
-    typedef typename _RmExpr::result_type result_type;
+    typedef typename _RmExpr::__result_type __result_type;
 
     _LIBCPP_INLINE_VISIBILITY
     explicit __val_expr(const _RmExpr& __e) : __expr_(__e) {}
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type operator[](size_t __i) const
+    __result_type operator[](size_t __i) const
         {return __expr_[__i];}
 
     _LIBCPP_INLINE_VISIBILITY
@@ -2673,29 +2694,29 @@ public:
         return __val_expr<_NewExpr>(_NewExpr(logical_not<value_type>(), __expr_));
     }
 
-    operator valarray<result_type>() const;
+    operator valarray<__result_type>() const;
 
     _LIBCPP_INLINE_VISIBILITY
     size_t size() const {return __expr_.size();}
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type sum() const
+    __result_type sum() const
     {
         size_t __n = __expr_.size();
-        result_type __r = __n ? __expr_[0] : result_type();
+        __result_type __r = __n ? __expr_[0] : __result_type();
         for (size_t __i = 1; __i < __n; ++__i)
             __r += __expr_[__i];
         return __r;
     }
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type min() const
+    __result_type min() const
     {
         size_t __n = size();
-        result_type __r = __n ? (*this)[0] : result_type();
+        __result_type __r = __n ? (*this)[0] : __result_type();
         for (size_t __i = 1; __i < __n; ++__i)
         {
-            result_type __x = __expr_[__i];
+            __result_type __x = __expr_[__i];
             if (__x < __r)
                 __r = __x;
         }
@@ -2703,13 +2724,13 @@ public:
     }
 
     _LIBCPP_INLINE_VISIBILITY
-    result_type max() const
+    __result_type max() const
     {
         size_t __n = size();
-        result_type __r = __n ? (*this)[0] : result_type();
+        __result_type __r = __n ? (*this)[0] : __result_type();
         for (size_t __i = 1; __i < __n; ++__i)
         {
-            result_type __x = __expr_[__i];
+            __result_type __x = __expr_[__i];
             if (__r < __x)
                 __r = __x;
         }
@@ -2744,16 +2765,16 @@ public:
 };
 
 template<class _ValExpr>
-__val_expr<_ValExpr>::operator valarray<__val_expr::result_type>() const
+__val_expr<_ValExpr>::operator valarray<__val_expr::__result_type>() const
 {
-    valarray<result_type> __r;
+    valarray<__result_type> __r;
     size_t __n = __expr_.size();
     if (__n)
     {
         __r.__begin_ =
-            __r.__end_ = allocator<result_type>().allocate(__n);
+            __r.__end_ = allocator<__result_type>().allocate(__n);
         for (size_t __i = 0; __i != __n; ++__r.__end_, ++__i)
-            ::new ((void*)__r.__end_) result_type(__expr_[__i]);
+            ::new ((void*)__r.__end_) __result_type(__expr_[__i]);
     }
     return __r;
 }
@@ -2772,7 +2793,7 @@ valarray<_Tp>::valarray(size_t __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (size_t __n_left = __n; __n_left; --__n_left, ++__end_)
                 ::new ((void*)__end_) value_type();
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2782,7 +2803,7 @@ valarray<_Tp>::valarray(size_t __n)
             __clear(__n);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -2806,7 +2827,7 @@ valarray<_Tp>::valarray(const value_type* __p, size_t __n)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (size_t __n_left = __n; __n_left; ++__end_, ++__p, --__n_left)
                 ::new ((void*)__end_) value_type(*__p);
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2816,7 +2837,7 @@ valarray<_Tp>::valarray(const value_type* __p, size_t __n)
             __clear(__n);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -2831,7 +2852,7 @@ valarray<_Tp>::valarray(const valarray& __v)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (value_type* __p = __v.__begin_; __p != __v.__end_; ++__end_, ++__p)
                 ::new ((void*)__end_) value_type(*__p);
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2841,7 +2862,7 @@ valarray<_Tp>::valarray(const valarray& __v)
             __clear(__v.size());
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -2868,7 +2889,7 @@ valarray<_Tp>::valarray(initializer_list<value_type> __il)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             size_t __n_left = __n;
             for (const value_type* __p = __il.begin(); __n_left; ++__end_, ++__p, --__n_left)
                 ::new ((void*)__end_) value_type(*__p);
@@ -2879,11 +2900,11 @@ valarray<_Tp>::valarray(initializer_list<value_type> __il)
             __clear(__n);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp>
 valarray<_Tp>::valarray(const slice_array<value_type>& __sa)
@@ -2897,7 +2918,7 @@ valarray<_Tp>::valarray(const slice_array<value_type>& __sa)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             size_t __n_left = __n;
             for (const value_type* __p = __sa.__vp_; __n_left; ++__end_, __p += __sa.__stride_, --__n_left)
                 ::new ((void*)__end_) value_type(*__p);
@@ -2908,7 +2929,7 @@ valarray<_Tp>::valarray(const slice_array<value_type>& __sa)
             __clear(__n);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -2924,7 +2945,7 @@ valarray<_Tp>::valarray(const gslice_array<value_type>& __ga)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             typedef const size_t* _Ip;
             const value_type* __s = __ga.__vp_;
             for (_Ip __i = __ga.__1d_.__begin_, __e = __ga.__1d_.__end_;
@@ -2937,7 +2958,7 @@ valarray<_Tp>::valarray(const gslice_array<value_type>& __ga)
             __clear(__n);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -2953,7 +2974,7 @@ valarray<_Tp>::valarray(const mask_array<value_type>& __ma)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             typedef const size_t* _Ip;
             const value_type* __s = __ma.__vp_;
             for (_Ip __i = __ma.__1d_.__begin_, __e = __ma.__1d_.__end_;
@@ -2966,7 +2987,7 @@ valarray<_Tp>::valarray(const mask_array<value_type>& __ma)
             __clear(__n);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -2982,7 +3003,7 @@ valarray<_Tp>::valarray(const indirect_array<value_type>& __ia)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             typedef const size_t* _Ip;
             const value_type* __s = __ia.__vp_;
             for (_Ip __i = __ia.__1d_.__begin_, __e = __ia.__1d_.__end_;
@@ -2995,7 +3016,7 @@ valarray<_Tp>::valarray(const indirect_array<value_type>& __ia)
             __clear(__n);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -3055,7 +3076,7 @@ valarray<_Tp>::operator=(initializer_list<value_type> __il)
     return __assign_range(__il.begin(), __il.end());
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp>
 inline
@@ -3131,7 +3152,7 @@ valarray<_Tp>::operator=(const __val_expr<_ValExpr>& __v)
         resize(__n);
     value_type* __t = __begin_;
     for (size_t __i = 0; __i != __n; ++__t, ++__i)
-        *__t = result_type(__v[__i]);
+        *__t = __result_type(__v[__i]);
     return *this;
 }
 
@@ -3185,7 +3206,7 @@ valarray<_Tp>::operator[](gslice&& __gs)
     return gslice_array<value_type>(move(__gs), *this);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp>
 inline
@@ -3221,7 +3242,7 @@ valarray<_Tp>::operator[](valarray<bool>&& __vb)
     return mask_array<value_type>(move(__vb), *this);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp>
 inline
@@ -3257,7 +3278,7 @@ valarray<_Tp>::operator[](valarray<size_t>&& __vs)
     return indirect_array<value_type>(move(__vs), *this);
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Tp>
 valarray<_Tp>
@@ -3731,7 +3752,7 @@ valarray<_Tp>::resize(size_t __n, value_type __x)
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             for (size_t __n_left = __n; __n_left; --__n_left, ++__end_)
                 ::new ((void*)__end_) value_type(__x);
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -3741,7 +3762,7 @@ valarray<_Tp>::resize(size_t __n, value_type __x)
             __clear(__n);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -4905,4 +4926,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_VALARRAY
+#endif // _LIBCPP_VALARRAY
lib/libcxx/include/variant
@@ -199,18 +199,20 @@ namespace std {
 
 */
 
-#include <__config>
 #include <__availability>
+#include <__config>
+#include <__functional/hash.h>
 #include <__tuple>
-#include <array>
+#include <__utility/forward.h>
+#include <__variant/monostate.h>
+#include <compare>
 #include <exception>
-#include <functional>
 #include <initializer_list>
+#include <limits>
 #include <new>
 #include <tuple>
 #include <type_traits>
 #include <utility>
-#include <limits>
 #include <version>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -236,6 +238,19 @@ _LIBCPP_BEGIN_NAMESPACE_STD
 //       Remove this once we drop support for GCC 5.
 #if _LIBCPP_STD_VER > 14 && !(defined(_LIBCPP_COMPILER_GCC) && _GNUC_VER_NEW < 6000)
 
+// Light N-dimensional array of function pointers. Used in place of std::array to avoid
+// adding a dependency.
+template<class _Tp, size_t _Size>
+struct __farray {
+  static_assert(_Size > 0, "N-dimensional array should never be empty in std::visit");
+  _Tp __buf_[_Size] = {};
+
+  _LIBCPP_INLINE_VISIBILITY constexpr
+  const _Tp &operator[](size_t __n) const noexcept {
+      return __buf_[__n];
+  }
+};
+
 _LIBCPP_NORETURN
 inline _LIBCPP_INLINE_VISIBILITY
 _LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS
@@ -318,6 +333,33 @@ using __variant_index_t =
 template <class _IndexType>
 constexpr _IndexType __variant_npos = static_cast<_IndexType>(-1);
 
+template <class... _Types>
+class _LIBCPP_TEMPLATE_VIS variant;
+
+template <class... _Types>
+_LIBCPP_INLINE_VISIBILITY constexpr variant<_Types...>&
+__as_variant(variant<_Types...>& __vs) noexcept {
+  return __vs;
+}
+
+template <class... _Types>
+_LIBCPP_INLINE_VISIBILITY constexpr const variant<_Types...>&
+__as_variant(const variant<_Types...>& __vs) noexcept {
+  return __vs;
+}
+
+template <class... _Types>
+_LIBCPP_INLINE_VISIBILITY constexpr variant<_Types...>&&
+__as_variant(variant<_Types...>&& __vs) noexcept {
+  return _VSTD::move(__vs);
+}
+
+template <class... _Types>
+_LIBCPP_INLINE_VISIBILITY constexpr const variant<_Types...>&&
+__as_variant(const variant<_Types...>&& __vs) noexcept {
+  return _VSTD::move(__vs);
+}
+
 namespace __find_detail {
 
 template <class _Tp, class... _Types>
@@ -469,7 +511,7 @@ private:
 
   template <class _Tp, size_t _Np, typename... _Indices>
   inline _LIBCPP_INLINE_VISIBILITY
-  static constexpr auto&& __at(const array<_Tp, _Np>& __elems,
+  static constexpr auto&& __at(const __farray<_Tp, _Np>& __elems,
                                size_t __index, _Indices... __indices) {
     return __at(__elems[__index], __indices...);
   }
@@ -485,7 +527,7 @@ private:
   inline _LIBCPP_INLINE_VISIBILITY
   static constexpr auto __make_farray(_Fs&&... __fs) {
     __std_visit_visitor_return_type_check<__uncvref_t<_Fs>...>();
-    using __result = array<common_type_t<__uncvref_t<_Fs>...>, sizeof...(_Fs)>;
+    using __result = __farray<common_type_t<__uncvref_t<_Fs>...>, sizeof...(_Fs)>;
     return __result{{_VSTD::forward<_Fs>(__fs)...}};
   }
 
@@ -564,8 +606,9 @@ struct __variant {
   inline _LIBCPP_INLINE_VISIBILITY
   static constexpr decltype(auto) __visit_alt(_Visitor&& __visitor,
                                               _Vs&&... __vs) {
-    return __base::__visit_alt(_VSTD::forward<_Visitor>(__visitor),
-                               _VSTD::forward<_Vs>(__vs).__impl...);
+    return __base::__visit_alt(
+        _VSTD::forward<_Visitor>(__visitor),
+        _VSTD::__as_variant(_VSTD::forward<_Vs>(__vs)).__impl...);
   }
 
   template <class _Visitor, class... _Vs>
@@ -586,6 +629,7 @@ struct __variant {
         __make_value_visitor(_VSTD::forward<_Visitor>(__visitor)),
         _VSTD::forward<_Vs>(__vs)...);
   }
+
 #if _LIBCPP_STD_VER > 17
   template <class _Rp, class _Visitor, class... _Vs>
   inline _LIBCPP_INLINE_VISIBILITY
@@ -1152,7 +1196,7 @@ struct __narrowing_check {
   template <class _Dest>
   static auto __test_impl(_Dest (&&)[1]) -> __identity<_Dest>;
   template <class _Dest, class _Source>
-  using _Apply _LIBCPP_NODEBUG_TYPE = decltype(__test_impl<_Dest>({_VSTD::declval<_Source>()}));
+  using _Apply _LIBCPP_NODEBUG_TYPE = decltype(__test_impl<_Dest>({declval<_Source>()}));
 };
 
 template <class _Dest, class _Source>
@@ -1637,18 +1681,21 @@ constexpr bool operator>=(const variant<_Types...>& __lhs,
 
 template <class... _Vs>
 inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS
-constexpr void __throw_if_valueless(_Vs&&... __vs) {
-  const bool __valueless = (... || __vs.valueless_by_exception());
+    _LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS constexpr void
+    __throw_if_valueless(_Vs&&... __vs) {
+  const bool __valueless =
+      (... || _VSTD::__as_variant(__vs).valueless_by_exception());
   if (__valueless) {
-      __throw_bad_variant_access();
+    __throw_bad_variant_access();
   }
 }
 
-template <class _Visitor, class... _Vs>
+template <
+    class _Visitor, class... _Vs,
+    typename = void_t<decltype(_VSTD::__as_variant(declval<_Vs>()))...> >
 inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS
-constexpr decltype(auto) visit(_Visitor&& __visitor, _Vs&&... __vs) {
+    _LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS constexpr
+    decltype(auto) visit(_Visitor&& __visitor, _Vs&&... __vs) {
   using __variant_detail::__visitation::__variant;
   _VSTD::__throw_if_valueless(_VSTD::forward<_Vs>(__vs)...);
   return __variant::__visit_value(_VSTD::forward<_Visitor>(__visitor),
@@ -1656,10 +1703,12 @@ constexpr decltype(auto) visit(_Visitor&& __visitor, _Vs&&... __vs) {
 }
 
 #if _LIBCPP_STD_VER > 17
-template <class _Rp, class _Visitor, class... _Vs>
+template <
+    class _Rp, class _Visitor, class... _Vs,
+    typename = void_t<decltype(_VSTD::__as_variant(declval<_Vs>()))...> >
 inline _LIBCPP_INLINE_VISIBILITY
-_LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS
-constexpr _Rp visit(_Visitor&& __visitor, _Vs&&... __vs) {
+    _LIBCPP_AVAILABILITY_THROW_BAD_VARIANT_ACCESS constexpr _Rp
+    visit(_Visitor&& __visitor, _Vs&&... __vs) {
   using __variant_detail::__visitation::__variant;
   _VSTD::__throw_if_valueless(_VSTD::forward<_Vs>(__vs)...);
   return __variant::__visit_value<_Rp>(_VSTD::forward<_Visitor>(__visitor),
@@ -1667,26 +1716,6 @@ constexpr _Rp visit(_Visitor&& __visitor, _Vs&&... __vs) {
 }
 #endif
 
-struct _LIBCPP_TEMPLATE_VIS monostate {};
-
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr bool operator<(monostate, monostate) noexcept { return false; }
-
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr bool operator>(monostate, monostate) noexcept { return false; }
-
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr bool operator<=(monostate, monostate) noexcept { return true; }
-
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr bool operator>=(monostate, monostate) noexcept { return true; }
-
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr bool operator==(monostate, monostate) noexcept { return true; }
-
-inline _LIBCPP_INLINE_VISIBILITY
-constexpr bool operator!=(monostate, monostate) noexcept { return false; }
-
 template <class... _Types>
 inline _LIBCPP_INLINE_VISIBILITY
 auto swap(variant<_Types...>& __lhs,
@@ -1719,21 +1748,32 @@ struct _LIBCPP_TEMPLATE_VIS hash<
   }
 };
 
-template <>
-struct _LIBCPP_TEMPLATE_VIS hash<monostate> {
-  using argument_type = monostate;
-  using result_type = size_t;
+// __unchecked_get is the same as std::get, except, it is UB to use it with the wrong
+// type whereas std::get will throw or returning nullptr. This makes it faster than
+// std::get.
+template <size_t _Ip, class _Vp>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr auto&& __unchecked_get(_Vp&& __v) noexcept {
+  using __variant_detail::__access::__variant;
+  return __variant::__get_alt<_Ip>(_VSTD::forward<_Vp>(__v)).__value;
+}
 
-  inline _LIBCPP_INLINE_VISIBILITY
-  result_type operator()(const argument_type&) const _NOEXCEPT {
-    return 66740831; // return a fundamentally attractive random value.
-  }
-};
+template <class _Tp, class... _Types>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr auto&& __unchecked_get(const variant<_Types...>& __v) noexcept {
+  return __unchecked_get<__find_exactly_one_t<_Tp, _Types...>::value>(__v);
+}
+
+template <class _Tp, class... _Types>
+inline _LIBCPP_INLINE_VISIBILITY
+constexpr auto&& __unchecked_get(variant<_Types...>& __v) noexcept {
+  return __unchecked_get<__find_exactly_one_t<_Tp, _Types...>::value>(__v);
+}
 
-#endif  // _LIBCPP_STD_VER > 14
+#endif // _LIBCPP_STD_VER > 14
 
 _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_VARIANT
+#endif // _LIBCPP_VARIANT
lib/libcxx/include/vector
@@ -144,7 +144,7 @@ public:
     public:
         reference(const reference&) noexcept;
         operator bool() const noexcept;
-        reference& operator=(const bool x) noexcept;
+        reference& operator=(bool x) noexcept;
         reference& operator=(const reference& x) noexcept;
         iterator operator&() const noexcept;
         void flip() noexcept;
@@ -272,21 +272,23 @@ erase_if(vector<T, Allocator>& c, Predicate pred);    // C++20
 */
 
 #include <__config>
-#include <iosfwd> // for forward declaration of vector
 #include <__bit_reference>
-#include <type_traits>
+#include <__debug>
+#include <__functional_base>
+#include <__iterator/wrap_iter.h>
+#include <__split_buffer>
+#include <__utility/forward.h>
+#include <algorithm>
 #include <climits>
-#include <limits>
+#include <compare>
+#include <cstring>
 #include <initializer_list>
+#include <iosfwd> // for forward declaration of vector
+#include <limits>
 #include <memory>
 #include <stdexcept>
-#include <algorithm>
-#include <cstring>
+#include <type_traits>
 #include <version>
-#include <__split_buffer>
-#include <__functional_base>
-
-#include <__debug>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #pragma GCC system_header
@@ -557,7 +559,7 @@ public:
     }
 
     vector(const vector& __x);
-    vector(const vector& __x, const allocator_type& __a);
+    vector(const vector& __x, const __identity_t<allocator_type>& __a);
     _LIBCPP_INLINE_VISIBILITY
     vector& operator=(const vector& __x);
 
@@ -577,7 +579,7 @@ public:
 #endif
 
     _LIBCPP_INLINE_VISIBILITY
-    vector(vector&& __x, const allocator_type& __a);
+    vector(vector&& __x, const __identity_t<allocator_type>& __a);
     _LIBCPP_INLINE_VISIBILITY
     vector& operator=(vector&& __x)
         _NOEXCEPT_((__noexcept_move_assign_container<_Allocator, __alloc_traits>::value));
@@ -586,7 +588,7 @@ public:
     vector& operator=(initializer_list<value_type> __il)
         {assign(__il.begin(), __il.end()); return *this;}
 
-#endif  // !_LIBCPP_CXX03_LANG
+#endif // !_LIBCPP_CXX03_LANG
 
     template <class _InputIterator>
         typename enable_if
@@ -673,22 +675,22 @@ public:
 
     _LIBCPP_INLINE_VISIBILITY reference       front() _NOEXCEPT
     {
-        _LIBCPP_ASSERT(!empty(), "front() called for empty vector");
+        _LIBCPP_ASSERT(!empty(), "front() called on an empty vector");
         return *this->__begin_;
     }
     _LIBCPP_INLINE_VISIBILITY const_reference front() const _NOEXCEPT
     {
-        _LIBCPP_ASSERT(!empty(), "front() called for empty vector");
+        _LIBCPP_ASSERT(!empty(), "front() called on an empty vector");
         return *this->__begin_;
     }
     _LIBCPP_INLINE_VISIBILITY reference       back() _NOEXCEPT
     {
-        _LIBCPP_ASSERT(!empty(), "back() called for empty vector");
+        _LIBCPP_ASSERT(!empty(), "back() called on an empty vector");
         return *(this->__end_ - 1);
     }
     _LIBCPP_INLINE_VISIBILITY const_reference back()  const _NOEXCEPT
     {
-        _LIBCPP_ASSERT(!empty(), "back() called for empty vector");
+        _LIBCPP_ASSERT(!empty(), "back() called on an empty vector");
         return *(this->__end_ - 1);
     }
 
@@ -733,7 +735,7 @@ public:
     iterator insert(const_iterator __position, value_type&& __x);
     template <class... _Args>
         iterator emplace(const_iterator __position, _Args&&... __args);
-#endif  // !_LIBCPP_CXX03_LANG
+#endif // !_LIBCPP_CXX03_LANG
 
     iterator insert(const_iterator __position, size_type __n, const_reference __x);
     template <class _InputIterator>
@@ -796,7 +798,7 @@ public:
     bool __addable(const const_iterator* __i, ptrdiff_t __n) const;
     bool __subscriptable(const const_iterator* __i, ptrdiff_t __n) const;
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 private:
     _LIBCPP_INLINE_VISIBILITY void __invalidate_all_iterators();
@@ -931,18 +933,18 @@ private:
 
 #ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
 template<class _InputIterator,
-         class _Alloc = allocator<typename iterator_traits<_InputIterator>::value_type>,
-         class = typename enable_if<__is_allocator<_Alloc>::value, void>::type
+         class _Alloc = allocator<__iter_value_type<_InputIterator>>,
+         class = _EnableIf<__is_allocator<_Alloc>::value>
          >
 vector(_InputIterator, _InputIterator)
-  -> vector<typename iterator_traits<_InputIterator>::value_type, _Alloc>;
+  -> vector<__iter_value_type<_InputIterator>, _Alloc>;
 
 template<class _InputIterator,
          class _Alloc,
-         class = typename enable_if<__is_allocator<_Alloc>::value, void>::type
+         class = _EnableIf<__is_allocator<_Alloc>::value>
          >
 vector(_InputIterator, _InputIterator, _Alloc)
-  -> vector<typename iterator_traits<_InputIterator>::value_type, _Alloc>;
+  -> vector<__iter_value_type<_InputIterator>, _Alloc>;
 #endif
 
 template <class _Tp, class _Allocator>
@@ -1027,7 +1029,7 @@ vector<_Tp, _Allocator>::__recommend(size_type __new_size) const
     const size_type __cap = capacity();
     if (__cap >= __ms / 2)
         return __ms;
-    return _VSTD::max<size_type>(2*__cap, __new_size);
+    return _VSTD::max<size_type>(2 * __cap, __new_size);
 }
 
 //  Default constructs __n objects starting at __end_
@@ -1261,7 +1263,7 @@ vector<_Tp, _Allocator>::vector(const vector& __x)
 }
 
 template <class _Tp, class _Allocator>
-vector<_Tp, _Allocator>::vector(const vector& __x, const allocator_type& __a)
+vector<_Tp, _Allocator>::vector(const vector& __x, const __identity_t<allocator_type>& __a)
     : __base(__a)
 {
 #if _LIBCPP_DEBUG_LEVEL == 2
@@ -1299,7 +1301,7 @@ vector<_Tp, _Allocator>::vector(vector&& __x)
 
 template <class _Tp, class _Allocator>
 inline _LIBCPP_INLINE_VISIBILITY
-vector<_Tp, _Allocator>::vector(vector&& __x, const allocator_type& __a)
+vector<_Tp, _Allocator>::vector(vector&& __x, const __identity_t<allocator_type>& __a)
     : __base(__a)
 {
 #if _LIBCPP_DEBUG_LEVEL == 2
@@ -1392,7 +1394,7 @@ vector<_Tp, _Allocator>::__move_assign(vector& __c, true_type)
 #endif
 }
 
-#endif  // !_LIBCPP_CXX03_LANG
+#endif // !_LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Allocator>
 inline _LIBCPP_INLINE_VISIBILITY
@@ -1598,7 +1600,7 @@ vector<_Tp, _Allocator>::shrink_to_fit() _NOEXCEPT
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             allocator_type& __a = this->__alloc();
             __split_buffer<value_type, allocator_type&> __v(size(), size(), __a);
             __swap_out_circular_buffer(__v);
@@ -1607,7 +1609,7 @@ vector<_Tp, _Allocator>::shrink_to_fit() _NOEXCEPT
         catch (...)
         {
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -1690,14 +1692,14 @@ vector<_Tp, _Allocator>::emplace_back(_Args&&... __args)
 #endif
 }
 
-#endif  // !_LIBCPP_CXX03_LANG
+#endif // !_LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Allocator>
 inline
 void
 vector<_Tp, _Allocator>::pop_back()
 {
-    _LIBCPP_ASSERT(!empty(), "vector::pop_back called for empty vector");
+    _LIBCPP_ASSERT(!empty(), "vector::pop_back called on an empty vector");
     this->__destruct_at_end(this->__end_ - 1);
 }
 
@@ -1865,7 +1867,7 @@ vector<_Tp, _Allocator>::emplace(const_iterator __position, _Args&&... __args)
     return __make_iter(__p);
 }
 
-#endif  // !_LIBCPP_CXX03_LANG
+#endif // !_LIBCPP_CXX03_LANG
 
 template <class _Tp, class _Allocator>
 typename vector<_Tp, _Allocator>::iterator
@@ -1941,7 +1943,7 @@ vector<_Tp, _Allocator>::insert(const_iterator __position, _InputIterator __firs
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             __v.__construct_at_end(__first, __last);
             difference_type __old_size = __old_last - this->__begin_;
             difference_type __old_p = __p - this->__begin_;
@@ -1955,7 +1957,7 @@ vector<_Tp, _Allocator>::insert(const_iterator __position, _InputIterator __firs
             erase(__make_iter(__old_last), end());
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
     __p = _VSTD::rotate(__p, __old_last, this->__end_);
     insert(__make_iter(__p), _VSTD::make_move_iterator(__v.begin()),
@@ -2114,7 +2116,7 @@ vector<_Tp, _Allocator>::__subscriptable(const const_iterator* __i, ptrdiff_t __
     return this->__begin_ <= __p && __p < this->__end_;
 }
 
-#endif  // _LIBCPP_DEBUG_LEVEL == 2
+#endif // _LIBCPP_DEBUG_LEVEL == 2
 
 template <class _Tp, class _Allocator>
 inline _LIBCPP_INLINE_VISIBILITY
@@ -2261,7 +2263,7 @@ public:
 #else
         _NOEXCEPT_(is_nothrow_move_constructible<allocator_type>::value);
 #endif
-    vector(vector&& __v, const allocator_type& __a);
+    vector(vector&& __v, const __identity_t<allocator_type>& __a);
     _LIBCPP_INLINE_VISIBILITY
     vector& operator=(vector&& __v)
         _NOEXCEPT_((__noexcept_move_assign_container<_Allocator, __alloc_traits>::value));
@@ -2270,7 +2272,7 @@ public:
     vector& operator=(initializer_list<value_type> __il)
         {assign(__il.begin(), __il.end()); return *this;}
 
-#endif  // !_LIBCPP_CXX03_LANG
+#endif // !_LIBCPP_CXX03_LANG
 
     template <class _InputIterator>
         typename enable_if
@@ -2573,7 +2575,7 @@ vector<bool, _Allocator>::__recommend(size_type __new_size) const
     const size_type __cap = capacity();
     if (__cap >= __ms / 2)
         return __ms;
-    return _VSTD::max(2*__cap, __align_it(__new_size));
+    return _VSTD::max(2 * __cap, __align_it(__new_size));
 }
 
 //  Default constructs __n objects starting at __end_
@@ -2708,7 +2710,7 @@ vector<bool, _Allocator>::vector(_InputIterator __first, _InputIterator __last,
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         for (; __first != __last; ++__first)
             push_back(*__first);
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2720,7 +2722,7 @@ vector<bool, _Allocator>::vector(_InputIterator __first, _InputIterator __last,
         __invalidate_all_iterators();
         throw;
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template <class _Allocator>
@@ -2735,7 +2737,7 @@ vector<bool, _Allocator>::vector(_InputIterator __first, _InputIterator __last,
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         for (; __first != __last; ++__first)
             push_back(*__first);
 #ifndef _LIBCPP_NO_EXCEPTIONS
@@ -2747,7 +2749,7 @@ vector<bool, _Allocator>::vector(_InputIterator __first, _InputIterator __last,
         __invalidate_all_iterators();
         throw;
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template <class _Allocator>
@@ -2812,7 +2814,7 @@ vector<bool, _Allocator>::vector(initializer_list<value_type> __il, const alloca
     }
 }
 
-#endif  // _LIBCPP_CXX03_LANG
+#endif // _LIBCPP_CXX03_LANG
 
 template <class _Allocator>
 vector<bool, _Allocator>::~vector()
@@ -2887,7 +2889,7 @@ inline _LIBCPP_INLINE_VISIBILITY vector<bool, _Allocator>::vector(vector&& __v)
 }
 
 template <class _Allocator>
-vector<bool, _Allocator>::vector(vector&& __v, const allocator_type& __a)
+vector<bool, _Allocator>::vector(vector&& __v, const __identity_t<allocator_type>& __a)
     : __begin_(nullptr),
       __size_(0),
       __cap_alloc_(0, __a)
@@ -2942,7 +2944,7 @@ vector<bool, _Allocator>::__move_assign(vector& __c, true_type)
     __c.__cap() = __c.__size_ = 0;
 }
 
-#endif  // !_LIBCPP_CXX03_LANG
+#endif // !_LIBCPP_CXX03_LANG
 
 template <class _Allocator>
 void
@@ -3028,14 +3030,14 @@ vector<bool, _Allocator>::shrink_to_fit() _NOEXCEPT
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             vector(*this, allocator_type(__alloc())).swap(*this);
 #ifndef _LIBCPP_NO_EXCEPTIONS
         }
         catch (...)
         {
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 }
 
@@ -3142,7 +3144,7 @@ vector<bool, _Allocator>::insert(const_iterator __position, _InputIterator __fir
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             __v.assign(__first, __last);
             difference_type __old_size = static_cast<difference_type>(__old_end - begin());
             difference_type __old_p = __p - begin();
@@ -3156,7 +3158,7 @@ vector<bool, _Allocator>::insert(const_iterator __position, _InputIterator __fir
             erase(__old_end, end());
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
     __p = _VSTD::rotate(__p, __old_end, end());
     insert(__p, __v.begin(), __v.end());
@@ -3411,4 +3413,4 @@ _LIBCPP_END_NAMESPACE_STD
 
 _LIBCPP_POP_MACROS
 
-#endif  // _LIBCPP_VECTOR
+#endif // _LIBCPP_VECTOR
lib/libcxx/include/version
@@ -56,7 +56,7 @@ __cpp_lib_constexpr_functional                          201907L <functional>
 __cpp_lib_constexpr_iterator                            201811L <iterator>
 __cpp_lib_constexpr_memory                              201811L <memory>
 __cpp_lib_constexpr_numeric                             201911L <numeric>
-__cpp_lib_constexpr_string                              201907L <string>
+__cpp_lib_constexpr_string                              201811L <string>
 __cpp_lib_constexpr_string_view                         201811L <string_view>
 __cpp_lib_constexpr_tuple                               201811L <tuple>
 __cpp_lib_constexpr_utility                             201811L <utility>
@@ -72,6 +72,7 @@ __cpp_lib_exchange_function                             201304L <utility>
 __cpp_lib_execution                                     201902L <execution>
                                                         201603L // C++17
 __cpp_lib_filesystem                                    201703L <filesystem>
+__cpp_lib_format                                        201907L <format>
 __cpp_lib_gcd_lcm                                       201606L <numeric>
 __cpp_lib_generic_associative_lookup                    201304L <map> <set>
 __cpp_lib_generic_unordered_lookup                      201811L <unordered_map> <unordered_set>
@@ -149,6 +150,7 @@ __cpp_lib_three_way_comparison                          201907L <compare>
 __cpp_lib_to_address                                    201711L <memory>
 __cpp_lib_to_array                                      201907L <array>
 __cpp_lib_to_chars                                      201611L <utility>
+__cpp_lib_to_underlying                                 202102L <utility>
 __cpp_lib_transformation_trait_aliases                  201304L <type_traits>
 __cpp_lib_transparent_operators                         201510L <functional> <memory>
                                                         201210L // C++14
@@ -158,7 +160,7 @@ __cpp_lib_type_trait_variable_templates                 201510L <type_traits>
 __cpp_lib_uncaught_exceptions                           201411L <exception>
 __cpp_lib_unordered_map_try_emplace                     201411L <unordered_map>
 __cpp_lib_unwrap_ref                                    201811L <functional>
-__cpp_lib_variant                                       201606L <variant>
+__cpp_lib_variant                                       202102L <variant>
 __cpp_lib_void_t                                        201411L <type_traits>
 
 */
@@ -169,6 +171,8 @@ __cpp_lib_void_t                                        201411L <type_traits>
 #pragma GCC system_header
 #endif
 
+// clang-format off
+
 #if _LIBCPP_STD_VER > 11
 # define __cpp_lib_chrono_udls                          201304L
 # define __cpp_lib_complex_udls                         201309L
@@ -184,7 +188,7 @@ __cpp_lib_void_t                                        201411L <type_traits>
 # define __cpp_lib_quoted_string_io                     201304L
 # define __cpp_lib_result_of_sfinae                     201210L
 # define __cpp_lib_robust_nonmodifying_seq_ops          201304L
-# if !defined(_LIBCPP_HAS_NO_THREADS)
+# if !defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_timed_mutex)
 #   define __cpp_lib_shared_timed_mutex                 201402L
 # endif
 # define __cpp_lib_string_udls                          201304L
@@ -213,7 +217,9 @@ __cpp_lib_void_t                                        201411L <type_traits>
 # define __cpp_lib_clamp                                201603L
 # define __cpp_lib_enable_shared_from_this              201603L
 // # define __cpp_lib_execution                            201603L
-# define __cpp_lib_filesystem                           201703L
+# if !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_filesystem)
+#   define __cpp_lib_filesystem                         201703L
+# endif
 # define __cpp_lib_gcd_lcm                              201606L
 // # define __cpp_lib_hardware_interference_size           201703L
 # if defined(_LIBCPP_HAS_UNIQUE_OBJECT_REPRESENTATIONS)
@@ -241,7 +247,7 @@ __cpp_lib_void_t                                        201411L <type_traits>
 # define __cpp_lib_raw_memory_algorithms                201606L
 # define __cpp_lib_sample                               201603L
 # define __cpp_lib_scoped_lock                          201703L
-# if !defined(_LIBCPP_HAS_NO_THREADS)
+# if !defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_shared_mutex)
 #   define __cpp_lib_shared_mutex                       201505L
 # endif
 # define __cpp_lib_shared_ptr_arrays                    201611L
@@ -253,7 +259,7 @@ __cpp_lib_void_t                                        201411L <type_traits>
 # define __cpp_lib_type_trait_variable_templates        201510L
 # define __cpp_lib_uncaught_exceptions                  201411L
 # define __cpp_lib_unordered_map_try_emplace            201411L
-# define __cpp_lib_variant                              201606L
+# define __cpp_lib_variant                              202102L
 # define __cpp_lib_void_t                               201411L
 #endif
 
@@ -277,32 +283,32 @@ __cpp_lib_void_t                                        201411L <type_traits>
 // #   define __cpp_lib_atomic_shared_ptr                  201711L
 # endif
 # if !defined(_LIBCPP_HAS_NO_THREADS)
-// #   define __cpp_lib_atomic_value_initialization        201911L
+#   define __cpp_lib_atomic_value_initialization        201911L
 # endif
-# if !defined(_LIBCPP_HAS_NO_THREADS)
+# if !defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_atomic_wait)
 #   define __cpp_lib_atomic_wait                        201907L
 # endif
-# if !defined(_LIBCPP_HAS_NO_THREADS)
+# if !defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_barrier)
 #   define __cpp_lib_barrier                            201907L
 # endif
-// # define __cpp_lib_bind_front                           201907L
+# define __cpp_lib_bind_front                           201907L
 // # define __cpp_lib_bit_cast                             201806L
 // # define __cpp_lib_bitops                               201907L
 # define __cpp_lib_bounded_array_traits                 201902L
-# if !defined(_LIBCPP_NO_HAS_CHAR8_T)
+# if !defined(_LIBCPP_HAS_NO_CHAR8_T)
 #   define __cpp_lib_char8_t                            201811L
 # endif
-// # define __cpp_lib_concepts                             202002L
-// # define __cpp_lib_constexpr_algorithms                 201806L
+# define __cpp_lib_concepts                             202002L
+# define __cpp_lib_constexpr_algorithms                 201806L
 // # define __cpp_lib_constexpr_complex                    201711L
 # define __cpp_lib_constexpr_dynamic_alloc              201907L
 # define __cpp_lib_constexpr_functional                 201907L
-// # define __cpp_lib_constexpr_iterator                   201811L
-// # define __cpp_lib_constexpr_memory                     201811L
+# define __cpp_lib_constexpr_iterator                   201811L
+# define __cpp_lib_constexpr_memory                     201811L
 # define __cpp_lib_constexpr_numeric                    201911L
-// # define __cpp_lib_constexpr_string                     201907L
-// # define __cpp_lib_constexpr_string_view                201811L
-// # define __cpp_lib_constexpr_tuple                      201811L
+# define __cpp_lib_constexpr_string                     201811L
+# define __cpp_lib_constexpr_string_view                201811L
+# define __cpp_lib_constexpr_tuple                      201811L
 # define __cpp_lib_constexpr_utility                    201811L
 // # define __cpp_lib_constexpr_vector                     201907L
 // # define __cpp_lib_coroutine                            201902L
@@ -313,9 +319,14 @@ __cpp_lib_void_t                                        201411L <type_traits>
 # define __cpp_lib_erase_if                             202002L
 # undef  __cpp_lib_execution
 // # define __cpp_lib_execution                            201902L
+# if !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_format)
+// #   define __cpp_lib_format                             201907L
+# endif
 # define __cpp_lib_generic_unordered_lookup             201811L
 # define __cpp_lib_int_pow2                             202002L
-// # define __cpp_lib_integer_comparison_functions         202002L
+# if !defined(_LIBCPP_HAS_NO_CONCEPTS)
+#   define __cpp_lib_integer_comparison_functions       202002L
+# endif
 # define __cpp_lib_interpolate                          201902L
 # if !defined(_LIBCPP_HAS_NO_BUILTIN_IS_CONSTANT_EVALUATED)
 #   define __cpp_lib_is_constant_evaluated              201811L
@@ -326,17 +337,17 @@ __cpp_lib_void_t                                        201411L <type_traits>
 # if !defined(_LIBCPP_HAS_NO_THREADS)
 // #   define __cpp_lib_jthread                            201911L
 # endif
-# if !defined(_LIBCPP_HAS_NO_THREADS)
+# if !defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_latch)
 #   define __cpp_lib_latch                              201907L
 # endif
 # define __cpp_lib_list_remove_return_type              201806L
-# if defined(__cpp_concepts) && __cpp_concepts >= 201811L
+# if !defined(_LIBCPP_HAS_NO_CONCEPTS)
 #   define __cpp_lib_math_constants                     201907L
 # endif
 // # define __cpp_lib_polymorphic_allocator                201902L
 // # define __cpp_lib_ranges                               201811L
 # define __cpp_lib_remove_cvref                         201711L
-# if !defined(_LIBCPP_HAS_NO_THREADS)
+# if !defined(_LIBCPP_HAS_NO_THREADS) && !defined(_LIBCPP_AVAILABILITY_DISABLE_FTM___cpp_lib_semaphore)
 #   define __cpp_lib_semaphore                          201907L
 # endif
 # define __cpp_lib_shift                                201806L
@@ -359,6 +370,9 @@ __cpp_lib_void_t                                        201411L <type_traits>
 // # define __cpp_lib_stacktrace                           202011L
 // # define __cpp_lib_stdatomic_h                          202011L
 # define __cpp_lib_string_contains                      202011L
+# define __cpp_lib_to_underlying                        202102L
 #endif
 
+// clang-format on
+
 #endif // _LIBCPP_VERSIONH
lib/libcxx/include/wchar.h
@@ -177,6 +177,6 @@ size_t mbsnrtowcs(wchar_t *__restrict dst, const char **__restrict src,
 size_t wcsnrtombs(char *__restrict dst, const wchar_t **__restrict src,
                   size_t nwc, size_t len, mbstate_t *__restrict ps);
 }  // extern "C++"
-#endif  // __cplusplus && _LIBCPP_MSVCRT
+#endif // __cplusplus && _LIBCPP_MSVCRT
 
-#endif  // _LIBCPP_WCHAR_H
+#endif // _LIBCPP_WCHAR_H
lib/libcxx/include/wctype.h
@@ -75,6 +75,6 @@ wctrans_t wctrans(const char* property);
 #undef towctrans
 #undef wctrans
 
-#endif  // __cplusplus
+#endif // __cplusplus
 
-#endif  // _LIBCPP_WCTYPE_H
+#endif // _LIBCPP_WCTYPE_H
lib/libcxx/src/experimental/memory_resource.cpp
@@ -40,7 +40,7 @@ class _LIBCPP_TYPE_VIS __new_delete_memory_resource_imp
       _VSTD::__libcpp_deallocate(p, n, align);
     }
 
-    bool do_is_equal(memory_resource const & other) const _NOEXCEPT override
+    bool do_is_equal(memory_resource const & other) const noexcept override
         { return &other == this; }
 
 public:
@@ -60,7 +60,7 @@ protected:
         __throw_bad_alloc();
     }
     virtual void do_deallocate(void *, size_t, size_t) {}
-    virtual bool do_is_equal(memory_resource const & __other) const _NOEXCEPT
+    virtual bool do_is_equal(memory_resource const & __other) const noexcept
     { return &__other == this; }
 };
 
@@ -76,28 +76,23 @@ union ResourceInitHelper {
   ~ResourceInitHelper() {}
 };
 
-// When compiled in C++14 this initialization should be a constant expression.
-// Only in C++11 is "init_priority" needed to ensure initialization order.
-#if _LIBCPP_STD_VER > 11
-_LIBCPP_SAFE_STATIC
-#endif
-ResourceInitHelper res_init _LIBCPP_INIT_PRIORITY_MAX;
+_LIBCPP_SAFE_STATIC ResourceInitHelper res_init _LIBCPP_INIT_PRIORITY_MAX;
 
 } // end namespace
 
 
-memory_resource * new_delete_resource() _NOEXCEPT {
+memory_resource * new_delete_resource() noexcept {
     return &res_init.resources.new_delete_res;
 }
 
-memory_resource * null_memory_resource() _NOEXCEPT {
+memory_resource * null_memory_resource() noexcept {
     return &res_init.resources.null_res;
 }
 
 // default_memory_resource()
 
 static memory_resource *
-__default_memory_resource(bool set = false, memory_resource * new_res = nullptr) _NOEXCEPT
+__default_memory_resource(bool set = false, memory_resource * new_res = nullptr) noexcept
 {
 #ifndef _LIBCPP_HAS_NO_ATOMIC_HEADER
     _LIBCPP_SAFE_STATIC static atomic<memory_resource*> __res =
@@ -138,12 +133,12 @@ __default_memory_resource(bool set = false, memory_resource * new_res = nullptr)
 #endif
 }
 
-memory_resource * get_default_resource() _NOEXCEPT
+memory_resource * get_default_resource() noexcept
 {
     return __default_memory_resource();
 }
 
-memory_resource * set_default_resource(memory_resource * __new_res) _NOEXCEPT
+memory_resource * set_default_resource(memory_resource * __new_res) noexcept
 {
     return __default_memory_resource(true, __new_res);
 }
lib/libcxx/src/filesystem/directory_iterator.cpp
@@ -124,7 +124,8 @@ public:
       ec = detail::make_windows_error(GetLastError());
       const bool ignore_permission_denied =
           bool(opts & directory_options::skip_permission_denied);
-      if (ignore_permission_denied && ec.value() == ERROR_ACCESS_DENIED)
+      if (ignore_permission_denied &&
+          ec.value() == static_cast<int>(errc::permission_denied))
         ec.clear();
       return;
     }
@@ -272,7 +273,7 @@ directory_iterator& directory_iterator::__increment(error_code* ec) {
     path root = move(__imp_->__root_);
     __imp_.reset();
     if (m_ec)
-      err.report(m_ec, "at root \"%s\"", root);
+      err.report(m_ec, "at root " PATH_CSTR_FMT, root.c_str());
   }
   return *this;
 }
@@ -359,7 +360,7 @@ void recursive_directory_iterator::__advance(error_code* ec) {
   if (m_ec) {
     path root = move(stack.top().__root_);
     __imp_.reset();
-    err.report(m_ec, "at root \"%s\"", root);
+    err.report(m_ec, "at root " PATH_CSTR_FMT, root.c_str());
   } else {
     __imp_.reset();
   }
@@ -404,7 +405,8 @@ bool recursive_directory_iterator::__try_recursion(error_code* ec) {
     } else {
       path at_ent = move(curr_it.__entry_.__p_);
       __imp_.reset();
-      err.report(m_ec, "attempting recursion into \"%s\"", at_ent);
+      err.report(m_ec, "attempting recursion into " PATH_CSTR_FMT,
+                 at_ent.c_str());
     }
   }
   return false;
lib/libcxx/src/filesystem/filesystem_common.h
@@ -35,15 +35,17 @@
 #endif
 #endif
 
-#if defined(__GNUC__)
+#if defined(__GNUC__) || defined(__clang__)
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wunused-function"
 #endif
 
 #if defined(_LIBCPP_WIN32API)
 #define PS(x) (L##x)
+#define PATH_CSTR_FMT "\"%ls\""
 #else
 #define PS(x) (x)
+#define PATH_CSTR_FMT "\"%s\""
 #endif
 
 _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
@@ -57,68 +59,47 @@ errc __win_err_to_errc(int err);
 
 namespace {
 
-static string format_string_imp(const char* msg, ...) {
-  // we might need a second shot at this, so pre-emptivly make a copy
-  struct GuardVAList {
-    va_list& target;
-    bool active = true;
-    GuardVAList(va_list& tgt) : target(tgt), active(true) {}
-    void clear() {
-      if (active)
-        va_end(target);
-      active = false;
-    }
-    ~GuardVAList() {
-      if (active)
-        va_end(target);
-    }
-  };
-  va_list args;
-  va_start(args, msg);
-  GuardVAList args_guard(args);
-
-  va_list args_cp;
-  va_copy(args_cp, args);
-  GuardVAList args_copy_guard(args_cp);
-
-  std::string result;
-
-  array<char, 256> local_buff;
-  size_t size_with_null = local_buff.size();
-  auto ret = ::vsnprintf(local_buff.data(), size_with_null, msg, args_cp);
-
-  args_copy_guard.clear();
-
-  // handle empty expansion
-  if (ret == 0)
-    return result;
-  if (static_cast<size_t>(ret) < size_with_null) {
-    result.assign(local_buff.data(), static_cast<size_t>(ret));
-    return result;
+static _LIBCPP_FORMAT_PRINTF(1, 0) string
+format_string_impl(const char* msg, va_list ap) {
+  array<char, 256> buf;
+
+  va_list apcopy;
+  va_copy(apcopy, ap);
+  int ret = ::vsnprintf(buf.data(), buf.size(), msg, apcopy);
+  va_end(apcopy);
+
+  string result;
+  if (static_cast<size_t>(ret) < buf.size()) {
+    result.assign(buf.data(), static_cast<size_t>(ret));
+  } else {
+    // we did not provide a long enough buffer on our first attempt. The
+    // return value is the number of bytes (excluding the null byte) that are
+    // needed for formatting.
+    size_t size_with_null = static_cast<size_t>(ret) + 1;
+    result.__resize_default_init(size_with_null - 1);
+    ret = ::vsnprintf(&result[0], size_with_null, msg, ap);
+    _LIBCPP_ASSERT(static_cast<size_t>(ret) == (size_with_null - 1), "TODO");
   }
-
-  // we did not provide a long enough buffer on our first attempt. The
-  // return value is the number of bytes (excluding the null byte) that are
-  // needed for formatting.
-  size_with_null = static_cast<size_t>(ret) + 1;
-  result.__resize_default_init(size_with_null - 1);
-  ret = ::vsnprintf(&result[0], size_with_null, msg, args);
-  _LIBCPP_ASSERT(static_cast<size_t>(ret) == (size_with_null - 1), "TODO");
-
   return result;
 }
 
-const path::value_type* unwrap(path::string_type const& s) { return s.c_str(); }
-const path::value_type* unwrap(path const& p) { return p.native().c_str(); }
-template <class Arg>
-Arg const& unwrap(Arg const& a) {
-  static_assert(!is_class<Arg>::value, "cannot pass class here");
-  return a;
-}
-
-template <class... Args>
-string format_string(const char* fmt, Args const&... args) {
-  return format_string_imp(fmt, unwrap(args)...);
+static _LIBCPP_FORMAT_PRINTF(1, 2) string
+format_string(const char* msg, ...) {
+  string ret;
+  va_list ap;
+  va_start(ap, msg);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+  try {
+#endif // _LIBCPP_NO_EXCEPTIONS
+    ret = format_string_impl(msg, ap);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+  } catch (...) {
+    va_end(ap);
+    throw;
+  }
+#endif // _LIBCPP_NO_EXCEPTIONS
+  va_end(ap);
+  return ret;
 }
 
 error_code capture_errno() {
@@ -190,14 +171,14 @@ struct ErrorHandler {
     _LIBCPP_UNREACHABLE();
   }
 
-  template <class... Args>
-  T report(const error_code& ec, const char* msg, Args const&... args) const {
+  _LIBCPP_FORMAT_PRINTF(3, 0)
+  void report_impl(const error_code& ec, const char* msg, va_list ap) const {
     if (ec_) {
       *ec_ = ec;
-      return error_value<T>();
+      return;
     }
     string what =
-        string("in ") + func_name_ + ": " + format_string(msg, args...);
+        string("in ") + func_name_ + ": " + format_string_impl(msg, ap);
     switch (bool(p1_) + bool(p2_)) {
     case 0:
       __throw_filesystem_error(what, ec);
@@ -209,11 +190,44 @@ struct ErrorHandler {
     _LIBCPP_UNREACHABLE();
   }
 
-  T report(errc const& err) const { return report(make_error_code(err)); }
+  _LIBCPP_FORMAT_PRINTF(3, 4)
+  T report(const error_code& ec, const char* msg, ...) const {
+    va_list ap;
+    va_start(ap, msg);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try {
+#endif // _LIBCPP_NO_EXCEPTIONS
+      report_impl(ec, msg, ap);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    } catch (...) {
+      va_end(ap);
+      throw;
+    }
+#endif // _LIBCPP_NO_EXCEPTIONS
+    va_end(ap);
+    return error_value<T>();
+  }
+
+  T report(errc const& err) const {
+    return report(make_error_code(err));
+  }
 
-  template <class... Args>
-  T report(errc const& err, const char* msg, Args const&... args) const {
-    return report(make_error_code(err), msg, args...);
+  _LIBCPP_FORMAT_PRINTF(3, 4)
+  T report(errc const& err, const char* msg, ...) const {
+    va_list ap;
+    va_start(ap, msg);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    try {
+#endif // _LIBCPP_NO_EXCEPTIONS
+      report_impl(make_error_code(err), msg, ap);
+#ifndef _LIBCPP_NO_EXCEPTIONS
+    } catch (...) {
+      va_end(ap);
+      throw;
+    }
+#endif // _LIBCPP_NO_EXCEPTIONS
+    va_end(ap);
+    return error_value<T>();
   }
 
 private:
@@ -224,9 +238,41 @@ private:
 using chrono::duration;
 using chrono::duration_cast;
 
+#if defined(_LIBCPP_WIN32API)
+// Various C runtime versions (UCRT, or the legacy msvcrt.dll used by
+// some mingw toolchains) provide different stat function implementations,
+// with a number of limitations with respect to what we want from the
+// stat function. Instead provide our own (in the anonymous detail namespace
+// in posix_compat.h) which does exactly what we want, along with our own
+// stat structure and flag macros.
+
+struct TimeSpec {
+  int64_t tv_sec;
+  int64_t tv_nsec;
+};
+struct StatT {
+  unsigned st_mode;
+  TimeSpec st_atim;
+  TimeSpec st_mtim;
+  uint64_t st_dev; // FILE_ID_INFO::VolumeSerialNumber
+  struct FileIdStruct {
+    unsigned char id[16]; // FILE_ID_INFO::FileId
+    bool operator==(const FileIdStruct &other) const {
+      for (int i = 0; i < 16; i++)
+        if (id[i] != other.id[i])
+          return false;
+      return true;
+    }
+  } st_ino;
+  uint32_t st_nlink;
+  uintmax_t st_size;
+};
+
+#else
 using TimeSpec = struct timespec;
 using TimeVal = struct timeval;
 using StatT = struct stat;
+#endif
 
 template <class FileTimeT, class TimeT,
           bool IsFloat = is_floating_point<typename FileTimeT::rep>::value>
@@ -255,8 +301,7 @@ struct time_util_base {
           .count();
 
 private:
-#if _LIBCPP_STD_VER > 11 && !defined(_LIBCPP_HAS_NO_CXX14_CONSTEXPR)
-  static constexpr fs_duration get_min_nsecs() {
+  static _LIBCPP_CONSTEXPR_AFTER_CXX11 fs_duration get_min_nsecs() {
     return duration_cast<fs_duration>(
         fs_nanoseconds(min_nsec_timespec) -
         duration_cast<fs_nanoseconds>(fs_seconds(1)));
@@ -266,7 +311,7 @@ private:
                     FileTimeT::duration::min(),
                 "value doesn't roundtrip");
 
-  static constexpr bool check_range() {
+  static _LIBCPP_CONSTEXPR_AFTER_CXX11 bool check_range() {
     // This kinda sucks, but it's what happens when we don't have __int128_t.
     if (sizeof(TimeT) == sizeof(rep)) {
       typedef duration<long long, ratio<3600 * 24 * 365> > Years;
@@ -277,7 +322,6 @@ private:
            min_seconds <= numeric_limits<TimeT>::min();
   }
   static_assert(check_range(), "the representable range is unacceptable small");
-#endif
 };
 
 template <class FileTimeT, class TimeT>
@@ -405,7 +449,11 @@ public:
   }
 };
 
+#if defined(_LIBCPP_WIN32API)
+using fs_time = time_util<file_time_type, int64_t, TimeSpec>;
+#else
 using fs_time = time_util<file_time_type, time_t, TimeSpec>;
+#endif
 
 #if defined(__APPLE__)
 inline TimeSpec extract_mtime(StatT const& st) { return st.st_mtimespec; }
@@ -419,11 +467,21 @@ inline TimeSpec extract_atime(StatT const& st) {
   TimeSpec TS = {st.st_atime, 0};
   return TS;
 }
+#elif defined(_AIX)
+inline TimeSpec extract_mtime(StatT const& st) {
+  TimeSpec TS = {st.st_mtime, st.st_mtime_n};
+  return TS;
+}
+inline TimeSpec extract_atime(StatT const& st) {
+  TimeSpec TS = {st.st_atime, st.st_atime_n};
+  return TS;
+}
 #else
 inline TimeSpec extract_mtime(StatT const& st) { return st.st_mtim; }
 inline TimeSpec extract_atime(StatT const& st) { return st.st_atim; }
 #endif
 
+#if !defined(_LIBCPP_WIN32API)
 inline TimeVal make_timeval(TimeSpec const& ts) {
   using namespace chrono;
   auto Convert = [](long nsec) {
@@ -466,6 +524,7 @@ bool set_file_times(const path& p, std::array<TimeSpec, 2> const& TS,
   return posix_utimensat(p, TS, ec);
 #endif
 }
+#endif /* !_LIBCPP_WIN32API */
 
 } // namespace
 } // end namespace detail
lib/libcxx/src/filesystem/operations.cpp
@@ -17,6 +17,8 @@
 
 #include "filesystem_common.h"
 
+#include "posix_compat.h"
+
 #if defined(_LIBCPP_WIN32API)
 # define WIN32_LEAN_AND_MEAN
 # define NOMINMAX
@@ -40,7 +42,7 @@
 # define _LIBCPP_FILESYSTEM_USE_FSTREAM
 #endif
 
-#if !defined(CLOCK_REALTIME)
+#if !defined(CLOCK_REALTIME) && !defined(_LIBCPP_WIN32API)
 # include <sys/time.h> // for gettimeofday and timeval
 #endif
 
@@ -62,6 +64,10 @@ bool isSeparator(path::value_type C) {
   return false;
 }
 
+bool isDriveLetter(path::value_type C) {
+  return (C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z');
+}
+
 namespace parser {
 
 using string_view_t = path::__string_view;
@@ -118,7 +124,13 @@ public:
 
     switch (State) {
     case PS_BeforeBegin: {
-      PosPtr TkEnd = consumeSeparator(Start, End);
+      PosPtr TkEnd = consumeRootName(Start, End);
+      if (TkEnd)
+        return makeState(PS_InRootName, Start, TkEnd);
+    }
+      _LIBCPP_FALLTHROUGH();
+    case PS_InRootName: {
+      PosPtr TkEnd = consumeAllSeparators(Start, End);
       if (TkEnd)
         return makeState(PS_InRootDir, Start, TkEnd);
       else
@@ -128,7 +140,7 @@ public:
       return makeState(PS_InFilenames, Start, consumeName(Start, End));
 
     case PS_InFilenames: {
-      PosPtr SepEnd = consumeSeparator(Start, End);
+      PosPtr SepEnd = consumeAllSeparators(Start, End);
       if (SepEnd != End) {
         PosPtr TkEnd = consumeName(SepEnd, End);
         if (TkEnd)
@@ -140,7 +152,6 @@ public:
     case PS_InTrailingSep:
       return makeState(PS_AtEnd);
 
-    case PS_InRootName:
     case PS_AtEnd:
       _LIBCPP_UNREACHABLE();
     }
@@ -155,12 +166,18 @@ public:
     switch (State) {
     case PS_AtEnd: {
       // Try to consume a trailing separator or root directory first.
-      if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
+      if (PosPtr SepEnd = consumeAllSeparators(RStart, REnd)) {
         if (SepEnd == REnd)
           return makeState(PS_InRootDir, Path.data(), RStart + 1);
+        PosPtr TkStart = consumeRootName(SepEnd, REnd);
+        if (TkStart == REnd)
+          return makeState(PS_InRootDir, RStart, RStart + 1);
         return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
       } else {
-        PosPtr TkStart = consumeName(RStart, REnd);
+        PosPtr TkStart = consumeRootName(RStart, REnd);
+        if (TkStart == REnd)
+          return makeState(PS_InRootName, TkStart + 1, RStart + 1);
+        TkStart = consumeName(RStart, REnd);
         return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
       }
     }
@@ -168,14 +185,20 @@ public:
       return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
                        RStart + 1);
     case PS_InFilenames: {
-      PosPtr SepEnd = consumeSeparator(RStart, REnd);
+      PosPtr SepEnd = consumeAllSeparators(RStart, REnd);
       if (SepEnd == REnd)
         return makeState(PS_InRootDir, Path.data(), RStart + 1);
-      PosPtr TkEnd = consumeName(SepEnd, REnd);
-      return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
+      PosPtr TkStart = consumeRootName(SepEnd ? SepEnd : RStart, REnd);
+      if (TkStart == REnd) {
+        if (SepEnd)
+          return makeState(PS_InRootDir, SepEnd + 1, RStart + 1);
+        return makeState(PS_InRootName, TkStart + 1, RStart + 1);
+      }
+      TkStart = consumeName(SepEnd, REnd);
+      return makeState(PS_InFilenames, TkStart + 1, SepEnd + 1);
     }
     case PS_InRootDir:
-      // return makeState(PS_InRootName, Path.data(), RStart + 1);
+      return makeState(PS_InRootName, Path.data(), RStart + 1);
     case PS_InRootName:
     case PS_BeforeBegin:
       _LIBCPP_UNREACHABLE();
@@ -281,8 +304,9 @@ private:
     _LIBCPP_UNREACHABLE();
   }
 
-  PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
-    if (P == End || !isSeparator(*P))
+  // Consume all consecutive separators.
+  PosPtr consumeAllSeparators(PosPtr P, PosPtr End) const noexcept {
+    if (P == nullptr || P == End || !isSeparator(*P))
       return nullptr;
     const int Inc = P < End ? 1 : -1;
     P += Inc;
@@ -291,15 +315,72 @@ private:
     return P;
   }
 
+  // Consume exactly N separators, or return nullptr.
+  PosPtr consumeNSeparators(PosPtr P, PosPtr End, int N) const noexcept {
+    PosPtr Ret = consumeAllSeparators(P, End);
+    if (Ret == nullptr)
+      return nullptr;
+    if (P < End) {
+      if (Ret == P + N)
+        return Ret;
+    } else {
+      if (Ret == P - N)
+        return Ret;
+    }
+    return nullptr;
+  }
+
   PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
-    if (P == End || isSeparator(*P))
+    PosPtr Start = P;
+    if (P == nullptr || P == End || isSeparator(*P))
       return nullptr;
     const int Inc = P < End ? 1 : -1;
     P += Inc;
     while (P != End && !isSeparator(*P))
       P += Inc;
+    if (P == End && Inc < 0) {
+      // Iterating backwards and consumed all the rest of the input.
+      // Check if the start of the string would have been considered
+      // a root name.
+      PosPtr RootEnd = consumeRootName(End + 1, Start);
+      if (RootEnd)
+        return RootEnd - 1;
+    }
     return P;
   }
+
+  PosPtr consumeDriveLetter(PosPtr P, PosPtr End) const noexcept {
+    if (P == End)
+      return nullptr;
+    if (P < End) {
+      if (P + 1 == End || !isDriveLetter(P[0]) || P[1] != ':')
+        return nullptr;
+      return P + 2;
+    } else {
+      if (P - 1 == End || !isDriveLetter(P[-1]) || P[0] != ':')
+        return nullptr;
+      return P - 2;
+    }
+  }
+
+  PosPtr consumeNetworkRoot(PosPtr P, PosPtr End) const noexcept {
+    if (P == End)
+      return nullptr;
+    if (P < End)
+      return consumeName(consumeNSeparators(P, End, 2), End);
+    else
+      return consumeNSeparators(consumeName(P, End), End, 2);
+  }
+
+  PosPtr consumeRootName(PosPtr P, PosPtr End) const noexcept {
+#if defined(_LIBCPP_WIN32API)
+    if (PosPtr Ret = consumeDriveLetter(P, End))
+      return Ret;
+    if (PosPtr Ret = consumeNetworkRoot(P, End))
+      return Ret;
+#endif
+    return nullptr;
+  }
 };
 
 string_view_pair separate_filename(string_view_t const& s) {
@@ -331,6 +412,7 @@ errc __win_err_to_errc(int err) {
       {ERROR_ACCESS_DENIED, errc::permission_denied},
       {ERROR_ALREADY_EXISTS, errc::file_exists},
       {ERROR_BAD_NETPATH, errc::no_such_file_or_directory},
+      {ERROR_BAD_PATHNAME, errc::no_such_file_or_directory},
       {ERROR_BAD_UNIT, errc::no_such_device},
       {ERROR_BROKEN_PIPE, errc::broken_pipe},
       {ERROR_BUFFER_OVERFLOW, errc::filename_too_long},
@@ -403,7 +485,7 @@ struct FileDescriptor {
   static FileDescriptor create(const path* p, error_code& ec, Args... args) {
     ec.clear();
     int fd;
-    if ((fd = ::open(p->c_str(), args...)) == -1) {
+    if ((fd = detail::open(p->c_str(), args...)) == -1) {
       ec = capture_errno();
       return FileDescriptor{p};
     }
@@ -429,7 +511,7 @@ struct FileDescriptor {
 
   void close() noexcept {
     if (fd != -1)
-      ::close(fd);
+      detail::close(fd);
     fd = -1;
   }
 
@@ -453,10 +535,6 @@ perms posix_get_perms(const StatT& st) noexcept {
   return static_cast<perms>(st.st_mode) & perms::mask;
 }
 
-::mode_t posix_convert_perms(perms prms) {
-  return static_cast< ::mode_t>(prms & perms::mask);
-}
-
 file_status create_file_status(error_code& m_ec, path const& p,
                                const StatT& path_stat, error_code* ec) {
   if (ec)
@@ -495,7 +573,7 @@ file_status create_file_status(error_code& m_ec, path const& p,
 
 file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
   error_code m_ec;
-  if (::stat(p.c_str(), &path_stat) == -1)
+  if (detail::stat(p.c_str(), &path_stat) == -1)
     m_ec = detail::capture_errno();
   return create_file_status(m_ec, p, path_stat, ec);
 }
@@ -507,7 +585,7 @@ file_status posix_stat(path const& p, error_code* ec) {
 
 file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
   error_code m_ec;
-  if (::lstat(p.c_str(), &path_stat) == -1)
+  if (detail::lstat(p.c_str(), &path_stat) == -1)
     m_ec = detail::capture_errno();
   return create_file_status(m_ec, p, path_stat, ec);
 }
@@ -519,7 +597,7 @@ file_status posix_lstat(path const& p, error_code* ec) {
 
 // http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
 bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
-  if (::ftruncate(fd.fd, to_size) == -1) {
+  if (detail::ftruncate(fd.fd, to_size) == -1) {
     ec = capture_errno();
     return true;
   }
@@ -528,7 +606,7 @@ bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
 }
 
 bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
-  if (::fchmod(fd.fd, st.st_mode) == -1) {
+  if (detail::fchmod(fd.fd, st.st_mode) == -1) {
     ec = capture_errno();
     return true;
   }
@@ -545,7 +623,7 @@ file_status FileDescriptor::refresh_status(error_code& ec) {
   m_status = file_status{};
   m_stat = {};
   error_code m_ec;
-  if (::fstat(fd, &m_stat) == -1)
+  if (detail::fstat(fd, &m_stat) == -1)
     m_ec = capture_errno();
   m_status = create_file_status(m_ec, name, m_stat, &ec);
   return m_status;
@@ -565,7 +643,14 @@ const bool _FilesystemClock::is_steady;
 
 _FilesystemClock::time_point _FilesystemClock::now() noexcept {
   typedef chrono::duration<rep> __secs;
-#if defined(CLOCK_REALTIME)
+#if defined(_LIBCPP_WIN32API)
+  typedef chrono::duration<rep, nano> __nsecs;
+  FILETIME time;
+  GetSystemTimeAsFileTime(&time);
+  TimeSpec tp = detail::filetime_to_timespec(time);
+  return time_point(__secs(tp.tv_sec) +
+                    chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
+#elif defined(CLOCK_REALTIME)
   typedef chrono::duration<rep, nano> __nsecs;
   struct timespec tp;
   if (0 != clock_gettime(CLOCK_REALTIME, &tp))
@@ -582,27 +667,20 @@ _FilesystemClock::time_point _FilesystemClock::now() noexcept {
 
 filesystem_error::~filesystem_error() {}
 
-#if defined(_LIBCPP_WIN32API)
-#define PS_FMT "%ls"
-#else
-#define PS_FMT "%s"
-#endif
-
 void filesystem_error::__create_what(int __num_paths) {
   const char* derived_what = system_error::what();
   __storage_->__what_ = [&]() -> string {
-    const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str();
-    const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str();
     switch (__num_paths) {
-    default:
+    case 0:
       return detail::format_string("filesystem error: %s", derived_what);
     case 1:
-      return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what,
-                                   p1);
+      return detail::format_string("filesystem error: %s [" PATH_CSTR_FMT "]",
+                                   derived_what, path1().c_str());
     case 2:
-      return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]",
-                                   derived_what, p1, p2);
+      return detail::format_string("filesystem error: %s [" PATH_CSTR_FMT "] [" PATH_CSTR_FMT "]",
+                                   derived_what, path1().c_str(), path2().c_str());
     }
+    _LIBCPP_UNREACHABLE();
   }();
 }
 
@@ -627,20 +705,20 @@ path __canonical(path const& orig_p, error_code* ec) {
   ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
 
   path p = __do_absolute(orig_p, &cwd, ec);
-#if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112
-  std::unique_ptr<char, decltype(&::free)>
-    hold(::realpath(p.c_str(), nullptr), &::free);
+#if (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112) || defined(_LIBCPP_WIN32API)
+  std::unique_ptr<path::value_type, decltype(&::free)>
+    hold(detail::realpath(p.c_str(), nullptr), &::free);
   if (hold.get() == nullptr)
     return err.report(capture_errno());
   return {hold.get()};
 #else
   #if defined(__MVS__) && !defined(PATH_MAX)
-    char buff[ _XOPEN_PATH_MAX + 1 ];
+    path::value_type buff[ _XOPEN_PATH_MAX + 1 ];
   #else
-    char buff[PATH_MAX + 1];
+    path::value_type buff[PATH_MAX + 1];
   #endif
-  char* ret;
-  if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
+  path::value_type* ret;
+  if ((ret = detail::realpath(p.c_str(), buff)) == nullptr)
     return err.report(capture_errno());
   return {ret};
 #endif
@@ -819,8 +897,8 @@ bool __copy_file(const path& from, const path& to, copy_options options,
   ErrorHandler<bool> err("copy_file", ec, &to, &from);
 
   error_code m_ec;
-  FileDescriptor from_fd =
-      FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
+  FileDescriptor from_fd = FileDescriptor::create_with_status(
+      &from, m_ec, O_RDONLY | O_NONBLOCK | O_BINARY);
   if (m_ec)
     return err.report(m_ec);
 
@@ -872,7 +950,7 @@ bool __copy_file(const path& from, const path& to, copy_options options,
 
   // Don't truncate right away. We may not be opening the file we originally
   // looked at; we'll check this later.
-  int to_open_flags = O_WRONLY;
+  int to_open_flags = O_WRONLY | O_BINARY;
   if (!to_exists)
     to_open_flags |= O_CREAT;
   FileDescriptor to_fd = FileDescriptor::create_with_status(
@@ -908,10 +986,13 @@ void __copy_symlink(const path& existing_symlink, const path& new_symlink,
   if (ec && *ec) {
     return;
   }
-  // NOTE: proposal says you should detect if you should call
-  // create_symlink or create_directory_symlink. I don't think this
-  // is needed with POSIX
-  __create_symlink(real_path, new_symlink, ec);
+#if defined(_LIBCPP_WIN32API)
+  error_code local_ec;
+  if (is_directory(real_path, local_ec))
+    __create_directory_symlink(real_path, new_symlink, ec);
+  else
+#endif
+    __create_symlink(real_path, new_symlink, ec);
 }
 
 bool __create_directories(const path& p, error_code* ec) {
@@ -932,31 +1013,34 @@ bool __create_directories(const path& p, error_code* ec) {
     if (not status_known(parent_st))
       return err.report(m_ec);
     if (not exists(parent_st)) {
+      if (parent == p)
+        return err.report(errc::invalid_argument);
       __create_directories(parent, ec);
       if (ec && *ec) {
         return false;
       }
-    }
+    } else if (not is_directory(parent_st))
+      return err.report(errc::not_a_directory);
   }
-  return __create_directory(p, ec);
+  bool ret = __create_directory(p, &m_ec);
+  if (m_ec)
+    return err.report(m_ec);
+  return ret;
 }
 
 bool __create_directory(const path& p, error_code* ec) {
   ErrorHandler<bool> err("create_directory", ec, &p);
 
-  if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
+  if (detail::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
     return true;
 
-  if (errno == EEXIST) {
-    error_code mec = capture_errno();
-    error_code ignored_ec;
-    const file_status st = status(p, ignored_ec);
-    if (!is_directory(st)) {
-      err.report(mec);
-    }
-  } else {
-    err.report(capture_errno());
-  }
+  if (errno != EEXIST)
+    return err.report(capture_errno());
+  error_code mec = capture_errno();
+  error_code ignored_ec;
+  const file_status st = status(p, ignored_ec);
+  if (!is_directory(st))
+    return err.report(mec);
   return false;
 }
 
@@ -965,65 +1049,80 @@ bool __create_directory(path const& p, path const& attributes, error_code* ec) {
 
   StatT attr_stat;
   error_code mec;
-  auto st = detail::posix_stat(attributes, attr_stat, &mec);
+  file_status st = detail::posix_stat(attributes, attr_stat, &mec);
   if (!status_known(st))
     return err.report(mec);
   if (!is_directory(st))
     return err.report(errc::not_a_directory,
                       "the specified attribute path is invalid");
 
-  if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
+  if (detail::mkdir(p.c_str(), attr_stat.st_mode) == 0)
     return true;
 
-  if (errno == EEXIST) {
-    error_code mec = capture_errno();
-    error_code ignored_ec;
-    const file_status st = status(p, ignored_ec);
-    if (!is_directory(st)) {
-      err.report(mec);
-    }
-  } else {
-    err.report(capture_errno());
-  }
+  if (errno != EEXIST)
+    return err.report(capture_errno());
+
+  mec = capture_errno();
+  error_code ignored_ec;
+  st = status(p, ignored_ec);
+  if (!is_directory(st))
+    return err.report(mec);
   return false;
 }
 
 void __create_directory_symlink(path const& from, path const& to,
                                 error_code* ec) {
   ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
-  if (::symlink(from.c_str(), to.c_str()) != 0)
+  if (detail::symlink_dir(from.c_str(), to.c_str()) == -1)
     return err.report(capture_errno());
 }
 
 void __create_hard_link(const path& from, const path& to, error_code* ec) {
   ErrorHandler<void> err("create_hard_link", ec, &from, &to);
-  if (::link(from.c_str(), to.c_str()) == -1)
+  if (detail::link(from.c_str(), to.c_str()) == -1)
     return err.report(capture_errno());
 }
 
 void __create_symlink(path const& from, path const& to, error_code* ec) {
   ErrorHandler<void> err("create_symlink", ec, &from, &to);
-  if (::symlink(from.c_str(), to.c_str()) == -1)
+  if (detail::symlink_file(from.c_str(), to.c_str()) == -1)
     return err.report(capture_errno());
 }
 
 path __current_path(error_code* ec) {
   ErrorHandler<path> err("current_path", ec);
 
+#if defined(_LIBCPP_WIN32API) || defined(__GLIBC__) || defined(__APPLE__)
+  // Common extension outside of POSIX getcwd() spec, without needing to
+  // preallocate a buffer. Also supported by a number of other POSIX libcs.
+  int size = 0;
+  path::value_type* ptr = nullptr;
+  typedef decltype(&::free) Deleter;
+  Deleter deleter = &::free;
+#else
   auto size = ::pathconf(".", _PC_PATH_MAX);
   _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
 
-  auto buff = unique_ptr<char[]>(new char[size + 1]);
-  char* ret;
-  if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
+  auto buff = unique_ptr<path::value_type[]>(new path::value_type[size + 1]);
+  path::value_type* ptr = buff.get();
+
+  // Preallocated buffer, don't free the buffer in the second unique_ptr
+  // below.
+  struct Deleter { void operator()(void*) const {} };
+  Deleter deleter;
+#endif
+
+  unique_ptr<path::value_type, Deleter> hold(detail::getcwd(ptr, size),
+                                             deleter);
+  if (hold.get() == nullptr)
     return err.report(capture_errno(), "call to getcwd failed");
 
-  return {buff.get()};
+  return {hold.get()};
 }
 
 void __current_path(const path& p, error_code* ec) {
   ErrorHandler<void> err("current_path", ec, &p);
-  if (::chdir(p.c_str()) == -1)
+  if (detail::chdir(p.c_str()) == -1)
     err.report(capture_errno());
 }
 
@@ -1119,6 +1218,17 @@ void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
   using detail::fs_time;
   ErrorHandler<void> err("last_write_time", ec, &p);
 
+#if defined(_LIBCPP_WIN32API)
+  TimeSpec ts;
+  if (!fs_time::convert_to_timespec(ts, new_time))
+    return err.report(errc::value_too_large);
+  detail::WinHandle h(p.c_str(), FILE_WRITE_ATTRIBUTES, 0);
+  if (!h)
+    return err.report(detail::make_windows_error(GetLastError()));
+  FILETIME last_write = timespec_to_filetime(ts);
+  if (!SetFileTime(h, nullptr, nullptr, &last_write))
+    return err.report(detail::make_windows_error(GetLastError()));
+#else
   error_code m_ec;
   array<TimeSpec, 2> tbuf;
 #if !defined(_LIBCPP_USE_UTIMENSAT)
@@ -1140,6 +1250,7 @@ void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
   detail::set_file_times(p, tbuf, m_ec);
   if (m_ec)
     return err.report(m_ec);
+#endif
 }
 
 void __permissions(const path& p, perms prms, perm_options opts,
@@ -1171,11 +1282,11 @@ void __permissions(const path& p, perms prms, perm_options opts,
     else if (remove_perms)
       prms = st.permissions() & ~prms;
   }
-  const auto real_perms = detail::posix_convert_perms(prms);
+  const auto real_perms = static_cast<detail::ModeT>(prms & perms::mask);
 
 #if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
   const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
-  if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
+  if (detail::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
     return err.report(capture_errno());
   }
 #else
@@ -1190,21 +1301,25 @@ void __permissions(const path& p, perms prms, perm_options opts,
 path __read_symlink(const path& p, error_code* ec) {
   ErrorHandler<path> err("read_symlink", ec, &p);
 
-#ifdef PATH_MAX
+#if defined(PATH_MAX) || defined(MAX_SYMLINK_SIZE)
   struct NullDeleter { void operator()(void*) const {} };
+#ifdef MAX_SYMLINK_SIZE
+  const size_t size = MAX_SYMLINK_SIZE + 1;
+#else
   const size_t size = PATH_MAX + 1;
-  char stack_buff[size];
-  auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
+#endif
+  path::value_type stack_buff[size];
+  auto buff = std::unique_ptr<path::value_type[], NullDeleter>(stack_buff);
 #else
   StatT sb;
-  if (::lstat(p.c_str(), &sb) == -1) {
+  if (detail::lstat(p.c_str(), &sb) == -1) {
     return err.report(capture_errno());
   }
   const size_t size = sb.st_size + 1;
-  auto buff = unique_ptr<char[]>(new char[size]);
+  auto buff = unique_ptr<path::value_type[]>(new path::value_type[size]);
 #endif
-  ::ssize_t ret;
-  if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
+  detail::SSizeT ret;
+  if ((ret = detail::readlink(p.c_str(), buff.get(), size)) == -1)
     return err.report(capture_errno());
   _LIBCPP_ASSERT(ret > 0, "TODO");
   if (static_cast<size_t>(ret) >= size)
@@ -1215,7 +1330,7 @@ path __read_symlink(const path& p, error_code* ec) {
 
 bool __remove(const path& p, error_code* ec) {
   ErrorHandler<bool> err("remove", ec, &p);
-  if (::remove(p.c_str()) == -1) {
+  if (detail::remove(p.c_str()) == -1) {
     if (errno != ENOENT)
       err.report(capture_errno());
     return false;
@@ -1264,21 +1379,21 @@ uintmax_t __remove_all(const path& p, error_code* ec) {
 
 void __rename(const path& from, const path& to, error_code* ec) {
   ErrorHandler<void> err("rename", ec, &from, &to);
-  if (::rename(from.c_str(), to.c_str()) == -1)
+  if (detail::rename(from.c_str(), to.c_str()) == -1)
     err.report(capture_errno());
 }
 
 void __resize_file(const path& p, uintmax_t size, error_code* ec) {
   ErrorHandler<void> err("resize_file", ec, &p);
-  if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
+  if (detail::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
     return err.report(capture_errno());
 }
 
 space_info __space(const path& p, error_code* ec) {
   ErrorHandler<void> err("space", ec, &p);
   space_info si;
-  struct statvfs m_svfs = {};
-  if (::statvfs(p.c_str(), &m_svfs) == -1) {
+  detail::StatVFS m_svfs = {};
+  if (detail::statvfs(p.c_str(), &m_svfs) == -1) {
     err.report(capture_errno());
     si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
     return si;
@@ -1306,6 +1421,19 @@ file_status __symlink_status(const path& p, error_code* ec) {
 path __temp_directory_path(error_code* ec) {
   ErrorHandler<path> err("temp_directory_path", ec);
 
+#if defined(_LIBCPP_WIN32API)
+  wchar_t buf[MAX_PATH];
+  DWORD retval = GetTempPathW(MAX_PATH, buf);
+  if (!retval)
+    return err.report(detail::make_windows_error(GetLastError()));
+  if (retval > MAX_PATH)
+    return err.report(errc::filename_too_long);
+  // GetTempPathW returns a path with a trailing slash, which we
+  // shouldn't include for consistency.
+  if (buf[retval-1] == L'\\')
+    buf[retval-1] = L'\0';
+  path p(buf);
+#else
   const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
   const char* ret = nullptr;
 
@@ -1316,14 +1444,15 @@ path __temp_directory_path(error_code* ec) {
     ret = "/tmp";
 
   path p(ret);
+#endif
   error_code m_ec;
   file_status st = detail::posix_stat(p, &m_ec);
   if (!status_known(st))
-    return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p);
+    return err.report(m_ec, "cannot access path " PATH_CSTR_FMT, p.c_str());
 
   if (!exists(st) || !is_directory(st))
-    return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory",
-                      p);
+    return err.report(errc::not_a_directory,
+                      "path " PATH_CSTR_FMT " is not a directory", p.c_str());
 
   return p;
 }
@@ -1586,6 +1715,7 @@ path path::lexically_normal() const {
   if (NeedTrailingSep)
     Result /= PS("");
 
+  Result.make_preferred();
   return Result;
 }
 
@@ -1806,7 +1936,6 @@ size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) {
 //                           directory entry definitions
 ///////////////////////////////////////////////////////////////////////////////
 
-#ifndef _LIBCPP_WIN32API
 error_code directory_entry::__do_refresh() noexcept {
   __data_.__reset();
   error_code failure_ec;
@@ -1860,47 +1989,5 @@ error_code directory_entry::__do_refresh() noexcept {
 
   return failure_ec;
 }
-#else
-error_code directory_entry::__do_refresh() noexcept {
-  __data_.__reset();
-  error_code failure_ec;
-
-  file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
-  if (!status_known(st)) {
-    __data_.__reset();
-    return failure_ec;
-  }
-
-  if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
-    __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
-    __data_.__type_ = st.type();
-    __data_.__non_sym_perms_ = st.permissions();
-  } else { // we have a symlink
-    __data_.__sym_perms_ = st.permissions();
-    // Get the information about the linked entity.
-    // Ignore errors from stat, since we don't want errors regarding symlink
-    // resolution to be reported to the user.
-    error_code ignored_ec;
-    st = _VSTD_FS::status(__p_, ignored_ec);
-
-    __data_.__type_ = st.type();
-    __data_.__non_sym_perms_ = st.permissions();
-
-    // If we failed to resolve the link, then only partially populate the
-    // cache.
-    if (!status_known(st)) {
-      __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
-      return error_code{};
-    }
-    __data_.__cache_type_ = directory_entry::_RefreshSymlink;
-  }
-
-  // FIXME: This is currently broken, and the implementation only a placeholder.
-  // We need to cache last_write_time, file_size, and hard_link_count here before
-  // the implementation actually works.
-
-  return failure_ec;
-}
-#endif
 
 _LIBCPP_END_NAMESPACE_FILESYSTEM
lib/libcxx/src/filesystem/posix_compat.h
@@ -0,0 +1,521 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+//
+// POSIX-like portability helper functions.
+//
+// These generally behave like the proper posix functions, with these
+// exceptions:
+// On Windows, they take paths in wchar_t* form, instead of char* form.
+// The symlink() function is split into two frontends, symlink_file()
+// and symlink_dir().
+//
+// These are provided within an anonymous namespace within the detail
+// namespace - callers need to include this header and call them as
+// detail::function(), regardless of platform.
+//
+
+#ifndef POSIX_COMPAT_H
+#define POSIX_COMPAT_H
+
+#include "filesystem"
+
+#include "filesystem_common.h"
+
+#if defined(_LIBCPP_WIN32API)
+# define WIN32_LEAN_AND_MEAN
+# define NOMINMAX
+# include <windows.h>
+# include <io.h>
+# include <winioctl.h>
+#else
+# include <unistd.h>
+# include <sys/stat.h>
+# include <sys/statvfs.h>
+#endif
+#include <time.h>
+
+#if defined(_LIBCPP_WIN32API)
+// This struct isn't defined in the normal Windows SDK, but only in the
+// Windows Driver Kit.
+struct LIBCPP_REPARSE_DATA_BUFFER {
+  unsigned long  ReparseTag;
+  unsigned short ReparseDataLength;
+  unsigned short Reserved;
+  union {
+    struct {
+      unsigned short SubstituteNameOffset;
+      unsigned short SubstituteNameLength;
+      unsigned short PrintNameOffset;
+      unsigned short PrintNameLength;
+      unsigned long  Flags;
+      wchar_t        PathBuffer[1];
+    } SymbolicLinkReparseBuffer;
+    struct {
+      unsigned short SubstituteNameOffset;
+      unsigned short SubstituteNameLength;
+      unsigned short PrintNameOffset;
+      unsigned short PrintNameLength;
+      wchar_t        PathBuffer[1];
+    } MountPointReparseBuffer;
+    struct {
+      unsigned char DataBuffer[1];
+    } GenericReparseBuffer;
+  };
+};
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
+
+namespace detail {
+namespace {
+
+#if defined(_LIBCPP_WIN32API)
+
+// Various C runtime header sets provide more or less of these. As we
+// provide our own implementation, undef all potential defines from the
+// C runtime headers and provide a complete set of macros of our own.
+
+#undef _S_IFMT
+#undef _S_IFDIR
+#undef _S_IFCHR
+#undef _S_IFIFO
+#undef _S_IFREG
+#undef _S_IFBLK
+#undef _S_IFLNK
+#undef _S_IFSOCK
+
+#define _S_IFMT   0xF000
+#define _S_IFDIR  0x4000
+#define _S_IFCHR  0x2000
+#define _S_IFIFO  0x1000
+#define _S_IFREG  0x8000
+#define _S_IFBLK  0x6000
+#define _S_IFLNK  0xA000
+#define _S_IFSOCK 0xC000
+
+#undef S_ISDIR
+#undef S_ISFIFO
+#undef S_ISCHR
+#undef S_ISREG
+#undef S_ISLNK
+#undef S_ISBLK
+#undef S_ISSOCK
+
+#define S_ISDIR(m)      (((m) & _S_IFMT) == _S_IFDIR)
+#define S_ISCHR(m)      (((m) & _S_IFMT) == _S_IFCHR)
+#define S_ISFIFO(m)     (((m) & _S_IFMT) == _S_IFIFO)
+#define S_ISREG(m)      (((m) & _S_IFMT) == _S_IFREG)
+#define S_ISBLK(m)      (((m) & _S_IFMT) == _S_IFBLK)
+#define S_ISLNK(m)      (((m) & _S_IFMT) == _S_IFLNK)
+#define S_ISSOCK(m)     (((m) & _S_IFMT) == _S_IFSOCK)
+
+#define O_NONBLOCK 0
+
+
+// There were 369 years and 89 leap days from the Windows epoch
+// (1601) to the Unix epoch (1970).
+#define FILE_TIME_OFFSET_SECS (uint64_t(369 * 365 + 89) * (24 * 60 * 60))
+
+TimeSpec filetime_to_timespec(LARGE_INTEGER li) {
+  TimeSpec ret;
+  ret.tv_sec = li.QuadPart / 10000000 - FILE_TIME_OFFSET_SECS;
+  ret.tv_nsec = (li.QuadPart % 10000000) * 100;
+  return ret;
+}
+
+TimeSpec filetime_to_timespec(FILETIME ft) {
+  LARGE_INTEGER li;
+  li.LowPart = ft.dwLowDateTime;
+  li.HighPart = ft.dwHighDateTime;
+  return filetime_to_timespec(li);
+}
+
+FILETIME timespec_to_filetime(TimeSpec ts) {
+  LARGE_INTEGER li;
+  li.QuadPart =
+      ts.tv_nsec / 100 + (ts.tv_sec + FILE_TIME_OFFSET_SECS) * 10000000;
+  FILETIME ft;
+  ft.dwLowDateTime = li.LowPart;
+  ft.dwHighDateTime = li.HighPart;
+  return ft;
+}
+
+int set_errno(int e = GetLastError()) {
+  errno = static_cast<int>(__win_err_to_errc(e));
+  return -1;
+}
+
+class WinHandle {
+public:
+  WinHandle(const wchar_t *p, DWORD access, DWORD flags) {
+    h = CreateFileW(
+        p, access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+        nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | flags, nullptr);
+  }
+  ~WinHandle() {
+    if (h != INVALID_HANDLE_VALUE)
+      CloseHandle(h);
+  }
+  operator HANDLE() const { return h; }
+  operator bool() const { return h != INVALID_HANDLE_VALUE; }
+
+private:
+  HANDLE h;
+};
+
+int stat_handle(HANDLE h, StatT *buf) {
+  FILE_BASIC_INFO basic;
+  if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic)))
+    return set_errno();
+  memset(buf, 0, sizeof(*buf));
+  buf->st_mtim = filetime_to_timespec(basic.LastWriteTime);
+  buf->st_atim = filetime_to_timespec(basic.LastAccessTime);
+  buf->st_mode = 0555; // Read-only
+  if (!(basic.FileAttributes & FILE_ATTRIBUTE_READONLY))
+    buf->st_mode |= 0222; // Write
+  if (basic.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
+    buf->st_mode |= _S_IFDIR;
+  } else {
+    buf->st_mode |= _S_IFREG;
+  }
+  if (basic.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+    FILE_ATTRIBUTE_TAG_INFO tag;
+    if (!GetFileInformationByHandleEx(h, FileAttributeTagInfo, &tag,
+                                      sizeof(tag)))
+      return set_errno();
+    if (tag.ReparseTag == IO_REPARSE_TAG_SYMLINK)
+      buf->st_mode = (buf->st_mode & ~_S_IFMT) | _S_IFLNK;
+  }
+  FILE_STANDARD_INFO standard;
+  if (!GetFileInformationByHandleEx(h, FileStandardInfo, &standard,
+                                    sizeof(standard)))
+    return set_errno();
+  buf->st_nlink = standard.NumberOfLinks;
+  buf->st_size = standard.EndOfFile.QuadPart;
+  BY_HANDLE_FILE_INFORMATION info;
+  if (!GetFileInformationByHandle(h, &info))
+    return set_errno();
+  buf->st_dev = info.dwVolumeSerialNumber;
+  memcpy(&buf->st_ino.id[0], &info.nFileIndexHigh, 4);
+  memcpy(&buf->st_ino.id[4], &info.nFileIndexLow, 4);
+  return 0;
+}
+
+int stat_file(const wchar_t *path, StatT *buf, DWORD flags) {
+  WinHandle h(path, FILE_READ_ATTRIBUTES, flags);
+  if (!h)
+    return set_errno();
+  int ret = stat_handle(h, buf);
+  return ret;
+}
+
+int stat(const wchar_t *path, StatT *buf) { return stat_file(path, buf, 0); }
+
+int lstat(const wchar_t *path, StatT *buf) {
+  return stat_file(path, buf, FILE_FLAG_OPEN_REPARSE_POINT);
+}
+
+int fstat(int fd, StatT *buf) {
+  HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
+  return stat_handle(h, buf);
+}
+
+int mkdir(const wchar_t *path, int permissions) {
+  (void)permissions;
+  return _wmkdir(path);
+}
+
+int symlink_file_dir(const wchar_t *oldname, const wchar_t *newname,
+                     bool is_dir) {
+  path dest(oldname);
+  dest.make_preferred();
+  oldname = dest.c_str();
+  DWORD flags = is_dir ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0;
+  if (CreateSymbolicLinkW(newname, oldname,
+                          flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE))
+    return 0;
+  int e = GetLastError();
+  if (e != ERROR_INVALID_PARAMETER)
+    return set_errno(e);
+  if (CreateSymbolicLinkW(newname, oldname, flags))
+    return 0;
+  return set_errno();
+}
+
+int symlink_file(const wchar_t *oldname, const wchar_t *newname) {
+  return symlink_file_dir(oldname, newname, false);
+}
+
+int symlink_dir(const wchar_t *oldname, const wchar_t *newname) {
+  return symlink_file_dir(oldname, newname, true);
+}
+
+int link(const wchar_t *oldname, const wchar_t *newname) {
+  if (CreateHardLinkW(newname, oldname, nullptr))
+    return 0;
+  return set_errno();
+}
+
+int remove(const wchar_t *path) {
+  detail::WinHandle h(path, DELETE, FILE_FLAG_OPEN_REPARSE_POINT);
+  if (!h)
+    return set_errno();
+  FILE_DISPOSITION_INFO info;
+  info.DeleteFile = TRUE;
+  if (!SetFileInformationByHandle(h, FileDispositionInfo, &info, sizeof(info)))
+    return set_errno();
+  return 0;
+}
+
+int truncate_handle(HANDLE h, off_t length) {
+  LARGE_INTEGER size_param;
+  size_param.QuadPart = length;
+  if (!SetFilePointerEx(h, size_param, 0, FILE_BEGIN))
+    return set_errno();
+  if (!SetEndOfFile(h))
+    return set_errno();
+  return 0;
+}
+
+int ftruncate(int fd, off_t length) {
+  HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
+  return truncate_handle(h, length);
+}
+
+int truncate(const wchar_t *path, off_t length) {
+  detail::WinHandle h(path, GENERIC_WRITE, 0);
+  if (!h)
+    return set_errno();
+  return truncate_handle(h, length);
+}
+
+int rename(const wchar_t *from, const wchar_t *to) {
+  if (!(MoveFileExW(from, to,
+                    MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING |
+                        MOVEFILE_WRITE_THROUGH)))
+    return set_errno();
+  return 0;
+}
+
+template <class... Args> int open(const wchar_t *filename, Args... args) {
+  return _wopen(filename, args...);
+}
+int close(int fd) { return _close(fd); }
+int chdir(const wchar_t *path) { return _wchdir(path); }
+
+struct StatVFS {
+  uint64_t f_frsize;
+  uint64_t f_blocks;
+  uint64_t f_bfree;
+  uint64_t f_bavail;
+};
+
+int statvfs(const wchar_t *p, StatVFS *buf) {
+  path dir = p;
+  while (true) {
+    error_code local_ec;
+    const file_status st = status(dir, local_ec);
+    if (!exists(st) || is_directory(st))
+      break;
+    path parent = dir.parent_path();
+    if (parent == dir) {
+      errno = ENOENT;
+      return -1;
+    }
+    dir = parent;
+  }
+  ULARGE_INTEGER free_bytes_available_to_caller, total_number_of_bytes,
+      total_number_of_free_bytes;
+  if (!GetDiskFreeSpaceExW(dir.c_str(), &free_bytes_available_to_caller,
+                           &total_number_of_bytes, &total_number_of_free_bytes))
+    return set_errno();
+  buf->f_frsize = 1;
+  buf->f_blocks = total_number_of_bytes.QuadPart;
+  buf->f_bfree = total_number_of_free_bytes.QuadPart;
+  buf->f_bavail = free_bytes_available_to_caller.QuadPart;
+  return 0;
+}
+
+wchar_t *getcwd(wchar_t *buff, size_t size) { return _wgetcwd(buff, size); }
+
+wchar_t *realpath(const wchar_t *path, wchar_t *resolved_name) {
+  // Only expected to be used with us allocating the buffer.
+  _LIBCPP_ASSERT(resolved_name == nullptr,
+                 "Windows realpath() assumes a null resolved_name");
+
+  WinHandle h(path, FILE_READ_ATTRIBUTES, 0);
+  if (!h) {
+    set_errno();
+    return nullptr;
+  }
+  size_t buff_size = MAX_PATH + 10;
+  std::unique_ptr<wchar_t, decltype(&::free)> buff(
+      static_cast<wchar_t *>(malloc(buff_size * sizeof(wchar_t))), &::free);
+  DWORD retval = GetFinalPathNameByHandleW(
+      h, buff.get(), buff_size, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
+  if (retval > buff_size) {
+    buff_size = retval;
+    buff.reset(static_cast<wchar_t *>(malloc(buff_size * sizeof(wchar_t))));
+    retval = GetFinalPathNameByHandleW(h, buff.get(), buff_size,
+                                       FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
+  }
+  if (!retval) {
+    set_errno();
+    return nullptr;
+  }
+  wchar_t *ptr = buff.get();
+  if (!wcsncmp(ptr, L"\\\\?\\", 4)) {
+    if (ptr[5] == ':') { // \\?\X: -> X:
+      memmove(&ptr[0], &ptr[4], (wcslen(&ptr[4]) + 1) * sizeof(wchar_t));
+    } else if (!wcsncmp(&ptr[4], L"UNC\\", 4)) { // \\?\UNC\server -> \\server
+      wcscpy(&ptr[0], L"\\\\");
+      memmove(&ptr[2], &ptr[8], (wcslen(&ptr[8]) + 1) * sizeof(wchar_t));
+    }
+  }
+  return buff.release();
+}
+
+#define AT_FDCWD -1
+#define AT_SYMLINK_NOFOLLOW 1
+using ModeT = int;
+
+int fchmod_handle(HANDLE h, int perms) {
+  FILE_BASIC_INFO basic;
+  if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic)))
+    return set_errno();
+  DWORD orig_attributes = basic.FileAttributes;
+  basic.FileAttributes &= ~FILE_ATTRIBUTE_READONLY;
+  if ((perms & 0222) == 0)
+    basic.FileAttributes |= FILE_ATTRIBUTE_READONLY;
+  if (basic.FileAttributes != orig_attributes &&
+      !SetFileInformationByHandle(h, FileBasicInfo, &basic, sizeof(basic)))
+    return set_errno();
+  return 0;
+}
+
+int fchmodat(int fd, const wchar_t *path, int perms, int flag) {
+  DWORD attributes = GetFileAttributesW(path);
+  if (attributes == INVALID_FILE_ATTRIBUTES)
+    return set_errno();
+  if (attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
+      !(flag & AT_SYMLINK_NOFOLLOW)) {
+    // If the file is a symlink, and we are supposed to operate on the target
+    // of the symlink, we need to open a handle to it, without the
+    // FILE_FLAG_OPEN_REPARSE_POINT flag, to open the destination of the
+    // symlink, and operate on it via the handle.
+    detail::WinHandle h(path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, 0);
+    if (!h)
+      return set_errno();
+    return fchmod_handle(h, perms);
+  } else {
+    // For a non-symlink, or if operating on the symlink itself instead of
+    // its target, we can use SetFileAttributesW, saving a few calls.
+    DWORD orig_attributes = attributes;
+    attributes &= ~FILE_ATTRIBUTE_READONLY;
+    if ((perms & 0222) == 0)
+      attributes |= FILE_ATTRIBUTE_READONLY;
+    if (attributes != orig_attributes && !SetFileAttributesW(path, attributes))
+      return set_errno();
+  }
+  return 0;
+}
+
+int fchmod(int fd, int perms) {
+  HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
+  return fchmod_handle(h, perms);
+}
+
+#define MAX_SYMLINK_SIZE MAXIMUM_REPARSE_DATA_BUFFER_SIZE
+using SSizeT = ::int64_t;
+
+SSizeT readlink(const wchar_t *path, wchar_t *ret_buf, size_t bufsize) {
+  uint8_t buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+  detail::WinHandle h(path, FILE_READ_ATTRIBUTES, FILE_FLAG_OPEN_REPARSE_POINT);
+  if (!h)
+    return set_errno();
+  DWORD out;
+  if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, nullptr, 0, buf, sizeof(buf),
+                       &out, 0))
+    return set_errno();
+  const auto *reparse = reinterpret_cast<LIBCPP_REPARSE_DATA_BUFFER *>(buf);
+  size_t path_buf_offset = offsetof(LIBCPP_REPARSE_DATA_BUFFER,
+                                    SymbolicLinkReparseBuffer.PathBuffer[0]);
+  if (out < path_buf_offset) {
+    errno = EINVAL;
+    return -1;
+  }
+  if (reparse->ReparseTag != IO_REPARSE_TAG_SYMLINK) {
+    errno = EINVAL;
+    return -1;
+  }
+  const auto &symlink = reparse->SymbolicLinkReparseBuffer;
+  unsigned short name_offset, name_length;
+  if (symlink.PrintNameLength == 0) {
+    name_offset = symlink.SubstituteNameOffset;
+    name_length = symlink.SubstituteNameLength;
+  } else {
+    name_offset = symlink.PrintNameOffset;
+    name_length = symlink.PrintNameLength;
+  }
+  // name_offset/length are expressed in bytes, not in wchar_t
+  if (path_buf_offset + name_offset + name_length > out) {
+    errno = EINVAL;
+    return -1;
+  }
+  if (name_length / sizeof(wchar_t) > bufsize) {
+    errno = ENOMEM;
+    return -1;
+  }
+  memcpy(ret_buf, &symlink.PathBuffer[name_offset / sizeof(wchar_t)],
+         name_length);
+  return name_length / sizeof(wchar_t);
+}
+
+#else
+int symlink_file(const char *oldname, const char *newname) {
+  return ::symlink(oldname, newname);
+}
+int symlink_dir(const char *oldname, const char *newname) {
+  return ::symlink(oldname, newname);
+}
+using ::chdir;
+using ::close;
+using ::fchmod;
+#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
+using ::fchmodat;
+#endif
+using ::fstat;
+using ::ftruncate;
+using ::getcwd;
+using ::link;
+using ::lstat;
+using ::mkdir;
+using ::open;
+using ::readlink;
+using ::realpath;
+using ::remove;
+using ::rename;
+using ::stat;
+using ::statvfs;
+using ::truncate;
+
+#define O_BINARY 0
+
+using StatVFS = struct statvfs;
+using ModeT = ::mode_t;
+using SSizeT = ::ssize_t;
+
+#endif
+
+} // namespace
+} // end namespace detail
+
+_LIBCPP_END_NAMESPACE_FILESYSTEM
+
+#endif // POSIX_COMPAT_H
lib/libcxx/src/include/config_elast.h
@@ -35,8 +35,12 @@
 // No _LIBCPP_ELAST needed on Apple
 #elif defined(__sun__)
 #define _LIBCPP_ELAST ESTALE
+#elif defined(__MVS__)
+#define _LIBCPP_ELAST 1160
 #elif defined(_LIBCPP_MSVCRT_LIKE)
 #define _LIBCPP_ELAST (_sys_nerr - 1)
+#elif defined(_AIX)
+#define _LIBCPP_ELAST 127
 #else
 // Warn here so that the person doing the libcxx port has an easier time:
 #warning ELAST for this platform not yet implemented
lib/libcxx/src/include/refstring.h
@@ -55,7 +55,7 @@ inline char * data_from_rep(_Rep_base *rep) noexcept {
 
 #if defined(_LIBCPP_CHECK_FOR_GCC_EMPTY_STRING_STORAGE)
 inline
-const char* compute_gcc_empty_string_storage() _NOEXCEPT
+const char* compute_gcc_empty_string_storage() noexcept
 {
     void* handle = dlopen("/usr/lib/libstdc++.6.dylib", RTLD_NOLOAD);
     if (handle == nullptr)
@@ -68,7 +68,7 @@ const char* compute_gcc_empty_string_storage() _NOEXCEPT
 
 inline
 const char*
-get_gcc_empty_string_storage() _NOEXCEPT
+get_gcc_empty_string_storage() noexcept
 {
     static const char* p = compute_gcc_empty_string_storage();
     return p;
@@ -92,7 +92,7 @@ __libcpp_refstring::__libcpp_refstring(const char* msg) {
 }
 
 inline
-__libcpp_refstring::__libcpp_refstring(const __libcpp_refstring &s) _NOEXCEPT
+__libcpp_refstring::__libcpp_refstring(const __libcpp_refstring &s) noexcept
     : __imp_(s.__imp_)
 {
     if (__uses_refcount())
@@ -100,7 +100,7 @@ __libcpp_refstring::__libcpp_refstring(const __libcpp_refstring &s) _NOEXCEPT
 }
 
 inline
-__libcpp_refstring& __libcpp_refstring::operator=(__libcpp_refstring const& s) _NOEXCEPT {
+__libcpp_refstring& __libcpp_refstring::operator=(__libcpp_refstring const& s) noexcept {
     bool adjust_old_count = __uses_refcount();
     struct _Rep_base *old_rep = rep_from_data(__imp_);
     __imp_ = s.__imp_;
lib/libcxx/include/__sso_allocator โ†’ lib/libcxx/src/include/sso_allocator.h
@@ -7,8 +7,8 @@
 //
 //===----------------------------------------------------------------------===//
 
-#ifndef _LIBCPP___SSO_ALLOCATOR
-#define _LIBCPP___SSO_ALLOCATOR
+#ifndef _LIBCPP_SSO_ALLOCATOR_H
+#define _LIBCPP_SSO_ALLOCATOR_H
 
 #include <__config>
 #include <memory>
@@ -67,11 +67,11 @@ public:
     _LIBCPP_INLINE_VISIBILITY size_type max_size() const throw() {return size_type(~0) / sizeof(_Tp);}
 
     _LIBCPP_INLINE_VISIBILITY
-    bool operator==(__sso_allocator& __a) const {return &buf_ == &__a.buf_;}
+    bool operator==(const __sso_allocator& __a) const {return &buf_ == &__a.buf_;}
     _LIBCPP_INLINE_VISIBILITY
-    bool operator!=(__sso_allocator& __a) const {return &buf_ != &__a.buf_;}
+    bool operator!=(const __sso_allocator& __a) const {return &buf_ != &__a.buf_;}
 };
 
 _LIBCPP_END_NAMESPACE_STD
 
-#endif  // _LIBCPP___SSO_ALLOCATOR
+#endif // _LIBCPP_SSO_ALLOCATOR_H
lib/libcxx/src/support/ibm/xlocale_zos.cpp
@@ -0,0 +1,137 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include <__support/ibm/xlocale.h>
+#include <sstream>
+#include <vector>
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+locale_t newlocale(int category_mask, const char* locale, locale_t base) {
+  // Maintain current locale name(s) to restore later.
+  std::string current_loc_name(setlocale(LC_ALL, 0));
+
+  // Check for errors.
+  if (category_mask == LC_ALL_MASK && setlocale(LC_ALL, locale) == NULL) {
+    errno = EINVAL;
+    return (locale_t)0;
+  } else {
+    for (int _Cat = 0; _Cat <= _LC_MAX; ++_Cat) {
+      if ((_CATMASK(_Cat) & category_mask) != 0 && setlocale(_Cat, locale) == NULL) {
+        setlocale(LC_ALL, current_loc_name.c_str());
+        errno = EINVAL;
+        return (locale_t)0;
+      }
+    }
+  }
+  
+  // Create new locale.
+  locale_t newloc = new locale_struct();
+
+  if (base) {
+    if (category_mask != LC_ALL_MASK) {
+      // Copy base when it will not be overwritten.
+      memcpy(newloc, base, sizeof (locale_struct));
+      newloc->category_mask = category_mask | base->category_mask;
+    }
+    delete base;
+  } else {
+    newloc->category_mask = category_mask;
+  }
+
+  if (category_mask & LC_COLLATE_MASK)
+    newloc->lc_collate = locale;
+  if (category_mask & LC_CTYPE_MASK)
+    newloc->lc_ctype = locale;
+  if (category_mask & LC_MONETARY_MASK)
+    newloc->lc_monetary = locale;
+  if (category_mask & LC_NUMERIC_MASK)
+    newloc->lc_numeric = locale;
+  if (category_mask & LC_TIME_MASK)
+    newloc->lc_time = locale;
+  if (category_mask & LC_MESSAGES_MASK)
+    newloc->lc_messages = locale;
+
+  // Restore current locale.
+  setlocale(LC_ALL, current_loc_name.c_str());
+  return (locale_t)newloc;
+}
+
+void freelocale(locale_t locobj) {
+  delete locobj;
+}
+
+locale_t uselocale(locale_t newloc) {
+  // Maintain current locale name(s).
+  std::string current_loc_name(setlocale(LC_ALL, 0));
+
+  if (newloc) {
+    // Set locales and check for errors.
+    bool is_error = 
+      (newloc->category_mask & LC_COLLATE_MASK && 
+        setlocale(LC_COLLATE, newloc->lc_collate.c_str()) == NULL) ||
+      (newloc->category_mask & LC_CTYPE_MASK && 
+        setlocale(LC_CTYPE, newloc->lc_ctype.c_str()) == NULL) ||
+      (newloc->category_mask & LC_MONETARY_MASK && 
+        setlocale(LC_MONETARY, newloc->lc_monetary.c_str()) == NULL) ||
+      (newloc->category_mask & LC_NUMERIC_MASK && 
+        setlocale(LC_NUMERIC, newloc->lc_numeric.c_str()) == NULL) ||
+      (newloc->category_mask & LC_TIME_MASK && 
+        setlocale(LC_TIME, newloc->lc_time.c_str()) == NULL) ||
+      (newloc->category_mask & LC_MESSAGES_MASK && 
+        setlocale(LC_MESSAGES, newloc->lc_messages.c_str()) == NULL);
+
+    if (is_error) {
+      setlocale(LC_ALL, current_loc_name.c_str());
+      errno = EINVAL;
+      return (locale_t)0;
+    }
+  }
+
+  // Construct and return previous locale.
+  locale_t previous_loc = new locale_struct();
+
+  // current_loc_name might be a comma-separated locale name list.
+  if (current_loc_name.find(',') != std::string::npos) {
+    // Tokenize locale name list.
+    const char delimiter = ',';
+    std::vector<std::string> tokenized;
+    std::stringstream ss(current_loc_name);
+    std::string s;
+
+    while (std::getline(ss, s, delimiter)) {
+        tokenized.push_back(s);
+    }
+
+    _LIBCPP_ASSERT(tokenized.size() >= _NCAT, "locale-name list is too short");
+
+    previous_loc->lc_collate = tokenized[LC_COLLATE];
+    previous_loc->lc_ctype = tokenized[LC_CTYPE];
+    previous_loc->lc_monetary = tokenized[LC_MONETARY];
+    previous_loc->lc_numeric = tokenized[LC_NUMERIC];
+    previous_loc->lc_time = tokenized[LC_TIME];
+    // Skip LC_TOD.
+    previous_loc->lc_messages = tokenized[LC_MESSAGES];
+  } else {
+    previous_loc->lc_collate = current_loc_name;
+    previous_loc->lc_ctype = current_loc_name;
+    previous_loc->lc_monetary = current_loc_name;
+    previous_loc->lc_numeric = current_loc_name;
+    previous_loc->lc_time = current_loc_name;
+    previous_loc->lc_messages = current_loc_name;
+  }
+
+  previous_loc->category_mask = LC_ALL_MASK;
+  return previous_loc;
+}
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
lib/libcxx/src/support/runtime/exception_fallback.ipp
@@ -17,13 +17,13 @@ _LIBCPP_SAFE_STATIC static std::unexpected_handler __unexpected_handler;
 
 // libcxxrt provides implementations of these functions itself.
 unexpected_handler
-set_unexpected(unexpected_handler func) _NOEXCEPT
+set_unexpected(unexpected_handler func) noexcept
 {
   return __libcpp_atomic_exchange(&__unexpected_handler, func);
 }
 
 unexpected_handler
-get_unexpected() _NOEXCEPT
+get_unexpected() noexcept
 {
   return __libcpp_atomic_load(&__unexpected_handler);
 
@@ -38,25 +38,25 @@ void unexpected()
 }
 
 terminate_handler
-set_terminate(terminate_handler func) _NOEXCEPT
+set_terminate(terminate_handler func) noexcept
 {
   return __libcpp_atomic_exchange(&__terminate_handler, func);
 }
 
 terminate_handler
-get_terminate() _NOEXCEPT
+get_terminate() noexcept
 {
   return __libcpp_atomic_load(&__terminate_handler);
 }
 
 _LIBCPP_NORETURN
 void
-terminate() _NOEXCEPT
+terminate() noexcept
 {
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         (*get_terminate())();
         // handler should not return
         fprintf(stderr, "terminate_handler unexpectedly returned\n");
@@ -69,12 +69,12 @@ terminate() _NOEXCEPT
         fprintf(stderr, "terminate_handler unexpectedly threw an exception\n");
         ::abort();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
-bool uncaught_exception() _NOEXCEPT { return uncaught_exceptions() > 0; }
+bool uncaught_exception() noexcept { return uncaught_exceptions() > 0; }
 
-int uncaught_exceptions() _NOEXCEPT
+int uncaught_exceptions() noexcept
 {
 #warning uncaught_exception not yet implemented
   fprintf(stderr, "uncaught_exceptions not yet implemented\n");
@@ -82,77 +82,77 @@ int uncaught_exceptions() _NOEXCEPT
 }
 
 
-exception::~exception() _NOEXCEPT
+exception::~exception() noexcept
 {
 }
 
-const char* exception::what() const _NOEXCEPT
+const char* exception::what() const noexcept
 {
   return "std::exception";
 }
 
-bad_exception::~bad_exception() _NOEXCEPT
+bad_exception::~bad_exception() noexcept
 {
 }
 
-const char* bad_exception::what() const _NOEXCEPT
+const char* bad_exception::what() const noexcept
 {
   return "std::bad_exception";
 }
 
 
-bad_alloc::bad_alloc() _NOEXCEPT
+bad_alloc::bad_alloc() noexcept
 {
 }
 
-bad_alloc::~bad_alloc() _NOEXCEPT
+bad_alloc::~bad_alloc() noexcept
 {
 }
 
 const char*
-bad_alloc::what() const _NOEXCEPT
+bad_alloc::what() const noexcept
 {
     return "std::bad_alloc";
 }
 
-bad_array_new_length::bad_array_new_length() _NOEXCEPT
+bad_array_new_length::bad_array_new_length() noexcept
 {
 }
 
-bad_array_new_length::~bad_array_new_length() _NOEXCEPT
+bad_array_new_length::~bad_array_new_length() noexcept
 {
 }
 
 const char*
-bad_array_new_length::what() const _NOEXCEPT
+bad_array_new_length::what() const noexcept
 {
     return "bad_array_new_length";
 }
 
-bad_cast::bad_cast() _NOEXCEPT
+bad_cast::bad_cast() noexcept
 {
 }
 
-bad_typeid::bad_typeid() _NOEXCEPT
+bad_typeid::bad_typeid() noexcept
 {
 }
 
-bad_cast::~bad_cast() _NOEXCEPT
+bad_cast::~bad_cast() noexcept
 {
 }
 
 const char*
-bad_cast::what() const _NOEXCEPT
+bad_cast::what() const noexcept
 {
   return "std::bad_cast";
 }
 
-bad_typeid::~bad_typeid() _NOEXCEPT
+bad_typeid::~bad_typeid() noexcept
 {
 }
 
 const char*
-bad_typeid::what() const _NOEXCEPT
+bad_typeid::what() const noexcept
 {
   return "std::bad_typeid";
 }
lib/libcxx/src/support/runtime/exception_glibcxx.ipp
@@ -13,19 +13,19 @@
 
 namespace std {
 
-bad_alloc::bad_alloc() _NOEXCEPT
+bad_alloc::bad_alloc() noexcept
 {
 }
 
-bad_array_new_length::bad_array_new_length() _NOEXCEPT
+bad_array_new_length::bad_array_new_length() noexcept
 {
 }
 
-bad_cast::bad_cast() _NOEXCEPT
+bad_cast::bad_cast() noexcept
 {
 }
 
-bad_typeid::bad_typeid() _NOEXCEPT
+bad_typeid::bad_typeid() noexcept
 {
 }
 
lib/libcxx/src/support/runtime/exception_libcxxabi.ipp
@@ -13,9 +13,9 @@
 
 namespace std {
 
-bool uncaught_exception() _NOEXCEPT { return uncaught_exceptions() > 0; }
+bool uncaught_exception() noexcept { return uncaught_exceptions() > 0; }
 
-int uncaught_exceptions() _NOEXCEPT
+int uncaught_exceptions() noexcept
 {
 # if _LIBCPPABI_VERSION > 1001
     return __cxa_uncaught_exceptions();
lib/libcxx/src/support/runtime/exception_libcxxrt.ipp
@@ -13,11 +13,11 @@
 
 namespace std {
 
-bad_exception::~bad_exception() _NOEXCEPT
+bad_exception::~bad_exception() noexcept
 {
 }
 
-const char* bad_exception::what() const _NOEXCEPT
+const char* bad_exception::what() const noexcept
 {
   return "std::bad_exception";
 }
lib/libcxx/src/support/runtime/exception_msvc.ipp
@@ -31,11 +31,11 @@ int __cdecl __uncaught_exceptions();
 namespace std {
 
 unexpected_handler
-set_unexpected(unexpected_handler func) _NOEXCEPT {
+set_unexpected(unexpected_handler func) noexcept {
   return ::set_unexpected(func);
 }
 
-unexpected_handler get_unexpected() _NOEXCEPT {
+unexpected_handler get_unexpected() noexcept {
   return ::_get_unexpected();
 }
 
@@ -46,21 +46,21 @@ void unexpected() {
     terminate();
 }
 
-terminate_handler set_terminate(terminate_handler func) _NOEXCEPT {
+terminate_handler set_terminate(terminate_handler func) noexcept {
   return ::set_terminate(func);
 }
 
-terminate_handler get_terminate() _NOEXCEPT {
+terminate_handler get_terminate() noexcept {
   return ::_get_terminate();
 }
 
 _LIBCPP_NORETURN
-void terminate() _NOEXCEPT
+void terminate() noexcept
 {
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         (*get_terminate())();
         // handler should not return
         fprintf(stderr, "terminate_handler unexpectedly returned\n");
@@ -73,88 +73,88 @@ void terminate() _NOEXCEPT
         fprintf(stderr, "terminate_handler unexpectedly threw an exception\n");
         ::abort();
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
-bool uncaught_exception() _NOEXCEPT { return uncaught_exceptions() > 0; }
+bool uncaught_exception() noexcept { return uncaught_exceptions() > 0; }
 
-int uncaught_exceptions() _NOEXCEPT {
+int uncaught_exceptions() noexcept {
     return __uncaught_exceptions();
 }
 
 #if !defined(_LIBCPP_ABI_VCRUNTIME)
-bad_cast::bad_cast() _NOEXCEPT
+bad_cast::bad_cast() noexcept
 {
 }
 
-bad_cast::~bad_cast() _NOEXCEPT
+bad_cast::~bad_cast() noexcept
 {
 }
 
 const char *
-bad_cast::what() const _NOEXCEPT
+bad_cast::what() const noexcept
 {
   return "std::bad_cast";
 }
 
-bad_typeid::bad_typeid() _NOEXCEPT
+bad_typeid::bad_typeid() noexcept
 {
 }
 
-bad_typeid::~bad_typeid() _NOEXCEPT
+bad_typeid::~bad_typeid() noexcept
 {
 }
 
 const char *
-bad_typeid::what() const _NOEXCEPT
+bad_typeid::what() const noexcept
 {
   return "std::bad_typeid";
 }
 
-exception::~exception() _NOEXCEPT
+exception::~exception() noexcept
 {
 }
 
-const char* exception::what() const _NOEXCEPT
+const char* exception::what() const noexcept
 {
   return "std::exception";
 }
 
 
-bad_exception::~bad_exception() _NOEXCEPT
+bad_exception::~bad_exception() noexcept
 {
 }
 
-const char* bad_exception::what() const _NOEXCEPT
+const char* bad_exception::what() const noexcept
 {
   return "std::bad_exception";
 }
 
 
-bad_alloc::bad_alloc() _NOEXCEPT
+bad_alloc::bad_alloc() noexcept
 {
 }
 
-bad_alloc::~bad_alloc() _NOEXCEPT
+bad_alloc::~bad_alloc() noexcept
 {
 }
 
 const char*
-bad_alloc::what() const _NOEXCEPT
+bad_alloc::what() const noexcept
 {
     return "std::bad_alloc";
 }
 
-bad_array_new_length::bad_array_new_length() _NOEXCEPT
+bad_array_new_length::bad_array_new_length() noexcept
 {
 }
 
-bad_array_new_length::~bad_array_new_length() _NOEXCEPT
+bad_array_new_length::~bad_array_new_length() noexcept
 {
 }
 
 const char*
-bad_array_new_length::what() const _NOEXCEPT
+bad_array_new_length::what() const noexcept
 {
     return "bad_array_new_length";
 }
lib/libcxx/src/support/runtime/exception_pointer_cxxabi.ipp
@@ -13,17 +13,17 @@
 
 namespace std {
 
-exception_ptr::~exception_ptr() _NOEXCEPT {
+exception_ptr::~exception_ptr() noexcept {
   __cxa_decrement_exception_refcount(__ptr_);
 }
 
-exception_ptr::exception_ptr(const exception_ptr& other) _NOEXCEPT
+exception_ptr::exception_ptr(const exception_ptr& other) noexcept
     : __ptr_(other.__ptr_)
 {
     __cxa_increment_exception_refcount(__ptr_);
 }
 
-exception_ptr& exception_ptr::operator=(const exception_ptr& other) _NOEXCEPT
+exception_ptr& exception_ptr::operator=(const exception_ptr& other) noexcept
 {
     if (__ptr_ != other.__ptr_)
     {
@@ -34,12 +34,12 @@ exception_ptr& exception_ptr::operator=(const exception_ptr& other) _NOEXCEPT
     return *this;
 }
 
-nested_exception::nested_exception() _NOEXCEPT
+nested_exception::nested_exception() noexcept
     : __ptr_(current_exception())
 {
 }
 
-nested_exception::~nested_exception() _NOEXCEPT
+nested_exception::~nested_exception() noexcept
 {
 }
 
@@ -52,7 +52,7 @@ nested_exception::rethrow_nested() const
     rethrow_exception(__ptr_);
 }
 
-exception_ptr current_exception() _NOEXCEPT
+exception_ptr current_exception() noexcept
 {
     // be nicer if there was a constructor that took a ptr, then
     // this whole function would be just:
lib/libcxx/src/support/runtime/exception_pointer_glibcxx.ipp
@@ -25,35 +25,35 @@ struct exception_ptr
 {
     void* __ptr_;
 
-    exception_ptr(const exception_ptr&) _NOEXCEPT;
-    exception_ptr& operator=(const exception_ptr&) _NOEXCEPT;
-    ~exception_ptr() _NOEXCEPT;
+    exception_ptr(const exception_ptr&) noexcept;
+    exception_ptr& operator=(const exception_ptr&) noexcept;
+    ~exception_ptr() noexcept;
 };
 
 }
 
 _LIBCPP_NORETURN void rethrow_exception(__exception_ptr::exception_ptr);
 
-exception_ptr::~exception_ptr() _NOEXCEPT
+exception_ptr::~exception_ptr() noexcept
 {
     reinterpret_cast<__exception_ptr::exception_ptr*>(this)->~exception_ptr();
 }
 
-exception_ptr::exception_ptr(const exception_ptr& other) _NOEXCEPT
+exception_ptr::exception_ptr(const exception_ptr& other) noexcept
     : __ptr_(other.__ptr_)
 {
     new (reinterpret_cast<void*>(this)) __exception_ptr::exception_ptr(
         reinterpret_cast<const __exception_ptr::exception_ptr&>(other));
 }
 
-exception_ptr& exception_ptr::operator=(const exception_ptr& other) _NOEXCEPT
+exception_ptr& exception_ptr::operator=(const exception_ptr& other) noexcept
 {
     *reinterpret_cast<__exception_ptr::exception_ptr*>(this) =
         reinterpret_cast<const __exception_ptr::exception_ptr&>(other);
     return *this;
 }
 
-nested_exception::nested_exception() _NOEXCEPT
+nested_exception::nested_exception() noexcept
     : __ptr_(current_exception())
 {
 }
lib/libcxx/src/support/runtime/exception_pointer_msvc.ipp
@@ -24,35 +24,35 @@ __ExceptionPtrCopyException(void*, const void*, const void*);
 
 namespace std {
 
-exception_ptr::exception_ptr() _NOEXCEPT { __ExceptionPtrCreate(this); }
-exception_ptr::exception_ptr(nullptr_t) _NOEXCEPT { __ExceptionPtrCreate(this); }
+exception_ptr::exception_ptr() noexcept { __ExceptionPtrCreate(this); }
+exception_ptr::exception_ptr(nullptr_t) noexcept { __ExceptionPtrCreate(this); }
 
-exception_ptr::exception_ptr(const exception_ptr& __other) _NOEXCEPT {
+exception_ptr::exception_ptr(const exception_ptr& __other) noexcept {
   __ExceptionPtrCopy(this, &__other);
 }
-exception_ptr& exception_ptr::operator=(const exception_ptr& __other) _NOEXCEPT {
+exception_ptr& exception_ptr::operator=(const exception_ptr& __other) noexcept {
   __ExceptionPtrAssign(this, &__other);
   return *this;
 }
 
-exception_ptr& exception_ptr::operator=(nullptr_t) _NOEXCEPT {
+exception_ptr& exception_ptr::operator=(nullptr_t) noexcept {
   exception_ptr dummy;
   __ExceptionPtrAssign(this, &dummy);
   return *this;
 }
 
-exception_ptr::~exception_ptr() _NOEXCEPT { __ExceptionPtrDestroy(this); }
+exception_ptr::~exception_ptr() noexcept { __ExceptionPtrDestroy(this); }
 
-exception_ptr::operator bool() const _NOEXCEPT {
+exception_ptr::operator bool() const noexcept {
   return __ExceptionPtrToBool(this);
 }
 
-bool operator==(const exception_ptr& __x, const exception_ptr& __y) _NOEXCEPT {
+bool operator==(const exception_ptr& __x, const exception_ptr& __y) noexcept {
   return __ExceptionPtrCompare(&__x, &__y);
 }
 
 
-void swap(exception_ptr& lhs, exception_ptr& rhs) _NOEXCEPT {
+void swap(exception_ptr& lhs, exception_ptr& rhs) noexcept {
   __ExceptionPtrSwap(&rhs, &lhs);
 }
 
@@ -63,7 +63,7 @@ exception_ptr __copy_exception_ptr(void* __except, const void* __ptr) {
   return __ret;
 }
 
-exception_ptr current_exception() _NOEXCEPT {
+exception_ptr current_exception() noexcept {
   exception_ptr __ret;
   __ExceptionPtrCurrentException(&__ret);
   return __ret;
@@ -72,9 +72,9 @@ exception_ptr current_exception() _NOEXCEPT {
 _LIBCPP_NORETURN
 void rethrow_exception(exception_ptr p) { __ExceptionPtrRethrow(&p); }
 
-nested_exception::nested_exception() _NOEXCEPT : __ptr_(current_exception()) {}
+nested_exception::nested_exception() noexcept : __ptr_(current_exception()) {}
 
-nested_exception::~nested_exception() _NOEXCEPT {}
+nested_exception::~nested_exception() noexcept {}
 
 _LIBCPP_NORETURN
 void nested_exception::rethrow_nested() const {
lib/libcxx/src/support/runtime/exception_pointer_unimplemented.ipp
@@ -12,14 +12,14 @@
 
 namespace std {
 
-exception_ptr::~exception_ptr() _NOEXCEPT
+exception_ptr::~exception_ptr() noexcept
 {
 #  warning exception_ptr not yet implemented
   fprintf(stderr, "exception_ptr not yet implemented\n");
   ::abort();
 }
 
-exception_ptr::exception_ptr(const exception_ptr& other) _NOEXCEPT
+exception_ptr::exception_ptr(const exception_ptr& other) noexcept
     : __ptr_(other.__ptr_)
 {
 #  warning exception_ptr not yet implemented
@@ -27,21 +27,21 @@ exception_ptr::exception_ptr(const exception_ptr& other) _NOEXCEPT
   ::abort();
 }
 
-exception_ptr& exception_ptr::operator=(const exception_ptr& other) _NOEXCEPT
+exception_ptr& exception_ptr::operator=(const exception_ptr& other) noexcept
 {
 #  warning exception_ptr not yet implemented
   fprintf(stderr, "exception_ptr not yet implemented\n");
   ::abort();
 }
 
-nested_exception::nested_exception() _NOEXCEPT
+nested_exception::nested_exception() noexcept
     : __ptr_(current_exception())
 {
 }
 
 #if !defined(__GLIBCXX__)
 
-nested_exception::~nested_exception() _NOEXCEPT
+nested_exception::~nested_exception() noexcept
 {
 }
 
@@ -61,7 +61,7 @@ nested_exception::rethrow_nested() const
 #endif // FIXME
 }
 
-exception_ptr current_exception() _NOEXCEPT
+exception_ptr current_exception() noexcept
 {
 #  warning exception_ptr not yet implemented
   fprintf(stderr, "exception_ptr not yet implemented\n");
lib/libcxx/src/support/runtime/new_handler_fallback.ipp
@@ -12,13 +12,13 @@ namespace std {
 _LIBCPP_SAFE_STATIC static std::new_handler __new_handler;
 
 new_handler
-set_new_handler(new_handler handler) _NOEXCEPT
+set_new_handler(new_handler handler) noexcept
 {
     return __libcpp_atomic_exchange(&__new_handler, handler);
 }
 
 new_handler
-get_new_handler() _NOEXCEPT
+get_new_handler() noexcept
 {
     return __libcpp_atomic_load(&__new_handler);
 }
lib/libcxx/src/support/runtime/stdexcept_default.ipp
@@ -23,9 +23,9 @@ logic_error::logic_error(const string& msg) : __imp_(msg.c_str()) {}
 
 logic_error::logic_error(const char* msg) : __imp_(msg) {}
 
-logic_error::logic_error(const logic_error& le) _NOEXCEPT : __imp_(le.__imp_) {}
+logic_error::logic_error(const logic_error& le) noexcept : __imp_(le.__imp_) {}
 
-logic_error& logic_error::operator=(const logic_error& le) _NOEXCEPT {
+logic_error& logic_error::operator=(const logic_error& le) noexcept {
   __imp_ = le.__imp_;
   return *this;
 }
@@ -34,30 +34,30 @@ runtime_error::runtime_error(const string& msg) : __imp_(msg.c_str()) {}
 
 runtime_error::runtime_error(const char* msg) : __imp_(msg) {}
 
-runtime_error::runtime_error(const runtime_error& re) _NOEXCEPT
+runtime_error::runtime_error(const runtime_error& re) noexcept
     : __imp_(re.__imp_) {}
 
-runtime_error& runtime_error::operator=(const runtime_error& re) _NOEXCEPT {
+runtime_error& runtime_error::operator=(const runtime_error& re) noexcept {
   __imp_ = re.__imp_;
   return *this;
 }
 
 #if !defined(_LIBCPPABI_VERSION) && !defined(LIBSTDCXX)
 
-const char* logic_error::what() const _NOEXCEPT { return __imp_.c_str(); }
+const char* logic_error::what() const noexcept { return __imp_.c_str(); }
 
-const char* runtime_error::what() const _NOEXCEPT { return __imp_.c_str(); }
+const char* runtime_error::what() const noexcept { return __imp_.c_str(); }
 
-logic_error::~logic_error() _NOEXCEPT {}
-domain_error::~domain_error() _NOEXCEPT {}
-invalid_argument::~invalid_argument() _NOEXCEPT {}
-length_error::~length_error() _NOEXCEPT {}
-out_of_range::~out_of_range() _NOEXCEPT {}
+logic_error::~logic_error() noexcept {}
+domain_error::~domain_error() noexcept {}
+invalid_argument::~invalid_argument() noexcept {}
+length_error::~length_error() noexcept {}
+out_of_range::~out_of_range() noexcept {}
 
-runtime_error::~runtime_error() _NOEXCEPT {}
-range_error::~range_error() _NOEXCEPT {}
-overflow_error::~overflow_error() _NOEXCEPT {}
-underflow_error::~underflow_error() _NOEXCEPT {}
+runtime_error::~runtime_error() noexcept {}
+range_error::~range_error() noexcept {}
+overflow_error::~overflow_error() noexcept {}
+underflow_error::~underflow_error() noexcept {}
 
 #endif
 
lib/libcxx/src/support/win32/support.cpp
@@ -22,7 +22,10 @@ int __libcpp_vasprintf( char **sptr, const char *__restrict format, va_list ap )
 {
     *sptr = NULL;
     // Query the count required.
-    int count = _vsnprintf( NULL, 0, format, ap );
+    va_list ap_copy;
+    va_copy(ap_copy, ap);
+    int count = _vsnprintf( NULL, 0, format, ap_copy );
+    va_end(ap_copy);
     if (count < 0)
         return count;
     size_t buffer_size = static_cast<size_t>(count) + 1;
lib/libcxx/src/support/win32/thread_win32.cpp
@@ -8,6 +8,8 @@
 //===----------------------------------------------------------------------===//
 
 #include <__threading_support>
+#define NOMINMAX
+#define WIN32_LEAN_AND_MEAN
 #include <windows.h>
 #include <process.h>
 #include <fibersapi.h>
@@ -37,6 +39,9 @@ static_assert(alignof(__libcpp_thread_t) == alignof(HANDLE), "");
 static_assert(sizeof(__libcpp_tls_key) == sizeof(DWORD), "");
 static_assert(alignof(__libcpp_tls_key) == alignof(DWORD), "");
 
+static_assert(sizeof(__libcpp_semaphore_t) == sizeof(HANDLE), "");
+static_assert(alignof(__libcpp_semaphore_t) == alignof(HANDLE), "");
+
 // Mutex
 int __libcpp_recursive_mutex_init(__libcpp_recursive_mutex_t *__m)
 {
@@ -241,10 +246,8 @@ void __libcpp_thread_yield()
 
 void __libcpp_thread_sleep_for(const chrono::nanoseconds& __ns)
 {
-  using namespace chrono;
-  // round-up to the nearest milisecond
-  milliseconds __ms =
-      duration_cast<milliseconds>(__ns + chrono::nanoseconds(999999));
+  // round-up to the nearest millisecond
+  chrono::milliseconds __ms = chrono::ceil<chrono::milliseconds>(__ns);
   // FIXME(compnerd) this should be an alertable sleep (WFSO or SleepEx)
   Sleep(__ms.count());
 }
@@ -272,4 +275,37 @@ int __libcpp_tls_set(__libcpp_tls_key __key, void *__p)
   return 0;
 }
 
+// Semaphores
+bool __libcpp_semaphore_init(__libcpp_semaphore_t* __sem, int __init)
+{
+  *(PHANDLE)__sem = CreateSemaphoreEx(nullptr, __init, _LIBCPP_SEMAPHORE_MAX,
+                                      nullptr, 0, SEMAPHORE_ALL_ACCESS);
+  return *__sem != nullptr;
+}
+
+bool __libcpp_semaphore_destroy(__libcpp_semaphore_t* __sem)
+{
+  CloseHandle(*(PHANDLE)__sem);
+  return true;
+}
+
+bool __libcpp_semaphore_post(__libcpp_semaphore_t* __sem)
+{
+  return ReleaseSemaphore(*(PHANDLE)__sem, 1, nullptr);
+}
+
+bool __libcpp_semaphore_wait(__libcpp_semaphore_t* __sem)
+{
+  return WaitForSingleObjectEx(*(PHANDLE)__sem, INFINITE, false) ==
+         WAIT_OBJECT_0;
+}
+
+bool __libcpp_semaphore_wait_timed(__libcpp_semaphore_t* __sem,
+                                   chrono::nanoseconds const& __ns)
+{
+  chrono::milliseconds __ms = chrono::ceil<chrono::milliseconds>(__ns);
+  return WaitForSingleObjectEx(*(PHANDLE)__sem, __ms.count(), false) ==
+         WAIT_OBJECT_0;
+}
+
 _LIBCPP_END_NAMESPACE_STD
lib/libcxx/src/any.cpp
@@ -9,7 +9,7 @@
 #include "any"
 
 namespace std {
-const char* bad_any_cast::what() const _NOEXCEPT {
+const char* bad_any_cast::what() const noexcept {
     return "bad any cast";
 }
 }
@@ -24,10 +24,10 @@ _LIBCPP_BEGIN_NAMESPACE_LFTS
 class _LIBCPP_EXCEPTION_ABI _LIBCPP_AVAILABILITY_BAD_ANY_CAST bad_any_cast : public bad_cast
 {
 public:
-    virtual const char* what() const _NOEXCEPT;
+    virtual const char* what() const noexcept;
 };
 
-const char* bad_any_cast::what() const _NOEXCEPT {
+const char* bad_any_cast::what() const noexcept {
     return "bad any cast";
 }
 
lib/libcxx/src/charconv.cpp
@@ -99,7 +99,7 @@ append8_no_zeros(char* buffer, T v) noexcept
 }
 
 char*
-__u32toa(uint32_t value, char* buffer) _NOEXCEPT
+__u32toa(uint32_t value, char* buffer) noexcept
 {
     if (value < 100000000)
     {
@@ -120,7 +120,7 @@ __u32toa(uint32_t value, char* buffer) _NOEXCEPT
 }
 
 char*
-__u64toa(uint64_t value, char* buffer) _NOEXCEPT
+__u64toa(uint64_t value, char* buffer) noexcept
 {
     if (value < 100000000)
     {
lib/libcxx/src/chrono.cpp
@@ -6,9 +6,20 @@
 //
 //===----------------------------------------------------------------------===//
 
+#if defined(__MVS__)
+// As part of monotonic clock support on z/OS we need macro _LARGE_TIME_API
+// to be defined before any system header to include definition of struct timespec64.
+#define _LARGE_TIME_API
+#endif
+
 #include "chrono"
 #include "cerrno"        // errno
 #include "system_error"  // __throw_system_error
+
+#if defined(__MVS__)
+#include <__support/ibm/gettod_zos.h> // gettimeofdayMonotonic
+#endif
+
 #include <time.h>        // clock_gettime and CLOCK_{MONOTONIC,REALTIME,MONOTONIC_RAW}
 #include "include/apple_availability.h"
 
@@ -20,7 +31,7 @@
 # include <sys/time.h> // for gettimeofday and timeval
 #endif
 
-#if !defined(__APPLE__) && _POSIX_TIMERS > 0
+#if !defined(__APPLE__) && defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0
 # define _LIBCPP_USE_CLOCK_GETTIME
 #endif
 
@@ -96,19 +107,19 @@ static system_clock::time_point __libcpp_system_clock_now() {
 const bool system_clock::is_steady;
 
 system_clock::time_point
-system_clock::now() _NOEXCEPT
+system_clock::now() noexcept
 {
     return __libcpp_system_clock_now();
 }
 
 time_t
-system_clock::to_time_t(const time_point& t) _NOEXCEPT
+system_clock::to_time_t(const time_point& t) noexcept
 {
     return time_t(duration_cast<seconds>(t.time_since_epoch()).count());
 }
 
 system_clock::time_point
-system_clock::from_time_t(time_t t) _NOEXCEPT
+system_clock::from_time_t(time_t t) noexcept
 {
     return system_clock::time_point(seconds(t));
 }
@@ -218,6 +229,16 @@ static steady_clock::time_point __libcpp_steady_clock_now() {
   return steady_clock::time_point(steady_clock::duration(dur));
 }
 
+#elif defined(__MVS__)
+
+static steady_clock::time_point __libcpp_steady_clock_now() {
+  struct timespec64 ts;
+  if (0 != gettimeofdayMonotonic(&ts))
+    __throw_system_error(errno, "failed to obtain time of day");
+
+  return steady_clock::time_point(seconds(ts.tv_sec) + nanoseconds(ts.tv_nsec));
+}
+
 #elif defined(CLOCK_MONOTONIC)
 
 static steady_clock::time_point __libcpp_steady_clock_now() {
@@ -234,7 +255,7 @@ static steady_clock::time_point __libcpp_steady_clock_now() {
 const bool steady_clock::is_steady;
 
 steady_clock::time_point
-steady_clock::now() _NOEXCEPT
+steady_clock::now() noexcept
 {
     return __libcpp_steady_clock_now();
 }
lib/libcxx/src/condition_variable.cpp
@@ -24,19 +24,19 @@ _LIBCPP_BEGIN_NAMESPACE_STD
 // ~condition_variable is defined elsewhere.
 
 void
-condition_variable::notify_one() _NOEXCEPT
+condition_variable::notify_one() noexcept
 {
     __libcpp_condvar_signal(&__cv_);
 }
 
 void
-condition_variable::notify_all() _NOEXCEPT
+condition_variable::notify_all() noexcept
 {
     __libcpp_condvar_broadcast(&__cv_);
 }
 
 void
-condition_variable::wait(unique_lock<mutex>& lk) _NOEXCEPT
+condition_variable::wait(unique_lock<mutex>& lk) noexcept
 {
     if (!lk.owns_lock())
         __throw_system_error(EPERM,
@@ -48,7 +48,7 @@ condition_variable::wait(unique_lock<mutex>& lk) _NOEXCEPT
 
 void
 condition_variable::__do_timed_wait(unique_lock<mutex>& lk,
-     chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp) _NOEXCEPT
+     chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp) noexcept
 {
     using namespace chrono;
     if (!lk.owns_lock())
lib/libcxx/src/debug.cpp
@@ -438,7 +438,7 @@ __libcpp_db::__less_than_comparable(const void* __i, const void* __j) const
     __i_node* j = __find_iterator(__j);
     __c_node* ci = i != nullptr ? i->__c_ : nullptr;
     __c_node* cj = j != nullptr ? j->__c_ : nullptr;
-    return ci != nullptr && ci == cj;
+    return ci == cj;
 }
 
 void
lib/libcxx/src/format.cpp
@@ -0,0 +1,19 @@
+//===------------------------- format.cpp ---------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "format"
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER > 17
+
+format_error::~format_error() noexcept = default;
+
+#endif //_LIBCPP_STD_VER > 17
+
+_LIBCPP_END_NAMESPACE_STD
lib/libcxx/src/functional.cpp
@@ -11,12 +11,12 @@
 _LIBCPP_BEGIN_NAMESPACE_STD
 
 #ifdef _LIBCPP_ABI_BAD_FUNCTION_CALL_KEY_FUNCTION
-bad_function_call::~bad_function_call() _NOEXCEPT
+bad_function_call::~bad_function_call() noexcept
 {
 }
 
 const char*
-bad_function_call::what() const _NOEXCEPT
+bad_function_call::what() const noexcept
 {
     return "std::bad_function_call";
 }
lib/libcxx/src/future.cpp
@@ -19,12 +19,12 @@ class _LIBCPP_HIDDEN __future_error_category
     : public __do_message
 {
 public:
-    virtual const char* name() const _NOEXCEPT;
+    virtual const char* name() const noexcept;
     virtual string message(int ev) const;
 };
 
 const char*
-__future_error_category::name() const _NOEXCEPT
+__future_error_category::name() const noexcept
 {
     return "future";
 }
@@ -65,7 +65,7 @@ __future_error_category::message(int ev) const
 #endif
 
 const error_category&
-future_category() _NOEXCEPT
+future_category() noexcept
 {
     static __future_error_category __f;
     return __f;
@@ -77,12 +77,12 @@ future_error::future_error(error_code __ec)
 {
 }
 
-future_error::~future_error() _NOEXCEPT
+future_error::~future_error() noexcept
 {
 }
 
 void
-__assoc_sub_state::__on_zero_shared() _NOEXCEPT
+__assoc_sub_state::__on_zero_shared() noexcept
 {
     delete this;
 }
lib/libcxx/src/ios.cpp
@@ -27,12 +27,12 @@ class _LIBCPP_HIDDEN __iostream_category
     : public __do_message
 {
 public:
-    virtual const char* name() const _NOEXCEPT;
+    virtual const char* name() const noexcept;
     virtual string message(int ev) const;
 };
 
 const char*
-__iostream_category::name() const _NOEXCEPT
+__iostream_category::name() const noexcept
 {
     return "iostream";
 }
@@ -43,14 +43,14 @@ __iostream_category::message(int ev) const
     if (ev != static_cast<int>(io_errc::stream)
 #ifdef _LIBCPP_ELAST
         && ev <= _LIBCPP_ELAST
-#endif  // _LIBCPP_ELAST
+#endif // _LIBCPP_ELAST
         )
         return __do_message::message(ev);
     return string("unspecified iostream_category error");
 }
 
 const error_category&
-iostream_category() _NOEXCEPT
+iostream_category() noexcept
 {
     static __iostream_category s;
     return s;
@@ -387,7 +387,7 @@ ios_base::move(ios_base& rhs)
 }
 
 void
-ios_base::swap(ios_base& rhs) _NOEXCEPT
+ios_base::swap(ios_base& rhs) noexcept
 {
     _VSTD::swap(__fmtflags_, rhs.__fmtflags_);
     _VSTD::swap(__precision_, rhs.__precision_);
@@ -416,7 +416,7 @@ ios_base::__set_badbit_and_consider_rethrow()
 #ifndef _LIBCPP_NO_EXCEPTIONS
     if (__exceptions_ & badbit)
         throw;
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 void
@@ -426,7 +426,7 @@ ios_base::__set_failbit_and_consider_rethrow()
 #ifndef _LIBCPP_NO_EXCEPTIONS
     if (__exceptions_ & failbit)
         throw;
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 bool
lib/libcxx/src/locale.cpp
@@ -27,7 +27,6 @@
 #define _CTYPE_DISABLE_MACROS
 #endif
 #include "cwctype"
-#include "__sso_allocator"
 #if defined(_LIBCPP_MSVCRT) || defined(__MINGW32__)
 #include "__support/win32/locale_win32.h"
 #elif !defined(__BIONIC__) && !defined(__NuttX__)
@@ -36,6 +35,7 @@
 #include <stdlib.h>
 #include <stdio.h>
 #include "include/atomic_support.h"
+#include "include/sso_allocator.h"
 #include "__undef_macros"
 
 // On Linux, wint_t and wchar_t have different signed-ness, and this causes
@@ -206,7 +206,7 @@ _LIBCPP_SUPPRESS_DEPRECATED_PUSH
     install(&make<codecvt<char16_t, char, mbstate_t> >(1u));
     install(&make<codecvt<char32_t, char, mbstate_t> >(1u));
 _LIBCPP_SUPPRESS_DEPRECATED_POP
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
     install(&make<codecvt<char16_t, char8_t, mbstate_t> >(1u));
     install(&make<codecvt<char32_t, char8_t, mbstate_t> >(1u));
 #endif
@@ -240,7 +240,7 @@ locale::__imp::__imp(const string& name, size_t refs)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         facets_ = locale::classic().__locale_->facets_;
         for (unsigned i = 0; i < facets_.size(); ++i)
             if (facets_[i])
@@ -255,7 +255,7 @@ _LIBCPP_SUPPRESS_DEPRECATED_PUSH
         install(new codecvt_byname<char16_t, char, mbstate_t>(name_));
         install(new codecvt_byname<char32_t, char, mbstate_t>(name_));
 _LIBCPP_SUPPRESS_DEPRECATED_POP
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
         install(new codecvt_byname<char16_t, char8_t, mbstate_t>(name_));
         install(new codecvt_byname<char32_t, char8_t, mbstate_t>(name_));
 #endif
@@ -280,7 +280,7 @@ _LIBCPP_SUPPRESS_DEPRECATED_POP
                 facets_[i]->__release_shared();
         throw;
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 // NOTE avoid the `base class should be explicitly initialized in the
@@ -315,7 +315,7 @@ locale::__imp::__imp(const __imp& other, const string& name, locale::category c)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         if (c & locale::collate)
         {
             install(new collate_byname<char>(name));
@@ -331,7 +331,7 @@ _LIBCPP_SUPPRESS_DEPRECATED_PUSH
             install(new codecvt_byname<char16_t, char, mbstate_t>(name));
             install(new codecvt_byname<char32_t, char, mbstate_t>(name));
 _LIBCPP_SUPPRESS_DEPRECATED_POP
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
             install(new codecvt_byname<char16_t, char8_t, mbstate_t>(name));
             install(new codecvt_byname<char32_t, char8_t, mbstate_t>(name));
 #endif
@@ -369,7 +369,7 @@ _LIBCPP_SUPPRESS_DEPRECATED_POP
                 facets_[i]->__release_shared();
         throw;
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 template<class F>
@@ -392,7 +392,7 @@ locale::__imp::__imp(const __imp& other, const __imp& one, locale::category c)
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         if (c & locale::collate)
         {
             install_from<_VSTD::collate<char> >(one);
@@ -407,7 +407,7 @@ _LIBCPP_SUPPRESS_DEPRECATED_PUSH
             install_from<_VSTD::codecvt<char16_t, char, mbstate_t> >(one);
             install_from<_VSTD::codecvt<char32_t, char, mbstate_t> >(one);
 _LIBCPP_SUPPRESS_DEPRECATED_POP
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
             install_from<_VSTD::codecvt<char16_t, char8_t, mbstate_t> >(one);
             install_from<_VSTD::codecvt<char32_t, char8_t, mbstate_t> >(one);
 #endif
@@ -454,7 +454,7 @@ _LIBCPP_SUPPRESS_DEPRECATED_POP
                 facets_[i]->__release_shared();
         throw;
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
 }
 
 locale::__imp::__imp(const __imp& other, facet* f, long id)
@@ -532,13 +532,13 @@ locale::__global()
     return g;
 }
 
-locale::locale()  _NOEXCEPT
+locale::locale() noexcept
     : __locale_(__global().__locale_)
 {
     __locale_->__add_shared();
 }
 
-locale::locale(const locale& l)  _NOEXCEPT
+locale::locale(const locale& l) noexcept
     : __locale_(l.__locale_)
 {
     __locale_->__add_shared();
@@ -550,7 +550,7 @@ locale::~locale()
 }
 
 const locale&
-locale::operator=(const locale& other)  _NOEXCEPT
+locale::operator=(const locale& other) noexcept
 {
     other.__locale_->__add_shared();
     __locale_->__release_shared();
@@ -643,7 +643,7 @@ locale::facet::~facet()
 }
 
 void
-locale::facet::__on_zero_shared() _NOEXCEPT
+locale::facet::__on_zero_shared() noexcept
 {
     delete this;
 }
@@ -1051,7 +1051,7 @@ extern "C" const int ** __ctype_toupper_loc();
 
 #ifdef _LIBCPP_PROVIDES_DEFAULT_RUNE_TABLE
 const ctype<char>::mask*
-ctype<char>::classic_table()  _NOEXCEPT
+ctype<char>::classic_table() noexcept
 {
     static _LIBCPP_CONSTEXPR const ctype<char>::mask builtin_table[table_size] = {
         cntrl,                          cntrl,
@@ -1131,7 +1131,7 @@ ctype<char>::classic_table()  _NOEXCEPT
 }
 #else
 const ctype<char>::mask*
-ctype<char>::classic_table()  _NOEXCEPT
+ctype<char>::classic_table() noexcept
 {
 #if defined(__APPLE__) || defined(__FreeBSD__)
     return _DefaultRuneLocale.__runetype;
@@ -1139,7 +1139,7 @@ ctype<char>::classic_table()  _NOEXCEPT
     return _C_ctype_tab_ + 1;
 #elif defined(__GLIBC__)
     return _LIBCPP_GET_C_LOCALE->__ctype_b;
-#elif __sun__
+#elif defined(__sun__)
     return __ctype_mask;
 #elif defined(_LIBCPP_MSVCRT) || defined(__MINGW32__)
     return __pctype_func();
@@ -1163,38 +1163,38 @@ ctype<char>::classic_table()  _NOEXCEPT
 
 #if defined(__GLIBC__)
 const int*
-ctype<char>::__classic_lower_table() _NOEXCEPT
+ctype<char>::__classic_lower_table() noexcept
 {
     return _LIBCPP_GET_C_LOCALE->__ctype_tolower;
 }
 
 const int*
-ctype<char>::__classic_upper_table() _NOEXCEPT
+ctype<char>::__classic_upper_table() noexcept
 {
     return _LIBCPP_GET_C_LOCALE->__ctype_toupper;
 }
 #elif defined(__NetBSD__)
 const short*
-ctype<char>::__classic_lower_table() _NOEXCEPT
+ctype<char>::__classic_lower_table() noexcept
 {
     return _C_tolower_tab_ + 1;
 }
 
 const short*
-ctype<char>::__classic_upper_table() _NOEXCEPT
+ctype<char>::__classic_upper_table() noexcept
 {
     return _C_toupper_tab_ + 1;
 }
 
 #elif defined(__EMSCRIPTEN__)
 const int*
-ctype<char>::__classic_lower_table() _NOEXCEPT
+ctype<char>::__classic_lower_table() noexcept
 {
     return *__ctype_tolower_loc();
 }
 
 const int*
-ctype<char>::__classic_upper_table() _NOEXCEPT
+ctype<char>::__classic_upper_table() noexcept
 {
     return *__ctype_toupper_loc();
 }
@@ -1492,13 +1492,13 @@ codecvt<char, char, mbstate_t>::do_unshift(state_type&,
 }
 
 int
-codecvt<char, char, mbstate_t>::do_encoding() const  _NOEXCEPT
+codecvt<char, char, mbstate_t>::do_encoding() const noexcept
 {
     return 1;
 }
 
 bool
-codecvt<char, char, mbstate_t>::do_always_noconv() const  _NOEXCEPT
+codecvt<char, char, mbstate_t>::do_always_noconv() const noexcept
 {
     return true;
 }
@@ -1511,7 +1511,7 @@ codecvt<char, char, mbstate_t>::do_length(state_type&,
 }
 
 int
-codecvt<char, char, mbstate_t>::do_max_length() const  _NOEXCEPT
+codecvt<char, char, mbstate_t>::do_max_length() const noexcept
 {
     return 1;
 }
@@ -1682,7 +1682,7 @@ codecvt<wchar_t, char, mbstate_t>::do_unshift(state_type& st,
 }
 
 int
-codecvt<wchar_t, char, mbstate_t>::do_encoding() const  _NOEXCEPT
+codecvt<wchar_t, char, mbstate_t>::do_encoding() const noexcept
 {
     if (__libcpp_mbtowc_l(nullptr, nullptr, MB_LEN_MAX, __l) != 0)
         return -1;
@@ -1694,7 +1694,7 @@ codecvt<wchar_t, char, mbstate_t>::do_encoding() const  _NOEXCEPT
 }
 
 bool
-codecvt<wchar_t, char, mbstate_t>::do_always_noconv() const  _NOEXCEPT
+codecvt<wchar_t, char, mbstate_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -1726,7 +1726,7 @@ codecvt<wchar_t, char, mbstate_t>::do_length(state_type& st,
 }
 
 int
-codecvt<wchar_t, char, mbstate_t>::do_max_length() const  _NOEXCEPT
+codecvt<wchar_t, char, mbstate_t>::do_max_length() const noexcept
 {
     return __l == 0 ? 1 : static_cast<int>(__libcpp_mb_cur_max_l(__l));
 }
@@ -3169,13 +3169,13 @@ codecvt<char16_t, char, mbstate_t>::do_unshift(state_type&,
 }
 
 int
-codecvt<char16_t, char, mbstate_t>::do_encoding() const  _NOEXCEPT
+codecvt<char16_t, char, mbstate_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-codecvt<char16_t, char, mbstate_t>::do_always_noconv() const  _NOEXCEPT
+codecvt<char16_t, char, mbstate_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3190,12 +3190,12 @@ codecvt<char16_t, char, mbstate_t>::do_length(state_type&,
 }
 
 int
-codecvt<char16_t, char, mbstate_t>::do_max_length() const  _NOEXCEPT
+codecvt<char16_t, char, mbstate_t>::do_max_length() const noexcept
 {
     return 4;
 }
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 
 // template <> class codecvt<char16_t, char8_t, mbstate_t>
 
@@ -3248,13 +3248,13 @@ codecvt<char16_t, char8_t, mbstate_t>::do_unshift(state_type&,
 }
 
 int
-codecvt<char16_t, char8_t, mbstate_t>::do_encoding() const  _NOEXCEPT
+codecvt<char16_t, char8_t, mbstate_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-codecvt<char16_t, char8_t, mbstate_t>::do_always_noconv() const  _NOEXCEPT
+codecvt<char16_t, char8_t, mbstate_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3269,7 +3269,7 @@ codecvt<char16_t, char8_t, mbstate_t>::do_length(state_type&,
 }
 
 int
-codecvt<char16_t, char8_t, mbstate_t>::do_max_length() const  _NOEXCEPT
+codecvt<char16_t, char8_t, mbstate_t>::do_max_length() const noexcept
 {
     return 4;
 }
@@ -3327,13 +3327,13 @@ codecvt<char32_t, char, mbstate_t>::do_unshift(state_type&,
 }
 
 int
-codecvt<char32_t, char, mbstate_t>::do_encoding() const  _NOEXCEPT
+codecvt<char32_t, char, mbstate_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-codecvt<char32_t, char, mbstate_t>::do_always_noconv() const  _NOEXCEPT
+codecvt<char32_t, char, mbstate_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3348,12 +3348,12 @@ codecvt<char32_t, char, mbstate_t>::do_length(state_type&,
 }
 
 int
-codecvt<char32_t, char, mbstate_t>::do_max_length() const  _NOEXCEPT
+codecvt<char32_t, char, mbstate_t>::do_max_length() const noexcept
 {
     return 4;
 }
 
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 
 // template <> class codecvt<char32_t, char8_t, mbstate_t>
 
@@ -3406,13 +3406,13 @@ codecvt<char32_t, char8_t, mbstate_t>::do_unshift(state_type&,
 }
 
 int
-codecvt<char32_t, char8_t, mbstate_t>::do_encoding() const  _NOEXCEPT
+codecvt<char32_t, char8_t, mbstate_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-codecvt<char32_t, char8_t, mbstate_t>::do_always_noconv() const  _NOEXCEPT
+codecvt<char32_t, char8_t, mbstate_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3427,7 +3427,7 @@ codecvt<char32_t, char8_t, mbstate_t>::do_length(state_type&,
 }
 
 int
-codecvt<char32_t, char8_t, mbstate_t>::do_max_length() const  _NOEXCEPT
+codecvt<char32_t, char8_t, mbstate_t>::do_max_length() const noexcept
 {
     return 4;
 }
@@ -3500,13 +3500,13 @@ __codecvt_utf8<wchar_t>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf8<wchar_t>::do_encoding() const  _NOEXCEPT
+__codecvt_utf8<wchar_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf8<wchar_t>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf8<wchar_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3521,7 +3521,7 @@ __codecvt_utf8<wchar_t>::do_length(state_type&,
 }
 
 int
-__codecvt_utf8<wchar_t>::do_max_length() const  _NOEXCEPT
+__codecvt_utf8<wchar_t>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 7;
@@ -3575,13 +3575,13 @@ __codecvt_utf8<char16_t>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf8<char16_t>::do_encoding() const  _NOEXCEPT
+__codecvt_utf8<char16_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf8<char16_t>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf8<char16_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3596,7 +3596,7 @@ __codecvt_utf8<char16_t>::do_length(state_type&,
 }
 
 int
-__codecvt_utf8<char16_t>::do_max_length() const  _NOEXCEPT
+__codecvt_utf8<char16_t>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 6;
@@ -3650,13 +3650,13 @@ __codecvt_utf8<char32_t>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf8<char32_t>::do_encoding() const  _NOEXCEPT
+__codecvt_utf8<char32_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf8<char32_t>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf8<char32_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3671,7 +3671,7 @@ __codecvt_utf8<char32_t>::do_length(state_type&,
 }
 
 int
-__codecvt_utf8<char32_t>::do_max_length() const  _NOEXCEPT
+__codecvt_utf8<char32_t>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 7;
@@ -3725,13 +3725,13 @@ __codecvt_utf16<wchar_t, false>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf16<wchar_t, false>::do_encoding() const  _NOEXCEPT
+__codecvt_utf16<wchar_t, false>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf16<wchar_t, false>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf16<wchar_t, false>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3746,7 +3746,7 @@ __codecvt_utf16<wchar_t, false>::do_length(state_type&,
 }
 
 int
-__codecvt_utf16<wchar_t, false>::do_max_length() const  _NOEXCEPT
+__codecvt_utf16<wchar_t, false>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 6;
@@ -3800,13 +3800,13 @@ __codecvt_utf16<wchar_t, true>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf16<wchar_t, true>::do_encoding() const  _NOEXCEPT
+__codecvt_utf16<wchar_t, true>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf16<wchar_t, true>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf16<wchar_t, true>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3821,7 +3821,7 @@ __codecvt_utf16<wchar_t, true>::do_length(state_type&,
 }
 
 int
-__codecvt_utf16<wchar_t, true>::do_max_length() const  _NOEXCEPT
+__codecvt_utf16<wchar_t, true>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 6;
@@ -3875,13 +3875,13 @@ __codecvt_utf16<char16_t, false>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf16<char16_t, false>::do_encoding() const  _NOEXCEPT
+__codecvt_utf16<char16_t, false>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf16<char16_t, false>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf16<char16_t, false>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3896,7 +3896,7 @@ __codecvt_utf16<char16_t, false>::do_length(state_type&,
 }
 
 int
-__codecvt_utf16<char16_t, false>::do_max_length() const  _NOEXCEPT
+__codecvt_utf16<char16_t, false>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 4;
@@ -3950,13 +3950,13 @@ __codecvt_utf16<char16_t, true>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf16<char16_t, true>::do_encoding() const  _NOEXCEPT
+__codecvt_utf16<char16_t, true>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf16<char16_t, true>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf16<char16_t, true>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -3971,7 +3971,7 @@ __codecvt_utf16<char16_t, true>::do_length(state_type&,
 }
 
 int
-__codecvt_utf16<char16_t, true>::do_max_length() const  _NOEXCEPT
+__codecvt_utf16<char16_t, true>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 4;
@@ -4025,13 +4025,13 @@ __codecvt_utf16<char32_t, false>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf16<char32_t, false>::do_encoding() const  _NOEXCEPT
+__codecvt_utf16<char32_t, false>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf16<char32_t, false>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf16<char32_t, false>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -4046,7 +4046,7 @@ __codecvt_utf16<char32_t, false>::do_length(state_type&,
 }
 
 int
-__codecvt_utf16<char32_t, false>::do_max_length() const  _NOEXCEPT
+__codecvt_utf16<char32_t, false>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 6;
@@ -4100,13 +4100,13 @@ __codecvt_utf16<char32_t, true>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf16<char32_t, true>::do_encoding() const  _NOEXCEPT
+__codecvt_utf16<char32_t, true>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf16<char32_t, true>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf16<char32_t, true>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -4121,7 +4121,7 @@ __codecvt_utf16<char32_t, true>::do_length(state_type&,
 }
 
 int
-__codecvt_utf16<char32_t, true>::do_max_length() const  _NOEXCEPT
+__codecvt_utf16<char32_t, true>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 6;
@@ -4175,13 +4175,13 @@ __codecvt_utf8_utf16<wchar_t>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf8_utf16<wchar_t>::do_encoding() const  _NOEXCEPT
+__codecvt_utf8_utf16<wchar_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf8_utf16<wchar_t>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf8_utf16<wchar_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -4196,7 +4196,7 @@ __codecvt_utf8_utf16<wchar_t>::do_length(state_type&,
 }
 
 int
-__codecvt_utf8_utf16<wchar_t>::do_max_length() const  _NOEXCEPT
+__codecvt_utf8_utf16<wchar_t>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 7;
@@ -4250,13 +4250,13 @@ __codecvt_utf8_utf16<char16_t>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf8_utf16<char16_t>::do_encoding() const  _NOEXCEPT
+__codecvt_utf8_utf16<char16_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf8_utf16<char16_t>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf8_utf16<char16_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -4271,7 +4271,7 @@ __codecvt_utf8_utf16<char16_t>::do_length(state_type&,
 }
 
 int
-__codecvt_utf8_utf16<char16_t>::do_max_length() const  _NOEXCEPT
+__codecvt_utf8_utf16<char16_t>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 7;
@@ -4325,13 +4325,13 @@ __codecvt_utf8_utf16<char32_t>::do_unshift(state_type&,
 }
 
 int
-__codecvt_utf8_utf16<char32_t>::do_encoding() const  _NOEXCEPT
+__codecvt_utf8_utf16<char32_t>::do_encoding() const noexcept
 {
     return 0;
 }
 
 bool
-__codecvt_utf8_utf16<char32_t>::do_always_noconv() const  _NOEXCEPT
+__codecvt_utf8_utf16<char32_t>::do_always_noconv() const noexcept
 {
     return false;
 }
@@ -4346,7 +4346,7 @@ __codecvt_utf8_utf16<char32_t>::do_length(state_type&,
 }
 
 int
-__codecvt_utf8_utf16<char32_t>::do_max_length() const  _NOEXCEPT
+__codecvt_utf8_utf16<char32_t>::do_max_length() const noexcept
 {
     if (_Mode_ & consume_header)
         return 7;
@@ -4597,7 +4597,10 @@ void
 __num_put_base::__format_int(char* __fmtp, const char* __len, bool __signd,
                              ios_base::fmtflags __flags)
 {
-    if (__flags & ios_base::showpos)
+    if ((__flags & ios_base::showpos) &&
+        (__flags & ios_base::basefield) != ios_base::oct &&
+        (__flags & ios_base::basefield) != ios_base::hex &&
+	__signd)
         *__fmtp++ = '+';
     if (__flags & ios_base::showbase)
         *__fmtp++ = '#';
@@ -6336,7 +6339,7 @@ template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<char, cha
 template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<wchar_t, char, mbstate_t>;
 template class _LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<char16_t, char, mbstate_t>;
 template class _LIBCPP_DEPRECATED_IN_CXX20 _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<char32_t, char, mbstate_t>;
-#ifndef _LIBCPP_NO_HAS_CHAR8_T
+#ifndef _LIBCPP_HAS_NO_CHAR8_T
 template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<char16_t, char8_t, mbstate_t>;
 template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS codecvt_byname<char32_t, char8_t, mbstate_t>;
 #endif
lib/libcxx/src/memory.cpp
@@ -20,10 +20,10 @@ _LIBCPP_BEGIN_NAMESPACE_STD
 
 const allocator_arg_t allocator_arg = allocator_arg_t();
 
-bad_weak_ptr::~bad_weak_ptr() _NOEXCEPT {}
+bad_weak_ptr::~bad_weak_ptr() noexcept {}
 
 const char*
-bad_weak_ptr::what() const _NOEXCEPT
+bad_weak_ptr::what() const noexcept
 {
     return "bad_weak_ptr";
 }
@@ -38,13 +38,13 @@ __shared_weak_count::~__shared_weak_count()
 
 #if defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
 void
-__shared_count::__add_shared() _NOEXCEPT
+__shared_count::__add_shared() noexcept
 {
     __libcpp_atomic_refcount_increment(__shared_owners_);
 }
 
 bool
-__shared_count::__release_shared() _NOEXCEPT
+__shared_count::__release_shared() noexcept
 {
     if (__libcpp_atomic_refcount_decrement(__shared_owners_) == -1)
     {
@@ -55,19 +55,19 @@ __shared_count::__release_shared() _NOEXCEPT
 }
 
 void
-__shared_weak_count::__add_shared() _NOEXCEPT
+__shared_weak_count::__add_shared() noexcept
 {
     __shared_count::__add_shared();
 }
 
 void
-__shared_weak_count::__add_weak() _NOEXCEPT
+__shared_weak_count::__add_weak() noexcept
 {
     __libcpp_atomic_refcount_increment(__shared_weak_owners_);
 }
 
 void
-__shared_weak_count::__release_shared() _NOEXCEPT
+__shared_weak_count::__release_shared() noexcept
 {
     if (__shared_count::__release_shared())
         __release_weak();
@@ -76,7 +76,7 @@ __shared_weak_count::__release_shared() _NOEXCEPT
 #endif // _LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS
 
 void
-__shared_weak_count::__release_weak() _NOEXCEPT
+__shared_weak_count::__release_weak() noexcept
 {
     // NOTE: The acquire load here is an optimization of the very
     // common case where a shared pointer is being destructed while
@@ -111,7 +111,7 @@ __shared_weak_count::__release_weak() _NOEXCEPT
 }
 
 __shared_weak_count*
-__shared_weak_count::lock() _NOEXCEPT
+__shared_weak_count::lock() noexcept
 {
     long object_owners = __libcpp_atomic_load(&__shared_owners_);
     while (object_owners != -1)
@@ -125,7 +125,7 @@ __shared_weak_count::lock() _NOEXCEPT
 }
 
 const void*
-__shared_weak_count::__get_deleter(const type_info&) const _NOEXCEPT
+__shared_weak_count::__get_deleter(const type_info&) const noexcept
 {
     return nullptr;
 }
@@ -141,13 +141,13 @@ _LIBCPP_SAFE_STATIC static __libcpp_mutex_t mut_back[__sp_mut_count] =
     _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER
 };
 
-_LIBCPP_CONSTEXPR __sp_mut::__sp_mut(void* p) _NOEXCEPT
+_LIBCPP_CONSTEXPR __sp_mut::__sp_mut(void* p) noexcept
    : __lx(p)
 {
 }
 
 void
-__sp_mut::lock() _NOEXCEPT
+__sp_mut::lock() noexcept
 {
     auto m = static_cast<__libcpp_mutex_t*>(__lx);
     unsigned count = 0;
@@ -163,7 +163,7 @@ __sp_mut::lock() _NOEXCEPT
 }
 
 void
-__sp_mut::unlock() _NOEXCEPT
+__sp_mut::unlock() noexcept
 {
     __libcpp_mutex_unlock(static_cast<__libcpp_mutex_t*>(__lx));
 }
@@ -198,13 +198,6 @@ undeclare_no_pointers(char*, size_t)
 {
 }
 
-#if !defined(_LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE)
-pointer_safety get_pointer_safety() _NOEXCEPT
-{
-    return pointer_safety::relaxed;
-}
-#endif
-
 void*
 __undeclare_reachable(void* p)
 {
lib/libcxx/src/mutex.cpp
@@ -36,13 +36,13 @@ mutex::lock()
 }
 
 bool
-mutex::try_lock() _NOEXCEPT
+mutex::try_lock() noexcept
 {
     return __libcpp_mutex_trylock(&__m_);
 }
 
 void
-mutex::unlock() _NOEXCEPT
+mutex::unlock() noexcept
 {
     int ec = __libcpp_mutex_unlock(&__m_);
     (void)ec;
@@ -74,7 +74,7 @@ recursive_mutex::lock()
 }
 
 void
-recursive_mutex::unlock() _NOEXCEPT
+recursive_mutex::unlock() noexcept
 {
     int e = __libcpp_recursive_mutex_unlock(&__m_);
     (void)e;
@@ -82,7 +82,7 @@ recursive_mutex::unlock() _NOEXCEPT
 }
 
 bool
-recursive_mutex::try_lock() _NOEXCEPT
+recursive_mutex::try_lock() noexcept
 {
     return __libcpp_recursive_mutex_trylock(&__m_);
 }
@@ -109,7 +109,7 @@ timed_mutex::lock()
 }
 
 bool
-timed_mutex::try_lock() _NOEXCEPT
+timed_mutex::try_lock() noexcept
 {
     unique_lock<mutex> lk(__m_, try_to_lock);
     if (lk.owns_lock() && !__locked_)
@@ -121,7 +121,7 @@ timed_mutex::try_lock() _NOEXCEPT
 }
 
 void
-timed_mutex::unlock() _NOEXCEPT
+timed_mutex::unlock() noexcept
 {
     lock_guard<mutex> _(__m_);
     __locked_ = false;
@@ -160,7 +160,7 @@ recursive_timed_mutex::lock()
 }
 
 bool
-recursive_timed_mutex::try_lock() _NOEXCEPT
+recursive_timed_mutex::try_lock() noexcept
 {
     __thread_id id = this_thread::get_id();
     unique_lock<mutex> lk(__m_, try_to_lock);
@@ -176,7 +176,7 @@ recursive_timed_mutex::try_lock() _NOEXCEPT
 }
 
 void
-recursive_timed_mutex::unlock() _NOEXCEPT
+recursive_timed_mutex::unlock() noexcept
 {
     unique_lock<mutex> lk(__m_);
     if (--__count_ == 0)
@@ -209,7 +209,7 @@ void __call_once(volatile once_flag::_State_type& flag, void* arg,
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             flag = 1;
             func(arg);
             flag = ~once_flag::_State_type(0);
@@ -220,7 +220,7 @@ void __call_once(volatile once_flag::_State_type& flag, void* arg,
             flag = 0;
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
 #else // !_LIBCPP_HAS_NO_THREADS
     __libcpp_mutex_lock(&mut);
@@ -231,7 +231,7 @@ void __call_once(volatile once_flag::_State_type& flag, void* arg,
 #ifndef _LIBCPP_NO_EXCEPTIONS
         try
         {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
             __libcpp_relaxed_store(&flag, once_flag::_State_type(1));
             __libcpp_mutex_unlock(&mut);
             func(arg);
@@ -250,7 +250,7 @@ void __call_once(volatile once_flag::_State_type& flag, void* arg,
             __libcpp_condvar_broadcast(&cv);
             throw;
         }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     }
     else
         __libcpp_mutex_unlock(&mut);
lib/libcxx/src/mutex_destructor.cpp
@@ -41,7 +41,7 @@ public:
 };
 
 
-mutex::~mutex() _NOEXCEPT
+mutex::~mutex() noexcept
 {
     __libcpp_mutex_destroy(&__m_);
 }
lib/libcxx/src/new.cpp
@@ -83,20 +83,20 @@ operator new(std::size_t size) _THROW_BAD_ALLOC
 
 _LIBCPP_WEAK
 void*
-operator new(size_t size, const std::nothrow_t&) _NOEXCEPT
+operator new(size_t size, const std::nothrow_t&) noexcept
 {
     void* p = nullptr;
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         p = ::operator new(size);
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
     catch (...)
     {
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return p;
 }
 
@@ -109,61 +109,61 @@ operator new[](size_t size) _THROW_BAD_ALLOC
 
 _LIBCPP_WEAK
 void*
-operator new[](size_t size, const std::nothrow_t&) _NOEXCEPT
+operator new[](size_t size, const std::nothrow_t&) noexcept
 {
     void* p = nullptr;
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         p = ::operator new[](size);
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
     catch (...)
     {
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return p;
 }
 
 _LIBCPP_WEAK
 void
-operator delete(void* ptr) _NOEXCEPT
+operator delete(void* ptr) noexcept
 {
     ::free(ptr);
 }
 
 _LIBCPP_WEAK
 void
-operator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT
+operator delete(void* ptr, const std::nothrow_t&) noexcept
 {
     ::operator delete(ptr);
 }
 
 _LIBCPP_WEAK
 void
-operator delete(void* ptr, size_t) _NOEXCEPT
+operator delete(void* ptr, size_t) noexcept
 {
     ::operator delete(ptr);
 }
 
 _LIBCPP_WEAK
 void
-operator delete[] (void* ptr) _NOEXCEPT
+operator delete[] (void* ptr) noexcept
 {
     ::operator delete(ptr);
 }
 
 _LIBCPP_WEAK
 void
-operator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT
+operator delete[] (void* ptr, const std::nothrow_t&) noexcept
 {
     ::operator delete[](ptr);
 }
 
 _LIBCPP_WEAK
 void
-operator delete[] (void* ptr, size_t) _NOEXCEPT
+operator delete[] (void* ptr, size_t) noexcept
 {
     ::operator delete[](ptr);
 }
@@ -204,20 +204,20 @@ operator new(std::size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
 
 _LIBCPP_WEAK
 void*
-operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
+operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept
 {
     void* p = nullptr;
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         p = ::operator new(size, alignment);
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
     catch (...)
     {
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return p;
 }
 
@@ -230,61 +230,61 @@ operator new[](size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
 
 _LIBCPP_WEAK
 void*
-operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
+operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept
 {
     void* p = nullptr;
 #ifndef _LIBCPP_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
         p = ::operator new[](size, alignment);
 #ifndef _LIBCPP_NO_EXCEPTIONS
     }
     catch (...)
     {
     }
-#endif  // _LIBCPP_NO_EXCEPTIONS
+#endif // _LIBCPP_NO_EXCEPTIONS
     return p;
 }
 
 _LIBCPP_WEAK
 void
-operator delete(void* ptr, std::align_val_t) _NOEXCEPT
+operator delete(void* ptr, std::align_val_t) noexcept
 {
     std::__libcpp_aligned_free(ptr);
 }
 
 _LIBCPP_WEAK
 void
-operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
+operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) noexcept
 {
     ::operator delete(ptr, alignment);
 }
 
 _LIBCPP_WEAK
 void
-operator delete(void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
+operator delete(void* ptr, size_t, std::align_val_t alignment) noexcept
 {
     ::operator delete(ptr, alignment);
 }
 
 _LIBCPP_WEAK
 void
-operator delete[] (void* ptr, std::align_val_t alignment) _NOEXCEPT
+operator delete[] (void* ptr, std::align_val_t alignment) noexcept
 {
     ::operator delete(ptr, alignment);
 }
 
 _LIBCPP_WEAK
 void
-operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
+operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) noexcept
 {
     ::operator delete[](ptr, alignment);
 }
 
 _LIBCPP_WEAK
 void
-operator delete[] (void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
+operator delete[] (void* ptr, size_t, std::align_val_t alignment) noexcept
 {
     ::operator delete[](ptr, alignment);
 }
lib/libcxx/src/optional.cpp
@@ -12,9 +12,9 @@
 namespace std
 {
 
-bad_optional_access::~bad_optional_access() _NOEXCEPT = default;
+bad_optional_access::~bad_optional_access() noexcept = default;
 
-const char* bad_optional_access::what() const _NOEXCEPT {
+const char* bad_optional_access::what() const noexcept {
   return "bad_optional_access";
   }
 
@@ -34,9 +34,9 @@ public:
 	bad_optional_access() : std::logic_error("Bad optional Access") {}
 
 //	Get the key function ~bad_optional_access() into the dylib
-    virtual ~bad_optional_access() _NOEXCEPT;
+    virtual ~bad_optional_access() noexcept;
 };
 
-bad_optional_access::~bad_optional_access() _NOEXCEPT = default;
+bad_optional_access::~bad_optional_access() noexcept = default;
 
 _LIBCPP_END_NAMESPACE_EXPERIMENTAL
lib/libcxx/src/random.cpp
@@ -175,7 +175,7 @@ random_device::operator()()
 #endif
 
 double
-random_device::entropy() const _NOEXCEPT
+random_device::entropy() const noexcept
 {
 #if defined(_LIBCPP_USING_DEV_RANDOM) && defined(RNDGETENTCNT)
   int ent;
lib/libcxx/src/string.cpp
@@ -20,6 +20,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD
 
 template class _LIBCPP_CLASS_TEMPLATE_INSTANTIATION_VIS __basic_string_common<true>;
 
+#define _LIBCPP_EXTERN_TEMPLATE_DEFINE(...) template __VA_ARGS__;
 #ifdef _LIBCPP_ABI_STRING_OPTIMIZED_EXTERNAL_INSTANTIATION
 _LIBCPP_STRING_UNSTABLE_EXTERN_TEMPLATE_LIST(_LIBCPP_EXTERN_TEMPLATE_DEFINE, char)
 _LIBCPP_STRING_UNSTABLE_EXTERN_TEMPLATE_LIST(_LIBCPP_EXTERN_TEMPLATE_DEFINE, wchar_t)
@@ -27,10 +28,9 @@ _LIBCPP_STRING_UNSTABLE_EXTERN_TEMPLATE_LIST(_LIBCPP_EXTERN_TEMPLATE_DEFINE, wch
 _LIBCPP_STRING_V1_EXTERN_TEMPLATE_LIST(_LIBCPP_EXTERN_TEMPLATE_DEFINE, char)
 _LIBCPP_STRING_V1_EXTERN_TEMPLATE_LIST(_LIBCPP_EXTERN_TEMPLATE_DEFINE, wchar_t)
 #endif
+#undef _LIBCPP_EXTERN_TEMPLATE_DEFINE
 
-template
-    string
-    operator+<char, char_traits<char>, allocator<char> >(char const*, string const&);
+template string operator+<char, char_traits<char>, allocator<char> >(char const*, string const&);
 
 namespace
 {
@@ -423,7 +423,7 @@ get_swprintf()
 }
 
 template <typename S, typename V>
-S i_to_string(const V v)
+S i_to_string(V v)
 {
 //  numeric_limits::digits10 returns value less on 1 than desired for unsigned numbers.
 //  For example, for 1-byte unsigned value digits10 is 2 (999 can not be represented),
lib/libcxx/src/system_error.cpp
@@ -28,29 +28,29 @@ _LIBCPP_BEGIN_NAMESPACE_STD
 // class error_category
 
 #if defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
-error_category::error_category() _NOEXCEPT
+error_category::error_category() noexcept
 {
 }
 #endif
 
-error_category::~error_category() _NOEXCEPT
+error_category::~error_category() noexcept
 {
 }
 
 error_condition
-error_category::default_error_condition(int ev) const _NOEXCEPT
+error_category::default_error_condition(int ev) const noexcept
 {
     return error_condition(ev, *this);
 }
 
 bool
-error_category::equivalent(int code, const error_condition& condition) const _NOEXCEPT
+error_category::equivalent(int code, const error_condition& condition) const noexcept
 {
     return default_error_condition(code) == condition;
 }
 
 bool
-error_category::equivalent(const error_code& code, int condition) const _NOEXCEPT
+error_category::equivalent(const error_code& code, int condition) const noexcept
 {
     return *this == code.category() && code.value() == condition;
 }
@@ -141,12 +141,12 @@ class _LIBCPP_HIDDEN __generic_error_category
     : public __do_message
 {
 public:
-    virtual const char* name() const _NOEXCEPT;
+    virtual const char* name() const noexcept;
     virtual string message(int ev) const;
 };
 
 const char*
-__generic_error_category::name() const _NOEXCEPT
+__generic_error_category::name() const noexcept
 {
     return "generic";
 }
@@ -157,12 +157,12 @@ __generic_error_category::message(int ev) const
 #ifdef _LIBCPP_ELAST
     if (ev > _LIBCPP_ELAST)
       return string("unspecified generic_category error");
-#endif  // _LIBCPP_ELAST
+#endif // _LIBCPP_ELAST
     return __do_message::message(ev);
 }
 
 const error_category&
-generic_category() _NOEXCEPT
+generic_category() noexcept
 {
     static __generic_error_category s;
     return s;
@@ -172,13 +172,13 @@ class _LIBCPP_HIDDEN __system_error_category
     : public __do_message
 {
 public:
-    virtual const char* name() const _NOEXCEPT;
+    virtual const char* name() const noexcept;
     virtual string message(int ev) const;
-    virtual error_condition default_error_condition(int ev) const _NOEXCEPT;
+    virtual error_condition default_error_condition(int ev) const noexcept;
 };
 
 const char*
-__system_error_category::name() const _NOEXCEPT
+__system_error_category::name() const noexcept
 {
     return "system";
 }
@@ -189,22 +189,22 @@ __system_error_category::message(int ev) const
 #ifdef _LIBCPP_ELAST
     if (ev > _LIBCPP_ELAST)
       return string("unspecified system_category error");
-#endif  // _LIBCPP_ELAST
+#endif // _LIBCPP_ELAST
     return __do_message::message(ev);
 }
 
 error_condition
-__system_error_category::default_error_condition(int ev) const _NOEXCEPT
+__system_error_category::default_error_condition(int ev) const noexcept
 {
 #ifdef _LIBCPP_ELAST
     if (ev > _LIBCPP_ELAST)
       return error_condition(ev, system_category());
-#endif  // _LIBCPP_ELAST
+#endif // _LIBCPP_ELAST
     return error_condition(ev, generic_category());
 }
 
 const error_category&
-system_category() _NOEXCEPT
+system_category() noexcept
 {
     static __system_error_category s;
     return s;
@@ -276,7 +276,7 @@ system_error::system_error(int ev, const error_category& ecat)
 {
 }
 
-system_error::~system_error() _NOEXCEPT
+system_error::~system_error() noexcept
 {
 }
 
lib/libcxx/src/thread.cpp
@@ -70,7 +70,7 @@ thread::detach()
 }
 
 unsigned
-thread::hardware_concurrency() _NOEXCEPT
+thread::hardware_concurrency() noexcept
 {
 #if defined(_SC_NPROCESSORS_ONLN)
     long result = sysconf(_SC_NPROCESSORS_ONLN);
@@ -94,7 +94,7 @@ thread::hardware_concurrency() _NOEXCEPT
 #       warning hardware_concurrency not yet implemented
 #   endif
     return 0;  // Means not computable [thread.thread.static]
-#endif  // defined(CTL_HW) && defined(HW_NCPU)
+#endif // defined(CTL_HW) && defined(HW_NCPU)
 }
 
 namespace this_thread
lib/libcxx/src/typeinfo.cpp
@@ -11,18 +11,18 @@
 #if defined(_LIBCPP_ABI_MICROSOFT) && !defined(_LIBCPP_ABI_VCRUNTIME)
 #include <string.h>
 
-int std::type_info::__compare(const type_info &__rhs) const _NOEXCEPT {
+int std::type_info::__compare(const type_info &__rhs) const noexcept {
   if (&__data == &__rhs.__data)
     return 0;
   return strcmp(&__data.__decorated_name[1], &__rhs.__data.__decorated_name[1]);
 }
 
-const char *std::type_info::name() const _NOEXCEPT {
+const char *std::type_info::name() const noexcept {
   // TODO(compnerd) cache demangled &__data.__decorated_name[1]
   return &__data.__decorated_name[1];
 }
 
-size_t std::type_info::hash_code() const _NOEXCEPT {
+size_t std::type_info::hash_code() const noexcept {
 #if defined(_WIN64)
   constexpr size_t fnv_offset_basis = 14695981039346656037ull;
   constexpr size_t fnv_prime = 10995116282110ull;
lib/libcxxabi/src/demangle/ItaniumDemangle.h
@@ -280,17 +280,20 @@ public:
 class VendorExtQualType final : public Node {
   const Node *Ty;
   StringView Ext;
+  const Node *TA;
 
 public:
-  VendorExtQualType(const Node *Ty_, StringView Ext_)
-      : Node(KVendorExtQualType), Ty(Ty_), Ext(Ext_) {}
+  VendorExtQualType(const Node *Ty_, StringView Ext_, const Node *TA_)
+      : Node(KVendorExtQualType), Ty(Ty_), Ext(Ext_), TA(TA_) {}
 
-  template<typename Fn> void match(Fn F) const { F(Ty, Ext); }
+  template <typename Fn> void match(Fn F) const { F(Ty, Ext, TA); }
 
   void printLeft(OutputStream &S) const override {
     Ty->print(S);
     S += " ";
     S += Ext;
+    if (TA != nullptr)
+      TA->print(S);
   }
 };
 
@@ -3680,8 +3683,6 @@ Node *AbstractManglingParser<Derived, Alloc>::parseQualifiedType() {
     if (Qual.empty())
       return nullptr;
 
-    // FIXME parse the optional <template-args> here!
-
     // extension            ::= U <objc-name> <objc-type>  # objc-type<identifier>
     if (Qual.startsWith("objcproto")) {
       StringView ProtoSourceName = Qual.dropFront(std::strlen("objcproto"));
@@ -3699,10 +3700,17 @@ Node *AbstractManglingParser<Derived, Alloc>::parseQualifiedType() {
       return make<ObjCProtoName>(Child, Proto);
     }
 
+    Node *TA = nullptr;
+    if (look() == 'I') {
+      TA = getDerived().parseTemplateArgs();
+      if (TA == nullptr)
+        return nullptr;
+    }
+
     Node *Child = getDerived().parseQualifiedType();
     if (Child == nullptr)
       return nullptr;
-    return make<VendorExtQualType>(Child, Qual);
+    return make<VendorExtQualType>(Child, Qual, TA);
   }
 
   Qualifiers Quals = parseCVQualifiers();
@@ -3875,7 +3883,7 @@ Node *AbstractManglingParser<Derived, Alloc>::parseType() {
     //                ::= Dh   # IEEE 754r half-precision floating point (16 bits)
     case 'h':
       First += 2;
-      return make<NameType>("decimal16");
+      return make<NameType>("half");
     //                ::= Di   # char32_t
     case 'i':
       First += 2;
@@ -5227,14 +5235,18 @@ Node *AbstractManglingParser<Derived, Alloc>::parseEncoding() {
   class SaveTemplateParams {
     AbstractManglingParser *Parser;
     decltype(TemplateParams) OldParams;
+    decltype(OuterTemplateParams) OldOuterParams;
 
   public:
     SaveTemplateParams(AbstractManglingParser *TheParser) : Parser(TheParser) {
       OldParams = std::move(Parser->TemplateParams);
+      OldOuterParams = std::move(Parser->OuterTemplateParams);
       Parser->TemplateParams.clear();
+      Parser->OuterTemplateParams.clear();
     }
     ~SaveTemplateParams() {
       Parser->TemplateParams = std::move(OldParams);
+      Parser->OuterTemplateParams = std::move(OldOuterParams);
     }
   } SaveTemplateParams(this);
 
lib/libcxxabi/src/demangle/StringView.h
@@ -36,8 +36,9 @@ public:
   StringView(const char *Str) : First(Str), Last(Str + std::strlen(Str)) {}
   StringView() : First(nullptr), Last(nullptr) {}
 
-  StringView substr(size_t From) const {
-    return StringView(begin() + From, size() - From);
+  StringView substr(size_t Pos, size_t Len = npos) const {
+    assert(Pos <= size());
+    return StringView(begin() + Pos, std::min(Len, size() - Pos));
   }
 
   size_t find(char C, size_t From = 0) const {
@@ -51,14 +52,6 @@ public:
     return npos;
   }
 
-  StringView substr(size_t From, size_t To) const {
-    if (To >= size())
-      To = size() - 1;
-    if (From >= size())
-      From = size() - 1;
-    return StringView(First + From, First + To);
-  }
-
   StringView dropFront(size_t N = 1) const {
     if (N >= size())
       N = size();
lib/libcxxabi/src/cxa_default_handlers.cpp
@@ -108,7 +108,7 @@ namespace std
 {
 
 unexpected_handler
-set_unexpected(unexpected_handler func) _NOEXCEPT
+set_unexpected(unexpected_handler func) noexcept
 {
     if (func == 0)
         func = default_unexpected_handler;
@@ -117,7 +117,7 @@ set_unexpected(unexpected_handler func) _NOEXCEPT
 }
 
 terminate_handler
-set_terminate(terminate_handler func) _NOEXCEPT
+set_terminate(terminate_handler func) noexcept
 {
     if (func == 0)
         func = default_terminate_handler;
lib/libcxxabi/src/cxa_exception.cpp
@@ -20,7 +20,7 @@
 #include "include/atomic_support.h"
 
 #if __has_feature(address_sanitizer)
-extern "C" void __asan_handle_no_return(void);
+#include <sanitizer/asan_interface.h>
 #endif
 
 // +---------------------------+-----------------------------+---------------+
@@ -384,7 +384,7 @@ asm (
     "	bl	abort\n"
     "	.popsection"
 );
-#endif  // defined(_LIBCXXABI_ARM_EHABI)
+#endif // defined(_LIBCXXABI_ARM_EHABI)
 
 /*
 This routine can catch foreign or native exceptions.  If native, the exception
lib/libcxxabi/src/cxa_exception.h
@@ -161,4 +161,4 @@ extern "C" _LIBCXXABI_FUNC_VIS void __cxa_free_dependent_exception (void * depen
 
 }  // namespace __cxxabiv1
 
-#endif  // _CXA_EXCEPTION_H
+#endif // _CXA_EXCEPTION_H
lib/libcxxabi/src/cxa_handlers.cpp
@@ -23,7 +23,7 @@ namespace std
 {
 
 unexpected_handler
-get_unexpected() _NOEXCEPT
+get_unexpected() noexcept
 {
     return __libcpp_atomic_load(&__cxa_unexpected_handler, _AO_Acquire);
 }
@@ -44,18 +44,18 @@ unexpected()
 }
 
 terminate_handler
-get_terminate() _NOEXCEPT
+get_terminate() noexcept
 {
     return __libcpp_atomic_load(&__cxa_terminate_handler, _AO_Acquire);
 }
 
 void
-__terminate(terminate_handler func) _NOEXCEPT
+__terminate(terminate_handler func) noexcept
 {
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
         func();
         // handler should not return
         abort_message("terminate_handler unexpectedly returned");
@@ -66,12 +66,12 @@ __terminate(terminate_handler func) _NOEXCEPT
         // handler should not throw exception
         abort_message("terminate_handler unexpectedly threw an exception");
     }
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
 }
 
 __attribute__((noreturn))
 void
-terminate() _NOEXCEPT
+terminate() noexcept
 {
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     // If there might be an uncaught exception
@@ -97,13 +97,13 @@ new_handler __cxa_new_handler = 0;
 }
 
 new_handler
-set_new_handler(new_handler handler) _NOEXCEPT
+set_new_handler(new_handler handler) noexcept
 {
     return __libcpp_atomic_exchange(&__cxa_new_handler, handler, _AO_Acq_Rel);
 }
 
 new_handler
-get_new_handler() _NOEXCEPT
+get_new_handler() noexcept
 {
     return __libcpp_atomic_load(&__cxa_new_handler, _AO_Acquire);
 }
lib/libcxxabi/src/cxa_handlers.h
@@ -25,7 +25,7 @@ __unexpected(unexpected_handler func);
 
 _LIBCXXABI_HIDDEN _LIBCXXABI_NORETURN
 void
-__terminate(terminate_handler func) _NOEXCEPT;
+__terminate(terminate_handler func) noexcept;
 
 }  // std
 
@@ -52,4 +52,4 @@ _LIBCXXABI_DATA_VIS extern void (*__cxa_new_handler)();
 
 } // extern "C"
 
-#endif  // _CXA_HANDLERS_H
+#endif // _CXA_HANDLERS_H
lib/libcxxabi/src/cxa_personality.cpp
@@ -88,7 +88,7 @@ extern "C" EXCEPTION_DISPOSITION _GCC_specific_handler(PEXCEPTION_RECORD,
 | +-------------+---------------------------------+------------------------------+ |
 | ...                                                                              |
 +----------------------------------------------------------------------------------+
-#endif  // __USING_SJLJ_EXCEPTIONS__
+#endif // __USING_SJLJ_EXCEPTIONS__
 +---------------------------------------------------------------------+
 | Beginning of Action Table       ttypeIndex == 0 : cleanup           |
 | ...                             ttypeIndex  > 0 : catch             |
@@ -241,10 +241,11 @@ readSLEB128(const uint8_t** data)
 /// @link http://dwarfstd.org/Dwarf3.pdf @unlink
 /// @param data reference variable holding memory pointer to decode from
 /// @param encoding dwarf encoding type
+/// @param base for adding relative offset, default to 0
 /// @returns decoded value
 static
 uintptr_t
-readEncodedPointer(const uint8_t** data, uint8_t encoding)
+readEncodedPointer(const uint8_t** data, uint8_t encoding, uintptr_t base = 0)
 {
     uintptr_t result = 0;
     if (encoding == DW_EH_PE_omit)
@@ -295,8 +296,12 @@ readEncodedPointer(const uint8_t** data, uint8_t encoding)
         if (result)
             result += (uintptr_t)(*data);
         break;
-    case DW_EH_PE_textrel:
     case DW_EH_PE_datarel:
+        assert((base != 0) && "DW_EH_PE_datarel is invalid with a base of 0");
+        if (result)
+            result += base;
+        break;
+    case DW_EH_PE_textrel:
     case DW_EH_PE_funcrel:
     case DW_EH_PE_aligned:
     default:
@@ -348,7 +353,7 @@ static const void* read_target2_value(const void* ptr)
 static const __shim_type_info*
 get_shim_type_info(uint64_t ttypeIndex, const uint8_t* classInfo,
                    uint8_t ttypeEncoding, bool native_exception,
-                   _Unwind_Exception* unwind_exception)
+                   _Unwind_Exception* unwind_exception, uintptr_t /*base*/ = 0)
 {
     if (classInfo == 0)
     {
@@ -371,7 +376,7 @@ static
 const __shim_type_info*
 get_shim_type_info(uint64_t ttypeIndex, const uint8_t* classInfo,
                    uint8_t ttypeEncoding, bool native_exception,
-                   _Unwind_Exception* unwind_exception)
+                   _Unwind_Exception* unwind_exception, uintptr_t base = 0)
 {
     if (classInfo == 0)
     {
@@ -400,7 +405,8 @@ get_shim_type_info(uint64_t ttypeIndex, const uint8_t* classInfo,
         call_terminate(native_exception, unwind_exception);
     }
     classInfo -= ttypeIndex;
-    return (const __shim_type_info*)readEncodedPointer(&classInfo, ttypeEncoding);
+    return (const __shim_type_info*)readEncodedPointer(&classInfo,
+                                                       ttypeEncoding, base);
 }
 #endif // !defined(_LIBCXXABI_ARM_EHABI)
 
@@ -418,7 +424,8 @@ static
 bool
 exception_spec_can_catch(int64_t specIndex, const uint8_t* classInfo,
                          uint8_t ttypeEncoding, const __shim_type_info* excpType,
-                         void* adjustedPtr, _Unwind_Exception* unwind_exception)
+                         void* adjustedPtr, _Unwind_Exception* unwind_exception,
+                         uintptr_t /*base*/ = 0)
 {
     if (classInfo == 0)
     {
@@ -463,7 +470,8 @@ static
 bool
 exception_spec_can_catch(int64_t specIndex, const uint8_t* classInfo,
                          uint8_t ttypeEncoding, const __shim_type_info* excpType,
-                         void* adjustedPtr, _Unwind_Exception* unwind_exception)
+                         void* adjustedPtr, _Unwind_Exception* unwind_exception,
+                         uintptr_t base = 0)
 {
     if (classInfo == 0)
     {
@@ -485,7 +493,8 @@ exception_spec_can_catch(int64_t specIndex, const uint8_t* classInfo,
                                                                classInfo,
                                                                ttypeEncoding,
                                                                true,
-                                                               unwind_exception);
+                                                               unwind_exception,
+                                                               base);
         void* tempPtr = adjustedPtr;
         if (catchType->can_catch(excpType, tempPtr))
             return false;
@@ -531,6 +540,9 @@ set_registers(_Unwind_Exception* unwind_exception, _Unwind_Context* context,
 {
 #if defined(__USING_SJLJ_EXCEPTIONS__)
 #define __builtin_eh_return_data_regno(regno) regno
+#elif defined(__ibmxl__)
+// IBM xlclang++ compiler does not support __builtin_eh_return_data_regno.
+#define __builtin_eh_return_data_regno(regno) regno + 3
 #endif
   _Unwind_SetGR(context, __builtin_eh_return_data_regno(0),
                 reinterpret_cast<uintptr_t>(unwind_exception));
@@ -610,6 +622,11 @@ static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
         return;
     }
     results.languageSpecificData = lsda;
+#if defined(_AIX)
+    uintptr_t base = _Unwind_GetDataRelBase(context);
+#else
+    uintptr_t base = 0;
+#endif
     // Get the current instruction pointer and offset it before next
     // instruction in the current frame which threw the exception.
     uintptr_t ip = _Unwind_GetIP(context) - 1;
@@ -628,13 +645,14 @@ static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
     // ip is 1-based index into call site table
 #else  // !__USING_SJLJ_EXCEPTIONS__
     uintptr_t ipOffset = ip - funcStart;
-#endif  // !defined(_USING_SLJL_EXCEPTIONS__)
+#endif // !defined(_USING_SLJL_EXCEPTIONS__)
     const uint8_t* classInfo = NULL;
     // Note: See JITDwarfEmitter::EmitExceptionTable(...) for corresponding
     //       dwarf emission
     // Parse LSDA header.
     uint8_t lpStartEncoding = *lsda++;
-    const uint8_t* lpStart = (const uint8_t*)readEncodedPointer(&lsda, lpStartEncoding);
+    const uint8_t* lpStart =
+        (const uint8_t*)readEncodedPointer(&lsda, lpStartEncoding, base);
     if (lpStart == 0)
         lpStart = (const uint8_t*)funcStart;
     uint8_t ttypeEncoding = *lsda++;
@@ -673,7 +691,7 @@ static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
         uintptr_t landingPad = readULEB128(&callSitePtr);
         uintptr_t actionEntry = readULEB128(&callSitePtr);
         if (--ip == 0)
-#endif  // __USING_SJLJ_EXCEPTIONS__
+#endif // __USING_SJLJ_EXCEPTIONS__
         {
             // Found the call site containing ip.
 #ifndef __USING_SJLJ_EXCEPTIONS__
@@ -687,7 +705,7 @@ static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
             results.landingPad = landingPad;
 #else  // __USING_SJLJ_EXCEPTIONS__
             ++landingPad;
-#endif  // __USING_SJLJ_EXCEPTIONS__
+#endif // __USING_SJLJ_EXCEPTIONS__
             if (actionEntry == 0)
             {
                 // Found a cleanup
@@ -711,7 +729,8 @@ static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
                     const __shim_type_info* catchType =
                         get_shim_type_info(static_cast<uint64_t>(ttypeIndex),
                                            classInfo, ttypeEncoding,
-                                           native_exception, unwind_exception);
+                                           native_exception, unwind_exception,
+                                           base);
                     if (catchType == 0)
                     {
                         // Found catch (...) catches everything, including
@@ -772,7 +791,8 @@ static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
                         }
                         if (exception_spec_can_catch(ttypeIndex, classInfo,
                                                      ttypeEncoding, excpType,
-                                                     adjustedPtr, unwind_exception))
+                                                     adjustedPtr,
+                                                     unwind_exception, base))
                         {
                             // Native exception caught by exception
                             // specification.
@@ -820,7 +840,7 @@ static void scan_eh_tab(scan_results &results, _Unwind_Action actions,
             // Possible stack corruption.
             call_terminate(native_exception, unwind_exception);
         }
-#endif  // !__USING_SJLJ_EXCEPTIONS__
+#endif // !__USING_SJLJ_EXCEPTIONS__
     }  // there might be some tricky cases which break out of this loop
 
     // It is possible that no eh table entry specify how to handle
@@ -911,6 +931,15 @@ __gxx_personality_v0
 
         // Jump to the handler.
         set_registers(unwind_exception, context, results);
+        // Cache base for calculating the address of ttype in
+        // __cxa_call_unexpected.
+        if (results.ttypeIndex < 0) {
+#if defined(_AIX)
+          exception_header->catchTemp = (void *)_Unwind_GetDataRelBase(context);
+#else
+          exception_header->catchTemp = 0;
+#endif
+        }
         return _URC_INSTALL_CONTEXT;
     }
 
@@ -940,6 +969,16 @@ __gxx_personality_v0
     assert(actions & _UA_CLEANUP_PHASE);
     assert(results.reason == _URC_HANDLER_FOUND);
     set_registers(unwind_exception, context, results);
+    // Cache base for calculating the address of ttype in __cxa_call_unexpected.
+    if (results.ttypeIndex < 0) {
+      __cxa_exception* exception_header =
+            (__cxa_exception*)(unwind_exception + 1) - 1;
+#if defined(_AIX)
+      exception_header->catchTemp = (void *)_Unwind_GetDataRelBase(context);
+#else
+      exception_header->catchTemp = 0;
+#endif
+    }
     return _URC_INSTALL_CONTEXT;
 }
 
@@ -1114,6 +1153,8 @@ __cxa_call_unexpected(void* arg)
     __cxa_exception* old_exception_header = 0;
     int64_t ttypeIndex;
     const uint8_t* lsda;
+    uintptr_t base = 0;
+
     if (native_old_exception)
     {
         old_exception_header = (__cxa_exception*)(unwind_exception+1) - 1;
@@ -1127,6 +1168,7 @@ __cxa_call_unexpected(void* arg)
 #else
         ttypeIndex = old_exception_header->handlerSwitchValue;
         lsda = old_exception_header->languageSpecificData;
+        base = (uintptr_t)old_exception_header->catchTemp;
 #endif
     }
     else
@@ -1150,11 +1192,13 @@ __cxa_call_unexpected(void* arg)
             // Have:
             //   old_exception_header->languageSpecificData
             //   old_exception_header->actionRecord
+            //   old_exception_header->catchTemp, base for calculating ttype
             // Need
             //   const uint8_t* classInfo
             //   uint8_t ttypeEncoding
             uint8_t lpStartEncoding = *lsda++;
-            const uint8_t* lpStart = (const uint8_t*)readEncodedPointer(&lsda, lpStartEncoding);
+            const uint8_t* lpStart =
+                (const uint8_t*)readEncodedPointer(&lsda, lpStartEncoding, base);
             (void)lpStart;  // purposefully unused.  Just needed to increment lsda.
             uint8_t ttypeEncoding = *lsda++;
             if (ttypeEncoding == DW_EH_PE_omit)
@@ -1181,7 +1225,8 @@ __cxa_call_unexpected(void* arg)
                         ((__cxa_dependent_exception*)new_exception_header)->primaryException :
                         new_exception_header + 1;
                 if (!exception_spec_can_catch(ttypeIndex, classInfo, ttypeEncoding,
-                                              excpType, adjustedPtr, unwind_exception))
+                                              excpType, adjustedPtr,
+                                              unwind_exception, base))
                 {
                     // We need to __cxa_end_catch, but for the old exception,
                     //   not the new one.  This is a little tricky ...
@@ -1210,7 +1255,8 @@ __cxa_call_unexpected(void* arg)
             std::bad_exception be;
             adjustedPtr = &be;
             if (!exception_spec_can_catch(ttypeIndex, classInfo, ttypeEncoding,
-                                          excpType, adjustedPtr, unwind_exception))
+                                          excpType, adjustedPtr,
+                                          unwind_exception, base))
             {
                 // We need to __cxa_end_catch for both the old exception and the
                 //   new exception.  Technically we should do it in that order.
@@ -1226,6 +1272,15 @@ __cxa_call_unexpected(void* arg)
     std::__terminate(t_handler);
 }
 
+#if defined(_AIX)
+// Personality routine for EH using the range table. Make it an alias of
+// __gxx_personality_v0().
+_LIBCXXABI_FUNC_VIS _Unwind_Reason_Code __xlcxx_personality_v1(
+    int version, _Unwind_Action actions, uint64_t exceptionClass,
+    _Unwind_Exception* unwind_exception, _Unwind_Context* context)
+    __attribute__((__alias__("__gxx_personality_v0")));
+#endif
+
 }  // extern "C"
 
 }  // __cxxabiv1
lib/libcxxabi/src/private_typeinfo.cpp
@@ -679,7 +679,7 @@ __dynamic_cast(const void *static_ptr, const __class_type_info *static_type,
             info.number_of_dst_type = 1;
             dynamic_type->search_above_dst(&info, dynamic_ptr, dynamic_ptr, public_path, true);
         }
-#endif  // _LIBCXXABI_FORGIVING_DYNAMIC_CAST
+#endif // _LIBCXXABI_FORGIVING_DYNAMIC_CAST
         // Query the search.
         if (info.path_dst_ptr_to_static_ptr == public_path)
             dst_ptr = dynamic_ptr;
@@ -707,7 +707,7 @@ __dynamic_cast(const void *static_ptr, const __class_type_info *static_type,
             info = {dst_type, static_ptr, static_type, src2dst_offset, 0};
             dynamic_type->search_below_dst(&info, dynamic_ptr, public_path, true);
         }
-#endif  // _LIBCXXABI_FORGIVING_DYNAMIC_CAST
+#endif // _LIBCXXABI_FORGIVING_DYNAMIC_CAST
         // Query the search.
         switch (info.number_to_static_ptr)
         {
lib/libcxxabi/src/private_typeinfo.h
@@ -248,4 +248,4 @@ public:
 
 }  // __cxxabiv1
 
-#endif  // __PRIVATE_TYPEINFO_H_
+#endif // __PRIVATE_TYPEINFO_H_
lib/libcxxabi/src/stdlib_exception.cpp
@@ -14,22 +14,22 @@ namespace std
 
 // exception
 
-exception::~exception() _NOEXCEPT
+exception::~exception() noexcept
 {
 }
 
-const char* exception::what() const _NOEXCEPT
+const char* exception::what() const noexcept
 {
   return "std::exception";
 }
 
 // bad_exception
 
-bad_exception::~bad_exception() _NOEXCEPT
+bad_exception::~bad_exception() noexcept
 {
 }
 
-const char* bad_exception::what() const _NOEXCEPT
+const char* bad_exception::what() const noexcept
 {
   return "std::bad_exception";
 }
@@ -37,32 +37,32 @@ const char* bad_exception::what() const _NOEXCEPT
 
 //  bad_alloc
 
-bad_alloc::bad_alloc() _NOEXCEPT
+bad_alloc::bad_alloc() noexcept
 {
 }
 
-bad_alloc::~bad_alloc() _NOEXCEPT
+bad_alloc::~bad_alloc() noexcept
 {
 }
 
 const char*
-bad_alloc::what() const _NOEXCEPT
+bad_alloc::what() const noexcept
 {
     return "std::bad_alloc";
 }
 
 // bad_array_new_length
 
-bad_array_new_length::bad_array_new_length() _NOEXCEPT
+bad_array_new_length::bad_array_new_length() noexcept
 {
 }
 
-bad_array_new_length::~bad_array_new_length() _NOEXCEPT
+bad_array_new_length::~bad_array_new_length() noexcept
 {
 }
 
 const char*
-bad_array_new_length::what() const _NOEXCEPT
+bad_array_new_length::what() const noexcept
 {
     return "bad_array_new_length";
 }
lib/libcxxabi/src/stdlib_new_delete.cpp
@@ -12,8 +12,8 @@
 #include <new>
 #include <cstdlib>
 
-#if !defined(_THROW_BAD_ALLOC) || !defined(_NOEXCEPT) || !defined(_LIBCXXABI_WEAK)
-#error The _THROW_BAD_ALLOC, _NOEXCEPT, and _LIBCXXABI_WEAK libc++ macros must \
+#if !defined(_THROW_BAD_ALLOC) || !defined(_LIBCXXABI_WEAK)
+#error The _THROW_BAD_ALLOC and _LIBCXXABI_WEAK libc++ macros must \
        already be defined by libc++.
 #endif
 // Implement all new and delete operators as weak definitions
@@ -46,20 +46,20 @@ operator new(std::size_t size) _THROW_BAD_ALLOC
 
 _LIBCXXABI_WEAK
 void*
-operator new(size_t size, const std::nothrow_t&) _NOEXCEPT
+operator new(size_t size, const std::nothrow_t&) noexcept
 {
     void* p = nullptr;
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
         p = ::operator new(size);
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     }
     catch (...)
     {
     }
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
     return p;
 }
 
@@ -72,61 +72,61 @@ operator new[](size_t size) _THROW_BAD_ALLOC
 
 _LIBCXXABI_WEAK
 void*
-operator new[](size_t size, const std::nothrow_t&) _NOEXCEPT
+operator new[](size_t size, const std::nothrow_t&) noexcept
 {
     void* p = nullptr;
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
         p = ::operator new[](size);
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     }
     catch (...)
     {
     }
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
     return p;
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete(void* ptr) _NOEXCEPT
+operator delete(void* ptr) noexcept
 {
     ::free(ptr);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT
+operator delete(void* ptr, const std::nothrow_t&) noexcept
 {
     ::operator delete(ptr);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete(void* ptr, size_t) _NOEXCEPT
+operator delete(void* ptr, size_t) noexcept
 {
     ::operator delete(ptr);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete[] (void* ptr) _NOEXCEPT
+operator delete[] (void* ptr) noexcept
 {
     ::operator delete(ptr);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT
+operator delete[] (void* ptr, const std::nothrow_t&) noexcept
 {
     ::operator delete[](ptr);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete[] (void* ptr, size_t) _NOEXCEPT
+operator delete[] (void* ptr, size_t) noexcept
 {
     ::operator delete[](ptr);
 }
@@ -167,20 +167,20 @@ operator new(std::size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
 
 _LIBCXXABI_WEAK
 void*
-operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
+operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept
 {
     void* p = nullptr;
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
         p = ::operator new(size, alignment);
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     }
     catch (...)
     {
     }
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
     return p;
 }
 
@@ -193,61 +193,61 @@ operator new[](size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
 
 _LIBCXXABI_WEAK
 void*
-operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
+operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept
 {
     void* p = nullptr;
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     try
     {
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
         p = ::operator new[](size, alignment);
 #ifndef _LIBCXXABI_NO_EXCEPTIONS
     }
     catch (...)
     {
     }
-#endif  // _LIBCXXABI_NO_EXCEPTIONS
+#endif // _LIBCXXABI_NO_EXCEPTIONS
     return p;
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete(void* ptr, std::align_val_t) _NOEXCEPT
+operator delete(void* ptr, std::align_val_t) noexcept
 {
     std::__libcpp_aligned_free(ptr);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
+operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) noexcept
 {
     ::operator delete(ptr, alignment);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete(void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
+operator delete(void* ptr, size_t, std::align_val_t alignment) noexcept
 {
     ::operator delete(ptr, alignment);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete[] (void* ptr, std::align_val_t alignment) _NOEXCEPT
+operator delete[] (void* ptr, std::align_val_t alignment) noexcept
 {
     ::operator delete(ptr, alignment);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
+operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) noexcept
 {
     ::operator delete[](ptr, alignment);
 }
 
 _LIBCXXABI_WEAK
 void
-operator delete[] (void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
+operator delete[] (void* ptr, size_t, std::align_val_t alignment) noexcept
 {
     ::operator delete[](ptr, alignment);
 }
lib/libcxxabi/src/stdlib_stdexcept.cpp
@@ -6,7 +6,6 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "../../libcxx/src/include/refstring.h"
 #include "stdexcept"
 #include "new"
 #include <cstdlib>
@@ -14,34 +13,37 @@
 #include <cstdint>
 #include <cstddef>
 
+// This includes an implementation file from libc++.
+#include "../../libcxx/src/include/refstring.h"
+
 static_assert(sizeof(std::__libcpp_refstring) == sizeof(const char *), "");
 
 namespace std  // purposefully not using versioning namespace
 {
 
-logic_error::~logic_error() _NOEXCEPT {}
+logic_error::~logic_error() noexcept {}
 
 const char*
-logic_error::what() const _NOEXCEPT
+logic_error::what() const noexcept
 {
     return __imp_.c_str();
 }
 
-runtime_error::~runtime_error() _NOEXCEPT {}
+runtime_error::~runtime_error() noexcept {}
 
 const char*
-runtime_error::what() const _NOEXCEPT
+runtime_error::what() const noexcept
 {
     return __imp_.c_str();
 }
 
-domain_error::~domain_error() _NOEXCEPT {}
-invalid_argument::~invalid_argument() _NOEXCEPT {}
-length_error::~length_error() _NOEXCEPT {}
-out_of_range::~out_of_range() _NOEXCEPT {}
+domain_error::~domain_error() noexcept {}
+invalid_argument::~invalid_argument() noexcept {}
+length_error::~length_error() noexcept {}
+out_of_range::~out_of_range() noexcept {}
 
-range_error::~range_error() _NOEXCEPT {}
-overflow_error::~overflow_error() _NOEXCEPT {}
-underflow_error::~underflow_error() _NOEXCEPT {}
+range_error::~range_error() noexcept {}
+overflow_error::~overflow_error() noexcept {}
+underflow_error::~underflow_error() noexcept {}
 
 }  // std
lib/libcxxabi/src/stdlib_typeinfo.cpp
@@ -19,32 +19,32 @@ type_info::~type_info()
 
 // bad_cast
 
-bad_cast::bad_cast() _NOEXCEPT
+bad_cast::bad_cast() noexcept
 {
 }
 
-bad_cast::~bad_cast() _NOEXCEPT
+bad_cast::~bad_cast() noexcept
 {
 }
 
 const char*
-bad_cast::what() const _NOEXCEPT
+bad_cast::what() const noexcept
 {
   return "std::bad_cast";
 }
 
 // bad_typeid
 
-bad_typeid::bad_typeid() _NOEXCEPT
+bad_typeid::bad_typeid() noexcept
 {
 }
 
-bad_typeid::~bad_typeid() _NOEXCEPT
+bad_typeid::~bad_typeid() noexcept
 {
 }
 
 const char*
-bad_typeid::what() const _NOEXCEPT
+bad_typeid::what() const noexcept
 {
   return "std::bad_typeid";
 }
lib/libunwind/include/__libunwind_config.h
@@ -131,12 +131,19 @@
   #define _LIBUNWIND_CONTEXT_SIZE 16
   #define _LIBUNWIND_CURSOR_SIZE 23
 # elif defined(__riscv)
-#  if __riscv_xlen == 64
-#    define _LIBUNWIND_TARGET_RISCV 1
-#    define _LIBUNWIND_CONTEXT_SIZE 64
-#    define _LIBUNWIND_CURSOR_SIZE 76
+#  define _LIBUNWIND_TARGET_RISCV 1
+#  if defined(__riscv_flen)
+#   define RISCV_FLEN __riscv_flen
 #  else
-#    error "Unsupported RISC-V ABI"
+#   define RISCV_FLEN 0
+#  endif
+#  define _LIBUNWIND_CONTEXT_SIZE (32 * (__riscv_xlen + RISCV_FLEN) / 64)
+#  if __riscv_xlen == 32
+#   define _LIBUNWIND_CURSOR_SIZE (_LIBUNWIND_CONTEXT_SIZE + 7)
+#  elif __riscv_xlen == 64
+#   define _LIBUNWIND_CURSOR_SIZE (_LIBUNWIND_CONTEXT_SIZE + 12)
+#  else
+#   error "Unsupported RISC-V ABI"
 #  endif
 # define _LIBUNWIND_HIGHEST_DWARF_REGISTER _LIBUNWIND_HIGHEST_DWARF_REGISTER_RISCV
 # elif defined(__ve__)
lib/libunwind/include/libunwind.h
@@ -493,16 +493,16 @@ enum {
 
 // 64-bit ARM64 registers
 enum {
-  UNW_ARM64_X0  = 0,
-  UNW_ARM64_X1  = 1,
-  UNW_ARM64_X2  = 2,
-  UNW_ARM64_X3  = 3,
-  UNW_ARM64_X4  = 4,
-  UNW_ARM64_X5  = 5,
-  UNW_ARM64_X6  = 6,
-  UNW_ARM64_X7  = 7,
-  UNW_ARM64_X8  = 8,
-  UNW_ARM64_X9  = 9,
+  UNW_ARM64_X0 = 0,
+  UNW_ARM64_X1 = 1,
+  UNW_ARM64_X2 = 2,
+  UNW_ARM64_X3 = 3,
+  UNW_ARM64_X4 = 4,
+  UNW_ARM64_X5 = 5,
+  UNW_ARM64_X6 = 6,
+  UNW_ARM64_X7 = 7,
+  UNW_ARM64_X8 = 8,
+  UNW_ARM64_X9 = 9,
   UNW_ARM64_X10 = 10,
   UNW_ARM64_X11 = 11,
   UNW_ARM64_X12 = 12,
@@ -523,24 +523,25 @@ enum {
   UNW_ARM64_X27 = 27,
   UNW_ARM64_X28 = 28,
   UNW_ARM64_X29 = 29,
-  UNW_ARM64_FP  = 29,
+  UNW_ARM64_FP = 29,
   UNW_ARM64_X30 = 30,
-  UNW_ARM64_LR  = 30,
+  UNW_ARM64_LR = 30,
   UNW_ARM64_X31 = 31,
-  UNW_ARM64_SP  = 31,
+  UNW_ARM64_SP = 31,
+  UNW_ARM64_PC = 32,
   // reserved block
   UNW_ARM64_RA_SIGN_STATE = 34,
   // reserved block
-  UNW_ARM64_D0  = 64,
-  UNW_ARM64_D1  = 65,
-  UNW_ARM64_D2  = 66,
-  UNW_ARM64_D3  = 67,
-  UNW_ARM64_D4  = 68,
-  UNW_ARM64_D5  = 69,
-  UNW_ARM64_D6  = 70,
-  UNW_ARM64_D7  = 71,
-  UNW_ARM64_D8  = 72,
-  UNW_ARM64_D9  = 73,
+  UNW_ARM64_D0 = 64,
+  UNW_ARM64_D1 = 65,
+  UNW_ARM64_D2 = 66,
+  UNW_ARM64_D3 = 67,
+  UNW_ARM64_D4 = 68,
+  UNW_ARM64_D5 = 69,
+  UNW_ARM64_D6 = 70,
+  UNW_ARM64_D7 = 71,
+  UNW_ARM64_D8 = 72,
+  UNW_ARM64_D9 = 73,
   UNW_ARM64_D10 = 74,
   UNW_ARM64_D11 = 75,
   UNW_ARM64_D12 = 76,
lib/libunwind/src/assembly.h
@@ -27,6 +27,35 @@
 #define PPC64_OFFS_V      824
 #elif defined(__APPLE__) && defined(__aarch64__)
 #define SEPARATOR %%
+#elif defined(__riscv)
+# define RISCV_ISIZE (__riscv_xlen / 8)
+# define RISCV_FOFFSET (RISCV_ISIZE * 32)
+# if defined(__riscv_flen)
+#  define RISCV_FSIZE (__riscv_flen / 8)
+# endif
+
+# if __riscv_xlen == 64
+#  define ILOAD ld
+#  define ISTORE sd
+# elif __riscv_xlen == 32
+#  define ILOAD lw
+#  define ISTORE sw
+# else
+#  error "Unsupported __riscv_xlen"
+# endif
+
+# if defined(__riscv_flen)
+#  if __riscv_flen == 64
+#   define FLOAD fld
+#   define FSTORE fsd
+#  elif __riscv_flen == 32
+#   define FLOAD flw
+#   define FSTORE fsw
+#  else
+#   error "Unsupported __riscv_flen"
+#  endif
+# endif
+# define SEPARATOR ;
 #else
 #define SEPARATOR ;
 #endif
@@ -70,12 +99,15 @@
 #if defined(__APPLE__)
 
 #define SYMBOL_IS_FUNC(name)
-#define EXPORT_SYMBOL(name)
 #define HIDDEN_SYMBOL(name) .private_extern name
-#define WEAK_SYMBOL(name) .weak_reference name
+#if defined(_LIBUNWIND_HIDE_SYMBOLS)
+#define EXPORT_SYMBOL(name) HIDDEN_SYMBOL(name)
+#else
+#define EXPORT_SYMBOL(name)
+#endif
 #define WEAK_ALIAS(name, aliasname)                                            \
   .globl SYMBOL_NAME(aliasname) SEPARATOR                                      \
-  WEAK_SYMBOL(aliasname) SEPARATOR                                             \
+  EXPORT_SYMBOL(SYMBOL_NAME(aliasname)) SEPARATOR                              \
   SYMBOL_NAME(aliasname) = SYMBOL_NAME(name)
 
 #define NO_EXEC_STACK_DIRECTIVE
@@ -87,17 +119,23 @@
 #else
 #define SYMBOL_IS_FUNC(name) .type name,@function
 #endif
-#define EXPORT_SYMBOL(name)
 #define HIDDEN_SYMBOL(name) .hidden name
+#if defined(_LIBUNWIND_HIDE_SYMBOLS)
+#define EXPORT_SYMBOL(name) HIDDEN_SYMBOL(name)
+#else
+#define EXPORT_SYMBOL(name)
+#endif
 #define WEAK_SYMBOL(name) .weak name
 
 #if defined(__hexagon__)
-#define WEAK_ALIAS(name, aliasname) \
-  WEAK_SYMBOL(aliasname) SEPARATOR                                             \
+#define WEAK_ALIAS(name, aliasname)                                            \
+  EXPORT_SYMBOL(SYMBOL_NAME(aliasname)) SEPARATOR                              \
+  WEAK_SYMBOL(SYMBOL_NAME(aliasname)) SEPARATOR                                \
   .equiv SYMBOL_NAME(aliasname), SYMBOL_NAME(name)
 #else
 #define WEAK_ALIAS(name, aliasname)                                            \
-  WEAK_SYMBOL(aliasname) SEPARATOR                                             \
+  EXPORT_SYMBOL(SYMBOL_NAME(aliasname)) SEPARATOR                              \
+  WEAK_SYMBOL(SYMBOL_NAME(aliasname)) SEPARATOR                                \
   SYMBOL_NAME(aliasname) = SYMBOL_NAME(name)
 #endif
 
@@ -119,7 +157,7 @@
   .section .drectve,"yn" SEPARATOR                                             \
   .ascii "-export:", #name, "\0" SEPARATOR                                     \
   .text
-#if defined(_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS)
+#if defined(_LIBUNWIND_HIDE_SYMBOLS)
 #define EXPORT_SYMBOL(name)
 #else
 #define EXPORT_SYMBOL(name) EXPORT_SYMBOL2(name)
@@ -178,4 +216,8 @@
 #endif
 #endif /* __arm__ */
 
+#if defined(__ppc__) || defined(__powerpc64__)
+#define PPC_LEFT_SHIFT(index) << (index)
+#endif
+
 #endif /* UNWIND_ASSEMBLY_H */
lib/libunwind/src/config.h
@@ -52,7 +52,8 @@
   #endif
 #endif
 
-#if defined(_LIBUNWIND_DISABLE_VISIBILITY_ANNOTATIONS)
+#if defined(_LIBUNWIND_HIDE_SYMBOLS)
+  // The CMake file passes -fvisibility=hidden to control ELF/Mach-O visibility.
   #define _LIBUNWIND_EXPORT
   #define _LIBUNWIND_HIDDEN
 #else
@@ -70,11 +71,15 @@
 #define SYMBOL_NAME(name) XSTR(__USER_LABEL_PREFIX__) #name
 
 #if defined(__APPLE__)
+#if defined(_LIBUNWIND_HIDE_SYMBOLS)
+#define _LIBUNWIND_ALIAS_VISIBILITY(name) __asm__(".private_extern " name);
+#else
+#define _LIBUNWIND_ALIAS_VISIBILITY(name)
+#endif
 #define _LIBUNWIND_WEAK_ALIAS(name, aliasname)                                 \
   __asm__(".globl " SYMBOL_NAME(aliasname));                                   \
   __asm__(SYMBOL_NAME(aliasname) " = " SYMBOL_NAME(name));                     \
-  extern "C" _LIBUNWIND_EXPORT __typeof(name) aliasname                        \
-      __attribute__((weak_import));
+  _LIBUNWIND_ALIAS_VISIBILITY(SYMBOL_NAME(aliasname))
 #elif defined(__ELF__)
 #define _LIBUNWIND_WEAK_ALIAS(name, aliasname)                                 \
   extern "C" _LIBUNWIND_EXPORT __typeof(name) aliasname                        \
lib/libunwind/src/DwarfInstructions.hpp
@@ -167,6 +167,16 @@ int DwarfInstructions<A, R>::stepWithDwarf(A &addressSpace, pint_t pc,
 
        // restore registers that DWARF says were saved
       R newRegisters = registers;
+
+      // Typically, the CFA is the stack pointer at the call site in
+      // the previous frame. However, there are scenarios in which this is not
+      // true. For example, if we switched to a new stack. In that case, the
+      // value of the previous SP might be indicated by a CFI directive.
+      //
+      // We set the SP here to the CFA, allowing for it to be overridden
+      // by a CFI directive later on.
+      newRegisters.setSP(cfa);
+
       pint_t returnAddress = 0;
       const int lastReg = R::lastDwarfRegNum();
       assert(static_cast<int>(CFI_Parser<A>::kMaxRegisterNumber) >= lastReg &&
@@ -200,10 +210,6 @@ int DwarfInstructions<A, R>::stepWithDwarf(A &addressSpace, pint_t pc,
         }
       }
 
-      // By definition, the CFA is the stack pointer at the call site, so
-      // restoring SP means setting it to CFA.
-      newRegisters.setSP(cfa);
-
       isSignalFrame = cieInfo.isSignalFrame;
 
 #if defined(_LIBUNWIND_TARGET_AARCH64)
@@ -213,7 +219,8 @@ int DwarfInstructions<A, R>::stepWithDwarf(A &addressSpace, pint_t pc,
       // restored. autia1716 is used instead of autia as autia1716 assembles
       // to a NOP on pre-v8.3a architectures.
       if ((R::getArch() == REGISTERS_ARM64) &&
-          prolog.savedRegisters[UNW_ARM64_RA_SIGN_STATE].value) {
+          prolog.savedRegisters[UNW_ARM64_RA_SIGN_STATE].value &&
+          returnAddress != 0) {
 #if !defined(_LIBUNWIND_IS_NATIVE_ONLY)
         return UNW_ECROSSRASIGNING;
 #else
lib/libunwind/src/libunwind.cpp
@@ -16,6 +16,15 @@
 
 #include <stdlib.h>
 
+// Define the __has_feature extension for compilers that do not support it so
+// that we can later check for the presence of ASan in a compiler-neutral way.
+#if !defined(__has_feature)
+#define __has_feature(feature) 0
+#endif
+
+#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
+#include <sanitizer/asan_interface.h>
+#endif
 
 #if !defined(__USING_SJLJ_EXCEPTIONS__)
 #include "AddressSpace.hpp"
@@ -60,7 +69,7 @@ _LIBUNWIND_HIDDEN int __unw_init_local(unw_cursor_t *cursor,
 # warning The MIPS architecture is not supported with this ABI and environment!
 #elif defined(__sparc__)
 # define REGISTER_KIND Registers_sparc
-#elif defined(__riscv) && __riscv_xlen == 64
+#elif defined(__riscv)
 # define REGISTER_KIND Registers_riscv
 #elif defined(__ve__)
 # define REGISTER_KIND Registers_ve
@@ -184,6 +193,10 @@ _LIBUNWIND_WEAK_ALIAS(__unw_get_proc_info, unw_get_proc_info)
 /// Resume execution at cursor position (aka longjump).
 _LIBUNWIND_HIDDEN int __unw_resume(unw_cursor_t *cursor) {
   _LIBUNWIND_TRACE_API("__unw_resume(cursor=%p)", static_cast<void *>(cursor));
+#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__)
+  // Inform the ASan runtime that now might be a good time to clean stuff up.
+  __asan_handle_no_return();
+#endif
   AbstractUnwindCursor *co = (AbstractUnwindCursor *)cursor;
   co->jumpto();
   return UNW_EUNSPEC;
lib/libunwind/src/Registers.hpp
@@ -1849,31 +1849,39 @@ inline bool Registers_arm64::validRegister(int regNum) const {
     return false;
   if (regNum == UNW_ARM64_RA_SIGN_STATE)
     return true;
-  if ((regNum > 31) && (regNum < 64))
+  if ((regNum > 32) && (regNum < 64))
     return false;
   return true;
 }
 
 inline uint64_t Registers_arm64::getRegister(int regNum) const {
-  if (regNum == UNW_REG_IP)
+  if (regNum == UNW_REG_IP || regNum == UNW_ARM64_PC)
     return _registers.__pc;
-  if (regNum == UNW_REG_SP)
+  if (regNum == UNW_REG_SP || regNum == UNW_ARM64_SP)
     return _registers.__sp;
   if (regNum == UNW_ARM64_RA_SIGN_STATE)
     return _registers.__ra_sign_state;
-  if ((regNum >= 0) && (regNum < 32))
+  if (regNum == UNW_ARM64_FP)
+    return _registers.__fp;
+  if (regNum == UNW_ARM64_LR)
+    return _registers.__lr;
+  if ((regNum >= 0) && (regNum < 29))
     return _registers.__x[regNum];
   _LIBUNWIND_ABORT("unsupported arm64 register");
 }
 
 inline void Registers_arm64::setRegister(int regNum, uint64_t value) {
-  if (regNum == UNW_REG_IP)
+  if (regNum == UNW_REG_IP || regNum == UNW_ARM64_PC)
     _registers.__pc = value;
-  else if (regNum == UNW_REG_SP)
+  else if (regNum == UNW_REG_SP || regNum == UNW_ARM64_SP)
     _registers.__sp = value;
   else if (regNum == UNW_ARM64_RA_SIGN_STATE)
     _registers.__ra_sign_state = value;
-  else if ((regNum >= 0) && (regNum < 32))
+  else if (regNum == UNW_ARM64_FP)
+    _registers.__fp = value;
+  else if (regNum == UNW_ARM64_LR)
+    _registers.__lr = value;
+  else if ((regNum >= 0) && (regNum < 29))
     _registers.__x[regNum] = value;
   else
     _LIBUNWIND_ABORT("unsupported arm64 register");
@@ -1943,12 +1951,14 @@ inline const char *Registers_arm64::getRegisterName(int regNum) {
     return "x27";
   case UNW_ARM64_X28:
     return "x28";
-  case UNW_ARM64_X29:
+  case UNW_ARM64_FP:
     return "fp";
-  case UNW_ARM64_X30:
+  case UNW_ARM64_LR:
     return "lr";
-  case UNW_ARM64_X31:
+  case UNW_ARM64_SP:
     return "sp";
+  case UNW_ARM64_PC:
+    return "pc";
   case UNW_ARM64_D0:
     return "d0";
   case UNW_ARM64_D1:
@@ -3718,19 +3728,51 @@ inline const char *Registers_hexagon::getRegisterName(int regNum) {
 
 
 #if defined(_LIBUNWIND_TARGET_RISCV)
-/// Registers_riscv holds the register state of a thread in a 64-bit RISC-V
+/// Registers_riscv holds the register state of a thread in a RISC-V
 /// process.
+
+// This check makes it safe when LIBUNWIND_ENABLE_CROSS_UNWINDING enabled.
+# ifdef __riscv
+#  if __riscv_xlen == 32
+typedef uint32_t reg_t;
+#  elif __riscv_xlen == 64
+typedef uint64_t reg_t;
+#  else
+#   error "Unsupported __riscv_xlen"
+#  endif
+
+#  if defined(__riscv_flen)
+#   if __riscv_flen == 64
+typedef double fp_t;
+#   elif __riscv_flen == 32
+typedef float fp_t;
+#   else
+#    error "Unsupported __riscv_flen"
+#   endif
+#  else
+// This is just for supressing undeclared error of fp_t.
+typedef double fp_t;
+#  endif
+# else
+// Use Max possible width when cross unwinding
+typedef uint64_t reg_t;
+typedef double fp_t;
+# define __riscv_xlen 64
+# define __riscv_flen 64
+#endif
+
+/// Registers_riscv holds the register state of a thread.
 class _LIBUNWIND_HIDDEN Registers_riscv {
 public:
   Registers_riscv();
   Registers_riscv(const void *registers);
 
   bool        validRegister(int num) const;
-  uint64_t    getRegister(int num) const;
-  void        setRegister(int num, uint64_t value);
+  reg_t       getRegister(int num) const;
+  void        setRegister(int num, reg_t value);
   bool        validFloatRegister(int num) const;
-  double      getFloatRegister(int num) const;
-  void        setFloatRegister(int num, double value);
+  fp_t        getFloatRegister(int num) const;
+  void        setFloatRegister(int num, fp_t value);
   bool        validVectorRegister(int num) const;
   v128        getVectorRegister(int num) const;
   void        setVectorRegister(int num, v128 value);
@@ -3739,31 +3781,45 @@ public:
   static int  lastDwarfRegNum() { return _LIBUNWIND_HIGHEST_DWARF_REGISTER_RISCV; }
   static int  getArch() { return REGISTERS_RISCV; }
 
-  uint64_t  getSP() const         { return _registers[2]; }
-  void      setSP(uint64_t value) { _registers[2] = value; }
-  uint64_t  getIP() const         { return _registers[0]; }
-  void      setIP(uint64_t value) { _registers[0] = value; }
+  reg_t       getSP() const { return _registers[2]; }
+  void        setSP(reg_t value) { _registers[2] = value; }
+  reg_t       getIP() const { return _registers[0]; }
+  void        setIP(reg_t value) { _registers[0] = value; }
 
 private:
   // _registers[0] holds the pc
-  uint64_t _registers[32];
-  double   _floats[32];
+  reg_t _registers[32];
+# if defined(__riscv_flen)
+  fp_t _floats[32];
+# endif
 };
 
 inline Registers_riscv::Registers_riscv(const void *registers) {
   static_assert((check_fit<Registers_riscv, unw_context_t>::does_fit),
                 "riscv registers do not fit into unw_context_t");
   memcpy(&_registers, registers, sizeof(_registers));
+# if __riscv_xlen == 32
+  static_assert(sizeof(_registers) == 0x80,
+                "expected float registers to be at offset 128");
+# elif __riscv_xlen == 64
   static_assert(sizeof(_registers) == 0x100,
                 "expected float registers to be at offset 256");
+# else
+# error "Unexpected float registers."
+# endif
+
+# if defined(__riscv_flen)
   memcpy(_floats,
          static_cast<const uint8_t *>(registers) + sizeof(_registers),
          sizeof(_floats));
+# endif
 }
 
 inline Registers_riscv::Registers_riscv() {
   memset(&_registers, 0, sizeof(_registers));
+# if defined(__riscv_flen)
   memset(&_floats, 0, sizeof(_floats));
+# endif
 }
 
 inline bool Registers_riscv::validRegister(int regNum) const {
@@ -3778,7 +3834,7 @@ inline bool Registers_riscv::validRegister(int regNum) const {
   return true;
 }
 
-inline uint64_t Registers_riscv::getRegister(int regNum) const {
+inline reg_t Registers_riscv::getRegister(int regNum) const {
   if (regNum == UNW_REG_IP)
     return _registers[0];
   if (regNum == UNW_REG_SP)
@@ -3790,7 +3846,7 @@ inline uint64_t Registers_riscv::getRegister(int regNum) const {
   _LIBUNWIND_ABORT("unsupported riscv register");
 }
 
-inline void Registers_riscv::setRegister(int regNum, uint64_t value) {
+inline void Registers_riscv::setRegister(int regNum, reg_t value) {
   if (regNum == UNW_REG_IP)
     _registers[0] = value;
   else if (regNum == UNW_REG_SP)
@@ -3944,32 +4000,37 @@ inline const char *Registers_riscv::getRegisterName(int regNum) {
 }
 
 inline bool Registers_riscv::validFloatRegister(int regNum) const {
+# if defined(__riscv_flen)
   if (regNum < UNW_RISCV_F0)
     return false;
   if (regNum > UNW_RISCV_F31)
     return false;
   return true;
+# else
+  (void)regNum;
+  return false;
+# endif
 }
 
-inline double Registers_riscv::getFloatRegister(int regNum) const {
-#if defined(__riscv_flen) && __riscv_flen == 64
+inline fp_t Registers_riscv::getFloatRegister(int regNum) const {
+# if defined(__riscv_flen)
   assert(validFloatRegister(regNum));
   return _floats[regNum - UNW_RISCV_F0];
-#else
+# else
   (void)regNum;
   _LIBUNWIND_ABORT("libunwind not built with float support");
-#endif
+# endif
 }
 
-inline void Registers_riscv::setFloatRegister(int regNum, double value) {
-#if defined(__riscv_flen) && __riscv_flen == 64
+inline void Registers_riscv::setFloatRegister(int regNum, fp_t value) {
+# if defined(__riscv_flen)
   assert(validFloatRegister(regNum));
   _floats[regNum - UNW_RISCV_F0] = value;
-#else
+# else
   (void)regNum;
   (void)value;
   _LIBUNWIND_ABORT("libunwind not built with float support");
-#endif
+# endif
 }
 
 inline bool Registers_riscv::validVectorRegister(int) const {
lib/libunwind/src/UnwindCursor.hpp
@@ -1737,14 +1737,16 @@ bool UnwindCursor<A, R>::getInfoFromCompactEncodingSection(pint_t pc,
     else
       funcEnd = firstLevelNextPageFunctionOffset + sects.dso_base;
     if (pc < funcStart) {
-      _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX not in second  "
-                           "level compressed unwind table. funcStart=0x%llX",
+      _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
+                           "not in second level compressed unwind table. "
+                           "funcStart=0x%llX",
                             (uint64_t) pc, (uint64_t) funcStart);
       return false;
     }
     if (pc > funcEnd) {
-      _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX not in second  "
-                          "level compressed unwind table. funcEnd=0x%llX",
+      _LIBUNWIND_DEBUG_LOG("malformed __unwind_info, pc=0x%llX "
+                           "not in second level compressed unwind table. "
+                           "funcEnd=0x%llX",
                            (uint64_t) pc, (uint64_t) funcEnd);
       return false;
     }
@@ -1764,9 +1766,9 @@ bool UnwindCursor<A, R>::getInfoFromCompactEncodingSection(pint_t pc,
                                      pageEncodingIndex * sizeof(uint32_t));
     }
   } else {
-    _LIBUNWIND_DEBUG_LOG("malformed __unwind_info at 0x%0llX bad second "
-                         "level page",
-                          (uint64_t) sects.compact_unwind_section);
+    _LIBUNWIND_DEBUG_LOG(
+        "malformed __unwind_info at 0x%0llX bad second level page",
+        (uint64_t)sects.compact_unwind_section);
     return false;
   }
 
lib/libunwind/src/UnwindRegistersRestore.S
@@ -134,7 +134,7 @@ DEFINE_LIBUNWIND_FUNCTION(_ZN9libunwind15Registers_ppc646jumptoEv)
 
 // load register (GPR)
 #define PPC64_LR(n) \
-  ld    %r##n, (8 * (n + 2))(%r3)
+  ld    n, (8 * (n + 2))(3)
 
   // restore integral registers
   // skip r0 for now
@@ -176,12 +176,12 @@ DEFINE_LIBUNWIND_FUNCTION(_ZN9libunwind15Registers_ppc646jumptoEv)
   // (note that this also restores floating point registers and V registers,
   // because part of VS is mapped to these registers)
 
-  addi  %r4, %r3, PPC64_OFFS_FP
+  addi  4, 3, PPC64_OFFS_FP
 
 // load VS register
 #define PPC64_LVS(n)         \
-  lxvd2x  %vs##n, 0, %r4    ;\
-  addi    %r4, %r4, 16
+  lxvd2x  n, 0, 4           ;\
+  addi    4, 4, 16
 
   // restore the first 32 VS regs (and also all floating point regs)
   PPC64_LVS(0)
@@ -220,23 +220,23 @@ DEFINE_LIBUNWIND_FUNCTION(_ZN9libunwind15Registers_ppc646jumptoEv)
   // use VRSAVE to conditionally restore the remaining VS regs,
   // that are where the V regs are mapped
 
-  ld    %r5, PPC64_OFFS_VRSAVE(%r3)   // test VRsave
-  cmpwi %r5, 0
+  ld    5, PPC64_OFFS_VRSAVE(3)   // test VRsave
+  cmpwi 5, 0
   beq   Lnovec
 
 // conditionally load VS
 #define PPC64_CLVS_BOTTOM(n)               \
   beq    Ldone##n                         ;\
-  addi   %r4, %r3, PPC64_OFFS_FP + n * 16 ;\
-  lxvd2x %vs##n, 0, %r4                   ;\
+  addi   4, 3, PPC64_OFFS_FP + n * 16     ;\
+  lxvd2x n, 0, 4                          ;\
 Ldone##n:
 
-#define PPC64_CLVSl(n)           \
-  andis. %r0, %r5, (1<<(47-n))  ;\
+#define PPC64_CLVSl(n)                    \
+  andis. 0, 5, (1 PPC_LEFT_SHIFT(47-n))  ;\
 PPC64_CLVS_BOTTOM(n)
 
-#define PPC64_CLVSh(n)           \
-  andi.  %r0, %r5, (1<<(63-n))  ;\
+#define PPC64_CLVSh(n)                    \
+  andi.  0, 5, (1 PPC_LEFT_SHIFT(63-n))  ;\
 PPC64_CLVS_BOTTOM(n)
 
   PPC64_CLVSl(32)
@@ -276,7 +276,7 @@ PPC64_CLVS_BOTTOM(n)
 
 // load FP register
 #define PPC64_LF(n) \
-  lfd   %f##n, (PPC64_OFFS_FP + n * 16)(%r3)
+  lfd   n, (PPC64_OFFS_FP + n * 16)(3)
 
   // restore float registers
   PPC64_LF(0)
@@ -314,30 +314,30 @@ PPC64_CLVS_BOTTOM(n)
 
 #if defined(__ALTIVEC__)
   // restore vector registers if any are in use
-  ld    %r5, PPC64_OFFS_VRSAVE(%r3)   // test VRsave
-  cmpwi %r5, 0
+  ld    5, PPC64_OFFS_VRSAVE(3)   // test VRsave
+  cmpwi 5, 0
   beq   Lnovec
 
-  subi  %r4, %r1, 16
+  subi  4, 1, 16
   // r4 is now a 16-byte aligned pointer into the red zone
   // the _vectorScalarRegisters may not be 16-byte aligned
   // so copy via red zone temp buffer
 
 #define PPC64_CLV_UNALIGNED_BOTTOM(n)            \
   beq    Ldone##n                               ;\
-  ld     %r0, (PPC64_OFFS_V + n * 16)(%r3)      ;\
-  std    %r0, 0(%r4)                            ;\
-  ld     %r0, (PPC64_OFFS_V + n * 16 + 8)(%r3)  ;\
-  std    %r0, 8(%r4)                            ;\
-  lvx    %v##n, 0, %r4                          ;\
+  ld     0, (PPC64_OFFS_V + n * 16)(3)          ;\
+  std    0, 0(4)                                ;\
+  ld     0, (PPC64_OFFS_V + n * 16 + 8)(3)      ;\
+  std    0, 8(4)                                ;\
+  lvx    n, 0, 4                                ;\
 Ldone  ## n:
 
-#define PPC64_CLV_UNALIGNEDl(n)  \
-  andis. %r0, %r5, (1<<(15-n))  ;\
+#define PPC64_CLV_UNALIGNEDl(n)                 \
+  andis. 0, 5, (1 PPC_LEFT_SHIFT(15-n))        ;\
 PPC64_CLV_UNALIGNED_BOTTOM(n)
 
-#define PPC64_CLV_UNALIGNEDh(n)  \
-  andi.  %r0, %r5, (1<<(31-n))  ;\
+#define PPC64_CLV_UNALIGNEDh(n)                \
+  andi.  0, 5, (1 PPC_LEFT_SHIFT(31-n))       ;\
 PPC64_CLV_UNALIGNED_BOTTOM(n)
 
   PPC64_CLV_UNALIGNEDl(0)
@@ -377,10 +377,10 @@ PPC64_CLV_UNALIGNED_BOTTOM(n)
 #endif
 
 Lnovec:
-  ld    %r0, PPC64_OFFS_CR(%r3)
-  mtcr  %r0
-  ld    %r0, PPC64_OFFS_SRR0(%r3)
-  mtctr %r0
+  ld    0, PPC64_OFFS_CR(3)
+  mtcr  0
+  ld    0, PPC64_OFFS_SRR0(3)
+  mtctr 0
 
   PPC64_LR(0)
   PPC64_LR(5)
@@ -402,111 +402,111 @@ DEFINE_LIBUNWIND_FUNCTION(_ZN9libunwind13Registers_ppc6jumptoEv)
   // restore integral registerrs
   // skip r0 for now
   // skip r1 for now
-  lwz     %r2,  16(%r3)
+  lwz     2,  16(3)
   // skip r3 for now
   // skip r4 for now
   // skip r5 for now
-  lwz     %r6,  32(%r3)
-  lwz     %r7,  36(%r3)
-  lwz     %r8,  40(%r3)
-  lwz     %r9,  44(%r3)
-  lwz     %r10, 48(%r3)
-  lwz     %r11, 52(%r3)
-  lwz     %r12, 56(%r3)
-  lwz     %r13, 60(%r3)
-  lwz     %r14, 64(%r3)
-  lwz     %r15, 68(%r3)
-  lwz     %r16, 72(%r3)
-  lwz     %r17, 76(%r3)
-  lwz     %r18, 80(%r3)
-  lwz     %r19, 84(%r3)
-  lwz     %r20, 88(%r3)
-  lwz     %r21, 92(%r3)
-  lwz     %r22, 96(%r3)
-  lwz     %r23,100(%r3)
-  lwz     %r24,104(%r3)
-  lwz     %r25,108(%r3)
-  lwz     %r26,112(%r3)
-  lwz     %r27,116(%r3)
-  lwz     %r28,120(%r3)
-  lwz     %r29,124(%r3)
-  lwz     %r30,128(%r3)
-  lwz     %r31,132(%r3)
+  lwz     6,  32(3)
+  lwz     7,  36(3)
+  lwz     8,  40(3)
+  lwz     9,  44(3)
+  lwz     10, 48(3)
+  lwz     11, 52(3)
+  lwz     12, 56(3)
+  lwz     13, 60(3)
+  lwz     14, 64(3)
+  lwz     15, 68(3)
+  lwz     16, 72(3)
+  lwz     17, 76(3)
+  lwz     18, 80(3)
+  lwz     19, 84(3)
+  lwz     20, 88(3)
+  lwz     21, 92(3)
+  lwz     22, 96(3)
+  lwz     23,100(3)
+  lwz     24,104(3)
+  lwz     25,108(3)
+  lwz     26,112(3)
+  lwz     27,116(3)
+  lwz     28,120(3)
+  lwz     29,124(3)
+  lwz     30,128(3)
+  lwz     31,132(3)
 
 #ifndef __NO_FPRS__
   // restore float registers
-  lfd     %f0, 160(%r3)
-  lfd     %f1, 168(%r3)
-  lfd     %f2, 176(%r3)
-  lfd     %f3, 184(%r3)
-  lfd     %f4, 192(%r3)
-  lfd     %f5, 200(%r3)
-  lfd     %f6, 208(%r3)
-  lfd     %f7, 216(%r3)
-  lfd     %f8, 224(%r3)
-  lfd     %f9, 232(%r3)
-  lfd     %f10,240(%r3)
-  lfd     %f11,248(%r3)
-  lfd     %f12,256(%r3)
-  lfd     %f13,264(%r3)
-  lfd     %f14,272(%r3)
-  lfd     %f15,280(%r3)
-  lfd     %f16,288(%r3)
-  lfd     %f17,296(%r3)
-  lfd     %f18,304(%r3)
-  lfd     %f19,312(%r3)
-  lfd     %f20,320(%r3)
-  lfd     %f21,328(%r3)
-  lfd     %f22,336(%r3)
-  lfd     %f23,344(%r3)
-  lfd     %f24,352(%r3)
-  lfd     %f25,360(%r3)
-  lfd     %f26,368(%r3)
-  lfd     %f27,376(%r3)
-  lfd     %f28,384(%r3)
-  lfd     %f29,392(%r3)
-  lfd     %f30,400(%r3)
-  lfd     %f31,408(%r3)
+  lfd     0, 160(3)
+  lfd     1, 168(3)
+  lfd     2, 176(3)
+  lfd     3, 184(3)
+  lfd     4, 192(3)
+  lfd     5, 200(3)
+  lfd     6, 208(3)
+  lfd     7, 216(3)
+  lfd     8, 224(3)
+  lfd     9, 232(3)
+  lfd     10,240(3)
+  lfd     11,248(3)
+  lfd     12,256(3)
+  lfd     13,264(3)
+  lfd     14,272(3)
+  lfd     15,280(3)
+  lfd     16,288(3)
+  lfd     17,296(3)
+  lfd     18,304(3)
+  lfd     19,312(3)
+  lfd     20,320(3)
+  lfd     21,328(3)
+  lfd     22,336(3)
+  lfd     23,344(3)
+  lfd     24,352(3)
+  lfd     25,360(3)
+  lfd     26,368(3)
+  lfd     27,376(3)
+  lfd     28,384(3)
+  lfd     29,392(3)
+  lfd     30,400(3)
+  lfd     31,408(3)
 #endif
 
 #if defined(__ALTIVEC__)
   // restore vector registers if any are in use
-  lwz     %r5, 156(%r3)       // test VRsave
-  cmpwi   %r5, 0
+  lwz     5, 156(3)       // test VRsave
+  cmpwi   5, 0
   beq     Lnovec
 
-  subi    %r4, %r1, 16
-  rlwinm  %r4, %r4, 0, 0, 27  // mask low 4-bits
+  subi    4, 1, 16
+  rlwinm  4, 4, 0, 0, 27  // mask low 4-bits
   // r4 is now a 16-byte aligned pointer into the red zone
   // the _vectorRegisters may not be 16-byte aligned so copy via red zone temp buffer
- 
 
-#define LOAD_VECTOR_UNALIGNEDl(_index) \
-  andis.  %r0, %r5, (1<<(15-_index))  SEPARATOR \
+
+#define LOAD_VECTOR_UNALIGNEDl(_index)          \
+  andis.  0, 5, (1 PPC_LEFT_SHIFT(15-_index)) SEPARATOR \
   beq     Ldone ## _index             SEPARATOR \
-  lwz     %r0, 424+_index*16(%r3)     SEPARATOR \
-  stw     %r0, 0(%r4)                 SEPARATOR \
-  lwz     %r0, 424+_index*16+4(%r3)   SEPARATOR \
-  stw     %r0, 4(%r4)                 SEPARATOR \
-  lwz     %r0, 424+_index*16+8(%r3)   SEPARATOR \
-  stw     %r0, 8(%r4)                 SEPARATOR \
-  lwz     %r0, 424+_index*16+12(%r3)  SEPARATOR \
-  stw     %r0, 12(%r4)                SEPARATOR \
-  lvx     %v ## _index, 0, %r4        SEPARATOR \
+  lwz     0, 424+_index*16(3)         SEPARATOR \
+  stw     0, 0(%r4)                   SEPARATOR \
+  lwz     0, 424+_index*16+4(%r3)     SEPARATOR \
+  stw     0, 4(%r4)                   SEPARATOR \
+  lwz     0, 424+_index*16+8(%r3)     SEPARATOR \
+  stw     0, 8(%r4)                   SEPARATOR \
+  lwz     0, 424+_index*16+12(%r3)    SEPARATOR \
+  stw     0, 12(%r4)                  SEPARATOR \
+  lvx     _index, 0, 4                SEPARATOR \
   Ldone ## _index:
 
-#define LOAD_VECTOR_UNALIGNEDh(_index) \
-  andi.   %r0, %r5, (1<<(31-_index))  SEPARATOR \
+#define LOAD_VECTOR_UNALIGNEDh(_index)          \
+  andi.   0, 5, (1 PPC_LEFT_SHIFT(31-_index)) SEPARATOR \
   beq     Ldone ## _index             SEPARATOR \
-  lwz     %r0, 424+_index*16(%r3)     SEPARATOR \
-  stw     %r0, 0(%r4)                 SEPARATOR \
-  lwz     %r0, 424+_index*16+4(%r3)   SEPARATOR \
-  stw     %r0, 4(%r4)                 SEPARATOR \
-  lwz     %r0, 424+_index*16+8(%r3)   SEPARATOR \
-  stw     %r0, 8(%r4)                 SEPARATOR \
-  lwz     %r0, 424+_index*16+12(%r3)  SEPARATOR \
-  stw     %r0, 12(%r4)                SEPARATOR \
-  lvx     %v ## _index, 0, %r4        SEPARATOR \
+  lwz     0, 424+_index*16(3)         SEPARATOR \
+  stw     0, 0(4)                     SEPARATOR \
+  lwz     0, 424+_index*16+4(3)       SEPARATOR \
+  stw     0, 4(4)                     SEPARATOR \
+  lwz     0, 424+_index*16+8(3)       SEPARATOR \
+  stw     0, 8(%r4)                   SEPARATOR \
+  lwz     0, 424+_index*16+12(3)      SEPARATOR \
+  stw     0, 12(4)                    SEPARATOR \
+  lvx     _index, 0, 4                SEPARATOR \
   Ldone ## _index:
 
 
@@ -545,17 +545,17 @@ DEFINE_LIBUNWIND_FUNCTION(_ZN9libunwind13Registers_ppc6jumptoEv)
 #endif
 
 Lnovec:
-  lwz     %r0, 136(%r3)   // __cr
-  mtcr    %r0
-  lwz     %r0, 148(%r3)   // __ctr
-  mtctr   %r0
-  lwz     %r0,   0(%r3)   // __ssr0
-  mtctr   %r0
-  lwz     %r0,   8(%r3)   // do r0 now
-  lwz     %r5,  28(%r3)   // do r5 now
-  lwz     %r4,  24(%r3)   // do r4 now
-  lwz     %r1,  12(%r3)   // do sp now
-  lwz     %r3,  20(%r3)   // do r3 last
+  lwz     0, 136(3)   // __cr
+  mtcr    0
+  lwz     0, 148(3)   // __ctr
+  mtctr   0
+  lwz     0,   0(3)   // __ssr0
+  mtctr   0
+  lwz     0,   8(3)   // do r0 now
+  lwz     5,  28(3)   // do r5 now
+  lwz     4,  24(3)   // do r4 now
+  lwz     1,  12(3)   // do sp now
+  lwz     3,  20(3)   // do r3 last
   bctr
 
 #elif defined(__aarch64__)
@@ -1072,7 +1072,7 @@ DEFINE_LIBUNWIND_FUNCTION(_ZN9libunwind15Registers_sparc6jumptoEv)
   jmp %o7
    nop
 
-#elif defined(__riscv) && __riscv_xlen == 64
+#elif defined(__riscv)
 
 //
 // void libunwind::Registers_riscv::jumpto()
@@ -1082,74 +1082,74 @@ DEFINE_LIBUNWIND_FUNCTION(_ZN9libunwind15Registers_sparc6jumptoEv)
 //
   .p2align 2
 DEFINE_LIBUNWIND_FUNCTION(_ZN9libunwind15Registers_riscv6jumptoEv)
-#if defined(__riscv_flen) && __riscv_flen == 64
-  fld    f0, (8 * 32 + 8 * 0)(a0)
-  fld    f1, (8 * 32 + 8 * 1)(a0)
-  fld    f2, (8 * 32 + 8 * 2)(a0)
-  fld    f3, (8 * 32 + 8 * 3)(a0)
-  fld    f4, (8 * 32 + 8 * 4)(a0)
-  fld    f5, (8 * 32 + 8 * 5)(a0)
-  fld    f6, (8 * 32 + 8 * 6)(a0)
-  fld    f7, (8 * 32 + 8 * 7)(a0)
-  fld    f8, (8 * 32 + 8 * 8)(a0)
-  fld    f9, (8 * 32 + 8 * 9)(a0)
-  fld    f10, (8 * 32 + 8 * 10)(a0)
-  fld    f11, (8 * 32 + 8 * 11)(a0)
-  fld    f12, (8 * 32 + 8 * 12)(a0)
-  fld    f13, (8 * 32 + 8 * 13)(a0)
-  fld    f14, (8 * 32 + 8 * 14)(a0)
-  fld    f15, (8 * 32 + 8 * 15)(a0)
-  fld    f16, (8 * 32 + 8 * 16)(a0)
-  fld    f17, (8 * 32 + 8 * 17)(a0)
-  fld    f18, (8 * 32 + 8 * 18)(a0)
-  fld    f19, (8 * 32 + 8 * 19)(a0)
-  fld    f20, (8 * 32 + 8 * 20)(a0)
-  fld    f21, (8 * 32 + 8 * 21)(a0)
-  fld    f22, (8 * 32 + 8 * 22)(a0)
-  fld    f23, (8 * 32 + 8 * 23)(a0)
-  fld    f24, (8 * 32 + 8 * 24)(a0)
-  fld    f25, (8 * 32 + 8 * 25)(a0)
-  fld    f26, (8 * 32 + 8 * 26)(a0)
-  fld    f27, (8 * 32 + 8 * 27)(a0)
-  fld    f28, (8 * 32 + 8 * 28)(a0)
-  fld    f29, (8 * 32 + 8 * 29)(a0)
-  fld    f30, (8 * 32 + 8 * 30)(a0)
-  fld    f31, (8 * 32 + 8 * 31)(a0)
-#endif
+# if defined(__riscv_flen)
+  FLOAD    f0, (RISCV_FOFFSET + RISCV_FSIZE * 0)(a0)
+  FLOAD    f1, (RISCV_FOFFSET + RISCV_FSIZE * 1)(a0)
+  FLOAD    f2, (RISCV_FOFFSET + RISCV_FSIZE * 2)(a0)
+  FLOAD    f3, (RISCV_FOFFSET + RISCV_FSIZE * 3)(a0)
+  FLOAD    f4, (RISCV_FOFFSET + RISCV_FSIZE * 4)(a0)
+  FLOAD    f5, (RISCV_FOFFSET + RISCV_FSIZE * 5)(a0)
+  FLOAD    f6, (RISCV_FOFFSET + RISCV_FSIZE * 6)(a0)
+  FLOAD    f7, (RISCV_FOFFSET + RISCV_FSIZE * 7)(a0)
+  FLOAD    f8, (RISCV_FOFFSET + RISCV_FSIZE * 8)(a0)
+  FLOAD    f9, (RISCV_FOFFSET + RISCV_FSIZE * 9)(a0)
+  FLOAD    f10, (RISCV_FOFFSET + RISCV_FSIZE * 10)(a0)
+  FLOAD    f11, (RISCV_FOFFSET + RISCV_FSIZE * 11)(a0)
+  FLOAD    f12, (RISCV_FOFFSET + RISCV_FSIZE * 12)(a0)
+  FLOAD    f13, (RISCV_FOFFSET + RISCV_FSIZE * 13)(a0)
+  FLOAD    f14, (RISCV_FOFFSET + RISCV_FSIZE * 14)(a0)
+  FLOAD    f15, (RISCV_FOFFSET + RISCV_FSIZE * 15)(a0)
+  FLOAD    f16, (RISCV_FOFFSET + RISCV_FSIZE * 16)(a0)
+  FLOAD    f17, (RISCV_FOFFSET + RISCV_FSIZE * 17)(a0)
+  FLOAD    f18, (RISCV_FOFFSET + RISCV_FSIZE * 18)(a0)
+  FLOAD    f19, (RISCV_FOFFSET + RISCV_FSIZE * 19)(a0)
+  FLOAD    f20, (RISCV_FOFFSET + RISCV_FSIZE * 20)(a0)
+  FLOAD    f21, (RISCV_FOFFSET + RISCV_FSIZE * 21)(a0)
+  FLOAD    f22, (RISCV_FOFFSET + RISCV_FSIZE * 22)(a0)
+  FLOAD    f23, (RISCV_FOFFSET + RISCV_FSIZE * 23)(a0)
+  FLOAD    f24, (RISCV_FOFFSET + RISCV_FSIZE * 24)(a0)
+  FLOAD    f25, (RISCV_FOFFSET + RISCV_FSIZE * 25)(a0)
+  FLOAD    f26, (RISCV_FOFFSET + RISCV_FSIZE * 26)(a0)
+  FLOAD    f27, (RISCV_FOFFSET + RISCV_FSIZE * 27)(a0)
+  FLOAD    f28, (RISCV_FOFFSET + RISCV_FSIZE * 28)(a0)
+  FLOAD    f29, (RISCV_FOFFSET + RISCV_FSIZE * 29)(a0)
+  FLOAD    f30, (RISCV_FOFFSET + RISCV_FSIZE * 30)(a0)
+  FLOAD    f31, (RISCV_FOFFSET + RISCV_FSIZE * 31)(a0)
+# endif
 
   // x0 is zero
-  ld    x1, (8 * 0)(a0) // restore pc into ra
-  ld    x2, (8 * 2)(a0)
-  ld    x3, (8 * 3)(a0)
-  ld    x4, (8 * 4)(a0)
-  ld    x5, (8 * 5)(a0)
-  ld    x6, (8 * 6)(a0)
-  ld    x7, (8 * 7)(a0)
-  ld    x8, (8 * 8)(a0)
-  ld    x9, (8 * 9)(a0)
+  ILOAD    x1, (RISCV_ISIZE * 0)(a0) // restore pc into ra
+  ILOAD    x2, (RISCV_ISIZE * 2)(a0)
+  ILOAD    x3, (RISCV_ISIZE * 3)(a0)
+  ILOAD    x4, (RISCV_ISIZE * 4)(a0)
+  ILOAD    x5, (RISCV_ISIZE * 5)(a0)
+  ILOAD    x6, (RISCV_ISIZE * 6)(a0)
+  ILOAD    x7, (RISCV_ISIZE * 7)(a0)
+  ILOAD    x8, (RISCV_ISIZE * 8)(a0)
+  ILOAD    x9, (RISCV_ISIZE * 9)(a0)
   // skip a0 for now
-  ld    x11, (8 * 11)(a0)
-  ld    x12, (8 * 12)(a0)
-  ld    x13, (8 * 13)(a0)
-  ld    x14, (8 * 14)(a0)
-  ld    x15, (8 * 15)(a0)
-  ld    x16, (8 * 16)(a0)
-  ld    x17, (8 * 17)(a0)
-  ld    x18, (8 * 18)(a0)
-  ld    x19, (8 * 19)(a0)
-  ld    x20, (8 * 20)(a0)
-  ld    x21, (8 * 21)(a0)
-  ld    x22, (8 * 22)(a0)
-  ld    x23, (8 * 23)(a0)
-  ld    x24, (8 * 24)(a0)
-  ld    x25, (8 * 25)(a0)
-  ld    x26, (8 * 26)(a0)
-  ld    x27, (8 * 27)(a0)
-  ld    x28, (8 * 28)(a0)
-  ld    x29, (8 * 29)(a0)
-  ld    x30, (8 * 30)(a0)
-  ld    x31, (8 * 31)(a0)
-  ld    x10, (8 * 10)(a0)   // restore a0
+  ILOAD    x11, (RISCV_ISIZE * 11)(a0)
+  ILOAD    x12, (RISCV_ISIZE * 12)(a0)
+  ILOAD    x13, (RISCV_ISIZE * 13)(a0)
+  ILOAD    x14, (RISCV_ISIZE * 14)(a0)
+  ILOAD    x15, (RISCV_ISIZE * 15)(a0)
+  ILOAD    x16, (RISCV_ISIZE * 16)(a0)
+  ILOAD    x17, (RISCV_ISIZE * 17)(a0)
+  ILOAD    x18, (RISCV_ISIZE * 18)(a0)
+  ILOAD    x19, (RISCV_ISIZE * 19)(a0)
+  ILOAD    x20, (RISCV_ISIZE * 20)(a0)
+  ILOAD    x21, (RISCV_ISIZE * 21)(a0)
+  ILOAD    x22, (RISCV_ISIZE * 22)(a0)
+  ILOAD    x23, (RISCV_ISIZE * 23)(a0)
+  ILOAD    x24, (RISCV_ISIZE * 24)(a0)
+  ILOAD    x25, (RISCV_ISIZE * 25)(a0)
+  ILOAD    x26, (RISCV_ISIZE * 26)(a0)
+  ILOAD    x27, (RISCV_ISIZE * 27)(a0)
+  ILOAD    x28, (RISCV_ISIZE * 28)(a0)
+  ILOAD    x29, (RISCV_ISIZE * 29)(a0)
+  ILOAD    x30, (RISCV_ISIZE * 30)(a0)
+  ILOAD    x31, (RISCV_ISIZE * 31)(a0)
+  ILOAD    x10, (RISCV_ISIZE * 10)(a0)   // restore a0
 
   ret                       // jump to ra
 
lib/libunwind/src/UnwindRegistersSave.S
@@ -335,12 +335,12 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
 
 // store register (GPR)
 #define PPC64_STR(n) \
-  std   %r##n, (8 * (n + 2))(%r3)
+  std   n, (8 * (n + 2))(3)
 
   // save GPRs
   PPC64_STR(0)
-  mflr  %r0
-  std   %r0, PPC64_OFFS_SRR0(%r3) // store lr as ssr0
+  mflr  0
+  std   0, PPC64_OFFS_SRR0(3) // store lr as ssr0
   PPC64_STR(1)
   PPC64_STR(2)
   PPC64_STR(3)
@@ -373,28 +373,28 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
   PPC64_STR(30)
   PPC64_STR(31)
 
-  mfcr  %r0
-  std   %r0,  PPC64_OFFS_CR(%r3)
-  mfxer %r0
-  std   %r0,  PPC64_OFFS_XER(%r3)
-  mflr  %r0
-  std   %r0,  PPC64_OFFS_LR(%r3)
-  mfctr %r0
-  std   %r0,  PPC64_OFFS_CTR(%r3)
-  mfvrsave    %r0
-  std   %r0,  PPC64_OFFS_VRSAVE(%r3)
+  mfcr  0
+  std   0,  PPC64_OFFS_CR(3)
+  mfxer 0
+  std   0,  PPC64_OFFS_XER(3)
+  mflr  0
+  std   0,  PPC64_OFFS_LR(3)
+  mfctr 0
+  std   0,  PPC64_OFFS_CTR(3)
+  mfvrsave    0
+  std   0,  PPC64_OFFS_VRSAVE(3)
 
 #if defined(__VSX__)
   // save VS registers
   // (note that this also saves floating point registers and V registers,
   // because part of VS is mapped to these registers)
 
-  addi  %r4, %r3, PPC64_OFFS_FP
+  addi  4, 3, PPC64_OFFS_FP
 
 // store VS register
 #define PPC64_STVS(n)      \
-  stxvd2x %vs##n, 0, %r4  ;\
-  addi    %r4, %r4, 16
+  stxvd2x n, 0, 4         ;\
+  addi    4, 4, 16
 
   PPC64_STVS(0)
   PPC64_STVS(1)
@@ -465,7 +465,7 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
 
 // store FP register
 #define PPC64_STF(n) \
-  stfd  %f##n, (PPC64_OFFS_FP + n * 16)(%r3)
+  stfd  n, (PPC64_OFFS_FP + n * 16)(3)
 
   // save float registers
   PPC64_STF(0)
@@ -507,14 +507,14 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
   // Use 16-bytes below the stack pointer as an
   // aligned buffer to save each vector register.
   // Note that the stack pointer is always 16-byte aligned.
-  subi  %r4, %r1, 16
+  subi  4, 1, 16
 
-#define PPC64_STV_UNALIGNED(n)                 \
-  stvx  %v##n, 0, %r4                         ;\
-  ld    %r5, 0(%r4)                           ;\
-  std   %r5, (PPC64_OFFS_V + n * 16)(%r3)     ;\
-  ld    %r5, 8(%r4)                           ;\
-  std   %r5, (PPC64_OFFS_V + n * 16 + 8)(%r3)
+#define PPC64_STV_UNALIGNED(n)             \
+  stvx  n, 0, 4                           ;\
+  ld    5, 0(4)                           ;\
+  std   5, (PPC64_OFFS_V + n * 16)(3)     ;\
+  ld    5, 8(4)                           ;\
+  std   5, (PPC64_OFFS_V + n * 16 + 8)(3)
 
   PPC64_STV_UNALIGNED(0)
   PPC64_STV_UNALIGNED(1)
@@ -552,7 +552,7 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
 #endif
 #endif
 
-  li    %r3,  0   // return UNW_ESUCCESS
+  li    3,  0   // return UNW_ESUCCESS
   blr
 
 
@@ -565,140 +565,140 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
 //  thread_state pointer is in r3
 //
 DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
-  stw     %r0,   8(%r3)
-  mflr    %r0
-  stw     %r0,   0(%r3) // store lr as ssr0
-  stw     %r1,  12(%r3)
-  stw     %r2,  16(%r3)
-  stw     %r3,  20(%r3)
-  stw     %r4,  24(%r3)
-  stw     %r5,  28(%r3)
-  stw     %r6,  32(%r3)
-  stw     %r7,  36(%r3)
-  stw     %r8,  40(%r3)
-  stw     %r9,  44(%r3)
-  stw     %r10, 48(%r3)
-  stw     %r11, 52(%r3)
-  stw     %r12, 56(%r3)
-  stw     %r13, 60(%r3)
-  stw     %r14, 64(%r3)
-  stw     %r15, 68(%r3)
-  stw     %r16, 72(%r3)
-  stw     %r17, 76(%r3)
-  stw     %r18, 80(%r3)
-  stw     %r19, 84(%r3)
-  stw     %r20, 88(%r3)
-  stw     %r21, 92(%r3)
-  stw     %r22, 96(%r3)
-  stw     %r23,100(%r3)
-  stw     %r24,104(%r3)
-  stw     %r25,108(%r3)
-  stw     %r26,112(%r3)
-  stw     %r27,116(%r3)
-  stw     %r28,120(%r3)
-  stw     %r29,124(%r3)
-  stw     %r30,128(%r3)
-  stw     %r31,132(%r3)
+  stw     0,   8(3)
+  mflr    0
+  stw     0,   0(3) // store lr as ssr0
+  stw     1,  12(3)
+  stw     2,  16(3)
+  stw     3,  20(3)
+  stw     4,  24(3)
+  stw     5,  28(3)
+  stw     6,  32(3)
+  stw     7,  36(3)
+  stw     8,  40(3)
+  stw     9,  44(3)
+  stw     10, 48(3)
+  stw     11, 52(3)
+  stw     12, 56(3)
+  stw     13, 60(3)
+  stw     14, 64(3)
+  stw     15, 68(3)
+  stw     16, 72(3)
+  stw     17, 76(3)
+  stw     18, 80(3)
+  stw     19, 84(3)
+  stw     20, 88(3)
+  stw     21, 92(3)
+  stw     22, 96(3)
+  stw     23,100(3)
+  stw     24,104(3)
+  stw     25,108(3)
+  stw     26,112(3)
+  stw     27,116(3)
+  stw     28,120(3)
+  stw     29,124(3)
+  stw     30,128(3)
+  stw     31,132(3)
 
   // save VRSave register
-  mfspr   %r0, 256
-  stw     %r0, 156(%r3)
+  mfspr   0, 256
+  stw     0, 156(3)
   // save CR registers
-  mfcr    %r0
-  stw     %r0, 136(%r3)
+  mfcr    0
+  stw     0, 136(3)
   // save CTR register
-  mfctr   %r0
-  stw     %r0, 148(%r3)
+  mfctr   0
+  stw     0, 148(3)
 
 #if !defined(__NO_FPRS__)
   // save float registers
-  stfd    %f0, 160(%r3)
-  stfd    %f1, 168(%r3)
-  stfd    %f2, 176(%r3)
-  stfd    %f3, 184(%r3)
-  stfd    %f4, 192(%r3)
-  stfd    %f5, 200(%r3)
-  stfd    %f6, 208(%r3)
-  stfd    %f7, 216(%r3)
-  stfd    %f8, 224(%r3)
-  stfd    %f9, 232(%r3)
-  stfd    %f10,240(%r3)
-  stfd    %f11,248(%r3)
-  stfd    %f12,256(%r3)
-  stfd    %f13,264(%r3)
-  stfd    %f14,272(%r3)
-  stfd    %f15,280(%r3)
-  stfd    %f16,288(%r3)
-  stfd    %f17,296(%r3)
-  stfd    %f18,304(%r3)
-  stfd    %f19,312(%r3)
-  stfd    %f20,320(%r3)
-  stfd    %f21,328(%r3)
-  stfd    %f22,336(%r3)
-  stfd    %f23,344(%r3)
-  stfd    %f24,352(%r3)
-  stfd    %f25,360(%r3)
-  stfd    %f26,368(%r3)
-  stfd    %f27,376(%r3)
-  stfd    %f28,384(%r3)
-  stfd    %f29,392(%r3)
-  stfd    %f30,400(%r3)
-  stfd    %f31,408(%r3)
+  stfd    0, 160(3)
+  stfd    1, 168(3)
+  stfd    2, 176(3)
+  stfd    3, 184(3)
+  stfd    4, 192(3)
+  stfd    5, 200(3)
+  stfd    6, 208(3)
+  stfd    7, 216(3)
+  stfd    8, 224(3)
+  stfd    9, 232(3)
+  stfd    10,240(3)
+  stfd    11,248(3)
+  stfd    12,256(3)
+  stfd    13,264(3)
+  stfd    14,272(3)
+  stfd    15,280(3)
+  stfd    16,288(3)
+  stfd    17,296(3)
+  stfd    18,304(3)
+  stfd    19,312(3)
+  stfd    20,320(3)
+  stfd    21,328(3)
+  stfd    22,336(3)
+  stfd    23,344(3)
+  stfd    24,352(3)
+  stfd    25,360(3)
+  stfd    26,368(3)
+  stfd    27,376(3)
+  stfd    28,384(3)
+  stfd    29,392(3)
+  stfd    30,400(3)
+  stfd    31,408(3)
 #endif
 
 #if defined(__ALTIVEC__)
   // save vector registers
 
-  subi    %r4, %r1, 16
-  rlwinm  %r4, %r4, 0, 0, 27  // mask low 4-bits
+  subi    4, 1, 16
+  rlwinm  4, 4, 0, 0, 27  // mask low 4-bits
   // r4 is now a 16-byte aligned pointer into the red zone
 
 #define SAVE_VECTOR_UNALIGNED(_vec, _offset) \
-  stvx    _vec, 0, %r4          SEPARATOR \
-  lwz     %r5, 0(%r4)           SEPARATOR \
-  stw     %r5, _offset(%r3)     SEPARATOR \
-  lwz     %r5, 4(%r4)           SEPARATOR \
-  stw     %r5, _offset+4(%r3)   SEPARATOR \
-  lwz     %r5, 8(%r4)           SEPARATOR \
-  stw     %r5, _offset+8(%r3)   SEPARATOR \
-  lwz     %r5, 12(%r4)          SEPARATOR \
-  stw     %r5, _offset+12(%r3)
-
-  SAVE_VECTOR_UNALIGNED( %v0, 424+0x000)
-  SAVE_VECTOR_UNALIGNED( %v1, 424+0x010)
-  SAVE_VECTOR_UNALIGNED( %v2, 424+0x020)
-  SAVE_VECTOR_UNALIGNED( %v3, 424+0x030)
-  SAVE_VECTOR_UNALIGNED( %v4, 424+0x040)
-  SAVE_VECTOR_UNALIGNED( %v5, 424+0x050)
-  SAVE_VECTOR_UNALIGNED( %v6, 424+0x060)
-  SAVE_VECTOR_UNALIGNED( %v7, 424+0x070)
-  SAVE_VECTOR_UNALIGNED( %v8, 424+0x080)
-  SAVE_VECTOR_UNALIGNED( %v9, 424+0x090)
-  SAVE_VECTOR_UNALIGNED(%v10, 424+0x0A0)
-  SAVE_VECTOR_UNALIGNED(%v11, 424+0x0B0)
-  SAVE_VECTOR_UNALIGNED(%v12, 424+0x0C0)
-  SAVE_VECTOR_UNALIGNED(%v13, 424+0x0D0)
-  SAVE_VECTOR_UNALIGNED(%v14, 424+0x0E0)
-  SAVE_VECTOR_UNALIGNED(%v15, 424+0x0F0)
-  SAVE_VECTOR_UNALIGNED(%v16, 424+0x100)
-  SAVE_VECTOR_UNALIGNED(%v17, 424+0x110)
-  SAVE_VECTOR_UNALIGNED(%v18, 424+0x120)
-  SAVE_VECTOR_UNALIGNED(%v19, 424+0x130)
-  SAVE_VECTOR_UNALIGNED(%v20, 424+0x140)
-  SAVE_VECTOR_UNALIGNED(%v21, 424+0x150)
-  SAVE_VECTOR_UNALIGNED(%v22, 424+0x160)
-  SAVE_VECTOR_UNALIGNED(%v23, 424+0x170)
-  SAVE_VECTOR_UNALIGNED(%v24, 424+0x180)
-  SAVE_VECTOR_UNALIGNED(%v25, 424+0x190)
-  SAVE_VECTOR_UNALIGNED(%v26, 424+0x1A0)
-  SAVE_VECTOR_UNALIGNED(%v27, 424+0x1B0)
-  SAVE_VECTOR_UNALIGNED(%v28, 424+0x1C0)
-  SAVE_VECTOR_UNALIGNED(%v29, 424+0x1D0)
-  SAVE_VECTOR_UNALIGNED(%v30, 424+0x1E0)
-  SAVE_VECTOR_UNALIGNED(%v31, 424+0x1F0)
+  stvx    _vec, 0, 4               SEPARATOR \
+  lwz     5, 0(4)                  SEPARATOR \
+  stw     5, _offset(3)            SEPARATOR \
+  lwz     5, 4(4)                  SEPARATOR \
+  stw     5, _offset+4(3)          SEPARATOR \
+  lwz     5, 8(4)                  SEPARATOR \
+  stw     5, _offset+8(3)          SEPARATOR \
+  lwz     5, 12(4)                 SEPARATOR \
+  stw     5, _offset+12(3)
+
+  SAVE_VECTOR_UNALIGNED( 0, 424+0x000)
+  SAVE_VECTOR_UNALIGNED( 1, 424+0x010)
+  SAVE_VECTOR_UNALIGNED( 2, 424+0x020)
+  SAVE_VECTOR_UNALIGNED( 3, 424+0x030)
+  SAVE_VECTOR_UNALIGNED( 4, 424+0x040)
+  SAVE_VECTOR_UNALIGNED( 5, 424+0x050)
+  SAVE_VECTOR_UNALIGNED( 6, 424+0x060)
+  SAVE_VECTOR_UNALIGNED( 7, 424+0x070)
+  SAVE_VECTOR_UNALIGNED( 8, 424+0x080)
+  SAVE_VECTOR_UNALIGNED( 9, 424+0x090)
+  SAVE_VECTOR_UNALIGNED(10, 424+0x0A0)
+  SAVE_VECTOR_UNALIGNED(11, 424+0x0B0)
+  SAVE_VECTOR_UNALIGNED(12, 424+0x0C0)
+  SAVE_VECTOR_UNALIGNED(13, 424+0x0D0)
+  SAVE_VECTOR_UNALIGNED(14, 424+0x0E0)
+  SAVE_VECTOR_UNALIGNED(15, 424+0x0F0)
+  SAVE_VECTOR_UNALIGNED(16, 424+0x100)
+  SAVE_VECTOR_UNALIGNED(17, 424+0x110)
+  SAVE_VECTOR_UNALIGNED(18, 424+0x120)
+  SAVE_VECTOR_UNALIGNED(19, 424+0x130)
+  SAVE_VECTOR_UNALIGNED(20, 424+0x140)
+  SAVE_VECTOR_UNALIGNED(21, 424+0x150)
+  SAVE_VECTOR_UNALIGNED(22, 424+0x160)
+  SAVE_VECTOR_UNALIGNED(23, 424+0x170)
+  SAVE_VECTOR_UNALIGNED(24, 424+0x180)
+  SAVE_VECTOR_UNALIGNED(25, 424+0x190)
+  SAVE_VECTOR_UNALIGNED(26, 424+0x1A0)
+  SAVE_VECTOR_UNALIGNED(27, 424+0x1B0)
+  SAVE_VECTOR_UNALIGNED(28, 424+0x1C0)
+  SAVE_VECTOR_UNALIGNED(29, 424+0x1D0)
+  SAVE_VECTOR_UNALIGNED(30, 424+0x1E0)
+  SAVE_VECTOR_UNALIGNED(31, 424+0x1F0)
 #endif
 
-  li      %r3, 0  // return UNW_ESUCCESS
+  li      3, 0  // return UNW_ESUCCESS
   blr
 
 
@@ -1026,7 +1026,7 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
   jmp %o7
    clr %o0                   // return UNW_ESUCCESS
 
-#elif defined(__riscv) && __riscv_xlen == 64
+#elif defined(__riscv)
 
 #
 # extern int __unw_getcontext(unw_context_t* thread_state)
@@ -1035,73 +1035,73 @@ DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
 #  thread_state pointer is in a0
 #
 DEFINE_LIBUNWIND_FUNCTION(__unw_getcontext)
-  sd    x1, (8 * 0)(a0) // store ra as pc
-  sd    x1, (8 * 1)(a0)
-  sd    x2, (8 * 2)(a0)
-  sd    x3, (8 * 3)(a0)
-  sd    x4, (8 * 4)(a0)
-  sd    x5, (8 * 5)(a0)
-  sd    x6, (8 * 6)(a0)
-  sd    x7, (8 * 7)(a0)
-  sd    x8, (8 * 8)(a0)
-  sd    x9, (8 * 9)(a0)
-  sd    x10, (8 * 10)(a0)
-  sd    x11, (8 * 11)(a0)
-  sd    x12, (8 * 12)(a0)
-  sd    x13, (8 * 13)(a0)
-  sd    x14, (8 * 14)(a0)
-  sd    x15, (8 * 15)(a0)
-  sd    x16, (8 * 16)(a0)
-  sd    x17, (8 * 17)(a0)
-  sd    x18, (8 * 18)(a0)
-  sd    x19, (8 * 19)(a0)
-  sd    x20, (8 * 20)(a0)
-  sd    x21, (8 * 21)(a0)
-  sd    x22, (8 * 22)(a0)
-  sd    x23, (8 * 23)(a0)
-  sd    x24, (8 * 24)(a0)
-  sd    x25, (8 * 25)(a0)
-  sd    x26, (8 * 26)(a0)
-  sd    x27, (8 * 27)(a0)
-  sd    x28, (8 * 28)(a0)
-  sd    x29, (8 * 29)(a0)
-  sd    x30, (8 * 30)(a0)
-  sd    x31, (8 * 31)(a0)
-
-#if defined(__riscv_flen) && __riscv_flen == 64
-  fsd    f0, (8 * 32 + 8 * 0)(a0)
-  fsd    f1, (8 * 32 + 8 * 1)(a0)
-  fsd    f2, (8 * 32 + 8 * 2)(a0)
-  fsd    f3, (8 * 32 + 8 * 3)(a0)
-  fsd    f4, (8 * 32 + 8 * 4)(a0)
-  fsd    f5, (8 * 32 + 8 * 5)(a0)
-  fsd    f6, (8 * 32 + 8 * 6)(a0)
-  fsd    f7, (8 * 32 + 8 * 7)(a0)
-  fsd    f8, (8 * 32 + 8 * 8)(a0)
-  fsd    f9, (8 * 32 + 8 * 9)(a0)
-  fsd    f10, (8 * 32 + 8 * 10)(a0)
-  fsd    f11, (8 * 32 + 8 * 11)(a0)
-  fsd    f12, (8 * 32 + 8 * 12)(a0)
-  fsd    f13, (8 * 32 + 8 * 13)(a0)
-  fsd    f14, (8 * 32 + 8 * 14)(a0)
-  fsd    f15, (8 * 32 + 8 * 15)(a0)
-  fsd    f16, (8 * 32 + 8 * 16)(a0)
-  fsd    f17, (8 * 32 + 8 * 17)(a0)
-  fsd    f18, (8 * 32 + 8 * 18)(a0)
-  fsd    f19, (8 * 32 + 8 * 19)(a0)
-  fsd    f20, (8 * 32 + 8 * 20)(a0)
-  fsd    f21, (8 * 32 + 8 * 21)(a0)
-  fsd    f22, (8 * 32 + 8 * 22)(a0)
-  fsd    f23, (8 * 32 + 8 * 23)(a0)
-  fsd    f24, (8 * 32 + 8 * 24)(a0)
-  fsd    f25, (8 * 32 + 8 * 25)(a0)
-  fsd    f26, (8 * 32 + 8 * 26)(a0)
-  fsd    f27, (8 * 32 + 8 * 27)(a0)
-  fsd    f28, (8 * 32 + 8 * 28)(a0)
-  fsd    f29, (8 * 32 + 8 * 29)(a0)
-  fsd    f30, (8 * 32 + 8 * 30)(a0)
-  fsd    f31, (8 * 32 + 8 * 31)(a0)
-#endif
+  ISTORE    x1, (RISCV_ISIZE * 0)(a0) // store ra as pc
+  ISTORE    x1, (RISCV_ISIZE * 1)(a0)
+  ISTORE    x2, (RISCV_ISIZE * 2)(a0)
+  ISTORE    x3, (RISCV_ISIZE * 3)(a0)
+  ISTORE    x4, (RISCV_ISIZE * 4)(a0)
+  ISTORE    x5, (RISCV_ISIZE * 5)(a0)
+  ISTORE    x6, (RISCV_ISIZE * 6)(a0)
+  ISTORE    x7, (RISCV_ISIZE * 7)(a0)
+  ISTORE    x8, (RISCV_ISIZE * 8)(a0)
+  ISTORE    x9, (RISCV_ISIZE * 9)(a0)
+  ISTORE    x10, (RISCV_ISIZE * 10)(a0)
+  ISTORE    x11, (RISCV_ISIZE * 11)(a0)
+  ISTORE    x12, (RISCV_ISIZE * 12)(a0)
+  ISTORE    x13, (RISCV_ISIZE * 13)(a0)
+  ISTORE    x14, (RISCV_ISIZE * 14)(a0)
+  ISTORE    x15, (RISCV_ISIZE * 15)(a0)
+  ISTORE    x16, (RISCV_ISIZE * 16)(a0)
+  ISTORE    x17, (RISCV_ISIZE * 17)(a0)
+  ISTORE    x18, (RISCV_ISIZE * 18)(a0)
+  ISTORE    x19, (RISCV_ISIZE * 19)(a0)
+  ISTORE    x20, (RISCV_ISIZE * 20)(a0)
+  ISTORE    x21, (RISCV_ISIZE * 21)(a0)
+  ISTORE    x22, (RISCV_ISIZE * 22)(a0)
+  ISTORE    x23, (RISCV_ISIZE * 23)(a0)
+  ISTORE    x24, (RISCV_ISIZE * 24)(a0)
+  ISTORE    x25, (RISCV_ISIZE * 25)(a0)
+  ISTORE    x26, (RISCV_ISIZE * 26)(a0)
+  ISTORE    x27, (RISCV_ISIZE * 27)(a0)
+  ISTORE    x28, (RISCV_ISIZE * 28)(a0)
+  ISTORE    x29, (RISCV_ISIZE * 29)(a0)
+  ISTORE    x30, (RISCV_ISIZE * 30)(a0)
+  ISTORE    x31, (RISCV_ISIZE * 31)(a0)
+
+# if defined(__riscv_flen)
+  FSTORE    f0, (RISCV_FOFFSET + RISCV_FSIZE * 0)(a0)
+  FSTORE    f1, (RISCV_FOFFSET + RISCV_FSIZE * 1)(a0)
+  FSTORE    f2, (RISCV_FOFFSET + RISCV_FSIZE * 2)(a0)
+  FSTORE    f3, (RISCV_FOFFSET + RISCV_FSIZE * 3)(a0)
+  FSTORE    f4, (RISCV_FOFFSET + RISCV_FSIZE * 4)(a0)
+  FSTORE    f5, (RISCV_FOFFSET + RISCV_FSIZE * 5)(a0)
+  FSTORE    f6, (RISCV_FOFFSET + RISCV_FSIZE * 6)(a0)
+  FSTORE    f7, (RISCV_FOFFSET + RISCV_FSIZE * 7)(a0)
+  FSTORE    f8, (RISCV_FOFFSET + RISCV_FSIZE * 8)(a0)
+  FSTORE    f9, (RISCV_FOFFSET + RISCV_FSIZE * 9)(a0)
+  FSTORE    f10, (RISCV_FOFFSET + RISCV_FSIZE * 10)(a0)
+  FSTORE    f11, (RISCV_FOFFSET + RISCV_FSIZE * 11)(a0)
+  FSTORE    f12, (RISCV_FOFFSET + RISCV_FSIZE * 12)(a0)
+  FSTORE    f13, (RISCV_FOFFSET + RISCV_FSIZE * 13)(a0)
+  FSTORE    f14, (RISCV_FOFFSET + RISCV_FSIZE * 14)(a0)
+  FSTORE    f15, (RISCV_FOFFSET + RISCV_FSIZE * 15)(a0)
+  FSTORE    f16, (RISCV_FOFFSET + RISCV_FSIZE * 16)(a0)
+  FSTORE    f17, (RISCV_FOFFSET + RISCV_FSIZE * 17)(a0)
+  FSTORE    f18, (RISCV_FOFFSET + RISCV_FSIZE * 18)(a0)
+  FSTORE    f19, (RISCV_FOFFSET + RISCV_FSIZE * 19)(a0)
+  FSTORE    f20, (RISCV_FOFFSET + RISCV_FSIZE * 20)(a0)
+  FSTORE    f21, (RISCV_FOFFSET + RISCV_FSIZE * 21)(a0)
+  FSTORE    f22, (RISCV_FOFFSET + RISCV_FSIZE * 22)(a0)
+  FSTORE    f23, (RISCV_FOFFSET + RISCV_FSIZE * 23)(a0)
+  FSTORE    f24, (RISCV_FOFFSET + RISCV_FSIZE * 24)(a0)
+  FSTORE    f25, (RISCV_FOFFSET + RISCV_FSIZE * 25)(a0)
+  FSTORE    f26, (RISCV_FOFFSET + RISCV_FSIZE * 26)(a0)
+  FSTORE    f27, (RISCV_FOFFSET + RISCV_FSIZE * 27)(a0)
+  FSTORE    f28, (RISCV_FOFFSET + RISCV_FSIZE * 28)(a0)
+  FSTORE    f29, (RISCV_FOFFSET + RISCV_FSIZE * 29)(a0)
+  FSTORE    f30, (RISCV_FOFFSET + RISCV_FSIZE * 30)(a0)
+  FSTORE    f31, (RISCV_FOFFSET + RISCV_FSIZE * 31)(a0)
+# endif
 
   li     a0, 0  // return UNW_ESUCCESS
   ret           // jump to ra
lib/tsan/interception/interception.h
@@ -16,10 +16,10 @@
 
 #include "sanitizer_common/sanitizer_internal_defs.h"
 
-#if !SANITIZER_LINUX && !SANITIZER_FREEBSD && !SANITIZER_MAC && \
-    !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_WINDOWS && \
-    !SANITIZER_FUCHSIA && !SANITIZER_RTEMS && !SANITIZER_SOLARIS
-# error "Interception doesn't work on this operating system."
+#if !SANITIZER_LINUX && !SANITIZER_FREEBSD && !SANITIZER_MAC &&      \
+    !SANITIZER_NETBSD && !SANITIZER_WINDOWS && !SANITIZER_FUCHSIA && \
+    !SANITIZER_SOLARIS
+#  error "Interception doesn't work on this operating system."
 #endif
 
 // These typedefs should be used only in the interceptor definitions to replace
@@ -130,11 +130,6 @@ const interpose_substitution substitution_##func_name[] \
     extern "C" ret_type func(__VA_ARGS__);
 # define DECLARE_WRAPPER_WINAPI(ret_type, func, ...) \
     extern "C" __declspec(dllimport) ret_type __stdcall func(__VA_ARGS__);
-#elif SANITIZER_RTEMS
-# define WRAP(x) x
-# define WRAPPER_NAME(x) #x
-# define INTERCEPTOR_ATTRIBUTE
-# define DECLARE_WRAPPER(ret_type, func, ...)
 #elif SANITIZER_FREEBSD || SANITIZER_NETBSD
 # define WRAP(x) __interceptor_ ## x
 # define WRAPPER_NAME(x) "__interceptor_" #x
@@ -162,10 +157,6 @@ const interpose_substitution substitution_##func_name[] \
 # define INTERCEPTOR_ATTRIBUTE __attribute__((visibility("default")))
 # define REAL(x) __unsanitized_##x
 # define DECLARE_REAL(ret_type, func, ...)
-#elif SANITIZER_RTEMS
-# define REAL(x) __real_ ## x
-# define DECLARE_REAL(ret_type, func, ...) \
-    extern "C" ret_type REAL(func)(__VA_ARGS__);
 #elif !SANITIZER_MAC
 # define PTR_TO_REAL(x) real_##x
 # define REAL(x) __interception::PTR_TO_REAL(x)
@@ -184,10 +175,10 @@ const interpose_substitution substitution_##func_name[] \
 # define ASSIGN_REAL(x, y)
 #endif  // SANITIZER_MAC
 
-#if !SANITIZER_FUCHSIA && !SANITIZER_RTEMS
-# define DECLARE_REAL_AND_INTERCEPTOR(ret_type, func, ...) \
-  DECLARE_REAL(ret_type, func, __VA_ARGS__) \
-  extern "C" ret_type WRAP(func)(__VA_ARGS__);
+#if !SANITIZER_FUCHSIA
+#  define DECLARE_REAL_AND_INTERCEPTOR(ret_type, func, ...) \
+    DECLARE_REAL(ret_type, func, __VA_ARGS__)               \
+    extern "C" ret_type WRAP(func)(__VA_ARGS__);
 // Declare an interceptor and its wrapper defined in a different translation
 // unit (ex. asm).
 # define DECLARE_EXTERN_INTERCEPTOR_AND_WRAPPER(ret_type, func, ...)    \
@@ -202,11 +193,11 @@ const interpose_substitution substitution_##func_name[] \
 // macros does its job. In exceptional cases you may need to call REAL(foo)
 // without defining INTERCEPTOR(..., foo, ...). For example, if you override
 // foo with an interceptor for other function.
-#if !SANITIZER_MAC && !SANITIZER_FUCHSIA && !SANITIZER_RTEMS
-# define DEFINE_REAL(ret_type, func, ...) \
+#if !SANITIZER_MAC && !SANITIZER_FUCHSIA
+#  define DEFINE_REAL(ret_type, func, ...)            \
     typedef ret_type (*FUNC_TYPE(func))(__VA_ARGS__); \
-    namespace __interception { \
-      FUNC_TYPE(func) PTR_TO_REAL(func); \
+    namespace __interception {                        \
+    FUNC_TYPE(func) PTR_TO_REAL(func);                \
     }
 #else
 # define DEFINE_REAL(ret_type, func, ...)
@@ -281,7 +272,7 @@ typedef unsigned long uptr;
 #define INCLUDED_FROM_INTERCEPTION_LIB
 
 #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD || \
-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
+    SANITIZER_SOLARIS
 
 # include "interception_linux.h"
 # define INTERCEPT_FUNCTION(func) INTERCEPT_FUNCTION_LINUX_OR_FREEBSD(func)
lib/tsan/interception/interception_linux.cpp
@@ -14,7 +14,7 @@
 #include "interception.h"
 
 #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD || \
-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
+    SANITIZER_SOLARIS
 
 #include <dlfcn.h>   // for dlsym() and dlvsym()
 
@@ -63,8 +63,8 @@ bool InterceptFunction(const char *name, uptr *ptr_to_real, uptr func,
   return addr && (func == wrapper);
 }
 
-// Android and Solaris do not have dlvsym
-#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD
+// dlvsym is a GNU extension supported by some other platforms.
+#if SANITIZER_GLIBC || SANITIZER_FREEBSD || SANITIZER_NETBSD
 static void *GetFuncAddr(const char *name, const char *ver) {
   return dlvsym(RTLD_NEXT, name, ver);
 }
@@ -75,9 +75,9 @@ bool InterceptFunction(const char *name, const char *ver, uptr *ptr_to_real,
   *ptr_to_real = (uptr)addr;
   return addr && (func == wrapper);
 }
-#endif  // !SANITIZER_ANDROID
+#endif  // SANITIZER_GLIBC || SANITIZER_FREEBSD || SANITIZER_NETBSD
 
 }  // namespace __interception
 
 #endif  // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD ||
-        // SANITIZER_OPENBSD || SANITIZER_SOLARIS
+        // SANITIZER_SOLARIS
lib/tsan/interception/interception_linux.h
@@ -12,7 +12,7 @@
 //===----------------------------------------------------------------------===//
 
 #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD || \
-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
+    SANITIZER_SOLARIS
 
 #if !defined(INCLUDED_FROM_INTERCEPTION_LIB)
 # error "interception_linux.h should be included from interception library only"
@@ -35,8 +35,8 @@ bool InterceptFunction(const char *name, const char *ver, uptr *ptr_to_real,
       (::__interception::uptr) & (func),          \
       (::__interception::uptr) & WRAP(func))
 
-// Android,  Solaris and OpenBSD do not have dlvsym
-#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD
+// dlvsym is a GNU extension supported by some other platforms.
+#if SANITIZER_GLIBC || SANITIZER_FREEBSD || SANITIZER_NETBSD
 #define INTERCEPT_FUNCTION_VER_LINUX_OR_FREEBSD(func, symver) \
   ::__interception::InterceptFunction(                        \
       #func, symver,                                          \
@@ -46,8 +46,8 @@ bool InterceptFunction(const char *name, const char *ver, uptr *ptr_to_real,
 #else
 #define INTERCEPT_FUNCTION_VER_LINUX_OR_FREEBSD(func, symver) \
   INTERCEPT_FUNCTION_LINUX_OR_FREEBSD(func)
-#endif  // !SANITIZER_ANDROID && !SANITIZER_SOLARIS
+#endif  // SANITIZER_GLIBC || SANITIZER_FREEBSD || SANITIZER_NETBSD
 
 #endif  // INTERCEPTION_LINUX_H
 #endif  // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD ||
-        // SANITIZER_OPENBSD || SANITIZER_SOLARIS
+        // SANITIZER_SOLARIS
lib/tsan/interception/interception_win.cpp
@@ -136,7 +136,7 @@ namespace __interception {
 static const int kAddressLength = FIRST_32_SECOND_64(4, 8);
 static const int kJumpInstructionLength = 5;
 static const int kShortJumpInstructionLength = 2;
-static const int kIndirectJumpInstructionLength = 6;
+UNUSED static const int kIndirectJumpInstructionLength = 6;
 static const int kBranchLength =
     FIRST_32_SECOND_64(kJumpInstructionLength, kIndirectJumpInstructionLength);
 static const int kDirectBranchLength = kBranchLength + kAddressLength;
@@ -165,7 +165,7 @@ static uptr GetMmapGranularity() {
   return si.dwAllocationGranularity;
 }
 
-static uptr RoundUpTo(uptr size, uptr boundary) {
+UNUSED static uptr RoundUpTo(uptr size, uptr boundary) {
   return (size + boundary - 1) & ~(boundary - 1);
 }
 
@@ -309,7 +309,7 @@ struct TrampolineMemoryRegion {
   uptr max_size;
 };
 
-static const uptr kTrampolineScanLimitRange = 1 << 31;  // 2 gig
+UNUSED static const uptr kTrampolineScanLimitRange = 1 << 31;  // 2 gig
 static const int kMaxTrampolineRegion = 1024;
 static TrampolineMemoryRegion TrampolineRegions[kMaxTrampolineRegion];
 
lib/tsan/sanitizer_common/sanitizer_addrhashmap.h
@@ -162,8 +162,8 @@ AddrHashMap<T, kSize>::AddrHashMap() {
   table_ = (Bucket*)MmapOrDie(kSize * sizeof(table_[0]), "AddrHashMap");
 }
 
-template<typename T, uptr kSize>
-void AddrHashMap<T, kSize>::acquire(Handle *h) {
+template <typename T, uptr kSize>
+void AddrHashMap<T, kSize>::acquire(Handle *h) NO_THREAD_SAFETY_ANALYSIS {
   uptr addr = h->addr_;
   uptr hash = calcHash(addr);
   Bucket *b = &table_[hash];
@@ -289,57 +289,57 @@ void AddrHashMap<T, kSize>::acquire(Handle *h) {
   CHECK_EQ(atomic_load(&c->addr, memory_order_relaxed), 0);
   h->addidx_ = i;
   h->cell_ = c;
-}
-
-template<typename T, uptr kSize>
-void AddrHashMap<T, kSize>::release(Handle *h) {
-  if (!h->cell_)
-    return;
-  Bucket *b = h->bucket_;
-  Cell *c = h->cell_;
-  uptr addr1 = atomic_load(&c->addr, memory_order_relaxed);
-  if (h->created_) {
-    // Denote completion of insertion.
-    CHECK_EQ(addr1, 0);
-    // After the following store, the element becomes available
-    // for lock-free reads.
-    atomic_store(&c->addr, h->addr_, memory_order_release);
-    b->mtx.Unlock();
-  } else if (h->remove_) {
-    // Denote that the cell is empty now.
-    CHECK_EQ(addr1, h->addr_);
-    atomic_store(&c->addr, 0, memory_order_release);
-    // See if we need to compact the bucket.
-    AddBucket *add = (AddBucket*)atomic_load(&b->add, memory_order_relaxed);
-    if (h->addidx_ == -1U) {
-      // Removed from embed array, move an add element into the freed cell.
-      if (add && add->size != 0) {
-        uptr last = --add->size;
-        Cell *c1 = &add->cells[last];
-        c->val = c1->val;
-        uptr addr1 = atomic_load(&c1->addr, memory_order_relaxed);
-        atomic_store(&c->addr, addr1, memory_order_release);
-        atomic_store(&c1->addr, 0, memory_order_release);
-      }
-    } else {
-      // Removed from add array, compact it.
-      uptr last = --add->size;
-      Cell *c1 = &add->cells[last];
-      if (c != c1) {
-        *c = *c1;
-        atomic_store(&c1->addr, 0, memory_order_relaxed);
-      }
-    }
-    if (add && add->size == 0) {
-      // FIXME(dvyukov): free add?
-    }
-    b->mtx.Unlock();
-  } else {
-    CHECK_EQ(addr1, h->addr_);
-    if (h->addidx_ != -1U)
-      b->mtx.ReadUnlock();
-  }
-}
+ }
+
+ template <typename T, uptr kSize>
+ void AddrHashMap<T, kSize>::release(Handle *h) NO_THREAD_SAFETY_ANALYSIS {
+   if (!h->cell_)
+     return;
+   Bucket *b = h->bucket_;
+   Cell *c = h->cell_;
+   uptr addr1 = atomic_load(&c->addr, memory_order_relaxed);
+   if (h->created_) {
+     // Denote completion of insertion.
+     CHECK_EQ(addr1, 0);
+     // After the following store, the element becomes available
+     // for lock-free reads.
+     atomic_store(&c->addr, h->addr_, memory_order_release);
+     b->mtx.Unlock();
+   } else if (h->remove_) {
+     // Denote that the cell is empty now.
+     CHECK_EQ(addr1, h->addr_);
+     atomic_store(&c->addr, 0, memory_order_release);
+     // See if we need to compact the bucket.
+     AddBucket *add = (AddBucket *)atomic_load(&b->add, memory_order_relaxed);
+     if (h->addidx_ == -1U) {
+       // Removed from embed array, move an add element into the freed cell.
+       if (add && add->size != 0) {
+         uptr last = --add->size;
+         Cell *c1 = &add->cells[last];
+         c->val = c1->val;
+         uptr addr1 = atomic_load(&c1->addr, memory_order_relaxed);
+         atomic_store(&c->addr, addr1, memory_order_release);
+         atomic_store(&c1->addr, 0, memory_order_release);
+       }
+     } else {
+       // Removed from add array, compact it.
+       uptr last = --add->size;
+       Cell *c1 = &add->cells[last];
+       if (c != c1) {
+         *c = *c1;
+         atomic_store(&c1->addr, 0, memory_order_relaxed);
+       }
+     }
+     if (add && add->size == 0) {
+       // FIXME(dvyukov): free add?
+     }
+     b->mtx.Unlock();
+   } else {
+     CHECK_EQ(addr1, h->addr_);
+     if (h->addidx_ != -1U)
+       b->mtx.ReadUnlock();
+   }
+ }
 
 template<typename T, uptr kSize>
 uptr AddrHashMap<T, kSize>::calcHash(uptr addr) {
lib/tsan/sanitizer_common/sanitizer_allocator.cpp
@@ -137,8 +137,6 @@ static void RawInternalFree(void *ptr, InternalAllocatorCache *cache) {
 
 #endif  // SANITIZER_GO || defined(SANITIZER_USE_MALLOC)
 
-const u64 kBlockMagic = 0x6A6CB03ABCEBC041ull;
-
 static void NORETURN ReportInternalAllocatorOutOfMemory(uptr requested_size) {
   SetAllocatorOutOfMemory();
   Report("FATAL: %s: internal allocator is out of memory trying to allocate "
@@ -147,27 +145,17 @@ static void NORETURN ReportInternalAllocatorOutOfMemory(uptr requested_size) {
 }
 
 void *InternalAlloc(uptr size, InternalAllocatorCache *cache, uptr alignment) {
-  if (size + sizeof(u64) < size)
-    return nullptr;
-  void *p = RawInternalAlloc(size + sizeof(u64), cache, alignment);
+  void *p = RawInternalAlloc(size, cache, alignment);
   if (UNLIKELY(!p))
-    ReportInternalAllocatorOutOfMemory(size + sizeof(u64));
-  ((u64*)p)[0] = kBlockMagic;
-  return (char*)p + sizeof(u64);
+    ReportInternalAllocatorOutOfMemory(size);
+  return p;
 }
 
 void *InternalRealloc(void *addr, uptr size, InternalAllocatorCache *cache) {
-  if (!addr)
-    return InternalAlloc(size, cache);
-  if (size + sizeof(u64) < size)
-    return nullptr;
-  addr = (char*)addr - sizeof(u64);
-  size = size + sizeof(u64);
-  CHECK_EQ(kBlockMagic, ((u64*)addr)[0]);
   void *p = RawInternalRealloc(addr, size, cache);
   if (UNLIKELY(!p))
     ReportInternalAllocatorOutOfMemory(size);
-  return (char*)p + sizeof(u64);
+  return p;
 }
 
 void *InternalReallocArray(void *addr, uptr count, uptr size,
@@ -196,11 +184,6 @@ void *InternalCalloc(uptr count, uptr size, InternalAllocatorCache *cache) {
 }
 
 void InternalFree(void *addr, InternalAllocatorCache *cache) {
-  if (!addr)
-    return;
-  addr = (char*)addr - sizeof(u64);
-  CHECK_EQ(kBlockMagic, ((u64*)addr)[0]);
-  ((u64*)addr)[0] = 0;
   RawInternalFree(addr, cache);
 }
 
lib/tsan/sanitizer_common/sanitizer_allocator.h
@@ -52,14 +52,14 @@ struct NoOpMapUnmapCallback {
 // Callback type for iterating over chunks.
 typedef void (*ForEachChunkCallback)(uptr chunk, void *arg);
 
-INLINE u32 Rand(u32 *state) {  // ANSI C linear congruential PRNG.
+inline u32 Rand(u32 *state) {  // ANSI C linear congruential PRNG.
   return (*state = *state * 1103515245 + 12345) >> 16;
 }
 
-INLINE u32 RandN(u32 *state, u32 n) { return Rand(state) % n; }  // [0, n)
+inline u32 RandN(u32 *state, u32 n) { return Rand(state) % n; }  // [0, n)
 
 template<typename T>
-INLINE void RandomShuffle(T *a, u32 n, u32 *rand_state) {
+inline void RandomShuffle(T *a, u32 n, u32 *rand_state) {
   if (n <= 1) return;
   u32 state = *rand_state;
   for (u32 i = n - 1; i > 0; i--)
lib/tsan/sanitizer_common/sanitizer_allocator_checks.h
@@ -27,7 +27,7 @@ namespace __sanitizer {
 void SetErrnoToENOMEM();
 
 // A common errno setting logic shared by almost all sanitizer allocator APIs.
-INLINE void *SetErrnoOnNull(void *ptr) {
+inline void *SetErrnoOnNull(void *ptr) {
   if (UNLIKELY(!ptr))
     SetErrnoToENOMEM();
   return ptr;
@@ -41,7 +41,7 @@ INLINE void *SetErrnoOnNull(void *ptr) {
 // two and that the size is a multiple of alignment for POSIX implementation,
 // and a bit relaxed requirement for non-POSIX ones, that the size is a multiple
 // of alignment.
-INLINE bool CheckAlignedAllocAlignmentAndSize(uptr alignment, uptr size) {
+inline bool CheckAlignedAllocAlignmentAndSize(uptr alignment, uptr size) {
 #if SANITIZER_POSIX
   return alignment != 0 && IsPowerOfTwo(alignment) &&
          (size & (alignment - 1)) == 0;
@@ -52,13 +52,13 @@ INLINE bool CheckAlignedAllocAlignmentAndSize(uptr alignment, uptr size) {
 
 // Checks posix_memalign() parameters, verifies that alignment is a power of two
 // and a multiple of sizeof(void *).
-INLINE bool CheckPosixMemalignAlignment(uptr alignment) {
+inline bool CheckPosixMemalignAlignment(uptr alignment) {
   return alignment != 0 && IsPowerOfTwo(alignment) &&
          (alignment % sizeof(void *)) == 0;
 }
 
 // Returns true if calloc(size, n) call overflows on size*n calculation.
-INLINE bool CheckForCallocOverflow(uptr size, uptr n) {
+inline bool CheckForCallocOverflow(uptr size, uptr n) {
   if (!size)
     return false;
   uptr max = (uptr)-1L;
@@ -67,7 +67,7 @@ INLINE bool CheckForCallocOverflow(uptr size, uptr n) {
 
 // Returns true if the size passed to pvalloc overflows when rounded to the next
 // multiple of page_size.
-INLINE bool CheckForPvallocOverflow(uptr size, uptr page_size) {
+inline bool CheckForPvallocOverflow(uptr size, uptr page_size) {
   return RoundUpTo(size, page_size) < size;
 }
 
lib/tsan/sanitizer_common/sanitizer_allocator_combined.h
@@ -35,9 +35,9 @@ class CombinedAllocator {
     secondary_.InitLinkerInitialized();
   }
 
-  void Init(s32 release_to_os_interval_ms) {
+  void Init(s32 release_to_os_interval_ms, uptr heap_start = 0) {
     stats_.Init();
-    primary_.Init(release_to_os_interval_ms);
+    primary_.Init(release_to_os_interval_ms, heap_start);
     secondary_.Init();
   }
 
@@ -177,12 +177,12 @@ class CombinedAllocator {
 
   // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone
   // introspection API.
-  void ForceLock() {
+  void ForceLock() NO_THREAD_SAFETY_ANALYSIS {
     primary_.ForceLock();
     secondary_.ForceLock();
   }
 
-  void ForceUnlock() {
+  void ForceUnlock() NO_THREAD_SAFETY_ANALYSIS {
     secondary_.ForceUnlock();
     primary_.ForceUnlock();
   }
lib/tsan/sanitizer_common/sanitizer_allocator_local_cache.h
@@ -17,6 +17,7 @@
 template <class SizeClassAllocator>
 struct SizeClassAllocator64LocalCache {
   typedef SizeClassAllocator Allocator;
+  typedef MemoryMapper<Allocator> MemoryMapperT;
 
   void Init(AllocatorGlobalStats *s) {
     stats_.Init();
@@ -53,7 +54,7 @@ struct SizeClassAllocator64LocalCache {
     PerClass *c = &per_class_[class_id];
     InitCache(c);
     if (UNLIKELY(c->count == c->max_count))
-      Drain(c, allocator, class_id, c->max_count / 2);
+      DrainHalfMax(c, allocator, class_id);
     CompactPtrT chunk = allocator->PointerToCompactPtr(
         allocator->GetRegionBeginBySizeClass(class_id),
         reinterpret_cast<uptr>(p));
@@ -62,10 +63,10 @@ struct SizeClassAllocator64LocalCache {
   }
 
   void Drain(SizeClassAllocator *allocator) {
+    MemoryMapperT memory_mapper(*allocator);
     for (uptr i = 1; i < kNumClasses; i++) {
       PerClass *c = &per_class_[i];
-      while (c->count > 0)
-        Drain(c, allocator, i, c->count);
+      while (c->count > 0) Drain(&memory_mapper, c, allocator, i, c->count);
     }
   }
 
@@ -106,12 +107,18 @@ struct SizeClassAllocator64LocalCache {
     return true;
   }
 
-  NOINLINE void Drain(PerClass *c, SizeClassAllocator *allocator, uptr class_id,
-                      uptr count) {
+  NOINLINE void DrainHalfMax(PerClass *c, SizeClassAllocator *allocator,
+                             uptr class_id) {
+    MemoryMapperT memory_mapper(*allocator);
+    Drain(&memory_mapper, c, allocator, class_id, c->max_count / 2);
+  }
+
+  void Drain(MemoryMapperT *memory_mapper, PerClass *c,
+             SizeClassAllocator *allocator, uptr class_id, uptr count) {
     CHECK_GE(c->count, count);
     const uptr first_idx_to_drain = c->count - count;
     c->count -= count;
-    allocator->ReturnToAllocator(&stats_, class_id,
+    allocator->ReturnToAllocator(memory_mapper, &stats_, class_id,
                                  &c->chunks[first_idx_to_drain], count);
   }
 };
lib/tsan/sanitizer_common/sanitizer_allocator_primary32.h
@@ -119,7 +119,8 @@ class SizeClassAllocator32 {
   typedef SizeClassAllocator32<Params> ThisT;
   typedef SizeClassAllocator32LocalCache<ThisT> AllocatorCache;
 
-  void Init(s32 release_to_os_interval_ms) {
+  void Init(s32 release_to_os_interval_ms, uptr heap_start = 0) {
+    CHECK(!heap_start);
     possible_regions.Init();
     internal_memset(size_class_info_array, 0, sizeof(size_class_info_array));
   }
@@ -153,6 +154,7 @@ class SizeClassAllocator32 {
   }
 
   void *GetMetaData(const void *p) {
+    CHECK(kMetadataSize);
     CHECK(PointerIsMine(p));
     uptr mem = reinterpret_cast<uptr>(p);
     uptr beg = ComputeRegionBeg(mem);
@@ -235,13 +237,13 @@ class SizeClassAllocator32 {
 
   // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone
   // introspection API.
-  void ForceLock() {
+  void ForceLock() NO_THREAD_SAFETY_ANALYSIS {
     for (uptr i = 0; i < kNumClasses; i++) {
       GetSizeClassInfo(i)->mutex.Lock();
     }
   }
 
-  void ForceUnlock() {
+  void ForceUnlock() NO_THREAD_SAFETY_ANALYSIS {
     for (int i = kNumClasses - 1; i >= 0; i--) {
       GetSizeClassInfo(i)->mutex.Unlock();
     }
lib/tsan/sanitizer_common/sanitizer_allocator_primary64.h
@@ -19,7 +19,7 @@ template<class SizeClassAllocator> struct SizeClassAllocator64LocalCache;
 // The template parameter Params is a class containing the actual parameters.
 //
 // Space: a portion of address space of kSpaceSize bytes starting at SpaceBeg.
-// If kSpaceBeg is ~0 then SpaceBeg is chosen dynamically my mmap.
+// If kSpaceBeg is ~0 then SpaceBeg is chosen dynamically by mmap.
 // Otherwise SpaceBeg=kSpaceBeg (fixed address).
 // kSpaceSize is a power of two.
 // At the beginning the entire space is mprotect-ed, then small parts of it
@@ -42,6 +42,44 @@ struct SizeClassAllocator64FlagMasks {  //  Bit masks.
   };
 };
 
+template <typename Allocator>
+class MemoryMapper {
+ public:
+  typedef typename Allocator::CompactPtrT CompactPtrT;
+
+  explicit MemoryMapper(const Allocator &allocator) : allocator_(allocator) {}
+
+  bool GetAndResetStats(uptr &ranges, uptr &bytes) {
+    ranges = released_ranges_count_;
+    released_ranges_count_ = 0;
+    bytes = released_bytes_;
+    released_bytes_ = 0;
+    return ranges != 0;
+  }
+
+  u64 *MapPackedCounterArrayBuffer(uptr count) {
+    buffer_.clear();
+    buffer_.resize(count);
+    return buffer_.data();
+  }
+
+  // Releases [from, to) range of pages back to OS.
+  void ReleasePageRangeToOS(uptr class_id, CompactPtrT from, CompactPtrT to) {
+    const uptr region_base = allocator_.GetRegionBeginBySizeClass(class_id);
+    const uptr from_page = allocator_.CompactPtrToPointer(region_base, from);
+    const uptr to_page = allocator_.CompactPtrToPointer(region_base, to);
+    ReleaseMemoryPagesToOS(from_page, to_page);
+    released_ranges_count_++;
+    released_bytes_ += to_page - from_page;
+  }
+
+ private:
+  const Allocator &allocator_;
+  uptr released_ranges_count_ = 0;
+  uptr released_bytes_ = 0;
+  InternalMmapVector<u64> buffer_;
+};
+
 template <class Params>
 class SizeClassAllocator64 {
  public:
@@ -57,6 +95,7 @@ class SizeClassAllocator64 {
 
   typedef SizeClassAllocator64<Params> ThisT;
   typedef SizeClassAllocator64LocalCache<ThisT> AllocatorCache;
+  typedef MemoryMapper<ThisT> MemoryMapperT;
 
   // When we know the size class (the region base) we can represent a pointer
   // as a 4-byte integer (offset from the region start shifted right by 4).
@@ -69,25 +108,45 @@ class SizeClassAllocator64 {
     return base + (static_cast<uptr>(ptr32) << kCompactPtrScale);
   }
 
-  void Init(s32 release_to_os_interval_ms) {
+  // If heap_start is nonzero, assumes kSpaceSize bytes are already mapped R/W
+  // at heap_start and places the heap there.  This mode requires kSpaceBeg ==
+  // ~(uptr)0.
+  void Init(s32 release_to_os_interval_ms, uptr heap_start = 0) {
     uptr TotalSpaceSize = kSpaceSize + AdditionalSize();
-    if (kUsingConstantSpaceBeg) {
-      CHECK(IsAligned(kSpaceBeg, SizeClassMap::kMaxSize));
-      CHECK_EQ(kSpaceBeg, address_range.Init(TotalSpaceSize,
-                                             PrimaryAllocatorName, kSpaceBeg));
+    PremappedHeap = heap_start != 0;
+    if (PremappedHeap) {
+      CHECK(!kUsingConstantSpaceBeg);
+      NonConstSpaceBeg = heap_start;
+      uptr RegionInfoSize = AdditionalSize();
+      RegionInfoSpace =
+          address_range.Init(RegionInfoSize, PrimaryAllocatorName);
+      CHECK_NE(RegionInfoSpace, ~(uptr)0);
+      CHECK_EQ(RegionInfoSpace,
+               address_range.MapOrDie(RegionInfoSpace, RegionInfoSize,
+                                      "SizeClassAllocator: region info"));
+      MapUnmapCallback().OnMap(RegionInfoSpace, RegionInfoSize);
     } else {
-      // Combined allocator expects that an 2^N allocation is always aligned to
-      // 2^N. For this to work, the start of the space needs to be aligned as
-      // high as the largest size class (which also needs to be a power of 2).
-      NonConstSpaceBeg = address_range.InitAligned(
-          TotalSpaceSize, SizeClassMap::kMaxSize, PrimaryAllocatorName);
-      CHECK_NE(NonConstSpaceBeg, ~(uptr)0);
+      if (kUsingConstantSpaceBeg) {
+        CHECK(IsAligned(kSpaceBeg, SizeClassMap::kMaxSize));
+        CHECK_EQ(kSpaceBeg,
+                 address_range.Init(TotalSpaceSize, PrimaryAllocatorName,
+                                    kSpaceBeg));
+      } else {
+        // Combined allocator expects that an 2^N allocation is always aligned
+        // to 2^N. For this to work, the start of the space needs to be aligned
+        // as high as the largest size class (which also needs to be a power of
+        // 2).
+        NonConstSpaceBeg = address_range.InitAligned(
+            TotalSpaceSize, SizeClassMap::kMaxSize, PrimaryAllocatorName);
+        CHECK_NE(NonConstSpaceBeg, ~(uptr)0);
+      }
+      RegionInfoSpace = SpaceEnd();
+      MapWithCallbackOrDie(RegionInfoSpace, AdditionalSize(),
+                           "SizeClassAllocator: region info");
     }
     SetReleaseToOSIntervalMs(release_to_os_interval_ms);
-    MapWithCallbackOrDie(SpaceEnd(), AdditionalSize(),
-                         "SizeClassAllocator: region info");
     // Check that the RegionInfo array is aligned on the CacheLine size.
-    DCHECK_EQ(SpaceEnd() % kCacheLineSize, 0);
+    DCHECK_EQ(RegionInfoSpace % kCacheLineSize, 0);
   }
 
   s32 ReleaseToOSIntervalMs() const {
@@ -100,9 +159,10 @@ class SizeClassAllocator64 {
   }
 
   void ForceReleaseToOS() {
+    MemoryMapperT memory_mapper(*this);
     for (uptr class_id = 1; class_id < kNumClasses; class_id++) {
       BlockingMutexLock l(&GetRegionInfo(class_id)->mutex);
-      MaybeReleaseToOS(class_id, true /*force*/);
+      MaybeReleaseToOS(&memory_mapper, class_id, true /*force*/);
     }
   }
 
@@ -111,7 +171,8 @@ class SizeClassAllocator64 {
       alignment <= SizeClassMap::kMaxSize;
   }
 
-  NOINLINE void ReturnToAllocator(AllocatorStats *stat, uptr class_id,
+  NOINLINE void ReturnToAllocator(MemoryMapperT *memory_mapper,
+                                  AllocatorStats *stat, uptr class_id,
                                   const CompactPtrT *chunks, uptr n_chunks) {
     RegionInfo *region = GetRegionInfo(class_id);
     uptr region_beg = GetRegionBeginBySizeClass(class_id);
@@ -134,7 +195,7 @@ class SizeClassAllocator64 {
     region->num_freed_chunks = new_num_freed_chunks;
     region->stats.n_freed += n_chunks;
 
-    MaybeReleaseToOS(class_id, false /*force*/);
+    MaybeReleaseToOS(memory_mapper, class_id, false /*force*/);
   }
 
   NOINLINE bool GetFromAllocator(AllocatorStats *stat, uptr class_id,
@@ -144,6 +205,17 @@ class SizeClassAllocator64 {
     CompactPtrT *free_array = GetFreeArray(region_beg);
 
     BlockingMutexLock l(&region->mutex);
+#if SANITIZER_WINDOWS
+    /* On Windows unmapping of memory during __sanitizer_purge_allocator is
+    explicit and immediate, so unmapped regions must be explicitly mapped back
+    in when they are accessed again. */
+    if (region->rtoi.last_released_bytes > 0) {
+      MmapFixedOrDie(region_beg, region->mapped_user,
+                                      "SizeClassAllocator: region data");
+      region->rtoi.n_freed_at_last_release = 0;
+      region->rtoi.last_released_bytes = 0;
+    }
+#endif
     if (UNLIKELY(region->num_freed_chunks < n_chunks)) {
       if (UNLIKELY(!PopulateFreeArray(stat, class_id, region,
                                       n_chunks - region->num_freed_chunks)))
@@ -186,13 +258,13 @@ class SizeClassAllocator64 {
 
   void *GetBlockBegin(const void *p) {
     uptr class_id = GetSizeClass(p);
+    if (class_id >= kNumClasses) return nullptr;
     uptr size = ClassIdToSize(class_id);
     if (!size) return nullptr;
     uptr chunk_idx = GetChunkIdx((uptr)p, size);
     uptr reg_beg = GetRegionBegin(p);
     uptr beg = chunk_idx * size;
     uptr next_beg = beg + size;
-    if (class_id >= kNumClasses) return nullptr;
     const RegionInfo *region = AddressSpaceView::Load(GetRegionInfo(class_id));
     if (region->mapped_user >= next_beg)
       return reinterpret_cast<void*>(reg_beg + beg);
@@ -207,6 +279,7 @@ class SizeClassAllocator64 {
   static uptr ClassID(uptr size) { return SizeClassMap::ClassID(size); }
 
   void *GetMetaData(const void *p) {
+    CHECK(kMetadataSize);
     uptr class_id = GetSizeClass(p);
     uptr size = ClassIdToSize(class_id);
     uptr chunk_idx = GetChunkIdx(reinterpret_cast<uptr>(p), size);
@@ -280,13 +353,13 @@ class SizeClassAllocator64 {
 
   // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone
   // introspection API.
-  void ForceLock() {
+  void ForceLock() NO_THREAD_SAFETY_ANALYSIS {
     for (uptr i = 0; i < kNumClasses; i++) {
       GetRegionInfo(i)->mutex.Lock();
     }
   }
 
-  void ForceUnlock() {
+  void ForceUnlock() NO_THREAD_SAFETY_ANALYSIS {
     for (int i = (int)kNumClasses - 1; i >= 0; i--) {
       GetRegionInfo(i)->mutex.Unlock();
     }
@@ -330,11 +403,11 @@ class SizeClassAllocator64 {
   // For the performance sake, none of the accessors check the validity of the
   // arguments, it is assumed that index is always in [0, n) range and the value
   // is not incremented past max_value.
-  template<class MemoryMapperT>
   class PackedCounterArray {
    public:
-    PackedCounterArray(u64 num_counters, u64 max_value, MemoryMapperT *mapper)
-        : n(num_counters), memory_mapper(mapper) {
+    template <typename MemoryMapper>
+    PackedCounterArray(u64 num_counters, u64 max_value, MemoryMapper *mapper)
+        : n(num_counters) {
       CHECK_GT(num_counters, 0);
       CHECK_GT(max_value, 0);
       constexpr u64 kMaxCounterBits = sizeof(*buffer) * 8ULL;
@@ -351,17 +424,8 @@ class SizeClassAllocator64 {
       packing_ratio_log = Log2(packing_ratio);
       bit_offset_mask = packing_ratio - 1;
 
-      buffer_size =
-          (RoundUpTo(n, 1ULL << packing_ratio_log) >> packing_ratio_log) *
-          sizeof(*buffer);
-      buffer = reinterpret_cast<u64*>(
-          memory_mapper->MapPackedCounterArrayBuffer(buffer_size));
-    }
-    ~PackedCounterArray() {
-      if (buffer) {
-        memory_mapper->UnmapPackedCounterArrayBuffer(
-            reinterpret_cast<uptr>(buffer), buffer_size);
-      }
+      buffer = mapper->MapPackedCounterArrayBuffer(
+          RoundUpTo(n, 1ULL << packing_ratio_log) >> packing_ratio_log);
     }
 
     bool IsAllocated() const {
@@ -398,19 +462,16 @@ class SizeClassAllocator64 {
     u64 counter_mask;
     u64 packing_ratio_log;
     u64 bit_offset_mask;
-
-    MemoryMapperT* const memory_mapper;
-    u64 buffer_size;
     u64* buffer;
   };
 
-  template<class MemoryMapperT>
+  template <class MemoryMapperT>
   class FreePagesRangeTracker {
    public:
-    explicit FreePagesRangeTracker(MemoryMapperT* mapper)
+    FreePagesRangeTracker(MemoryMapperT *mapper, uptr class_id)
         : memory_mapper(mapper),
-          page_size_scaled_log(Log2(GetPageSizeCached() >> kCompactPtrScale)),
-          in_the_range(false), current_page(0), current_range_start_page(0) {}
+          class_id(class_id),
+          page_size_scaled_log(Log2(GetPageSizeCached() >> kCompactPtrScale)) {}
 
     void NextPage(bool freed) {
       if (freed) {
@@ -432,28 +493,30 @@ class SizeClassAllocator64 {
     void CloseOpenedRange() {
       if (in_the_range) {
         memory_mapper->ReleasePageRangeToOS(
-            current_range_start_page << page_size_scaled_log,
+            class_id, current_range_start_page << page_size_scaled_log,
             current_page << page_size_scaled_log);
         in_the_range = false;
       }
     }
 
-    MemoryMapperT* const memory_mapper;
-    const uptr page_size_scaled_log;
-    bool in_the_range;
-    uptr current_page;
-    uptr current_range_start_page;
+    MemoryMapperT *const memory_mapper = nullptr;
+    const uptr class_id = 0;
+    const uptr page_size_scaled_log = 0;
+    bool in_the_range = false;
+    uptr current_page = 0;
+    uptr current_range_start_page = 0;
   };
 
   // Iterates over the free_array to identify memory pages containing freed
   // chunks only and returns these pages back to OS.
   // allocated_pages_count is the total number of pages allocated for the
   // current bucket.
-  template<class MemoryMapperT>
+  template <typename MemoryMapper>
   static void ReleaseFreeMemoryToOS(CompactPtrT *free_array,
                                     uptr free_array_count, uptr chunk_size,
                                     uptr allocated_pages_count,
-                                    MemoryMapperT *memory_mapper) {
+                                    MemoryMapper *memory_mapper,
+                                    uptr class_id) {
     const uptr page_size = GetPageSizeCached();
 
     // Figure out the number of chunks per page and whether we can take a fast
@@ -489,9 +552,8 @@ class SizeClassAllocator64 {
       UNREACHABLE("All chunk_size/page_size ratios must be handled.");
     }
 
-    PackedCounterArray<MemoryMapperT> counters(allocated_pages_count,
-                                               full_pages_chunk_count_max,
-                                               memory_mapper);
+    PackedCounterArray counters(allocated_pages_count,
+                                full_pages_chunk_count_max, memory_mapper);
     if (!counters.IsAllocated())
       return;
 
@@ -516,7 +578,7 @@ class SizeClassAllocator64 {
 
     // Iterate over pages detecting ranges of pages with chunk counters equal
     // to the expected number of chunks for the particular page.
-    FreePagesRangeTracker<MemoryMapperT> range_tracker(memory_mapper);
+    FreePagesRangeTracker<MemoryMapper> range_tracker(memory_mapper, class_id);
     if (same_chunk_count_per_page) {
       // Fast path, every page has the same number of chunks affecting it.
       for (uptr i = 0; i < counters.GetCount(); i++)
@@ -555,7 +617,7 @@ class SizeClassAllocator64 {
   }
 
  private:
-  friend class MemoryMapper;
+  friend class MemoryMapper<ThisT>;
 
   ReservedAddressRange address_range;
 
@@ -585,6 +647,11 @@ class SizeClassAllocator64 {
 
   atomic_sint32_t release_to_os_interval_ms_;
 
+  uptr RegionInfoSpace;
+
+  // True if the user has already mapped the entire heap R/W.
+  bool PremappedHeap;
+
   struct Stats {
     uptr n_allocated;
     uptr n_freed;
@@ -614,7 +681,7 @@ class SizeClassAllocator64 {
 
   RegionInfo *GetRegionInfo(uptr class_id) const {
     DCHECK_LT(class_id, kNumClasses);
-    RegionInfo *regions = reinterpret_cast<RegionInfo *>(SpaceEnd());
+    RegionInfo *regions = reinterpret_cast<RegionInfo *>(RegionInfoSpace);
     return &regions[class_id];
   }
 
@@ -639,6 +706,9 @@ class SizeClassAllocator64 {
   }
 
   bool MapWithCallback(uptr beg, uptr size, const char *name) {
+    if (PremappedHeap)
+      return beg >= NonConstSpaceBeg &&
+             beg + size <= NonConstSpaceBeg + kSpaceSize;
     uptr mapped = address_range.Map(beg, size, name);
     if (UNLIKELY(!mapped))
       return false;
@@ -648,11 +718,18 @@ class SizeClassAllocator64 {
   }
 
   void MapWithCallbackOrDie(uptr beg, uptr size, const char *name) {
+    if (PremappedHeap) {
+      CHECK_GE(beg, NonConstSpaceBeg);
+      CHECK_LE(beg + size, NonConstSpaceBeg + kSpaceSize);
+      return;
+    }
     CHECK_EQ(beg, address_range.MapOrDie(beg, size, name));
     MapUnmapCallback().OnMap(beg, size);
   }
 
   void UnmapWithCallbackOrDie(uptr beg, uptr size) {
+    if (PremappedHeap)
+      return;
     MapUnmapCallback().OnUnmap(beg, size);
     address_range.Unmap(beg, size);
   }
@@ -774,55 +851,13 @@ class SizeClassAllocator64 {
     return true;
   }
 
-  class MemoryMapper {
-   public:
-    MemoryMapper(const ThisT& base_allocator, uptr class_id)
-        : allocator(base_allocator),
-          region_base(base_allocator.GetRegionBeginBySizeClass(class_id)),
-          released_ranges_count(0),
-          released_bytes(0) {
-    }
-
-    uptr GetReleasedRangesCount() const {
-      return released_ranges_count;
-    }
-
-    uptr GetReleasedBytes() const {
-      return released_bytes;
-    }
-
-    uptr MapPackedCounterArrayBuffer(uptr buffer_size) {
-      // TODO(alekseyshl): The idea to explore is to check if we have enough
-      // space between num_freed_chunks*sizeof(CompactPtrT) and
-      // mapped_free_array to fit buffer_size bytes and use that space instead
-      // of mapping a temporary one.
-      return reinterpret_cast<uptr>(
-          MmapOrDieOnFatalError(buffer_size, "ReleaseToOSPageCounters"));
-    }
-
-    void UnmapPackedCounterArrayBuffer(uptr buffer, uptr buffer_size) {
-      UnmapOrDie(reinterpret_cast<void *>(buffer), buffer_size);
-    }
-
-    // Releases [from, to) range of pages back to OS.
-    void ReleasePageRangeToOS(CompactPtrT from, CompactPtrT to) {
-      const uptr from_page = allocator.CompactPtrToPointer(region_base, from);
-      const uptr to_page = allocator.CompactPtrToPointer(region_base, to);
-      ReleaseMemoryPagesToOS(from_page, to_page);
-      released_ranges_count++;
-      released_bytes += to_page - from_page;
-    }
-
-   private:
-    const ThisT& allocator;
-    const uptr region_base;
-    uptr released_ranges_count;
-    uptr released_bytes;
-  };
-
   // Attempts to release RAM occupied by freed chunks back to OS. The region is
   // expected to be locked.
-  void MaybeReleaseToOS(uptr class_id, bool force) {
+  //
+  // TODO(morehouse): Support a callback on memory release so HWASan can release
+  // aliases as well.
+  void MaybeReleaseToOS(MemoryMapperT *memory_mapper, uptr class_id,
+                        bool force) {
     RegionInfo *region = GetRegionInfo(class_id);
     const uptr chunk_size = ClassIdToSize(class_id);
     const uptr page_size = GetPageSizeCached();
@@ -846,17 +881,16 @@ class SizeClassAllocator64 {
       }
     }
 
-    MemoryMapper memory_mapper(*this, class_id);
-
-    ReleaseFreeMemoryToOS<MemoryMapper>(
+    ReleaseFreeMemoryToOS(
         GetFreeArray(GetRegionBeginBySizeClass(class_id)), n, chunk_size,
-        RoundUpTo(region->allocated_user, page_size) / page_size,
-        &memory_mapper);
+        RoundUpTo(region->allocated_user, page_size) / page_size, memory_mapper,
+        class_id);
 
-    if (memory_mapper.GetReleasedRangesCount() > 0) {
+    uptr ranges, bytes;
+    if (memory_mapper->GetAndResetStats(ranges, bytes)) {
       region->rtoi.n_freed_at_last_release = region->stats.n_freed;
-      region->rtoi.num_releases += memory_mapper.GetReleasedRangesCount();
-      region->rtoi.last_released_bytes = memory_mapper.GetReleasedBytes();
+      region->rtoi.num_releases += ranges;
+      region->rtoi.last_released_bytes = bytes;
     }
     region->rtoi.last_release_at_ns = MonotonicNanoTime();
   }
lib/tsan/sanitizer_common/sanitizer_allocator_report.cpp
@@ -134,4 +134,12 @@ void NORETURN ReportOutOfMemory(uptr requested_size, const StackTrace *stack) {
   Die();
 }
 
+void NORETURN ReportRssLimitExceeded(const StackTrace *stack) {
+  {
+    ScopedAllocatorErrorReport report("rss-limit-exceeded", stack);
+    Report("ERROR: %s: allocator exceeded the RSS limit\n", SanitizerToolName);
+  }
+  Die();
+}
+
 }  // namespace __sanitizer
lib/tsan/sanitizer_common/sanitizer_allocator_report.h
@@ -33,6 +33,7 @@ void NORETURN ReportInvalidPosixMemalignAlignment(uptr alignment,
 void NORETURN ReportAllocationSizeTooBig(uptr user_size, uptr max_size,
                                          const StackTrace *stack);
 void NORETURN ReportOutOfMemory(uptr requested_size, const StackTrace *stack);
+void NORETURN ReportRssLimitExceeded(const StackTrace *stack);
 
 }  // namespace __sanitizer
 
lib/tsan/sanitizer_common/sanitizer_allocator_secondary.h
@@ -18,8 +18,8 @@
 // (currently, 32 bits and internal allocator).
 class LargeMmapAllocatorPtrArrayStatic {
  public:
-  INLINE void *Init() { return &p_[0]; }
-  INLINE void EnsureSpace(uptr n) { CHECK_LT(n, kMaxNumChunks); }
+  inline void *Init() { return &p_[0]; }
+  inline void EnsureSpace(uptr n) { CHECK_LT(n, kMaxNumChunks); }
  private:
   static const int kMaxNumChunks = 1 << 15;
   uptr p_[kMaxNumChunks];
@@ -31,14 +31,14 @@ class LargeMmapAllocatorPtrArrayStatic {
 // same functionality in Fuchsia case, which does not support MAP_NORESERVE.
 class LargeMmapAllocatorPtrArrayDynamic {
  public:
-  INLINE void *Init() {
+  inline void *Init() {
     uptr p = address_range_.Init(kMaxNumChunks * sizeof(uptr),
                                  SecondaryAllocatorName);
     CHECK(p);
     return reinterpret_cast<void*>(p);
   }
 
-  INLINE void EnsureSpace(uptr n) {
+  inline void EnsureSpace(uptr n) {
     CHECK_LT(n, kMaxNumChunks);
     DCHECK(n <= n_reserved_);
     if (UNLIKELY(n == n_reserved_)) {
@@ -267,13 +267,9 @@ class LargeMmapAllocator {
 
   // ForceLock() and ForceUnlock() are needed to implement Darwin malloc zone
   // introspection API.
-  void ForceLock() {
-    mutex_.Lock();
-  }
+  void ForceLock() ACQUIRE(mutex_) { mutex_.Lock(); }
 
-  void ForceUnlock() {
-    mutex_.Unlock();
-  }
+  void ForceUnlock() RELEASE(mutex_) { mutex_.Unlock(); }
 
   // Iterate over all existing chunks.
   // The allocator must be locked when calling this function.
lib/tsan/sanitizer_common/sanitizer_allocator_size_class_map.h
@@ -24,7 +24,7 @@
 //             E.g. with kNumBits==3 all size classes after 2^kMidSizeLog
 //             look like 0b1xx0..0, where x is either 0 or 1.
 //
-// Example: kNumBits=3, kMidSizeLog=4, kMidSizeLog=8, kMaxSizeLog=17:
+// Example: kNumBits=3, kMinSizeLog=4, kMidSizeLog=8, kMaxSizeLog=17:
 //
 // Classes 1 - 16 correspond to sizes 16 to 256 (size = class_id * 16).
 // Next 4 classes: 256 + i * 64  (i = 1 to 4).
lib/tsan/sanitizer_common/sanitizer_atomic.h
@@ -72,12 +72,12 @@ namespace __sanitizer {
 // Clutter-reducing helpers.
 
 template<typename T>
-INLINE typename T::Type atomic_load_relaxed(const volatile T *a) {
+inline typename T::Type atomic_load_relaxed(const volatile T *a) {
   return atomic_load(a, memory_order_relaxed);
 }
 
 template<typename T>
-INLINE void atomic_store_relaxed(volatile T *a, typename T::Type v) {
+inline void atomic_store_relaxed(volatile T *a, typename T::Type v) {
   atomic_store(a, v, memory_order_relaxed);
 }
 
lib/tsan/sanitizer_common/sanitizer_atomic_clang.h
@@ -34,16 +34,16 @@ namespace __sanitizer {
 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
 // for mappings of the memory model to different processors.
 
-INLINE void atomic_signal_fence(memory_order) {
+inline void atomic_signal_fence(memory_order) {
   __asm__ __volatile__("" ::: "memory");
 }
 
-INLINE void atomic_thread_fence(memory_order) {
+inline void atomic_thread_fence(memory_order) {
   __sync_synchronize();
 }
 
 template<typename T>
-INLINE typename T::Type atomic_fetch_add(volatile T *a,
+inline typename T::Type atomic_fetch_add(volatile T *a,
     typename T::Type v, memory_order mo) {
   (void)mo;
   DCHECK(!((uptr)a % sizeof(*a)));
@@ -51,7 +51,7 @@ INLINE typename T::Type atomic_fetch_add(volatile T *a,
 }
 
 template<typename T>
-INLINE typename T::Type atomic_fetch_sub(volatile T *a,
+inline typename T::Type atomic_fetch_sub(volatile T *a,
     typename T::Type v, memory_order mo) {
   (void)mo;
   DCHECK(!((uptr)a % sizeof(*a)));
@@ -59,7 +59,7 @@ INLINE typename T::Type atomic_fetch_sub(volatile T *a,
 }
 
 template<typename T>
-INLINE typename T::Type atomic_exchange(volatile T *a,
+inline typename T::Type atomic_exchange(volatile T *a,
     typename T::Type v, memory_order mo) {
   DCHECK(!((uptr)a % sizeof(*a)));
   if (mo & (memory_order_release | memory_order_acq_rel | memory_order_seq_cst))
@@ -71,7 +71,7 @@ INLINE typename T::Type atomic_exchange(volatile T *a,
 }
 
 template <typename T>
-INLINE bool atomic_compare_exchange_strong(volatile T *a, typename T::Type *cmp,
+inline bool atomic_compare_exchange_strong(volatile T *a, typename T::Type *cmp,
                                            typename T::Type xchg,
                                            memory_order mo) {
   typedef typename T::Type Type;
@@ -84,7 +84,7 @@ INLINE bool atomic_compare_exchange_strong(volatile T *a, typename T::Type *cmp,
 }
 
 template<typename T>
-INLINE bool atomic_compare_exchange_weak(volatile T *a,
+inline bool atomic_compare_exchange_weak(volatile T *a,
                                          typename T::Type *cmp,
                                          typename T::Type xchg,
                                          memory_order mo) {
lib/tsan/sanitizer_common/sanitizer_atomic_clang_mips.h
@@ -37,11 +37,11 @@ static struct {
 } __attribute__((aligned(32))) lock = {0, {0}};
 
 template <>
-INLINE atomic_uint64_t::Type atomic_fetch_add(volatile atomic_uint64_t *ptr,
+inline atomic_uint64_t::Type atomic_fetch_add(volatile atomic_uint64_t *ptr,
                                               atomic_uint64_t::Type val,
                                               memory_order mo) {
   DCHECK(mo &
-         (memory_order_relaxed | memory_order_releasae | memory_order_seq_cst));
+         (memory_order_relaxed | memory_order_release | memory_order_seq_cst));
   DCHECK(!((uptr)ptr % sizeof(*ptr)));
 
   atomic_uint64_t::Type ret;
@@ -55,19 +55,19 @@ INLINE atomic_uint64_t::Type atomic_fetch_add(volatile atomic_uint64_t *ptr,
 }
 
 template <>
-INLINE atomic_uint64_t::Type atomic_fetch_sub(volatile atomic_uint64_t *ptr,
+inline atomic_uint64_t::Type atomic_fetch_sub(volatile atomic_uint64_t *ptr,
                                               atomic_uint64_t::Type val,
                                               memory_order mo) {
   return atomic_fetch_add(ptr, -val, mo);
 }
 
 template <>
-INLINE bool atomic_compare_exchange_strong(volatile atomic_uint64_t *ptr,
+inline bool atomic_compare_exchange_strong(volatile atomic_uint64_t *ptr,
                                            atomic_uint64_t::Type *cmp,
                                            atomic_uint64_t::Type xchg,
                                            memory_order mo) {
   DCHECK(mo &
-         (memory_order_relaxed | memory_order_releasae | memory_order_seq_cst));
+         (memory_order_relaxed | memory_order_release | memory_order_seq_cst));
   DCHECK(!((uptr)ptr % sizeof(*ptr)));
 
   typedef atomic_uint64_t::Type Type;
@@ -87,10 +87,10 @@ INLINE bool atomic_compare_exchange_strong(volatile atomic_uint64_t *ptr,
 }
 
 template <>
-INLINE atomic_uint64_t::Type atomic_load(const volatile atomic_uint64_t *ptr,
+inline atomic_uint64_t::Type atomic_load(const volatile atomic_uint64_t *ptr,
                                          memory_order mo) {
   DCHECK(mo &
-         (memory_order_relaxed | memory_order_releasae | memory_order_seq_cst));
+         (memory_order_relaxed | memory_order_release | memory_order_seq_cst));
   DCHECK(!((uptr)ptr % sizeof(*ptr)));
 
   atomic_uint64_t::Type zero = 0;
@@ -100,10 +100,10 @@ INLINE atomic_uint64_t::Type atomic_load(const volatile atomic_uint64_t *ptr,
 }
 
 template <>
-INLINE void atomic_store(volatile atomic_uint64_t *ptr, atomic_uint64_t::Type v,
+inline void atomic_store(volatile atomic_uint64_t *ptr, atomic_uint64_t::Type v,
                          memory_order mo) {
   DCHECK(mo &
-         (memory_order_relaxed | memory_order_releasae | memory_order_seq_cst));
+         (memory_order_relaxed | memory_order_release | memory_order_seq_cst));
   DCHECK(!((uptr)ptr % sizeof(*ptr)));
 
   __spin_lock(&lock.lock);
lib/tsan/sanitizer_common/sanitizer_atomic_clang_other.h
@@ -17,12 +17,12 @@
 namespace __sanitizer {
 
 
-INLINE void proc_yield(int cnt) {
+inline void proc_yield(int cnt) {
   __asm__ __volatile__("" ::: "memory");
 }
 
 template<typename T>
-INLINE typename T::Type atomic_load(
+inline typename T::Type atomic_load(
     const volatile T *a, memory_order mo) {
   DCHECK(mo & (memory_order_relaxed | memory_order_consume
       | memory_order_acquire | memory_order_seq_cst));
@@ -50,17 +50,14 @@ INLINE typename T::Type atomic_load(
       __sync_synchronize();
     }
   } else {
-    // 64-bit load on 32-bit platform.
-    // Gross, but simple and reliable.
-    // Assume that it is not in read-only memory.
-    v = __sync_fetch_and_add(
-        const_cast<typename T::Type volatile *>(&a->val_dont_use), 0);
+    __atomic_load(const_cast<typename T::Type volatile *>(&a->val_dont_use), &v,
+                  __ATOMIC_SEQ_CST);
   }
   return v;
 }
 
 template<typename T>
-INLINE void atomic_store(volatile T *a, typename T::Type v, memory_order mo) {
+inline void atomic_store(volatile T *a, typename T::Type v, memory_order mo) {
   DCHECK(mo & (memory_order_relaxed | memory_order_release
       | memory_order_seq_cst));
   DCHECK(!((uptr)a % sizeof(*a)));
@@ -79,16 +76,7 @@ INLINE void atomic_store(volatile T *a, typename T::Type v, memory_order mo) {
       __sync_synchronize();
     }
   } else {
-    // 64-bit store on 32-bit platform.
-    // Gross, but simple and reliable.
-    typename T::Type cmp = a->val_dont_use;
-    typename T::Type cur;
-    for (;;) {
-      cur = __sync_val_compare_and_swap(&a->val_dont_use, cmp, v);
-      if (cur == cmp || cur == v)
-        break;
-      cmp = cur;
-    }
+    __atomic_store(&a->val_dont_use, &v, __ATOMIC_SEQ_CST);
   }
 }
 
lib/tsan/sanitizer_common/sanitizer_atomic_clang_x86.h
@@ -16,7 +16,7 @@
 
 namespace __sanitizer {
 
-INLINE void proc_yield(int cnt) {
+inline void proc_yield(int cnt) {
   __asm__ __volatile__("" ::: "memory");
   for (int i = 0; i < cnt; i++)
     __asm__ __volatile__("pause");
@@ -24,7 +24,7 @@ INLINE void proc_yield(int cnt) {
 }
 
 template<typename T>
-INLINE typename T::Type atomic_load(
+inline typename T::Type atomic_load(
     const volatile T *a, memory_order mo) {
   DCHECK(mo & (memory_order_relaxed | memory_order_consume
       | memory_order_acquire | memory_order_seq_cst));
@@ -70,7 +70,7 @@ INLINE typename T::Type atomic_load(
 }
 
 template<typename T>
-INLINE void atomic_store(volatile T *a, typename T::Type v, memory_order mo) {
+inline void atomic_store(volatile T *a, typename T::Type v, memory_order mo) {
   DCHECK(mo & (memory_order_relaxed | memory_order_release
       | memory_order_seq_cst));
   DCHECK(!((uptr)a % sizeof(*a)));
lib/tsan/sanitizer_common/sanitizer_atomic_msvc.h
@@ -54,21 +54,21 @@ extern "C" long long _InterlockedExchangeAdd64(long long volatile *Addend,
 
 namespace __sanitizer {
 
-INLINE void atomic_signal_fence(memory_order) {
+inline void atomic_signal_fence(memory_order) {
   _ReadWriteBarrier();
 }
 
-INLINE void atomic_thread_fence(memory_order) {
+inline void atomic_thread_fence(memory_order) {
   _mm_mfence();
 }
 
-INLINE void proc_yield(int cnt) {
+inline void proc_yield(int cnt) {
   for (int i = 0; i < cnt; i++)
     _mm_pause();
 }
 
 template<typename T>
-INLINE typename T::Type atomic_load(
+inline typename T::Type atomic_load(
     const volatile T *a, memory_order mo) {
   DCHECK(mo & (memory_order_relaxed | memory_order_consume
       | memory_order_acquire | memory_order_seq_cst));
@@ -86,7 +86,7 @@ INLINE typename T::Type atomic_load(
 }
 
 template<typename T>
-INLINE void atomic_store(volatile T *a, typename T::Type v, memory_order mo) {
+inline void atomic_store(volatile T *a, typename T::Type v, memory_order mo) {
   DCHECK(mo & (memory_order_relaxed | memory_order_release
       | memory_order_seq_cst));
   DCHECK(!((uptr)a % sizeof(*a)));
@@ -102,7 +102,7 @@ INLINE void atomic_store(volatile T *a, typename T::Type v, memory_order mo) {
     atomic_thread_fence(memory_order_seq_cst);
 }
 
-INLINE u32 atomic_fetch_add(volatile atomic_uint32_t *a,
+inline u32 atomic_fetch_add(volatile atomic_uint32_t *a,
     u32 v, memory_order mo) {
   (void)mo;
   DCHECK(!((uptr)a % sizeof(*a)));
@@ -110,7 +110,7 @@ INLINE u32 atomic_fetch_add(volatile atomic_uint32_t *a,
                                       (long)v);
 }
 
-INLINE uptr atomic_fetch_add(volatile atomic_uintptr_t *a,
+inline uptr atomic_fetch_add(volatile atomic_uintptr_t *a,
     uptr v, memory_order mo) {
   (void)mo;
   DCHECK(!((uptr)a % sizeof(*a)));
@@ -123,7 +123,7 @@ INLINE uptr atomic_fetch_add(volatile atomic_uintptr_t *a,
 #endif
 }
 
-INLINE u32 atomic_fetch_sub(volatile atomic_uint32_t *a,
+inline u32 atomic_fetch_sub(volatile atomic_uint32_t *a,
     u32 v, memory_order mo) {
   (void)mo;
   DCHECK(!((uptr)a % sizeof(*a)));
@@ -131,7 +131,7 @@ INLINE u32 atomic_fetch_sub(volatile atomic_uint32_t *a,
                                       -(long)v);
 }
 
-INLINE uptr atomic_fetch_sub(volatile atomic_uintptr_t *a,
+inline uptr atomic_fetch_sub(volatile atomic_uintptr_t *a,
     uptr v, memory_order mo) {
   (void)mo;
   DCHECK(!((uptr)a % sizeof(*a)));
@@ -144,28 +144,28 @@ INLINE uptr atomic_fetch_sub(volatile atomic_uintptr_t *a,
 #endif
 }
 
-INLINE u8 atomic_exchange(volatile atomic_uint8_t *a,
+inline u8 atomic_exchange(volatile atomic_uint8_t *a,
     u8 v, memory_order mo) {
   (void)mo;
   DCHECK(!((uptr)a % sizeof(*a)));
   return (u8)_InterlockedExchange8((volatile char*)&a->val_dont_use, v);
 }
 
-INLINE u16 atomic_exchange(volatile atomic_uint16_t *a,
+inline u16 atomic_exchange(volatile atomic_uint16_t *a,
     u16 v, memory_order mo) {
   (void)mo;
   DCHECK(!((uptr)a % sizeof(*a)));
   return (u16)_InterlockedExchange16((volatile short*)&a->val_dont_use, v);
 }
 
-INLINE u32 atomic_exchange(volatile atomic_uint32_t *a,
+inline u32 atomic_exchange(volatile atomic_uint32_t *a,
     u32 v, memory_order mo) {
   (void)mo;
   DCHECK(!((uptr)a % sizeof(*a)));
   return (u32)_InterlockedExchange((volatile long*)&a->val_dont_use, v);
 }
 
-INLINE bool atomic_compare_exchange_strong(volatile atomic_uint8_t *a,
+inline bool atomic_compare_exchange_strong(volatile atomic_uint8_t *a,
                                            u8 *cmp,
                                            u8 xchgv,
                                            memory_order mo) {
@@ -191,7 +191,7 @@ INLINE bool atomic_compare_exchange_strong(volatile atomic_uint8_t *a,
   return false;
 }
 
-INLINE bool atomic_compare_exchange_strong(volatile atomic_uintptr_t *a,
+inline bool atomic_compare_exchange_strong(volatile atomic_uintptr_t *a,
                                            uptr *cmp,
                                            uptr xchg,
                                            memory_order mo) {
@@ -204,7 +204,7 @@ INLINE bool atomic_compare_exchange_strong(volatile atomic_uintptr_t *a,
   return false;
 }
 
-INLINE bool atomic_compare_exchange_strong(volatile atomic_uint16_t *a,
+inline bool atomic_compare_exchange_strong(volatile atomic_uint16_t *a,
                                            u16 *cmp,
                                            u16 xchg,
                                            memory_order mo) {
@@ -217,7 +217,7 @@ INLINE bool atomic_compare_exchange_strong(volatile atomic_uint16_t *a,
   return false;
 }
 
-INLINE bool atomic_compare_exchange_strong(volatile atomic_uint32_t *a,
+inline bool atomic_compare_exchange_strong(volatile atomic_uint32_t *a,
                                            u32 *cmp,
                                            u32 xchg,
                                            memory_order mo) {
@@ -230,7 +230,7 @@ INLINE bool atomic_compare_exchange_strong(volatile atomic_uint32_t *a,
   return false;
 }
 
-INLINE bool atomic_compare_exchange_strong(volatile atomic_uint64_t *a,
+inline bool atomic_compare_exchange_strong(volatile atomic_uint64_t *a,
                                            u64 *cmp,
                                            u64 xchg,
                                            memory_order mo) {
@@ -244,7 +244,7 @@ INLINE bool atomic_compare_exchange_strong(volatile atomic_uint64_t *a,
 }
 
 template<typename T>
-INLINE bool atomic_compare_exchange_weak(volatile T *a,
+inline bool atomic_compare_exchange_weak(volatile T *a,
                                          typename T::Type *cmp,
                                          typename T::Type xchg,
                                          memory_order mo) {
lib/tsan/sanitizer_common/sanitizer_common.cpp
@@ -37,10 +37,9 @@ void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
                                       const char *mmap_type, error_t err,
                                       bool raw_report) {
   static int recursion_count;
-  if (SANITIZER_RTEMS || raw_report || recursion_count) {
-    // If we are on RTEMS or raw report is requested or we went into recursion,
-    // just die.  The Report() and CHECK calls below may call mmap recursively
-    // and fail.
+  if (raw_report || recursion_count) {
+    // If raw report is requested or we went into recursion just die.  The
+    // Report() and CHECK calls below may call mmap recursively and fail.
     RawWrite("ERROR: Failed to mmap\n");
     Die();
   }
@@ -87,7 +86,7 @@ const char *StripModuleName(const char *module) {
 void ReportErrorSummary(const char *error_message, const char *alt_tool_name) {
   if (!common_flags()->print_summary)
     return;
-  InternalScopedString buff(kMaxSummaryLength);
+  InternalScopedString buff;
   buff.append("SUMMARY: %s: %s",
               alt_tool_name ? alt_tool_name : SanitizerToolName, error_message);
   __sanitizer_report_error_summary(buff.data());
@@ -274,6 +273,14 @@ uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len) {
   return name_len;
 }
 
+uptr ReadBinaryDir(/*out*/ char *buf, uptr buf_len) {
+  ReadBinaryNameCached(buf, buf_len);
+  const char *exec_name_pos = StripModuleName(buf);
+  uptr name_len = exec_name_pos - buf;
+  buf[name_len] = '\0';
+  return name_len;
+}
+
 #if !SANITIZER_GO
 void PrintCmdline() {
   char **argv = GetArgv();
@@ -323,6 +330,14 @@ static int InstallMallocFreeHooks(void (*malloc_hook)(const void *, uptr),
   return 0;
 }
 
+void internal_sleep(unsigned seconds) {
+  internal_usleep((u64)seconds * 1000 * 1000);
+}
+void SleepForSeconds(unsigned seconds) {
+  internal_usleep((u64)seconds * 1000 * 1000);
+}
+void SleepForMillis(unsigned millis) { internal_usleep((u64)millis * 1000); }
+
 } // namespace __sanitizer
 
 using namespace __sanitizer;
lib/tsan/sanitizer_common/sanitizer_common.h
@@ -44,7 +44,7 @@ const uptr kMaxPathLength = 4096;
 
 const uptr kMaxThreadStackSize = 1 << 30;  // 1Gb
 
-static const uptr kErrorMessageBufferSize = 1 << 16;
+const uptr kErrorMessageBufferSize = 1 << 16;
 
 // Denotes fake PC values that come from JIT/JAVA/etc.
 // For such PC values __tsan_symbolize_external_ex() will be called.
@@ -53,25 +53,25 @@ const u64 kExternalPCBit = 1ULL << 60;
 extern const char *SanitizerToolName;  // Can be changed by the tool.
 
 extern atomic_uint32_t current_verbosity;
-INLINE void SetVerbosity(int verbosity) {
+inline void SetVerbosity(int verbosity) {
   atomic_store(&current_verbosity, verbosity, memory_order_relaxed);
 }
-INLINE int Verbosity() {
+inline int Verbosity() {
   return atomic_load(&current_verbosity, memory_order_relaxed);
 }
 
 #if SANITIZER_ANDROID
-INLINE uptr GetPageSize() {
+inline uptr GetPageSize() {
 // Android post-M sysconf(_SC_PAGESIZE) crashes if called from .preinit_array.
   return 4096;
 }
-INLINE uptr GetPageSizeCached() {
+inline uptr GetPageSizeCached() {
   return 4096;
 }
 #else
 uptr GetPageSize();
 extern uptr PageSizeCached;
-INLINE uptr GetPageSizeCached() {
+inline uptr GetPageSizeCached() {
   if (!PageSizeCached)
     PageSizeCached = GetPageSize();
   return PageSizeCached;
@@ -91,7 +91,7 @@ void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
 
 // Memory management
 void *MmapOrDie(uptr size, const char *mem_type, bool raw_report = false);
-INLINE void *MmapOrDieQuietly(uptr size, const char *mem_type) {
+inline void *MmapOrDieQuietly(uptr size, const char *mem_type) {
   return MmapOrDie(size, mem_type, /*raw_report*/ true);
 }
 void UnmapOrDie(void *addr, uptr size);
@@ -121,6 +121,40 @@ bool MprotectReadOnly(uptr addr, uptr size);
 
 void MprotectMallocZones(void *addr, int prot);
 
+#if SANITIZER_LINUX
+// Unmap memory. Currently only used on Linux.
+void UnmapFromTo(uptr from, uptr to);
+#endif
+
+// Maps shadow_size_bytes of shadow memory and returns shadow address. It will
+// be aligned to the mmap granularity * 2^shadow_scale, or to
+// 2^min_shadow_base_alignment if that is larger. The returned address will
+// have max(2^min_shadow_base_alignment, mmap granularity) on the left, and
+// shadow_size_bytes bytes on the right, which on linux is mapped no access.
+// The high_mem_end may be updated if the original shadow size doesn't fit.
+uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
+                      uptr min_shadow_base_alignment, uptr &high_mem_end);
+
+// Let S = max(shadow_size, num_aliases * alias_size, ring_buffer_size).
+// Reserves 2*S bytes of address space to the right of the returned address and
+// ring_buffer_size bytes to the left.  The returned address is aligned to 2*S.
+// Also creates num_aliases regions of accessible memory starting at offset S
+// from the returned address.  Each region has size alias_size and is backed by
+// the same physical memory.
+uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
+                                uptr num_aliases, uptr ring_buffer_size);
+
+// Reserve memory range [beg, end]. If madvise_shadow is true then apply
+// madvise (e.g. hugepages, core dumping) requested by options.
+void ReserveShadowMemoryRange(uptr beg, uptr end, const char *name,
+                              bool madvise_shadow = true);
+
+// Protect size bytes of memory starting at addr. Also try to protect
+// several pages at the start of the address space as specified by
+// zero_base_shadow_start, at most up to the size or zero_base_max_shadow_start.
+void ProtectGap(uptr addr, uptr size, uptr zero_base_shadow_start,
+                uptr zero_base_max_shadow_start);
+
 // Find an available address space.
 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
                               uptr *largest_gap_found, uptr *max_occupied_addr);
@@ -203,10 +237,16 @@ void SetPrintfAndReportCallback(void (*callback)(const char *));
 // Lock sanitizer error reporting and protects against nested errors.
 class ScopedErrorReportLock {
  public:
-  ScopedErrorReportLock();
-  ~ScopedErrorReportLock();
+  ScopedErrorReportLock() ACQUIRE(mutex_) { Lock(); }
+  ~ScopedErrorReportLock() RELEASE(mutex_) { Unlock(); }
 
-  static void CheckLocked();
+  static void Lock() ACQUIRE(mutex_);
+  static void Unlock() RELEASE(mutex_);
+  static void CheckLocked() CHECK_LOCKED(mutex_);
+
+ private:
+  static atomic_uintptr_t reporting_thread_;
+  static StaticSpinMutex mutex_;
 };
 
 extern uptr stoptheworld_tracer_pid;
@@ -223,13 +263,13 @@ const char *StripModuleName(const char *module);
 // OS
 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len);
 uptr ReadBinaryNameCached(/*out*/char *buf, uptr buf_len);
+uptr ReadBinaryDir(/*out*/ char *buf, uptr buf_len);
 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len);
 const char *GetProcessName();
 void UpdateProcessName();
 void CacheBinaryName();
 void DisableCoreDumperIfNecessary();
 void DumpProcessMap();
-void PrintModuleMap();
 const char *GetEnv(const char *name);
 bool SetEnv(const char *name, const char *value);
 
@@ -254,8 +294,8 @@ void InitTlsSize();
 uptr GetTlsSize();
 
 // Other
-void SleepForSeconds(int seconds);
-void SleepForMillis(int millis);
+void SleepForSeconds(unsigned seconds);
+void SleepForMillis(unsigned millis);
 u64 NanoTime();
 u64 MonotonicNanoTime();
 int Atexit(void (*function)(void));
@@ -270,8 +310,8 @@ void NORETURN ReportMmapFailureAndDie(uptr size, const char *mem_type,
                                       const char *mmap_type, error_t err,
                                       bool raw_report = false);
 
-// Specific tools may override behavior of "Die" and "CheckFailed" functions
-// to do tool-specific job.
+// Specific tools may override behavior of "Die" function to do tool-specific
+// job.
 typedef void (*DieCallbackType)(void);
 
 // It's possible to add several callbacks that would be run when "Die" is
@@ -283,9 +323,7 @@ bool RemoveDieCallback(DieCallbackType callback);
 
 void SetUserDieCallback(DieCallbackType callback);
 
-typedef void (*CheckFailedCallbackType)(const char *, int, const char *,
-                                       u64, u64);
-void SetCheckFailedCallback(CheckFailedCallbackType callback);
+void SetCheckUnwindCallback(void (*callback)());
 
 // Callback will be called if soft_rss_limit_mb is given and the limit is
 // exceeded (exceeded==true) or if rss went down below the limit
@@ -319,8 +357,6 @@ void ReportDeadlySignal(const SignalContext &sig, u32 tid,
 void SetAlternateSignalStack();
 void UnsetAlternateSignalStack();
 
-// We don't want a summary too long.
-const int kMaxSummaryLength = 1024;
 // Construct a one-line string:
 //   SUMMARY: SanitizerToolName: error_message
 // and pass it to __sanitizer_report_error_summary.
@@ -349,7 +385,7 @@ unsigned char _BitScanReverse64(unsigned long *index, unsigned __int64 mask);
 }
 #endif
 
-INLINE uptr MostSignificantSetBitIndex(uptr x) {
+inline uptr MostSignificantSetBitIndex(uptr x) {
   CHECK_NE(x, 0U);
   unsigned long up;
 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
@@ -366,7 +402,7 @@ INLINE uptr MostSignificantSetBitIndex(uptr x) {
   return up;
 }
 
-INLINE uptr LeastSignificantSetBitIndex(uptr x) {
+inline uptr LeastSignificantSetBitIndex(uptr x) {
   CHECK_NE(x, 0U);
   unsigned long up;
 #if !SANITIZER_WINDOWS || defined(__clang__) || defined(__GNUC__)
@@ -383,11 +419,11 @@ INLINE uptr LeastSignificantSetBitIndex(uptr x) {
   return up;
 }
 
-INLINE bool IsPowerOfTwo(uptr x) {
+inline bool IsPowerOfTwo(uptr x) {
   return (x & (x - 1)) == 0;
 }
 
-INLINE uptr RoundUpToPowerOfTwo(uptr size) {
+inline uptr RoundUpToPowerOfTwo(uptr size) {
   CHECK(size);
   if (IsPowerOfTwo(size)) return size;
 
@@ -397,28 +433,34 @@ INLINE uptr RoundUpToPowerOfTwo(uptr size) {
   return 1ULL << (up + 1);
 }
 
-INLINE uptr RoundUpTo(uptr size, uptr boundary) {
+inline uptr RoundUpTo(uptr size, uptr boundary) {
   RAW_CHECK(IsPowerOfTwo(boundary));
   return (size + boundary - 1) & ~(boundary - 1);
 }
 
-INLINE uptr RoundDownTo(uptr x, uptr boundary) {
+inline uptr RoundDownTo(uptr x, uptr boundary) {
   return x & ~(boundary - 1);
 }
 
-INLINE bool IsAligned(uptr a, uptr alignment) {
+inline bool IsAligned(uptr a, uptr alignment) {
   return (a & (alignment - 1)) == 0;
 }
 
-INLINE uptr Log2(uptr x) {
+inline uptr Log2(uptr x) {
   CHECK(IsPowerOfTwo(x));
   return LeastSignificantSetBitIndex(x);
 }
 
 // Don't use std::min, std::max or std::swap, to minimize dependency
 // on libstdc++.
-template<class T> T Min(T a, T b) { return a < b ? a : b; }
-template<class T> T Max(T a, T b) { return a > b ? a : b; }
+template <class T>
+constexpr T Min(T a, T b) {
+  return a < b ? a : b;
+}
+template <class T>
+constexpr T Max(T a, T b) {
+  return a > b ? a : b;
+}
 template<class T> void Swap(T& a, T& b) {
   T tmp = a;
   a = b;
@@ -426,14 +468,14 @@ template<class T> void Swap(T& a, T& b) {
 }
 
 // Char handling
-INLINE bool IsSpace(int c) {
+inline bool IsSpace(int c) {
   return (c == ' ') || (c == '\n') || (c == '\t') ||
          (c == '\f') || (c == '\r') || (c == '\v');
 }
-INLINE bool IsDigit(int c) {
+inline bool IsDigit(int c) {
   return (c >= '0') && (c <= '9');
 }
-INLINE int ToLower(int c) {
+inline int ToLower(int c) {
   return (c >= 'A' && c <= 'Z') ? (c + 'a' - 'A') : c;
 }
 
@@ -443,6 +485,7 @@ INLINE int ToLower(int c) {
 template<typename T>
 class InternalMmapVectorNoCtor {
  public:
+  using value_type = T;
   void Initialize(uptr initial_capacity) {
     capacity_bytes_ = 0;
     size_ = 0;
@@ -566,21 +609,21 @@ class InternalMmapVector : public InternalMmapVectorNoCtor<T> {
   InternalMmapVector &operator=(InternalMmapVector &&) = delete;
 };
 
-class InternalScopedString : public InternalMmapVector<char> {
+class InternalScopedString {
  public:
-  explicit InternalScopedString(uptr max_length)
-      : InternalMmapVector<char>(max_length), length_(0) {
-    (*this)[0] = '\0';
-  }
-  uptr length() { return length_; }
+  InternalScopedString() : buffer_(1) { buffer_[0] = '\0'; }
+
+  uptr length() const { return buffer_.size() - 1; }
   void clear() {
-    (*this)[0] = '\0';
-    length_ = 0;
+    buffer_.resize(1);
+    buffer_[0] = '\0';
   }
   void append(const char *format, ...);
+  const char *data() const { return buffer_.data(); }
+  char *data() { return buffer_.data(); }
 
  private:
-  uptr length_;
+  InternalMmapVector<char> buffer_;
 };
 
 template <class T>
@@ -627,9 +670,13 @@ void Sort(T *v, uptr size, Compare comp = {}) {
 
 // Works like std::lower_bound: finds the first element that is not less
 // than the val.
-template <class Container, class Value, class Compare>
-uptr InternalLowerBound(const Container &v, uptr first, uptr last,
-                        const Value &val, Compare comp) {
+template <class Container,
+          class Compare = CompareLess<typename Container::value_type>>
+uptr InternalLowerBound(const Container &v,
+                        const typename Container::value_type &val,
+                        Compare comp = {}) {
+  uptr first = 0;
+  uptr last = v.size();
   while (last > first) {
     uptr mid = (first + last) / 2;
     if (comp(v[mid], val))
@@ -649,9 +696,31 @@ enum ModuleArch {
   kModuleArchARMV7,
   kModuleArchARMV7S,
   kModuleArchARMV7K,
-  kModuleArchARM64
+  kModuleArchARM64,
+  kModuleArchRISCV64
 };
 
+// Sorts and removes duplicates from the container.
+template <class Container,
+          class Compare = CompareLess<typename Container::value_type>>
+void SortAndDedup(Container &v, Compare comp = {}) {
+  Sort(v.data(), v.size(), comp);
+  uptr size = v.size();
+  if (size < 2)
+    return;
+  uptr last = 0;
+  for (uptr i = 1; i < size; ++i) {
+    if (comp(v[last], v[i])) {
+      ++last;
+      if (last != i)
+        v[last] = v[i];
+    } else {
+      CHECK(!comp(v[i], v[last]));
+    }
+  }
+  v.resize(last + 1);
+}
+
 // Opens the file 'file_name" and reads up to 'max_len' bytes.
 // The resulting buffer is mmaped and stored in '*buff'.
 // Returns true if file was successfully opened and read.
@@ -693,6 +762,8 @@ inline const char *ModuleArchToString(ModuleArch arch) {
       return "armv7k";
     case kModuleArchARM64:
       return "arm64";
+    case kModuleArchRISCV64:
+      return "riscv64";
   }
   CHECK(0 && "Invalid module arch");
   return "";
@@ -815,15 +886,15 @@ void WriteToSyslog(const char *buffer);
 #if SANITIZER_MAC || SANITIZER_WIN_TRACE
 void LogFullErrorReport(const char *buffer);
 #else
-INLINE void LogFullErrorReport(const char *buffer) {}
+inline void LogFullErrorReport(const char *buffer) {}
 #endif
 
 #if SANITIZER_LINUX || SANITIZER_MAC
 void WriteOneLineToSyslog(const char *s);
 void LogMessageOnPrintf(const char *str);
 #else
-INLINE void WriteOneLineToSyslog(const char *s) {}
-INLINE void LogMessageOnPrintf(const char *str) {}
+inline void WriteOneLineToSyslog(const char *s) {}
+inline void LogMessageOnPrintf(const char *str) {}
 #endif
 
 #if SANITIZER_LINUX || SANITIZER_WIN_TRACE
@@ -831,21 +902,21 @@ INLINE void LogMessageOnPrintf(const char *str) {}
 void AndroidLogInit();
 void SetAbortMessage(const char *);
 #else
-INLINE void AndroidLogInit() {}
+inline void AndroidLogInit() {}
 // FIXME: MacOS implementation could use CRSetCrashLogMessage.
-INLINE void SetAbortMessage(const char *) {}
+inline void SetAbortMessage(const char *) {}
 #endif
 
 #if SANITIZER_ANDROID
 void SanitizerInitializeUnwinder();
 AndroidApiLevel AndroidGetApiLevel();
 #else
-INLINE void AndroidLogWrite(const char *buffer_unused) {}
-INLINE void SanitizerInitializeUnwinder() {}
-INLINE AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
+inline void AndroidLogWrite(const char *buffer_unused) {}
+inline void SanitizerInitializeUnwinder() {}
+inline AndroidApiLevel AndroidGetApiLevel() { return ANDROID_NOT_ANDROID; }
 #endif
 
-INLINE uptr GetPthreadDestructorIterations() {
+inline uptr GetPthreadDestructorIterations() {
 #if SANITIZER_ANDROID
   return (AndroidGetApiLevel() == ANDROID_LOLLIPOP_MR1) ? 8 : 4;
 #elif SANITIZER_POSIX
@@ -951,7 +1022,7 @@ RunOnDestruction<Fn> at_scope_exit(Fn fn) {
 #if SANITIZER_LINUX && SANITIZER_S390_64
 void AvoidCVE_2016_2143();
 #else
-INLINE void AvoidCVE_2016_2143() {}
+inline void AvoidCVE_2016_2143() {}
 #endif
 
 struct StackDepotStats {
@@ -972,7 +1043,7 @@ bool GetRandom(void *buffer, uptr length, bool blocking = true);
 // Returns the number of logical processors on the system.
 u32 GetNumberOfCPUs();
 extern u32 NumberOfCPUsCached;
-INLINE u32 GetNumberOfCPUsCached() {
+inline u32 GetNumberOfCPUsCached() {
   if (!NumberOfCPUsCached)
     NumberOfCPUsCached = GetNumberOfCPUs();
   return NumberOfCPUsCached;
@@ -992,6 +1063,13 @@ class ArrayRef {
   T *end_ = nullptr;
 };
 
+#define PRINTF_128(v)                                                         \
+  (*((u8 *)&v + 0)), (*((u8 *)&v + 1)), (*((u8 *)&v + 2)), (*((u8 *)&v + 3)), \
+      (*((u8 *)&v + 4)), (*((u8 *)&v + 5)), (*((u8 *)&v + 6)),                \
+      (*((u8 *)&v + 7)), (*((u8 *)&v + 8)), (*((u8 *)&v + 9)),                \
+      (*((u8 *)&v + 10)), (*((u8 *)&v + 11)), (*((u8 *)&v + 12)),             \
+      (*((u8 *)&v + 13)), (*((u8 *)&v + 14)), (*((u8 *)&v + 15))
+
 }  // namespace __sanitizer
 
 inline void *operator new(__sanitizer::operator_new_size_type size,
lib/tsan/sanitizer_common/sanitizer_common_interceptors.inc
@@ -134,11 +134,11 @@ extern const short *_tolower_tab_;
 
 // Platform-specific options.
 #if SANITIZER_MAC
-#define PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE false
+#define PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE 0
 #elif SANITIZER_WINDOWS64
-#define PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE false
+#define PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE 0
 #else
-#define PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE true
+#define PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE 1
 #endif  // SANITIZER_MAC
 
 #ifndef COMMON_INTERCEPTOR_INITIALIZE_RANGE
@@ -239,6 +239,23 @@ extern const short *_tolower_tab_;
     COMMON_INTERCEPT_FUNCTION(fn)
 #endif
 
+#if SANITIZER_GLIBC
+// If we could not find the versioned symbol, fall back to an unversioned
+// lookup. This is needed to work around a GLibc bug that causes dlsym
+// with RTLD_NEXT to return the oldest versioned symbol.
+// See https://sourceware.org/bugzilla/show_bug.cgi?id=14932.
+// For certain symbols (e.g. regexec) we have to perform a versioned lookup,
+// but that versioned symbol will only exist for architectures where the
+// oldest Glibc version pre-dates support for that architecture.
+// For example, regexec@GLIBC_2.3.4 exists on x86_64, but not RISC-V.
+// See also https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98920.
+#define COMMON_INTERCEPT_FUNCTION_GLIBC_VER_MIN(fn, ver) \
+  COMMON_INTERCEPT_FUNCTION_VER_UNVERSIONED_FALLBACK(fn, ver)
+#else
+#define COMMON_INTERCEPT_FUNCTION_GLIBC_VER_MIN(fn, ver) \
+  COMMON_INTERCEPT_FUNCTION(fn)
+#endif
+
 #ifndef COMMON_INTERCEPTOR_MEMSET_IMPL
 #define COMMON_INTERCEPTOR_MEMSET_IMPL(ctx, dst, v, size) \
   {                                                       \
@@ -445,8 +462,10 @@ INTERCEPTOR(int, strcmp, const char *s1, const char *s2) {
     c2 = (unsigned char)s2[i];
     if (c1 != c2 || c1 == '\0') break;
   }
-  COMMON_INTERCEPTOR_READ_STRING(ctx, s1, i + 1);
-  COMMON_INTERCEPTOR_READ_STRING(ctx, s2, i + 1);
+  if (common_flags()->intercept_strcmp) {
+    COMMON_INTERCEPTOR_READ_STRING(ctx, s1, i + 1);
+    COMMON_INTERCEPTOR_READ_STRING(ctx, s2, i + 1);
+  }
   int result = CharCmpX(c1, c2);
   CALL_WEAK_INTERCEPTOR_HOOK(__sanitizer_weak_hook_strcmp, GET_CALLER_PC(), s1,
                              s2, result);
@@ -804,11 +823,11 @@ INTERCEPTOR(void *, memcpy, void *dst, const void *src, uptr size) {
   // N.B.: If we switch this to internal_ we'll have to use internal_memmove
   // due to memcpy being an alias of memmove on OS X.
   void *ctx;
-  if (PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE) {
+#if PLATFORM_HAS_DIFFERENT_MEMCPY_AND_MEMMOVE
     COMMON_INTERCEPTOR_MEMCPY_IMPL(ctx, dst, src, size);
-  } else {
+#else
     COMMON_INTERCEPTOR_MEMMOVE_IMPL(ctx, dst, src, size);
-  }
+#endif
 }
 
 #define INIT_MEMCPY                                  \
@@ -938,6 +957,7 @@ INTERCEPTOR(double, frexp, double x, int *exp) {
   // Assuming frexp() always writes to |exp|.
   COMMON_INTERCEPTOR_WRITE_RANGE(ctx, exp, sizeof(*exp));
   double res = REAL(frexp)(x, exp);
+  COMMON_INTERCEPTOR_INITIALIZE_RANGE(exp, sizeof(*exp));
   return res;
 }
 
@@ -950,22 +970,18 @@ INTERCEPTOR(double, frexp, double x, int *exp) {
 INTERCEPTOR(float, frexpf, float x, int *exp) {
   void *ctx;
   COMMON_INTERCEPTOR_ENTER(ctx, frexpf, x, exp);
-  // FIXME: under ASan the call below may write to freed memory and corrupt
-  // its metadata. See
-  // https://github.com/google/sanitizers/issues/321.
-  float res = REAL(frexpf)(x, exp);
   COMMON_INTERCEPTOR_WRITE_RANGE(ctx, exp, sizeof(*exp));
+  float res = REAL(frexpf)(x, exp);
+  COMMON_INTERCEPTOR_INITIALIZE_RANGE(exp, sizeof(*exp));
   return res;
 }
 
 INTERCEPTOR(long double, frexpl, long double x, int *exp) {
   void *ctx;
   COMMON_INTERCEPTOR_ENTER(ctx, frexpl, x, exp);
-  // FIXME: under ASan the call below may write to freed memory and corrupt
-  // its metadata. See
-  // https://github.com/google/sanitizers/issues/321.
-  long double res = REAL(frexpl)(x, exp);
   COMMON_INTERCEPTOR_WRITE_RANGE(ctx, exp, sizeof(*exp));
+  long double res = REAL(frexpl)(x, exp);
+  COMMON_INTERCEPTOR_INITIALIZE_RANGE(exp, sizeof(*exp));
   return res;
 }
 
@@ -1862,7 +1878,7 @@ UNUSED static void unpoison_passwd(void *ctx, __sanitizer_passwd *pwd) {
       COMMON_INTERCEPTOR_WRITE_RANGE(ctx, pwd->pw_gecos,
                                      REAL(strlen)(pwd->pw_gecos) + 1);
 #endif
-#if SANITIZER_MAC || SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
+#if SANITIZER_MAC || SANITIZER_FREEBSD || SANITIZER_NETBSD
     if (pwd->pw_class)
       COMMON_INTERCEPTOR_WRITE_RANGE(ctx, pwd->pw_class,
                                      REAL(strlen)(pwd->pw_class) + 1);
@@ -2176,6 +2192,7 @@ INTERCEPTOR(int, clock_gettime, u32 clk_id, void *tp) {
   }
   return res;
 }
+#if SANITIZER_GLIBC
 namespace __sanitizer {
 extern "C" {
 int real_clock_gettime(u32 clk_id, void *tp) {
@@ -2185,6 +2202,7 @@ int real_clock_gettime(u32 clk_id, void *tp) {
 }
 }  // extern "C"
 }  // namespace __sanitizer
+#endif
 INTERCEPTOR(int, clock_settime, u32 clk_id, const void *tp) {
   void *ctx;
   COMMON_INTERCEPTOR_ENTER(ctx, clock_settime, clk_id, tp);
@@ -3336,7 +3354,7 @@ INTERCEPTOR(char *, setlocale, int category, char *locale) {
     COMMON_INTERCEPTOR_READ_RANGE(ctx, locale, REAL(strlen)(locale) + 1);
   char *res = REAL(setlocale)(category, locale);
   if (res) {
-    COMMON_INTERCEPTOR_WRITE_RANGE(ctx, res, REAL(strlen)(res) + 1);
+    COMMON_INTERCEPTOR_INITIALIZE_RANGE(res, REAL(strlen)(res) + 1);
     unpoison_ctype_arrays(ctx);
   }
   return res;
@@ -3748,7 +3766,7 @@ INTERCEPTOR(char *, strerror, int errnum) {
 //    static storage.
 #if ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE) || \
     SANITIZER_MAC || SANITIZER_ANDROID || SANITIZER_NETBSD ||                 \
-    SANITIZER_FREEBSD || SANITIZER_OPENBSD
+    SANITIZER_FREEBSD
 // POSIX version. Spec is not clear on whether buf is NULL-terminated.
 // At least on OSX, buf contents are valid even when the call fails.
 INTERCEPTOR(int, strerror_r, int errnum, char *buf, SIZE_T buflen) {
@@ -4011,7 +4029,7 @@ INTERCEPTOR(int, sigwait, __sanitizer_sigset_t *set, int *sig) {
   // FIXME: under ASan the call below may write to freed memory and corrupt
   // its metadata. See
   // https://github.com/google/sanitizers/issues/321.
-  int res = REAL(sigwait)(set, sig);
+  int res = COMMON_INTERCEPTOR_BLOCK_REAL(sigwait)(set, sig);
   if (!res && sig) COMMON_INTERCEPTOR_WRITE_RANGE(ctx, sig, sizeof(*sig));
   return res;
 }
@@ -4028,7 +4046,7 @@ INTERCEPTOR(int, sigwaitinfo, __sanitizer_sigset_t *set, void *info) {
   // FIXME: under ASan the call below may write to freed memory and corrupt
   // its metadata. See
   // https://github.com/google/sanitizers/issues/321.
-  int res = REAL(sigwaitinfo)(set, info);
+  int res = COMMON_INTERCEPTOR_BLOCK_REAL(sigwaitinfo)(set, info);
   if (res > 0 && info) COMMON_INTERCEPTOR_WRITE_RANGE(ctx, info, siginfo_t_sz);
   return res;
 }
@@ -4047,7 +4065,7 @@ INTERCEPTOR(int, sigtimedwait, __sanitizer_sigset_t *set, void *info,
   // FIXME: under ASan the call below may write to freed memory and corrupt
   // its metadata. See
   // https://github.com/google/sanitizers/issues/321.
-  int res = REAL(sigtimedwait)(set, info, timeout);
+  int res = COMMON_INTERCEPTOR_BLOCK_REAL(sigtimedwait)(set, info, timeout);
   if (res > 0 && info) COMMON_INTERCEPTOR_WRITE_RANGE(ctx, info, siginfo_t_sz);
   return res;
 }
@@ -4085,6 +4103,41 @@ INTERCEPTOR(int, sigfillset, __sanitizer_sigset_t *set) {
 #define INIT_SIGSETOPS
 #endif
 
+#if SANITIZER_INTERCEPT_SIGSET_LOGICOPS
+INTERCEPTOR(int, sigandset, __sanitizer_sigset_t *dst,
+            __sanitizer_sigset_t *src1, __sanitizer_sigset_t *src2) {
+  void *ctx;
+  COMMON_INTERCEPTOR_ENTER(ctx, sigandset, dst, src1, src2);
+  if (src1)
+    COMMON_INTERCEPTOR_READ_RANGE(ctx, src1, sizeof(*src1));
+  if (src2)
+    COMMON_INTERCEPTOR_READ_RANGE(ctx, src2, sizeof(*src2));
+  int res = REAL(sigandset)(dst, src1, src2);
+  if (!res && dst)
+    COMMON_INTERCEPTOR_WRITE_RANGE(ctx, dst, sizeof(*dst));
+  return res;
+}
+
+INTERCEPTOR(int, sigorset, __sanitizer_sigset_t *dst,
+            __sanitizer_sigset_t *src1, __sanitizer_sigset_t *src2) {
+  void *ctx;
+  COMMON_INTERCEPTOR_ENTER(ctx, sigorset, dst, src1, src2);
+  if (src1)
+    COMMON_INTERCEPTOR_READ_RANGE(ctx, src1, sizeof(*src1));
+  if (src2)
+    COMMON_INTERCEPTOR_READ_RANGE(ctx, src2, sizeof(*src2));
+  int res = REAL(sigorset)(dst, src1, src2);
+  if (!res && dst)
+    COMMON_INTERCEPTOR_WRITE_RANGE(ctx, dst, sizeof(*dst));
+  return res;
+}
+#define INIT_SIGSET_LOGICOPS                    \
+  COMMON_INTERCEPT_FUNCTION(sigandset);   \
+  COMMON_INTERCEPT_FUNCTION(sigorset);
+#else
+#define INIT_SIGSET_LOGICOPS
+#endif
+
 #if SANITIZER_INTERCEPT_SIGPENDING
 INTERCEPTOR(int, sigpending, __sanitizer_sigset_t *set) {
   void *ctx;
@@ -4838,6 +4891,34 @@ INTERCEPTOR(char *, tmpnam_r, char *s) {
 #define INIT_TMPNAM_R
 #endif
 
+#if SANITIZER_INTERCEPT_PTSNAME
+INTERCEPTOR(char *, ptsname, int fd) {
+  void *ctx;
+  COMMON_INTERCEPTOR_ENTER(ctx, ptsname, fd);
+  char *res = REAL(ptsname)(fd);
+  if (res != nullptr)
+    COMMON_INTERCEPTOR_INITIALIZE_RANGE(res, REAL(strlen)(res) + 1);
+  return res;
+}
+#define INIT_PTSNAME COMMON_INTERCEPT_FUNCTION(ptsname);
+#else
+#define INIT_PTSNAME
+#endif
+
+#if SANITIZER_INTERCEPT_PTSNAME_R
+INTERCEPTOR(int, ptsname_r, int fd, char *name, SIZE_T namesize) {
+  void *ctx;
+  COMMON_INTERCEPTOR_ENTER(ctx, ptsname_r, fd, name, namesize);
+  int res = REAL(ptsname_r)(fd, name, namesize);
+  if (res == 0)
+    COMMON_INTERCEPTOR_WRITE_RANGE(ctx, name, REAL(strlen)(name) + 1);
+  return res;
+}
+#define INIT_PTSNAME_R COMMON_INTERCEPT_FUNCTION(ptsname_r);
+#else
+#define INIT_PTSNAME_R
+#endif
+
 #if SANITIZER_INTERCEPT_TTYNAME
 INTERCEPTOR(char *, ttyname, int fd) {
   void *ctx;
@@ -5219,6 +5300,12 @@ INTERCEPTOR(__sanitizer_clock_t, times, void *tms) {
 #define INIT_TIMES
 #endif
 
+#if SANITIZER_S390 && \
+    (SANITIZER_INTERCEPT_TLS_GET_ADDR || SANITIZER_INTERCEPT_TLS_GET_OFFSET)
+extern "C" uptr __tls_get_offset_wrapper(void *arg, uptr (*fn)(void *arg));
+DEFINE_REAL(uptr, __tls_get_offset, void *arg)
+#endif
+
 #if SANITIZER_INTERCEPT_TLS_GET_ADDR
 #if !SANITIZER_S390
 #define INIT_TLS_GET_ADDR COMMON_INTERCEPT_FUNCTION(__tls_get_addr)
@@ -5258,11 +5345,7 @@ void *__tls_get_addr_opt(void *arg);
 //   descriptor offset as an argument instead of a pointer.  GOT address
 //   is passed in r12, so it's necessary to write it in assembly.  This is
 //   the function used by the compiler.
-extern "C" uptr __tls_get_offset_wrapper(void *arg, uptr (*fn)(void *arg));
 #define INIT_TLS_GET_ADDR COMMON_INTERCEPT_FUNCTION(__tls_get_offset)
-DEFINE_REAL(uptr, __tls_get_offset, void *arg)
-extern "C" uptr __tls_get_offset(void *arg);
-extern "C" uptr __interceptor___tls_get_offset(void *arg);
 INTERCEPTOR(uptr, __tls_get_addr_internal, void *arg) {
   void *ctx;
   COMMON_INTERCEPTOR_ENTER(ctx, __tls_get_addr_internal, arg);
@@ -5278,6 +5361,15 @@ INTERCEPTOR(uptr, __tls_get_addr_internal, void *arg) {
   }
   return res;
 }
+#endif // SANITIZER_S390
+#else
+#define INIT_TLS_GET_ADDR
+#endif
+
+#if SANITIZER_S390 && \
+    (SANITIZER_INTERCEPT_TLS_GET_ADDR || SANITIZER_INTERCEPT_TLS_GET_OFFSET)
+extern "C" uptr __tls_get_offset(void *arg);
+extern "C" uptr __interceptor___tls_get_offset(void *arg);
 // We need a hidden symbol aliasing the above, so that we can jump
 // directly to it from the assembly below.
 extern "C" __attribute__((alias("__interceptor___tls_get_addr_internal"),
@@ -5316,9 +5408,6 @@ asm(
   "br %r3\n"
   ".size __tls_get_offset_wrapper, .-__tls_get_offset_wrapper\n"
 );
-#endif // SANITIZER_S390
-#else
-#define INIT_TLS_GET_ADDR
 #endif
 
 #if SANITIZER_INTERCEPT_LISTXATTR
@@ -5809,6 +5898,79 @@ INTERCEPTOR(int, xdr_string, __sanitizer_XDR *xdrs, char **p,
 #define INIT_XDR
 #endif  // SANITIZER_INTERCEPT_XDR
 
+#if SANITIZER_INTERCEPT_XDRREC
+typedef int (*xdrrec_cb)(char*, char*, int);
+struct XdrRecWrapper {
+  char *handle;
+  xdrrec_cb rd, wr;
+};
+typedef AddrHashMap<XdrRecWrapper *, 11> XdrRecWrapMap;
+static XdrRecWrapMap *xdrrec_wrap_map;
+
+static int xdrrec_wr_wrap(char *handle, char *buf, int count) {
+  COMMON_INTERCEPTOR_UNPOISON_PARAM(3);
+  COMMON_INTERCEPTOR_INITIALIZE_RANGE(buf, count);
+  XdrRecWrapper *wrap = (XdrRecWrapper *)handle;
+  return wrap->wr(wrap->handle, buf, count);
+}
+
+static int xdrrec_rd_wrap(char *handle, char *buf, int count) {
+  COMMON_INTERCEPTOR_UNPOISON_PARAM(3);
+  XdrRecWrapper *wrap = (XdrRecWrapper *)handle;
+  return wrap->rd(wrap->handle, buf, count);
+}
+
+// This doesn't apply to the solaris version as it has a different function
+// signature.
+INTERCEPTOR(void, xdrrec_create, __sanitizer_XDR *xdr, unsigned sndsize,
+            unsigned rcvsize, char *handle, int (*rd)(char*, char*, int),
+            int (*wr)(char*, char*, int)) {
+  void *ctx;
+  COMMON_INTERCEPTOR_ENTER(ctx, xdrrec_create, xdr, sndsize, rcvsize,
+                           handle, rd, wr);
+  COMMON_INTERCEPTOR_READ_RANGE(ctx, &xdr->x_op, sizeof xdr->x_op);
+
+  // We can't allocate a wrapper on the stack, as the handle is used outside
+  // this stack frame. So we put it on the heap, and keep track of it with
+  // the HashMap (keyed by x_private). When we later need to xdr_destroy,
+  // we can index the map, free the wrapper, and then clean the map entry.
+  XdrRecWrapper *wrap_data =
+      (XdrRecWrapper *)InternalAlloc(sizeof(XdrRecWrapper));
+  wrap_data->handle = handle;
+  wrap_data->rd = rd;
+  wrap_data->wr = wr;
+  if (wr)
+    wr = xdrrec_wr_wrap;
+  if (rd)
+    rd = xdrrec_rd_wrap;
+  handle = (char *)wrap_data;
+
+  REAL(xdrrec_create)(xdr, sndsize, rcvsize, handle, rd, wr);
+  COMMON_INTERCEPTOR_WRITE_RANGE(ctx, xdr, sizeof *xdr);
+
+  XdrRecWrapMap::Handle wrap(xdrrec_wrap_map, xdr->x_private, false, true);
+  *wrap = wrap_data;
+}
+
+// We have to intercept this to be able to free wrapper memory;
+// otherwise it's not necessary.
+INTERCEPTOR(void, xdr_destroy, __sanitizer_XDR *xdr) {
+  void *ctx;
+  COMMON_INTERCEPTOR_ENTER(ctx, xdr_destroy, xdr);
+
+  XdrRecWrapMap::Handle wrap(xdrrec_wrap_map, xdr->x_private, true);
+  InternalFree(*wrap);
+  REAL(xdr_destroy)(xdr);
+}
+#define INIT_XDRREC_LINUX \
+  static u64 xdrrec_wrap_mem[sizeof(XdrRecWrapMap) / sizeof(u64) + 1]; \
+  xdrrec_wrap_map = new ((void *)&xdrrec_wrap_mem) XdrRecWrapMap(); \
+  COMMON_INTERCEPT_FUNCTION(xdrrec_create); \
+  COMMON_INTERCEPT_FUNCTION(xdr_destroy);
+#else
+#define INIT_XDRREC_LINUX
+#endif
+
 #if SANITIZER_INTERCEPT_TSEARCH
 INTERCEPTOR(void *, tsearch, void *key, void **rootp,
             int (*compar)(const void *, const void *)) {
@@ -5840,6 +6002,9 @@ void unpoison_file(__sanitizer_FILE *fp) {
   if (fp->_IO_read_base && fp->_IO_read_base < fp->_IO_read_end)
     COMMON_INTERCEPTOR_INITIALIZE_RANGE(fp->_IO_read_base,
                                         fp->_IO_read_end - fp->_IO_read_base);
+  if (fp->_IO_write_base && fp->_IO_write_base < fp->_IO_write_end)
+    COMMON_INTERCEPTOR_INITIALIZE_RANGE(fp->_IO_write_base,
+                                        fp->_IO_write_end - fp->_IO_write_base);
 #endif
 #endif  // SANITIZER_HAS_STRUCT_FILE
 }
@@ -5939,6 +6104,40 @@ INTERCEPTOR(__sanitizer_FILE *, freopen, const char *path, const char *mode,
 #define INIT_FOPEN
 #endif
 
+#if SANITIZER_INTERCEPT_FLOPEN
+INTERCEPTOR(int, flopen, const char *path, int flags, ...) {
+  void *ctx;
+  va_list ap;
+  va_start(ap, flags);
+  u16 mode = static_cast<u16>(va_arg(ap, u32));
+  va_end(ap);
+  COMMON_INTERCEPTOR_ENTER(ctx, flopen, path, flags, mode);
+  if (path) {
+    COMMON_INTERCEPTOR_READ_RANGE(ctx, path, REAL(strlen)(path) + 1);
+  }
+  return REAL(flopen)(path, flags, mode);
+}
+
+INTERCEPTOR(int, flopenat, int dirfd, const char *path, int flags, ...) {
+  void *ctx;
+  va_list ap;
+  va_start(ap, flags);
+  u16 mode = static_cast<u16>(va_arg(ap, u32));
+  va_end(ap);
+  COMMON_INTERCEPTOR_ENTER(ctx, flopen, path, flags, mode);
+  if (path) {
+    COMMON_INTERCEPTOR_READ_RANGE(ctx, path, REAL(strlen)(path) + 1);
+  }
+  return REAL(flopenat)(dirfd, path, flags, mode);
+}
+
+#define INIT_FLOPEN    \
+  COMMON_INTERCEPT_FUNCTION(flopen); \
+  COMMON_INTERCEPT_FUNCTION(flopenat);
+#else
+#define INIT_FLOPEN
+#endif
+
 #if SANITIZER_INTERCEPT_FOPEN64
 INTERCEPTOR(__sanitizer_FILE *, fopen64, const char *path, const char *mode) {
   void *ctx;
@@ -6066,6 +6265,8 @@ INTERCEPTOR(void, _obstack_newchunk, __sanitizer_obstack *obstack, int length) {
 INTERCEPTOR(int, fflush, __sanitizer_FILE *fp) {
   void *ctx;
   COMMON_INTERCEPTOR_ENTER(ctx, fflush, fp);
+  if (fp)
+    unpoison_file(fp);
   int res = REAL(fflush)(fp);
   // FIXME: handle fp == NULL
   if (fp) {
@@ -6085,6 +6286,8 @@ INTERCEPTOR(int, fclose, __sanitizer_FILE *fp) {
   COMMON_INTERCEPTOR_ENTER(ctx, fclose, fp);
   COMMON_INTERCEPTOR_FILE_CLOSE(ctx, fp);
   const FileMetadata *m = GetInterceptorMetadata(fp);
+  if (fp)
+    unpoison_file(fp);
   int res = REAL(fclose)(fp);
   if (m) {
     COMMON_INTERCEPTOR_INITIALIZE_RANGE(*m->addr, *m->size);
@@ -6299,7 +6502,7 @@ INTERCEPTOR(int, sem_wait, __sanitizer_sem_t *s) {
 INTERCEPTOR(int, sem_trywait, __sanitizer_sem_t *s) {
   void *ctx;
   COMMON_INTERCEPTOR_ENTER(ctx, sem_trywait, s);
-  int res = COMMON_INTERCEPTOR_BLOCK_REAL(sem_trywait)(s);
+  int res = REAL(sem_trywait)(s);
   if (res == 0) {
     COMMON_INTERCEPTOR_ACQUIRE(ctx, (uptr)s);
   }
@@ -7634,7 +7837,7 @@ INTERCEPTOR(void, regfree, const void *preg) {
 }
 #define INIT_REGEX                                                             \
   COMMON_INTERCEPT_FUNCTION(regcomp);                                          \
-  COMMON_INTERCEPT_FUNCTION(regexec);                                          \
+  COMMON_INTERCEPT_FUNCTION_GLIBC_VER_MIN(regexec, "GLIBC_2.3.4");             \
   COMMON_INTERCEPT_FUNCTION(regerror);                                         \
   COMMON_INTERCEPT_FUNCTION(regfree);
 #else
@@ -9755,12 +9958,25 @@ INTERCEPTOR(void, qsort, void *base, SIZE_T nmemb, SIZE_T size,
     }
   }
   qsort_compar_f old_compar = qsort_compar;
-  qsort_compar = compar;
   SIZE_T old_size = qsort_size;
-  qsort_size = size;
+  // Handle qsort() implementations that recurse using an
+  // interposable function call:
+  bool already_wrapped = compar == wrapped_qsort_compar;
+  if (already_wrapped) {
+    // This case should only happen if the qsort() implementation calls itself
+    // using a preemptible function call (e.g. the FreeBSD libc version).
+    // Check that the size and comparator arguments are as expected.
+    CHECK_NE(compar, qsort_compar);
+    CHECK_EQ(qsort_size, size);
+  } else {
+    qsort_compar = compar;
+    qsort_size = size;
+  }
   REAL(qsort)(base, nmemb, size, wrapped_qsort_compar);
-  qsort_compar = old_compar;
-  qsort_size = old_size;
+  if (!already_wrapped) {
+    qsort_compar = old_compar;
+    qsort_size = old_size;
+  }
   COMMON_INTERCEPTOR_WRITE_RANGE(ctx, base, nmemb * size);
 }
 #define INIT_QSORT COMMON_INTERCEPT_FUNCTION(qsort)
@@ -9793,12 +10009,25 @@ INTERCEPTOR(void, qsort_r, void *base, SIZE_T nmemb, SIZE_T size,
     }
   }
   qsort_r_compar_f old_compar = qsort_r_compar;
-  qsort_r_compar = compar;
   SIZE_T old_size = qsort_r_size;
-  qsort_r_size = size;
+  // Handle qsort_r() implementations that recurse using an
+  // interposable function call:
+  bool already_wrapped = compar == wrapped_qsort_r_compar;
+  if (already_wrapped) {
+    // This case should only happen if the qsort() implementation calls itself
+    // using a preemptible function call (e.g. the FreeBSD libc version).
+    // Check that the size and comparator arguments are as expected.
+    CHECK_NE(compar, qsort_r_compar);
+    CHECK_EQ(qsort_r_size, size);
+  } else {
+    qsort_r_compar = compar;
+    qsort_r_size = size;
+  }
   REAL(qsort_r)(base, nmemb, size, wrapped_qsort_r_compar, arg);
-  qsort_r_compar = old_compar;
-  qsort_r_size = old_size;
+  if (!already_wrapped) {
+    qsort_r_compar = old_compar;
+    qsort_r_size = old_size;
+  }
   COMMON_INTERCEPTOR_WRITE_RANGE(ctx, base, nmemb * size);
 }
 #define INIT_QSORT_R COMMON_INTERCEPT_FUNCTION(qsort_r)
@@ -9996,6 +10225,7 @@ static void InitializeCommonInterceptors() {
   INIT_SIGWAITINFO;
   INIT_SIGTIMEDWAIT;
   INIT_SIGSETOPS;
+  INIT_SIGSET_LOGICOPS;
   INIT_SIGPENDING;
   INIT_SIGPROCMASK;
   INIT_PTHREAD_SIGMASK;
@@ -10037,6 +10267,8 @@ static void InitializeCommonInterceptors() {
   INIT_PTHREAD_BARRIERATTR_GETPSHARED;
   INIT_TMPNAM;
   INIT_TMPNAM_R;
+  INIT_PTSNAME;
+  INIT_PTSNAME_R;
   INIT_TTYNAME;
   INIT_TTYNAME_R;
   INIT_TEMPNAM;
@@ -10066,10 +10298,12 @@ static void InitializeCommonInterceptors() {
   INIT_BZERO;
   INIT_FTIME;
   INIT_XDR;
+  INIT_XDRREC_LINUX;
   INIT_TSEARCH;
   INIT_LIBIO_INTERNALS;
   INIT_FOPEN;
   INIT_FOPEN64;
+  INIT_FLOPEN;
   INIT_OPEN_MEMSTREAM;
   INIT_OBSTACK;
   INIT_FFLUSH;
lib/tsan/sanitizer_common/sanitizer_common_interceptors_format.inc
@@ -340,6 +340,12 @@ static void scanf_common(void *ctx, int n_inputs, bool allowGnuMalloc,
       size = 0;
     }
     COMMON_INTERCEPTOR_WRITE_RANGE(ctx, argp, size);
+    // For %ms/%mc, write the allocated output buffer as well.
+    if (dir.allocate) {
+      char *buf = *(char **)argp;
+      if (buf)
+        COMMON_INTERCEPTOR_WRITE_RANGE(ctx, buf, internal_strlen(buf) + 1);
+    }
   }
 }
 
lib/tsan/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
@@ -330,13 +330,17 @@ static void ioctl_table_fill() {
   _(SOUND_PCM_WRITE_CHANNELS, WRITE, sizeof(int));
   _(SOUND_PCM_WRITE_FILTER, WRITE, sizeof(int));
   _(TCFLSH, NONE, 0);
+#if SANITIZER_GLIBC
   _(TCGETA, WRITE, struct_termio_sz);
+#endif
   _(TCGETS, WRITE, struct_termios_sz);
   _(TCSBRK, NONE, 0);
   _(TCSBRKP, NONE, 0);
+#if SANITIZER_GLIBC
   _(TCSETA, READ, struct_termio_sz);
   _(TCSETAF, READ, struct_termio_sz);
   _(TCSETAW, READ, struct_termio_sz);
+#endif
   _(TCSETS, READ, struct_termios_sz);
   _(TCSETSF, READ, struct_termios_sz);
   _(TCSETSW, READ, struct_termios_sz);
@@ -364,17 +368,8 @@ static void ioctl_table_fill() {
   _(VT_WAITACTIVE, NONE, 0);
 #endif
 
-#if SANITIZER_LINUX && !SANITIZER_ANDROID
+#if SANITIZER_GLIBC
   // _(SIOCDEVPLIP, WRITE, struct_ifreq_sz); // the same as EQL_ENSLAVE
-  _(CYGETDEFTHRESH, WRITE, sizeof(int));
-  _(CYGETDEFTIMEOUT, WRITE, sizeof(int));
-  _(CYGETMON, WRITE, struct_cyclades_monitor_sz);
-  _(CYGETTHRESH, WRITE, sizeof(int));
-  _(CYGETTIMEOUT, WRITE, sizeof(int));
-  _(CYSETDEFTHRESH, NONE, 0);
-  _(CYSETDEFTIMEOUT, NONE, 0);
-  _(CYSETTHRESH, NONE, 0);
-  _(CYSETTIMEOUT, NONE, 0);
   _(EQL_EMANCIPATE, WRITE, struct_ifreq_sz);
   _(EQL_ENSLAVE, WRITE, struct_ifreq_sz);
   _(EQL_GETMASTRCFG, WRITE, struct_ifreq_sz);
lib/tsan/sanitizer_common/sanitizer_common_interface.inc
@@ -13,6 +13,7 @@ INTERFACE_FUNCTION(__sanitizer_contiguous_container_find_bad_address)
 INTERFACE_FUNCTION(__sanitizer_set_death_callback)
 INTERFACE_FUNCTION(__sanitizer_set_report_path)
 INTERFACE_FUNCTION(__sanitizer_set_report_fd)
+INTERFACE_FUNCTION(__sanitizer_get_report_path)
 INTERFACE_FUNCTION(__sanitizer_verify_contiguous_container)
 INTERFACE_WEAK_FUNCTION(__sanitizer_on_print)
 INTERFACE_WEAK_FUNCTION(__sanitizer_report_error_summary)
lib/tsan/sanitizer_common/sanitizer_common_libcdep.cpp
@@ -92,14 +92,13 @@ void *BackgroundThread(void *arg) {
 #endif
 
 void WriteToSyslog(const char *msg) {
-  InternalScopedString msg_copy(kErrorMessageBufferSize);
+  InternalScopedString msg_copy;
   msg_copy.append("%s", msg);
-  char *p = msg_copy.data();
-  char *q;
+  const char *p = msg_copy.data();
 
   // Print one line at a time.
   // syslog, at least on Android, has an implicit message length limit.
-  while ((q = internal_strchr(p, '\n'))) {
+  while (char* q = internal_strchr(p, '\n')) {
     *q = '\0';
     WriteOneLineToSyslog(p);
     p = q + 1;
@@ -139,6 +138,59 @@ uptr ReservedAddressRange::InitAligned(uptr size, uptr align,
   return start;
 }
 
+#if !SANITIZER_FUCHSIA
+
+// Reserve memory range [beg, end].
+// We need to use inclusive range because end+1 may not be representable.
+void ReserveShadowMemoryRange(uptr beg, uptr end, const char *name,
+                              bool madvise_shadow) {
+  CHECK_EQ((beg % GetMmapGranularity()), 0);
+  CHECK_EQ(((end + 1) % GetMmapGranularity()), 0);
+  uptr size = end - beg + 1;
+  DecreaseTotalMmap(size);  // Don't count the shadow against mmap_limit_mb.
+  if (madvise_shadow ? !MmapFixedSuperNoReserve(beg, size, name)
+                     : !MmapFixedNoReserve(beg, size, name)) {
+    Report(
+        "ReserveShadowMemoryRange failed while trying to map 0x%zx bytes. "
+        "Perhaps you're using ulimit -v\n",
+        size);
+    Abort();
+  }
+  if (madvise_shadow && common_flags()->use_madv_dontdump)
+    DontDumpShadowMemory(beg, size);
+}
+
+void ProtectGap(uptr addr, uptr size, uptr zero_base_shadow_start,
+                uptr zero_base_max_shadow_start) {
+  if (!size)
+    return;
+  void *res = MmapFixedNoAccess(addr, size, "shadow gap");
+  if (addr == (uptr)res)
+    return;
+  // A few pages at the start of the address space can not be protected.
+  // But we really want to protect as much as possible, to prevent this memory
+  // being returned as a result of a non-FIXED mmap().
+  if (addr == zero_base_shadow_start) {
+    uptr step = GetMmapGranularity();
+    while (size > step && addr < zero_base_max_shadow_start) {
+      addr += step;
+      size -= step;
+      void *res = MmapFixedNoAccess(addr, size, "shadow gap");
+      if (addr == (uptr)res)
+        return;
+    }
+  }
+
+  Report(
+      "ERROR: Failed to protect the shadow gap. "
+      "%s cannot proceed correctly. ABORTING.\n",
+      SanitizerToolName);
+  DumpProcessMap();
+  Die();
+}
+
+#endif  // !SANITIZER_FUCHSIA
+
 }  // namespace __sanitizer
 
 SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_sandbox_on_notify,
lib/tsan/sanitizer_common/sanitizer_common_nolibc.cpp
@@ -10,9 +10,10 @@
 // libc in no-libcdep sources.
 //===----------------------------------------------------------------------===//
 
-#include "sanitizer_platform.h"
 #include "sanitizer_common.h"
+#include "sanitizer_flags.h"
 #include "sanitizer_libc.h"
+#include "sanitizer_platform.h"
 
 namespace __sanitizer {
 
@@ -24,11 +25,11 @@ void LogMessageOnPrintf(const char *str) {}
 #endif
 void WriteToSyslog(const char *buffer) {}
 void Abort() { internal__exit(1); }
-void SleepForSeconds(int seconds) { internal_sleep(seconds); }
 #endif // !SANITIZER_WINDOWS
 
 #if !SANITIZER_WINDOWS && !SANITIZER_MAC
 void ListOfModules::init() {}
+void InitializePlatformCommonFlags(CommonFlags *cf) {}
 #endif
 
 }  // namespace __sanitizer
lib/tsan/sanitizer_common/sanitizer_common_syscalls.inc
@@ -2294,9 +2294,10 @@ PRE_SYSCALL(ni_syscall)() {}
 POST_SYSCALL(ni_syscall)(long res) {}
 
 PRE_SYSCALL(ptrace)(long request, long pid, long addr, long data) {
-#if !SANITIZER_ANDROID && \
-    (defined(__i386) || defined(__x86_64) || defined(__mips64) || \
-     defined(__powerpc64__) || defined(__aarch64__) || defined(__s390__))
+#if !SANITIZER_ANDROID &&                                                   \
+    (defined(__i386) || defined(__x86_64) || defined(__mips64) ||           \
+     defined(__powerpc64__) || defined(__aarch64__) || defined(__s390__) || \
+     SANITIZER_RISCV64)
   if (data) {
     if (request == ptrace_setregs) {
       PRE_READ((void *)data, struct_user_regs_struct_sz);
@@ -2315,9 +2316,10 @@ PRE_SYSCALL(ptrace)(long request, long pid, long addr, long data) {
 }
 
 POST_SYSCALL(ptrace)(long res, long request, long pid, long addr, long data) {
-#if !SANITIZER_ANDROID && \
-    (defined(__i386) || defined(__x86_64) || defined(__mips64) || \
-     defined(__powerpc64__) || defined(__aarch64__) || defined(__s390__))
+#if !SANITIZER_ANDROID &&                                                   \
+    (defined(__i386) || defined(__x86_64) || defined(__mips64) ||           \
+     defined(__powerpc64__) || defined(__aarch64__) || defined(__s390__) || \
+     SANITIZER_RISCV64)
   if (res >= 0 && data) {
     // Note that this is different from the interceptor in
     // sanitizer_common_interceptors.inc.
lib/tsan/sanitizer_common/sanitizer_deadlock_detector1.cpp
@@ -32,7 +32,7 @@ struct DDLogicalThread {
   bool report_pending;
 };
 
-struct DD : public DDetector {
+struct DD final : public DDetector {
   SpinMutex mtx;
   DeadlockDetector<DDBV> dd;
   DDFlags flags;
@@ -136,7 +136,7 @@ void DD::ReportDeadlock(DDCallback *cb, DDMutex *m) {
     DDMutex *m0 = (DDMutex*)dd.getData(from);
     DDMutex *m1 = (DDMutex*)dd.getData(to);
 
-    u32 stk_from = -1U, stk_to = -1U;
+    u32 stk_from = 0, stk_to = 0;
     int unique_tid = 0;
     dd.findEdge(from, to, &stk_from, &stk_to, &unique_tid);
     // Printf("Edge: %zd=>%zd: %u/%u T%d\n", from, to, stk_from, stk_to,
lib/tsan/sanitizer_common/sanitizer_deadlock_detector2.cpp
@@ -73,14 +73,14 @@ struct DDLogicalThread {
   int         nlocked;
 };
 
-struct Mutex {
+struct MutexState {
   StaticSpinMutex mtx;
   u32 seq;
   int nlink;
   Link link[kMaxLink];
 };
 
-struct DD : public DDetector {
+struct DD final : public DDetector {
   explicit DD(const DDFlags *flags);
 
   DDPhysicalThread* CreatePhysicalThread();
@@ -101,12 +101,12 @@ struct DD : public DDetector {
   void CycleCheck(DDPhysicalThread *pt, DDLogicalThread *lt, DDMutex *mtx);
   void Report(DDPhysicalThread *pt, DDLogicalThread *lt, int npath);
   u32 allocateId(DDCallback *cb);
-  Mutex *getMutex(u32 id);
-  u32 getMutexId(Mutex *m);
+  MutexState *getMutex(u32 id);
+  u32 getMutexId(MutexState *m);
 
   DDFlags flags;
 
-  Mutex* mutex[kL1Size];
+  MutexState *mutex[kL1Size];
 
   SpinMutex mtx;
   InternalMmapVector<u32> free_id;
@@ -152,13 +152,11 @@ void DD::MutexInit(DDCallback *cb, DDMutex *m) {
   atomic_store(&m->owner, 0, memory_order_relaxed);
 }
 
-Mutex *DD::getMutex(u32 id) {
-  return &mutex[id / kL2Size][id % kL2Size];
-}
+MutexState *DD::getMutex(u32 id) { return &mutex[id / kL2Size][id % kL2Size]; }
 
-u32 DD::getMutexId(Mutex *m) {
+u32 DD::getMutexId(MutexState *m) {
   for (int i = 0; i < kL1Size; i++) {
-    Mutex *tab = mutex[i];
+    MutexState *tab = mutex[i];
     if (tab == 0)
       break;
     if (m >= tab && m < tab + kL2Size)
@@ -176,8 +174,8 @@ u32 DD::allocateId(DDCallback *cb) {
   } else {
     CHECK_LT(id_gen, kMaxMutex);
     if ((id_gen % kL2Size) == 0) {
-      mutex[id_gen / kL2Size] = (Mutex*)MmapOrDie(kL2Size * sizeof(Mutex),
-          "deadlock detector (mutex table)");
+      mutex[id_gen / kL2Size] = (MutexState *)MmapOrDie(
+          kL2Size * sizeof(MutexState), "deadlock detector (mutex table)");
     }
     id = id_gen++;
   }
@@ -216,11 +214,11 @@ void DD::MutexBeforeLock(DDCallback *cb, DDMutex *m, bool wlock) {
   }
 
   bool added = false;
-  Mutex *mtx = getMutex(m->id);
+  MutexState *mtx = getMutex(m->id);
   for (int i = 0; i < lt->nlocked - 1; i++) {
     u32 id1 = lt->locked[i].id;
     u32 stk1 = lt->locked[i].stk;
-    Mutex *mtx1 = getMutex(id1);
+    MutexState *mtx1 = getMutex(id1);
     SpinMutexLock l(&mtx1->mtx);
     if (mtx1->nlink == kMaxLink) {
       // FIXME(dvyukov): check stale links
@@ -342,7 +340,7 @@ void DD::MutexDestroy(DDCallback *cb, DDMutex *m) {
 
   // Clear and invalidate the mutex descriptor.
   {
-    Mutex *mtx = getMutex(m->id);
+    MutexState *mtx = getMutex(m->id);
     SpinMutexLock l(&mtx->mtx);
     mtx->seq++;
     mtx->nlink = 0;
@@ -361,7 +359,7 @@ void DD::CycleCheck(DDPhysicalThread *pt, DDLogicalThread *lt,
   int npath = 0;
   int npending = 0;
   {
-    Mutex *mtx = getMutex(m->id);
+    MutexState *mtx = getMutex(m->id);
     SpinMutexLock l(&mtx->mtx);
     for (int li = 0; li < mtx->nlink; li++)
       pt->pending[npending++] = mtx->link[li];
@@ -374,7 +372,7 @@ void DD::CycleCheck(DDPhysicalThread *pt, DDLogicalThread *lt,
     }
     if (pt->visited[link.id])
       continue;
-    Mutex *mtx1 = getMutex(link.id);
+    MutexState *mtx1 = getMutex(link.id);
     SpinMutexLock l(&mtx1->mtx);
     if (mtx1->seq != link.seq)
       continue;
@@ -387,7 +385,7 @@ void DD::CycleCheck(DDPhysicalThread *pt, DDLogicalThread *lt,
       return Report(pt, lt, npath);  // Bingo!
     for (int li = 0; li < mtx1->nlink; li++) {
       Link *link1 = &mtx1->link[li];
-      // Mutex *mtx2 = getMutex(link->id);
+      // MutexState *mtx2 = getMutex(link->id);
       // FIXME(dvyukov): fast seq check
       // FIXME(dvyukov): fast nlink != 0 check
       // FIXME(dvyukov): fast pending check?
lib/tsan/sanitizer_common/sanitizer_deadlock_detector_interface.h
@@ -66,6 +66,9 @@ struct DDCallback {
 
   virtual u32 Unwind() { return 0; }
   virtual int UniqueTid() { return 0; }
+
+ protected:
+  ~DDCallback() {}
 };
 
 struct DDetector {
@@ -85,6 +88,9 @@ struct DDetector {
   virtual void MutexDestroy(DDCallback *cb, DDMutex *m) {}
 
   virtual DDReport *GetReport(DDCallback *cb) { return nullptr; }
+
+ protected:
+  ~DDetector() {}
 };
 
 } // namespace __sanitizer
lib/tsan/sanitizer_common/sanitizer_errno.h
@@ -23,8 +23,7 @@
 
 #if SANITIZER_FREEBSD || SANITIZER_MAC
 #  define __errno_location __error
-#elif SANITIZER_ANDROID || SANITIZER_NETBSD || SANITIZER_OPENBSD || \
-  SANITIZER_RTEMS
+#elif SANITIZER_ANDROID || SANITIZER_NETBSD
 #  define __errno_location __errno
 #elif SANITIZER_SOLARIS
 #  define __errno_location ___errno
lib/tsan/sanitizer_common/sanitizer_errno_codes.h
@@ -24,6 +24,7 @@ namespace __sanitizer {
 #define errno_ENOMEM 12
 #define errno_EBUSY 16
 #define errno_EINVAL 22
+#define errno_ENAMETOOLONG 36
 
 // Those might not present or their value differ on different platforms.
 extern const int errno_EOWNERDEAD;
lib/tsan/sanitizer_common/sanitizer_file.cpp
@@ -58,40 +58,52 @@ void ReportFile::ReopenIfNecessary() {
   } else {
     internal_snprintf(full_path, kMaxPathLength, "%s.%zu", path_prefix, pid);
   }
-  fd = OpenFile(full_path, WrOnly);
+  if (common_flags()->log_suffix) {
+    internal_strlcat(full_path, common_flags()->log_suffix, kMaxPathLength);
+  }
+  error_t err;
+  fd = OpenFile(full_path, WrOnly, &err);
   if (fd == kInvalidFd) {
     const char *ErrorMsgPrefix = "ERROR: Can't open file: ";
     WriteToFile(kStderrFd, ErrorMsgPrefix, internal_strlen(ErrorMsgPrefix));
     WriteToFile(kStderrFd, full_path, internal_strlen(full_path));
+    char errmsg[100];
+    internal_snprintf(errmsg, sizeof(errmsg), " (reason: %d)", err);
+    WriteToFile(kStderrFd, errmsg, internal_strlen(errmsg));
     Die();
   }
   fd_pid = pid;
 }
 
 void ReportFile::SetReportPath(const char *path) {
-  if (!path)
-    return;
-  uptr len = internal_strlen(path);
-  if (len > sizeof(path_prefix) - 100) {
-    Report("ERROR: Path is too long: %c%c%c%c%c%c%c%c...\n",
-           path[0], path[1], path[2], path[3],
-           path[4], path[5], path[6], path[7]);
-    Die();
+  if (path) {
+    uptr len = internal_strlen(path);
+    if (len > sizeof(path_prefix) - 100) {
+      Report("ERROR: Path is too long: %c%c%c%c%c%c%c%c...\n", path[0], path[1],
+             path[2], path[3], path[4], path[5], path[6], path[7]);
+      Die();
+    }
   }
 
   SpinMutexLock l(mu);
   if (fd != kStdoutFd && fd != kStderrFd && fd != kInvalidFd)
     CloseFile(fd);
   fd = kInvalidFd;
-  if (internal_strcmp(path, "stdout") == 0) {
-    fd = kStdoutFd;
-  } else if (internal_strcmp(path, "stderr") == 0) {
+  if (!path || internal_strcmp(path, "stderr") == 0) {
     fd = kStderrFd;
+  } else if (internal_strcmp(path, "stdout") == 0) {
+    fd = kStdoutFd;
   } else {
     internal_snprintf(path_prefix, kMaxPathLength, "%s", path);
   }
 }
 
+const char *ReportFile::GetReportPath() {
+  SpinMutexLock l(mu);
+  ReopenIfNecessary();
+  return full_path;
+}
+
 bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
                       uptr *read_len, uptr max_len, error_t *errno_p) {
   *buff = nullptr;
@@ -210,6 +222,10 @@ void __sanitizer_set_report_fd(void *fd) {
   report_file.fd = (fd_t)reinterpret_cast<uptr>(fd);
   report_file.fd_pid = internal_getpid();
 }
+
+const char *__sanitizer_get_report_path() {
+  return report_file.GetReportPath();
+}
 } // extern "C"
 
 #endif  // !SANITIZER_FUCHSIA
lib/tsan/sanitizer_common/sanitizer_file.h
@@ -26,6 +26,7 @@ struct ReportFile {
   void Write(const char *buffer, uptr length);
   bool SupportsColors();
   void SetReportPath(const char *path);
+  const char *GetReportPath();
 
   // Don't use fields directly. They are only declared public to allow
   // aggregate initialization.
lib/tsan/sanitizer_common/sanitizer_flag_parser.h
@@ -42,7 +42,7 @@ class FlagHandlerBase {
 };
 
 template <typename T>
-class FlagHandler : public FlagHandlerBase {
+class FlagHandler final : public FlagHandlerBase {
   T *t_;
 
  public:
lib/tsan/sanitizer_common/sanitizer_flags.cpp
@@ -13,9 +13,10 @@
 #include "sanitizer_flags.h"
 
 #include "sanitizer_common.h"
+#include "sanitizer_flag_parser.h"
 #include "sanitizer_libc.h"
+#include "sanitizer_linux.h"
 #include "sanitizer_list.h"
-#include "sanitizer_flag_parser.h"
 
 namespace __sanitizer {
 
@@ -34,6 +35,7 @@ void CommonFlags::CopyFrom(const CommonFlags &other) {
 // Copy the string from "s" to "out", making the following substitutions:
 // %b = binary basename
 // %p = pid
+// %d = binary directory
 void SubstituteForFlagValue(const char *s, char *out, uptr out_size) {
   char *out_end = out + out_size;
   while (*s && out < out_end - 1) {
@@ -63,6 +65,12 @@ void SubstituteForFlagValue(const char *s, char *out, uptr out_size) {
         s += 2; // skip "%p"
         break;
       }
+      case 'd': {
+        uptr len = ReadBinaryDir(out, out_end - out);
+        out += len;
+        s += 2;  // skip "%d"
+        break;
+      }
       default:
         *out++ = *s++;
         break;
@@ -72,7 +80,7 @@ void SubstituteForFlagValue(const char *s, char *out, uptr out_size) {
   *out = '\0';
 }
 
-class FlagHandlerInclude : public FlagHandlerBase {
+class FlagHandlerInclude final : public FlagHandlerBase {
   FlagParser *parser_;
   bool ignore_missing_;
   const char *original_path_;
@@ -91,7 +99,7 @@ class FlagHandlerInclude : public FlagHandlerBase {
     }
     return parser_->ParseFile(value, ignore_missing_);
   }
-  bool Format(char *buffer, uptr size) {
+  bool Format(char *buffer, uptr size) override {
     // Note `original_path_` isn't actually what's parsed due to `%`
     // substitutions. Printing the substituted path would require holding onto
     // mmap'ed memory.
@@ -124,6 +132,8 @@ void InitializeCommonFlags(CommonFlags *cf) {
   // need to record coverage to generate coverage report.
   cf->coverage |= cf->html_cov_report;
   SetVerbosity(cf->verbosity);
+
+  InitializePlatformCommonFlags(cf);
 }
 
 }  // namespace __sanitizer
lib/tsan/sanitizer_common/sanitizer_flags.h
@@ -62,6 +62,10 @@ void RegisterIncludeFlags(FlagParser *parser, CommonFlags *cf);
 // and perform initializations common to all sanitizers (e.g. setting
 // verbosity).
 void InitializeCommonFlags(CommonFlags *cf = &common_flags_dont_use);
+
+// Platform specific flags initialization.
+void InitializePlatformCommonFlags(CommonFlags *cf);
+
 }  // namespace __sanitizer
 
 #endif  // SANITIZER_FLAGS_H
lib/tsan/sanitizer_common/sanitizer_flags.inc
@@ -40,20 +40,27 @@ COMMON_FLAG(bool, fast_unwind_on_check, false,
 COMMON_FLAG(bool, fast_unwind_on_fatal, false,
             "If available, use the fast frame-pointer-based unwinder on fatal "
             "errors.")
-COMMON_FLAG(bool, fast_unwind_on_malloc, true,
+// ARM thumb/thumb2 frame pointer is inconsistent on GCC and Clang [1]
+// and fast-unwider is also unreliable with mixing arm and thumb code [2].
+// [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92172
+// [2] https://bugs.llvm.org/show_bug.cgi?id=44158
+COMMON_FLAG(bool, fast_unwind_on_malloc,
+            !(SANITIZER_LINUX && !SANITIZER_ANDROID && SANITIZER_ARM),
             "If available, use the fast frame-pointer-based unwinder on "
             "malloc/free.")
 COMMON_FLAG(bool, handle_ioctl, false, "Intercept and handle ioctl requests.")
 COMMON_FLAG(int, malloc_context_size, 1,
             "Max number of stack frames kept for each allocation/deallocation.")
 COMMON_FLAG(
-    const char *, log_path, "stderr",
+    const char *, log_path, nullptr,
     "Write logs to \"log_path.pid\". The special values are \"stdout\" and "
-    "\"stderr\". The default is \"stderr\".")
+    "\"stderr\". If unspecified, defaults to \"stderr\".")
 COMMON_FLAG(
     bool, log_exe_name, false,
     "Mention name of executable when reporting error and "
     "append executable name to logs (as in \"log_path.exe_name.pid\").")
+COMMON_FLAG(const char *, log_suffix, nullptr,
+            "String to append to log file name, e.g. \".txt\".")
 COMMON_FLAG(
     bool, log_to_syslog, (bool)SANITIZER_ANDROID || (bool)SANITIZER_MAC,
     "Write all sanitizer output to syslog in addition to other means of "
@@ -77,8 +84,9 @@ COMMON_FLAG(bool, print_summary, true,
             "If false, disable printing error summaries in addition to error "
             "reports.")
 COMMON_FLAG(int, print_module_map, 0,
-            "OS X only (0 - don't print, 1 - print only once before process "
-            "exits, 2 - print after each report).")
+            "Print the process module map where supported (0 - don't print, "
+            "1 - print only once before process exits, 2 - print after each "
+            "report).")
 COMMON_FLAG(bool, check_printf, true, "Check printf arguments.")
 #define COMMON_FLAG_HANDLE_SIGNAL_HELP(signal) \
     "Controls custom tool's " #signal " handler (0 - do not registers the " \
@@ -195,6 +203,9 @@ COMMON_FLAG(bool, intercept_strtok, true,
 COMMON_FLAG(bool, intercept_strpbrk, true,
             "If set, uses custom wrappers for strpbrk function "
             "to find more errors.")
+COMMON_FLAG(
+    bool, intercept_strcmp, true,
+    "If set, uses custom wrappers for strcmp functions to find more errors.")
 COMMON_FLAG(bool, intercept_strlen, true,
             "If set, uses custom wrappers for strlen and strnlen functions "
             "to find more errors.")
lib/tsan/sanitizer_common/sanitizer_fuchsia.cpp
@@ -14,17 +14,17 @@
 #include "sanitizer_fuchsia.h"
 #if SANITIZER_FUCHSIA
 
-#include "sanitizer_common.h"
-#include "sanitizer_libc.h"
-#include "sanitizer_mutex.h"
-
-#include <limits.h>
 #include <pthread.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <zircon/errors.h>
 #include <zircon/process.h>
 #include <zircon/syscalls.h>
+#include <zircon/utc.h>
+
+#include "sanitizer_common.h"
+#include "sanitizer_libc.h"
+#include "sanitizer_mutex.h"
 
 namespace __sanitizer {
 
@@ -36,19 +36,16 @@ uptr internal_sched_yield() {
   return 0;  // Why doesn't this return void?
 }
 
-static void internal_nanosleep(zx_time_t ns) {
-  zx_status_t status = _zx_nanosleep(_zx_deadline_after(ns));
+void internal_usleep(u64 useconds) {
+  zx_status_t status = _zx_nanosleep(_zx_deadline_after(ZX_USEC(useconds)));
   CHECK_EQ(status, ZX_OK);
 }
 
-unsigned int internal_sleep(unsigned int seconds) {
-  internal_nanosleep(ZX_SEC(seconds));
-  return 0;
-}
-
 u64 NanoTime() {
+  zx_handle_t utc_clock = _zx_utc_reference_get();
+  CHECK_NE(utc_clock, ZX_HANDLE_INVALID);
   zx_time_t time;
-  zx_status_t status = _zx_clock_get(ZX_CLOCK_UTC, &time);
+  zx_status_t status = _zx_clock_read(utc_clock, &time);
   CHECK_EQ(status, ZX_OK);
   return time;
 }
@@ -66,9 +63,7 @@ uptr internal_getpid() {
   return pid;
 }
 
-int internal_dlinfo(void *handle, int request, void *p) {
-  UNIMPLEMENTED();
-}
+int internal_dlinfo(void *handle, int request, void *p) { UNIMPLEMENTED(); }
 
 uptr GetThreadSelf() { return reinterpret_cast<uptr>(thrd_current()); }
 
@@ -78,10 +73,6 @@ void Abort() { abort(); }
 
 int Atexit(void (*function)(void)) { return atexit(function); }
 
-void SleepForSeconds(int seconds) { internal_sleep(seconds); }
-
-void SleepForMillis(int millis) { internal_nanosleep(ZX_MSEC(millis)); }
-
 void GetThreadStackTopAndBottom(bool, uptr *stack_top, uptr *stack_bottom) {
   pthread_attr_t attr;
   CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
@@ -105,12 +96,22 @@ void SetAlternateSignalStack() {}
 void UnsetAlternateSignalStack() {}
 void InitTlsSize() {}
 
-void PrintModuleMap() {}
-
 bool SignalContext::IsStackOverflow() const { return false; }
 void SignalContext::DumpAllRegisters(void *context) { UNIMPLEMENTED(); }
 const char *SignalContext::Describe() const { UNIMPLEMENTED(); }
 
+void FutexWait(atomic_uint32_t *p, u32 cmp) {
+  zx_status_t status = _zx_futex_wait(reinterpret_cast<zx_futex_t *>(p), cmp,
+                                      ZX_HANDLE_INVALID, ZX_TIME_INFINITE);
+  if (status != ZX_ERR_BAD_STATE)  // Normal race.
+    CHECK_EQ(status, ZX_OK);
+}
+
+void FutexWake(atomic_uint32_t *p, u32 count) {
+  zx_status_t status = _zx_futex_wake(reinterpret_cast<zx_futex_t *>(p), count);
+  CHECK_EQ(status, ZX_OK);
+}
+
 enum MutexState : int { MtxUnlocked = 0, MtxLocked = 1, MtxSleeping = 2 };
 
 BlockingMutex::BlockingMutex() {
@@ -147,19 +148,21 @@ void BlockingMutex::Unlock() {
   }
 }
 
-void BlockingMutex::CheckLocked() {
-  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
+void BlockingMutex::CheckLocked() const {
+  auto m = reinterpret_cast<atomic_uint32_t const *>(&opaque_storage_);
   CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
 }
 
-uptr GetPageSize() { return PAGE_SIZE; }
+uptr GetPageSize() { return _zx_system_get_page_size(); }
 
-uptr GetMmapGranularity() { return PAGE_SIZE; }
+uptr GetMmapGranularity() { return _zx_system_get_page_size(); }
 
 sanitizer_shadow_bounds_t ShadowBounds;
 
+void InitShadowBounds() { ShadowBounds = __sanitizer_shadow_bounds(); }
+
 uptr GetMaxUserVirtualAddress() {
-  ShadowBounds = __sanitizer_shadow_bounds();
+  InitShadowBounds();
   return ShadowBounds.memory_limit - 1;
 }
 
@@ -167,7 +170,7 @@ uptr GetMaxVirtualAddress() { return GetMaxUserVirtualAddress(); }
 
 static void *DoAnonymousMmapOrDie(uptr size, const char *mem_type,
                                   bool raw_report, bool die_for_nomem) {
-  size = RoundUpTo(size, PAGE_SIZE);
+  size = RoundUpTo(size, GetPageSize());
 
   zx_handle_t vmo;
   zx_status_t status = _zx_vmo_create(size, 0, &vmo);
@@ -213,15 +216,14 @@ void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
 
 uptr ReservedAddressRange::Init(uptr init_size, const char *name,
                                 uptr fixed_addr) {
-  init_size = RoundUpTo(init_size, PAGE_SIZE);
+  init_size = RoundUpTo(init_size, GetPageSize());
   DCHECK_EQ(os_handle_, ZX_HANDLE_INVALID);
   uintptr_t base;
   zx_handle_t vmar;
-  zx_status_t status =
-      _zx_vmar_allocate(
-          _zx_vmar_root_self(),
-          ZX_VM_CAN_MAP_READ | ZX_VM_CAN_MAP_WRITE | ZX_VM_CAN_MAP_SPECIFIC,
-          0, init_size, &vmar, &base);
+  zx_status_t status = _zx_vmar_allocate(
+      _zx_vmar_root_self(),
+      ZX_VM_CAN_MAP_READ | ZX_VM_CAN_MAP_WRITE | ZX_VM_CAN_MAP_SPECIFIC, 0,
+      init_size, &vmar, &base);
   if (status != ZX_OK)
     ReportMmapFailureAndDie(init_size, name, "zx_vmar_allocate", status);
   base_ = reinterpret_cast<void *>(base);
@@ -235,7 +237,7 @@ uptr ReservedAddressRange::Init(uptr init_size, const char *name,
 static uptr DoMmapFixedOrDie(zx_handle_t vmar, uptr fixed_addr, uptr map_size,
                              void *base, const char *name, bool die_for_nomem) {
   uptr offset = fixed_addr - reinterpret_cast<uptr>(base);
-  map_size = RoundUpTo(map_size, PAGE_SIZE);
+  map_size = RoundUpTo(map_size, GetPageSize());
   zx_handle_t vmo;
   zx_status_t status = _zx_vmo_create(map_size, 0, &vmo);
   if (status != ZX_OK) {
@@ -263,19 +265,19 @@ static uptr DoMmapFixedOrDie(zx_handle_t vmar, uptr fixed_addr, uptr map_size,
 
 uptr ReservedAddressRange::Map(uptr fixed_addr, uptr map_size,
                                const char *name) {
-  return DoMmapFixedOrDie(os_handle_, fixed_addr, map_size, base_,
-                          name_, false);
+  return DoMmapFixedOrDie(os_handle_, fixed_addr, map_size, base_, name_,
+                          false);
 }
 
 uptr ReservedAddressRange::MapOrDie(uptr fixed_addr, uptr map_size,
                                     const char *name) {
-  return DoMmapFixedOrDie(os_handle_, fixed_addr, map_size, base_,
-                          name_, true);
+  return DoMmapFixedOrDie(os_handle_, fixed_addr, map_size, base_, name_, true);
 }
 
 void UnmapOrDieVmar(void *addr, uptr size, zx_handle_t target_vmar) {
-  if (!addr || !size) return;
-  size = RoundUpTo(size, PAGE_SIZE);
+  if (!addr || !size)
+    return;
+  size = RoundUpTo(size, GetPageSize());
 
   zx_status_t status =
       _zx_vmar_unmap(target_vmar, reinterpret_cast<uintptr_t>(addr), size);
@@ -315,7 +317,7 @@ void *MmapFixedNoAccess(uptr fixed_addr, uptr size, const char *name) {
 
 void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
                                    const char *mem_type) {
-  CHECK_GE(size, PAGE_SIZE);
+  CHECK_GE(size, GetPageSize());
   CHECK(IsPowerOfTwo(size));
   CHECK(IsPowerOfTwo(alignment));
 
@@ -355,7 +357,8 @@ void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
             _zx_vmar_root_self(),
             ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_SPECIFIC_OVERWRITE,
             addr - info.base, vmo, 0, size, &new_addr);
-        if (status == ZX_OK) CHECK_EQ(new_addr, addr);
+        if (status == ZX_OK)
+          CHECK_EQ(new_addr, addr);
       }
     }
     if (status == ZX_OK && addr != map_addr)
@@ -380,9 +383,18 @@ void UnmapOrDie(void *addr, uptr size) {
   UnmapOrDieVmar(addr, size, _zx_vmar_root_self());
 }
 
-// This is used on the shadow mapping, which cannot be changed.
-// Zircon doesn't have anything like MADV_DONTNEED.
-void ReleaseMemoryPagesToOS(uptr beg, uptr end) {}
+void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
+  uptr beg_aligned = RoundUpTo(beg, GetPageSize());
+  uptr end_aligned = RoundDownTo(end, GetPageSize());
+  if (beg_aligned < end_aligned) {
+    zx_handle_t root_vmar = _zx_vmar_root_self();
+    CHECK_NE(root_vmar, ZX_HANDLE_INVALID);
+    zx_status_t status =
+        _zx_vmar_op_range(root_vmar, ZX_VMAR_OP_DECOMMIT, beg_aligned,
+                          end_aligned - beg_aligned, nullptr, 0);
+    CHECK_EQ(status, ZX_OK);
+  }
+}
 
 void DumpProcessMap() {
   // TODO(mcgrathr): write it
@@ -411,8 +423,9 @@ bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
     uint64_t vmo_size;
     status = _zx_vmo_get_size(vmo, &vmo_size);
     if (status == ZX_OK) {
-      if (vmo_size < max_len) max_len = vmo_size;
-      size_t map_size = RoundUpTo(max_len, PAGE_SIZE);
+      if (vmo_size < max_len)
+        max_len = vmo_size;
+      size_t map_size = RoundUpTo(max_len, GetPageSize());
       uintptr_t addr;
       status = _zx_vmar_map(_zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0,
                             map_size, &addr);
@@ -424,7 +437,8 @@ bool ReadFileToBuffer(const char *file_name, char **buff, uptr *buff_size,
     }
     _zx_handle_close(vmo);
   }
-  if (status != ZX_OK && errno_p) *errno_p = status;
+  if (status != ZX_OK && errno_p)
+    *errno_p = status;
   return status == ZX_OK;
 }
 
@@ -498,12 +512,12 @@ bool GetRandom(void *buffer, uptr length, bool blocking) {
   return true;
 }
 
-u32 GetNumberOfCPUs() {
-  return zx_system_get_num_cpus();
-}
+u32 GetNumberOfCPUs() { return zx_system_get_num_cpus(); }
 
 uptr GetRSS() { UNIMPLEMENTED(); }
 
+void InitializePlatformCommonFlags(CommonFlags *cf) {}
+
 }  // namespace __sanitizer
 
 using namespace __sanitizer;
@@ -526,6 +540,10 @@ void __sanitizer_set_report_path(const char *path) {
 void __sanitizer_set_report_fd(void *fd) {
   UNREACHABLE("not available on Fuchsia");
 }
+
+const char *__sanitizer_get_report_path() {
+  UNREACHABLE("not available on Fuchsia");
+}
 }  // extern "C"
 
 #endif  // SANITIZER_FUCHSIA
lib/tsan/sanitizer_common/sanitizer_fuchsia.h
@@ -30,6 +30,8 @@ struct MemoryMappingLayoutData {
   size_t current;  // Current index into the vector.
 };
 
+void InitShadowBounds();
+
 }  // namespace __sanitizer
 
 #endif  // SANITIZER_FUCHSIA
lib/tsan/sanitizer_common/sanitizer_getauxval.h
@@ -21,8 +21,9 @@
 
 #if SANITIZER_LINUX || SANITIZER_FUCHSIA
 
-# if __GLIBC_PREREQ(2, 16) || (SANITIZER_ANDROID && __ANDROID_API__ >= 21) || \
-     SANITIZER_FUCHSIA
+# if (__GLIBC_PREREQ(2, 16) || (SANITIZER_ANDROID && __ANDROID_API__ >= 21) || \
+      SANITIZER_FUCHSIA) &&                                                    \
+     !SANITIZER_GO
 #  define SANITIZER_USE_GETAUXVAL 1
 # else
 #  define SANITIZER_USE_GETAUXVAL 0
lib/tsan/sanitizer_common/sanitizer_interface_internal.h
@@ -28,6 +28,10 @@ extern "C" {
   // (casted to void *).
   SANITIZER_INTERFACE_ATTRIBUTE
   void __sanitizer_set_report_fd(void *fd);
+  // Get the current full report file path, if a path was specified by
+  // an earlier call to __sanitizer_set_report_path. Returns null otherwise.
+  SANITIZER_INTERFACE_ATTRIBUTE
+  const char *__sanitizer_get_report_path();
 
   typedef struct {
       int coverage_sandboxed;
lib/tsan/sanitizer_common/sanitizer_internal_defs.h
@@ -39,7 +39,7 @@
 
 // TLS is handled differently on different platforms
 #if SANITIZER_LINUX || SANITIZER_NETBSD || \
-  SANITIZER_FREEBSD || SANITIZER_OPENBSD
+  SANITIZER_FREEBSD
 # define SANITIZER_TLS_INITIAL_EXEC_ATTRIBUTE \
     __attribute__((tls_model("initial-exec"))) thread_local
 #else
@@ -104,8 +104,7 @@
 //
 // FIXME: do we have anything like this on Mac?
 #ifndef SANITIZER_CAN_USE_PREINIT_ARRAY
-#if ((SANITIZER_LINUX && !SANITIZER_ANDROID) || SANITIZER_OPENBSD || \
-     SANITIZER_FUCHSIA || SANITIZER_NETBSD) && !defined(PIC)
+#if (SANITIZER_LINUX || SANITIZER_FUCHSIA || SANITIZER_NETBSD) && !defined(PIC)
 #define SANITIZER_CAN_USE_PREINIT_ARRAY 1
 // Before Solaris 11.4, .preinit_array is fully supported only with GNU ld.
 // FIXME: Check for those conditions.
@@ -170,7 +169,7 @@ typedef int pid_t;
 #endif
 
 #if SANITIZER_FREEBSD || SANITIZER_NETBSD || \
-    SANITIZER_OPENBSD || SANITIZER_MAC || \
+    SANITIZER_MAC || \
     (SANITIZER_SOLARIS && (defined(_LP64) || _FILE_OFFSET_BITS == 64)) || \
     (SANITIZER_LINUX && defined(__x86_64__))
 typedef u64 OFF_T;
@@ -182,7 +181,7 @@ typedef u64  OFF64_T;
 #if (SANITIZER_WORDSIZE == 64) || SANITIZER_MAC
 typedef uptr operator_new_size_type;
 #else
-# if SANITIZER_OPENBSD || defined(__s390__) && !defined(__s390x__)
+# if defined(__s390__) && !defined(__s390x__)
 // Special case: 31-bit s390 has unsigned long as size_t.
 typedef unsigned long operator_new_size_type;
 # else
@@ -196,9 +195,6 @@ typedef u64 tid_t;
 // This header should NOT include any other headers to avoid portability issues.
 
 // Common defs.
-#ifndef INLINE
-#define INLINE inline
-#endif
 #define INTERFACE_ATTRIBUTE SANITIZER_INTERFACE_ATTRIBUTE
 #define SANITIZER_WEAK_DEFAULT_IMPL \
   extern "C" SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE NOINLINE
@@ -333,14 +329,10 @@ void NORETURN CheckFailed(const char *file, int line, const char *cond,
 
 #define UNIMPLEMENTED() UNREACHABLE("unimplemented")
 
-#define COMPILER_CHECK(pred) IMPL_COMPILER_ASSERT(pred, __LINE__)
+#define COMPILER_CHECK(pred) static_assert(pred, "")
 
 #define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
 
-#define IMPL_PASTE(a, b) a##b
-#define IMPL_COMPILER_ASSERT(pred, line) \
-    typedef char IMPL_PASTE(assertion_failed_##_, line)[2*(int)(pred)-1]
-
 // Limits for integral types. We have to redefine it in case we don't
 // have stdint.h (like in Visual Studio 9).
 #undef __INT64_C
@@ -417,6 +409,9 @@ inline void Trap() {
     (void)enable_fp;                      \
   } while (0)
 
+constexpr u32 kInvalidTid = -1;
+constexpr u32 kMainTid = 0;
+
 }  // namespace __sanitizer
 
 namespace __asan {
@@ -455,5 +450,8 @@ using namespace __sanitizer;
 namespace __hwasan {
 using namespace __sanitizer;
 }
+namespace __memprof {
+using namespace __sanitizer;
+}
 
 #endif  // SANITIZER_DEFS_H
lib/tsan/sanitizer_common/sanitizer_libc.h
@@ -67,7 +67,8 @@ uptr internal_ftruncate(fd_t fd, uptr size);
 
 // OS
 void NORETURN internal__exit(int exitcode);
-unsigned int internal_sleep(unsigned int seconds);
+void internal_sleep(unsigned seconds);
+void internal_usleep(u64 useconds);
 
 uptr internal_getpid();
 uptr internal_getppid();
lib/tsan/sanitizer_common/sanitizer_libignore.cpp
@@ -9,7 +9,7 @@
 #include "sanitizer_platform.h"
 
 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_MAC || \
-    SANITIZER_NETBSD || SANITIZER_OPENBSD
+    SANITIZER_NETBSD
 
 #include "sanitizer_libignore.h"
 #include "sanitizer_flags.h"
@@ -38,7 +38,7 @@ void LibIgnore::AddIgnoredLibrary(const char *name_templ) {
 void LibIgnore::OnLibraryLoaded(const char *name) {
   BlockingMutexLock lock(&mutex_);
   // Try to match suppressions with symlink target.
-  InternalScopedString buf(kMaxPathLength);
+  InternalMmapVector<char> buf(kMaxPathLength);
   if (name && internal_readlink(name, buf.data(), buf.size() - 1) > 0 &&
       buf[0]) {
     for (uptr i = 0; i < count_; i++) {
lib/tsan/sanitizer_common/sanitizer_linux.cpp
@@ -14,7 +14,7 @@
 #include "sanitizer_platform.h"
 
 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
+    SANITIZER_SOLARIS
 
 #include "sanitizer_common.h"
 #include "sanitizer_flags.h"
@@ -38,6 +38,14 @@
 #include <asm/unistd.h>
 #include <sys/types.h>
 #define stat kernel_stat
+#if SANITIZER_GO
+#undef st_atime
+#undef st_mtime
+#undef st_ctime
+#define st_atime st_atim
+#define st_mtime st_mtim
+#define st_ctime st_ctim
+#endif
 #include <asm/stat.h>
 #undef stat
 #endif
@@ -59,13 +67,7 @@
 #include <sys/syscall.h>
 #include <sys/time.h>
 #include <sys/types.h>
-#if !SANITIZER_OPENBSD
 #include <ucontext.h>
-#endif
-#if SANITIZER_OPENBSD
-#include <sys/futex.h>
-#include <sys/sysctl.h>
-#endif
 #include <unistd.h>
 
 #if SANITIZER_LINUX
@@ -129,7 +131,7 @@ const int FUTEX_WAKE_PRIVATE = FUTEX_WAKE | FUTEX_PRIVATE_FLAG;
 #endif
 
 // Note : FreeBSD had implemented both
-// Linux and OpenBSD apis, available from
+// Linux apis, available from
 // future 12.x version most likely
 #if SANITIZER_LINUX && defined(__NR_getrandom)
 # if !defined(GRND_NONBLOCK)
@@ -140,20 +142,18 @@ const int FUTEX_WAKE_PRIVATE = FUTEX_WAKE | FUTEX_PRIVATE_FLAG;
 # define SANITIZER_USE_GETRANDOM 0
 #endif  // SANITIZER_LINUX && defined(__NR_getrandom)
 
-#if SANITIZER_OPENBSD
-# define SANITIZER_USE_GETENTROPY 1
+#if SANITIZER_FREEBSD && __FreeBSD_version >= 1200000
+#  define SANITIZER_USE_GETENTROPY 1
 #else
-# if SANITIZER_FREEBSD && __FreeBSD_version >= 1200000
-#   define SANITIZER_USE_GETENTROPY 1
-# else
-#   define SANITIZER_USE_GETENTROPY 0
-# endif
-#endif // SANITIZER_USE_GETENTROPY
+#  define SANITIZER_USE_GETENTROPY 0
+#endif
 
 namespace __sanitizer {
 
 #if SANITIZER_LINUX && defined(__x86_64__)
 #include "sanitizer_syscall_linux_x86_64.inc"
+#elif SANITIZER_LINUX && SANITIZER_RISCV64
+#include "sanitizer_syscall_linux_riscv64.inc"
 #elif SANITIZER_LINUX && defined(__aarch64__)
 #include "sanitizer_syscall_linux_aarch64.inc"
 #elif SANITIZER_LINUX && defined(__arm__)
@@ -164,7 +164,7 @@ namespace __sanitizer {
 
 // --------------- sanitizer_libc.h
 #if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
-#if !SANITIZER_S390 && !SANITIZER_OPENBSD
+#if !SANITIZER_S390
 uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
                    u64 offset) {
 #if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
@@ -177,17 +177,27 @@ uptr internal_mmap(void *addr, uptr length, int prot, int flags, int fd,
                           offset / 4096);
 #endif
 }
-#endif // !SANITIZER_S390 && !SANITIZER_OPENBSD
+#endif // !SANITIZER_S390
 
-#if !SANITIZER_OPENBSD
 uptr internal_munmap(void *addr, uptr length) {
   return internal_syscall(SYSCALL(munmap), (uptr)addr, length);
 }
 
+#if SANITIZER_LINUX
+uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
+                     void *new_address) {
+  return internal_syscall(SYSCALL(mremap), (uptr)old_address, old_size,
+                          new_size, flags, (uptr)new_address);
+}
+#endif
+
 int internal_mprotect(void *addr, uptr length, int prot) {
   return internal_syscall(SYSCALL(mprotect), (uptr)addr, length, prot);
 }
-#endif
+
+int internal_madvise(uptr addr, uptr length, int advice) {
+  return internal_syscall(SYSCALL(madvise), addr, length, advice);
+}
 
 uptr internal_close(fd_t fd) {
   return internal_syscall(SYSCALL(close), fd);
@@ -254,9 +264,11 @@ static void stat64_to_stat(struct stat64 *in, struct stat *out) {
 // Undefine compatibility macros from <sys/stat.h>
 // so that they would not clash with the kernel_stat
 // st_[a|m|c]time fields
+#if !SANITIZER_GO
 #undef st_atime
 #undef st_mtime
 #undef st_ctime
+#endif
 #if defined(SANITIZER_ANDROID)
 // Bionic sys/stat.h defines additional macros
 // for compatibility with the old NDKs and
@@ -299,7 +311,7 @@ static void kernel_stat_to_stat(struct kernel_stat *in, struct stat *out) {
 #endif
 
 uptr internal_stat(const char *path, void *buf) {
-#if SANITIZER_FREEBSD || SANITIZER_OPENBSD
+#if SANITIZER_FREEBSD
   return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf, 0);
 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
   return internal_syscall(SYSCALL(newfstatat), AT_FDCWD, (uptr)path, (uptr)buf,
@@ -323,7 +335,7 @@ uptr internal_stat(const char *path, void *buf) {
 }
 
 uptr internal_lstat(const char *path, void *buf) {
-#if SANITIZER_FREEBSD || SANITIZER_OPENBSD
+#if SANITIZER_FREEBSD
   return internal_syscall(SYSCALL(fstatat), AT_FDCWD, (uptr)path, (uptr)buf,
                           AT_SYMLINK_NOFOLLOW);
 #elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
@@ -348,9 +360,8 @@ uptr internal_lstat(const char *path, void *buf) {
 }
 
 uptr internal_fstat(fd_t fd, void *buf) {
-#if SANITIZER_FREEBSD || SANITIZER_OPENBSD || \
-    SANITIZER_LINUX_USES_64BIT_SYSCALLS
-#if SANITIZER_MIPS64 && !SANITIZER_OPENBSD
+#if SANITIZER_FREEBSD || SANITIZER_LINUX_USES_64BIT_SYSCALLS
+#if SANITIZER_MIPS64
   // For mips64, fstat syscall fills buffer in the format of kernel_stat
   struct kernel_stat kbuf;
   int res = internal_syscall(SYSCALL(fstat), fd, &kbuf);
@@ -390,16 +401,13 @@ uptr internal_readlink(const char *path, char *buf, uptr bufsize) {
 #if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
   return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
                           bufsize);
-#elif SANITIZER_OPENBSD
-  return internal_syscall(SYSCALL(readlinkat), AT_FDCWD, (uptr)path, (uptr)buf,
-                          bufsize);
 #else
   return internal_syscall(SYSCALL(readlink), (uptr)path, (uptr)buf, bufsize);
 #endif
 }
 
 uptr internal_unlink(const char *path) {
-#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
+#if SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
   return internal_syscall(SYSCALL(unlinkat), AT_FDCWD, (uptr)path, 0);
 #else
   return internal_syscall(SYSCALL(unlink), (uptr)path);
@@ -410,7 +418,7 @@ uptr internal_rename(const char *oldpath, const char *newpath) {
 #if defined(__riscv)
   return internal_syscall(SYSCALL(renameat2), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
                           (uptr)newpath, 0);
-#elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS || SANITIZER_OPENBSD
+#elif SANITIZER_USES_CANONICAL_LINUX_SYSCALLS
   return internal_syscall(SYSCALL(renameat), AT_FDCWD, (uptr)oldpath, AT_FDCWD,
                           (uptr)newpath);
 #else
@@ -422,22 +430,11 @@ uptr internal_sched_yield() {
   return internal_syscall(SYSCALL(sched_yield));
 }
 
-void internal__exit(int exitcode) {
-#if SANITIZER_FREEBSD || SANITIZER_OPENBSD
-  internal_syscall(SYSCALL(exit), exitcode);
-#else
-  internal_syscall(SYSCALL(exit_group), exitcode);
-#endif
-  Die();  // Unreachable.
-}
-
-unsigned int internal_sleep(unsigned int seconds) {
+void internal_usleep(u64 useconds) {
   struct timespec ts;
-  ts.tv_sec = seconds;
-  ts.tv_nsec = 0;
-  int res = internal_syscall(SYSCALL(nanosleep), &ts, &ts);
-  if (res) return ts.tv_sec;
-  return 0;
+  ts.tv_sec = useconds / 1000000;
+  ts.tv_nsec = (useconds % 1000000) * 1000;
+  internal_syscall(SYSCALL(nanosleep), &ts, &ts);
 }
 
 uptr internal_execve(const char *filename, char *const argv[],
@@ -447,6 +444,17 @@ uptr internal_execve(const char *filename, char *const argv[],
 }
 #endif  // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
 
+#if !SANITIZER_NETBSD
+void internal__exit(int exitcode) {
+#if SANITIZER_FREEBSD || SANITIZER_SOLARIS
+  internal_syscall(SYSCALL(exit), exitcode);
+#else
+  internal_syscall(SYSCALL(exit_group), exitcode);
+#endif
+  Die();  // Unreachable.
+}
+#endif  // !SANITIZER_NETBSD
+
 // ----------------- sanitizer_common.h
 bool FileExists(const char *filename) {
   if (ShouldMockFailureToOpen(filename))
@@ -468,8 +476,6 @@ tid_t GetTid() {
   long Tid;
   thr_self(&Tid);
   return Tid;
-#elif SANITIZER_OPENBSD
-  return internal_syscall(SYSCALL(getthrid));
 #elif SANITIZER_SOLARIS
   return thr_self();
 #else
@@ -482,9 +488,6 @@ int TgKill(pid_t pid, tid_t tid, int sig) {
   return internal_syscall(SYSCALL(tgkill), pid, tid, sig);
 #elif SANITIZER_FREEBSD
   return internal_syscall(SYSCALL(thr_kill2), pid, tid, sig);
-#elif SANITIZER_OPENBSD
-  (void)pid;
-  return internal_syscall(SYSCALL(thrkill), tid, sig, nullptr);
 #elif SANITIZER_SOLARIS
   (void)pid;
   return thr_kill(tid, sig);
@@ -492,29 +495,30 @@ int TgKill(pid_t pid, tid_t tid, int sig) {
 }
 #endif
 
-#if !SANITIZER_SOLARIS && !SANITIZER_NETBSD
+#if SANITIZER_GLIBC
 u64 NanoTime() {
-#if SANITIZER_FREEBSD || SANITIZER_OPENBSD
-  timeval tv;
-#else
   kernel_timeval tv;
-#endif
   internal_memset(&tv, 0, sizeof(tv));
   internal_syscall(SYSCALL(gettimeofday), &tv, 0);
-  return (u64)tv.tv_sec * 1000*1000*1000 + tv.tv_usec * 1000;
+  return (u64)tv.tv_sec * 1000 * 1000 * 1000 + tv.tv_usec * 1000;
 }
-
+// Used by real_clock_gettime.
 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
   return internal_syscall(SYSCALL(clock_gettime), clk_id, tp);
 }
-#endif  // !SANITIZER_SOLARIS && !SANITIZER_NETBSD
+#elif !SANITIZER_SOLARIS && !SANITIZER_NETBSD
+u64 NanoTime() {
+  struct timespec ts;
+  clock_gettime(CLOCK_REALTIME, &ts);
+  return (u64)ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
+}
+#endif
 
 // Like getenv, but reads env directly from /proc (on Linux) or parses the
 // 'environ' array (on some others) and does not use libc. This function
 // should be called first inside __asan_init.
 const char *GetEnv(const char *name) {
-#if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD || \
-    SANITIZER_SOLARIS
+#if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_SOLARIS
   if (::environ != 0) {
     uptr NameLen = internal_strlen(name);
     for (char **Env = ::environ; *Env != 0; Env++) {
@@ -552,15 +556,13 @@ const char *GetEnv(const char *name) {
 #endif
 }
 
-#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD && \
-    !SANITIZER_GO
+#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_GO
 extern "C" {
 SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
 }
 #endif
 
-#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD &&                \
-    !SANITIZER_OPENBSD
+#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
 static void ReadNullSepFileToArray(const char *path, char ***arr,
                                    int arr_size) {
   char *buff;
@@ -585,7 +587,6 @@ static void ReadNullSepFileToArray(const char *path, char ***arr,
 }
 #endif
 
-#if !SANITIZER_OPENBSD
 static void GetArgsAndEnv(char ***argv, char ***envp) {
 #if SANITIZER_FREEBSD
   // On FreeBSD, retrieving the argument and environment arrays is done via the
@@ -637,14 +638,28 @@ char **GetEnviron() {
   return envp;
 }
 
-#endif  // !SANITIZER_OPENBSD
-
 #if !SANITIZER_SOLARIS
-enum MutexState {
-  MtxUnlocked = 0,
-  MtxLocked = 1,
-  MtxSleeping = 2
-};
+void FutexWait(atomic_uint32_t *p, u32 cmp) {
+#    if SANITIZER_FREEBSD
+  _umtx_op(p, UMTX_OP_WAIT_UINT, cmp, 0, 0);
+#    elif SANITIZER_NETBSD
+  sched_yield();   /* No userspace futex-like synchronization */
+#    else
+  internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAIT_PRIVATE, cmp, 0, 0, 0);
+#    endif
+}
+
+void FutexWake(atomic_uint32_t *p, u32 count) {
+#    if SANITIZER_FREEBSD
+  _umtx_op(p, UMTX_OP_WAKE, count, 0, 0);
+#    elif SANITIZER_NETBSD
+                   /* No userspace futex-like synchronization */
+#    else
+  internal_syscall(SYSCALL(futex), (uptr)p, FUTEX_WAKE_PRIVATE, count, 0, 0, 0);
+#    endif
+}
+
+enum { MtxUnlocked = 0, MtxLocked = 1, MtxSleeping = 2 };
 
 BlockingMutex::BlockingMutex() {
   internal_memset(this, 0, sizeof(*this));
@@ -682,11 +697,11 @@ void BlockingMutex::Unlock() {
   }
 }
 
-void BlockingMutex::CheckLocked() {
-  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
+void BlockingMutex::CheckLocked() const {
+  auto m = reinterpret_cast<atomic_uint32_t const *>(&opaque_storage_);
   CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
 }
-#endif // !SANITIZER_SOLARIS
+#  endif  // !SANITIZER_SOLARIS
 
 // ----------------- sanitizer_linux.h
 // The actual size of this structure is specified by d_reclen.
@@ -694,19 +709,9 @@ void BlockingMutex::CheckLocked() {
 // 32-bit syscall here.
 #if SANITIZER_NETBSD
 // Not used
-#elif SANITIZER_OPENBSD
-// struct dirent is different for Linux and us. At this moment, we use only
-// d_fileno (Linux call this d_ino), d_reclen, and d_name.
-struct linux_dirent {
-  u64 d_ino;  // d_fileno
-  u16 d_reclen;
-  u16 d_namlen;  // not used
-  u8 d_type;     // not used
-  char d_name[NAME_MAX + 1];
-};
 #else
 struct linux_dirent {
-#if SANITIZER_X32 || defined(__aarch64__)
+#if SANITIZER_X32 || defined(__aarch64__) || SANITIZER_RISCV64
   u64 d_ino;
   u64 d_off;
 #else
@@ -714,7 +719,7 @@ struct linux_dirent {
   unsigned long      d_off;
 #endif
   unsigned short     d_reclen;
-#ifdef __aarch64__
+#if defined(__aarch64__) || SANITIZER_RISCV64
   unsigned char      d_type;
 #endif
   char               d_name[256];
@@ -781,28 +786,39 @@ int internal_fork() {
 #endif
 }
 
-#if SANITIZER_FREEBSD || SANITIZER_OPENBSD
+#if SANITIZER_FREEBSD
 int internal_sysctl(const int *name, unsigned int namelen, void *oldp,
                     uptr *oldlenp, const void *newp, uptr newlen) {
-#if SANITIZER_OPENBSD
-  return sysctl(name, namelen, oldp, (size_t *)oldlenp, (void *)newp,
-                (size_t)newlen);
-#else
   return internal_syscall(SYSCALL(__sysctl), name, namelen, oldp,
                           (size_t *)oldlenp, newp, (size_t)newlen);
-#endif
 }
 
-#if SANITIZER_FREEBSD
 int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
                           const void *newp, uptr newlen) {
-  static decltype(sysctlbyname) *real = nullptr;
-  if (!real)
-    real = (decltype(sysctlbyname) *)dlsym(RTLD_NEXT, "sysctlbyname");
-  CHECK(real);
-  return real(sname, oldp, (size_t *)oldlenp, newp, (size_t)newlen);
-}
+  // Note: this function can be called during startup, so we need to avoid
+  // calling any interceptable functions. On FreeBSD >= 1300045 sysctlbyname()
+  // is a real syscall, but for older versions it calls sysctlnametomib()
+  // followed by sysctl(). To avoid calling the intercepted version and
+  // asserting if this happens during startup, call the real sysctlnametomib()
+  // followed by internal_sysctl() if the syscall is not available.
+#ifdef SYS___sysctlbyname
+  return internal_syscall(SYSCALL(__sysctlbyname), sname,
+                          internal_strlen(sname), oldp, (size_t *)oldlenp, newp,
+                          (size_t)newlen);
+#else
+  static decltype(sysctlnametomib) *real_sysctlnametomib = nullptr;
+  if (!real_sysctlnametomib)
+    real_sysctlnametomib =
+        (decltype(sysctlnametomib) *)dlsym(RTLD_NEXT, "sysctlnametomib");
+  CHECK(real_sysctlnametomib);
+
+  int oid[CTL_MAXNAME];
+  size_t len = CTL_MAXNAME;
+  if (real_sysctlnametomib(sname, oid, &len) == -1)
+    return (-1);
+  return internal_sysctl(oid, len, oldp, oldlenp, newp, newlen);
 #endif
+}
 #endif
 
 #if SANITIZER_LINUX
@@ -856,7 +872,7 @@ int internal_sigaction_norestorer(int signum, const void *act, void *oldact) {
 
 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
                           __sanitizer_sigset_t *oldset) {
-#if SANITIZER_FREEBSD || SANITIZER_OPENBSD
+#if SANITIZER_FREEBSD
   return internal_syscall(SYSCALL(sigprocmask), how, set, oldset);
 #else
   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
@@ -882,7 +898,7 @@ void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
-  k_set->sig[idx] &= ~(1 << bit);
+  k_set->sig[idx] &= ~((uptr)1 << bit);
 }
 
 bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
@@ -892,7 +908,7 @@ bool internal_sigismember(__sanitizer_sigset_t *set, int signum) {
   __sanitizer_kernel_sigset_t *k_set = (__sanitizer_kernel_sigset_t *)set;
   const uptr idx = signum / (sizeof(k_set->sig[0]) * 8);
   const uptr bit = signum % (sizeof(k_set->sig[0]) * 8);
-  return k_set->sig[idx] & (1 << bit);
+  return k_set->sig[idx] & ((uptr)1 << bit);
 }
 #elif SANITIZER_FREEBSD
 void internal_sigdelset(__sanitizer_sigset_t *set, int signum) {
@@ -1033,7 +1049,7 @@ static uptr GetKernelAreaSize() {
 #endif  // SANITIZER_WORDSIZE == 32
 
 uptr GetMaxVirtualAddress() {
-#if (SANITIZER_NETBSD || SANITIZER_OPENBSD) && defined(__x86_64__)
+#if SANITIZER_NETBSD && defined(__x86_64__)
   return 0x7f7ffffff000ULL;  // (0x00007f8000000000 - PAGE_SIZE)
 #elif SANITIZER_WORDSIZE == 64
 # if defined(__powerpc64__) || defined(__aarch64__)
@@ -1045,6 +1061,8 @@ uptr GetMaxVirtualAddress() {
   // This should (does) work for both PowerPC64 Endian modes.
   // Similarly, aarch64 has multiple address space layouts: 39, 42 and 47-bit.
   return (1ULL << (MostSignificantSetBitIndex(GET_CURRENT_FRAME()) + 1)) - 1;
+#elif SANITIZER_RISCV64
+  return (1ULL << 38) - 1;
 # elif defined(__mips64)
   return (1ULL << 40) - 1;  // 0x000000ffffffffffUL;
 # elif defined(__s390x__)
@@ -1094,7 +1112,6 @@ uptr GetPageSize() {
 }
 #endif // !SANITIZER_ANDROID
 
-#if !SANITIZER_OPENBSD
 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
 #if SANITIZER_SOLARIS
   const char *default_module_name = getexecname();
@@ -1131,7 +1148,6 @@ uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
   return module_name_len;
 #endif
 }
-#endif // !SANITIZER_OPENBSD
 
 uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
 #if SANITIZER_LINUX
@@ -1164,10 +1180,10 @@ bool LibraryNameIs(const char *full_name, const char *base_name) {
 // Call cb for each region mapped by map.
 void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr)) {
   CHECK_NE(map, nullptr);
-#if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
+#if !SANITIZER_FREEBSD
   typedef ElfW(Phdr) Elf_Phdr;
   typedef ElfW(Ehdr) Elf_Ehdr;
-#endif // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
+#endif // !SANITIZER_FREEBSD
   char *base = (char *)map->l_addr;
   Elf_Ehdr *ehdr = (Elf_Ehdr *)base;
   char *phdrs = base + ehdr->e_phoff;
@@ -1339,6 +1355,47 @@ uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
                        : "memory", "$29" );
   return res;
 }
+#elif SANITIZER_RISCV64
+uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
+                    int *parent_tidptr, void *newtls, int *child_tidptr) {
+  if (!fn || !child_stack)
+    return -EINVAL;
+
+  CHECK_EQ(0, (uptr)child_stack % 16);
+
+  register int res __asm__("a0");
+  register int __flags __asm__("a0") = flags;
+  register void *__stack __asm__("a1") = child_stack;
+  register int *__ptid __asm__("a2") = parent_tidptr;
+  register void *__tls __asm__("a3") = newtls;
+  register int *__ctid __asm__("a4") = child_tidptr;
+  register int (*__fn)(void *) __asm__("a5") = fn;
+  register void *__arg __asm__("a6") = arg;
+  register int nr_clone __asm__("a7") = __NR_clone;
+
+  __asm__ __volatile__(
+      "ecall\n"
+
+      /* if (a0 != 0)
+       *   return a0;
+       */
+      "bnez a0, 1f\n"
+
+      // In the child, now. Call "fn(arg)".
+      "mv a0, a6\n"
+      "jalr a5\n"
+
+      // Call _exit(a0).
+      "addi a7, zero, %9\n"
+      "ecall\n"
+      "1:\n"
+
+      : "=r"(res)
+      : "0"(__flags), "r"(__stack), "r"(__ptid), "r"(__tls), "r"(__ctid),
+        "r"(__fn), "r"(__arg), "r"(nr_clone), "i"(__NR_exit)
+      : "memory");
+  return res;
+}
 #elif defined(__aarch64__)
 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
                     int *parent_tidptr, void *newtls, int *child_tidptr) {
@@ -1768,11 +1825,7 @@ static bool Aarch64GetESR(ucontext_t *ucontext, u64 *esr) {
 }
 #endif
 
-#if SANITIZER_OPENBSD
-using Context = sigcontext;
-#else
 using Context = ucontext_t;
-#endif
 
 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
   Context *ucontext = (Context *)context;
@@ -1782,8 +1835,6 @@ SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
   uptr err = ucontext->uc_mcontext.mc_err;
 #elif SANITIZER_NETBSD
   uptr err = ucontext->uc_mcontext.__gregs[_REG_ERR];
-#elif SANITIZER_OPENBSD
-  uptr err = ucontext->sc_err;
 #elif SANITIZER_SOLARIS && defined(__i386__)
   const int Err = 13;
   uptr err = ucontext->uc_mcontext.gregs[Err];
@@ -2009,11 +2060,6 @@ static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
   *pc = ucontext->uc_mcontext.mc_rip;
   *bp = ucontext->uc_mcontext.mc_rbp;
   *sp = ucontext->uc_mcontext.mc_rsp;
-#elif SANITIZER_OPENBSD
-  sigcontext *ucontext = (sigcontext *)context;
-  *pc = ucontext->sc_rip;
-  *bp = ucontext->sc_rbp;
-  *sp = ucontext->sc_rsp;
 # else
   ucontext_t *ucontext = (ucontext_t*)context;
   *pc = ucontext->uc_mcontext.gregs[REG_RIP];
@@ -2026,11 +2072,6 @@ static void GetPcSpBp(void *context, uptr *pc, uptr *sp, uptr *bp) {
   *pc = ucontext->uc_mcontext.mc_eip;
   *bp = ucontext->uc_mcontext.mc_ebp;
   *sp = ucontext->uc_mcontext.mc_esp;
-#elif SANITIZER_OPENBSD
-  sigcontext *ucontext = (sigcontext *)context;
-  *pc = ucontext->sc_eip;
-  *bp = ucontext->sc_ebp;
-  *sp = ucontext->sc_esp;
 # else
   ucontext_t *ucontext = (ucontext_t*)context;
 # if SANITIZER_SOLARIS
@@ -2203,8 +2244,6 @@ void CheckMPROTECT() {
 #endif
 }
 
-void PrintModuleMap() { }
-
 void CheckNoDeepBind(const char *filename, int flag) {
 #ifdef RTLD_DEEPBIND
   if (flag & RTLD_DEEPBIND) {
lib/tsan/sanitizer_common/sanitizer_linux.h
@@ -14,12 +14,11 @@
 
 #include "sanitizer_platform.h"
 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD ||                \
-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
+    SANITIZER_SOLARIS
 #include "sanitizer_common.h"
 #include "sanitizer_internal_defs.h"
 #include "sanitizer_platform_limits_freebsd.h"
 #include "sanitizer_platform_limits_netbsd.h"
-#include "sanitizer_platform_limits_openbsd.h"
 #include "sanitizer_platform_limits_posix.h"
 #include "sanitizer_platform_limits_solaris.h"
 #include "sanitizer_posix.h"
@@ -50,7 +49,9 @@ uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count);
 uptr internal_sigaltstack(const void* ss, void* oss);
 uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
     __sanitizer_sigset_t *oldset);
+#if SANITIZER_GLIBC
 uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp);
+#endif
 
 // Linux-only syscalls.
 #if SANITIZER_LINUX
@@ -60,9 +61,9 @@ uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5);
 // internal_sigaction instead.
 int internal_sigaction_norestorer(int signum, const void *act, void *oldact);
 void internal_sigdelset(__sanitizer_sigset_t *set, int signum);
-#if defined(__x86_64__) || defined(__mips__) || defined(__aarch64__) \
-  || defined(__powerpc64__) || defined(__s390__) || defined(__i386__) \
-  || defined(__arm__)
+#if defined(__x86_64__) || defined(__mips__) || defined(__aarch64__) || \
+    defined(__powerpc64__) || defined(__s390__) || defined(__i386__) || \
+    defined(__arm__) || SANITIZER_RISCV64
 uptr internal_clone(int (*fn)(void *), void *child_stack, int flags, void *arg,
                     int *parent_tidptr, void *newtls, int *child_tidptr);
 #endif
@@ -97,7 +98,6 @@ class ThreadLister {
 // Exposed for testing.
 uptr ThreadDescriptorSize();
 uptr ThreadSelf();
-uptr ThreadSelfOffset();
 
 // Matches a library's file name against a base name (stripping path and version
 // information).
@@ -109,7 +109,7 @@ void ForEachMappedRegion(link_map *map, void (*cb)(const void *, uptr));
 // Releases memory pages entirely within the [beg, end] address range.
 // The pages no longer count toward RSS; reads are guaranteed to return 0.
 // Requires (but does not verify!) that pages are MAP_PRIVATE.
-INLINE void ReleaseMemoryPagesToOSAndZeroFill(uptr beg, uptr end) {
+inline void ReleaseMemoryPagesToOSAndZeroFill(uptr beg, uptr end) {
   // man madvise on Linux promises zero-fill for anonymous private pages.
   // Testing shows the same behaviour for private (but not anonymous) mappings
   // of shm_open() files, as long as the underlying file is untouched.
lib/tsan/sanitizer_common/sanitizer_linux_libcdep.cpp
@@ -13,8 +13,8 @@
 
 #include "sanitizer_platform.h"
 
-#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD ||                \
-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
+#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
+    SANITIZER_SOLARIS
 
 #include "sanitizer_allocator_internal.h"
 #include "sanitizer_atomic.h"
@@ -28,10 +28,15 @@
 #include "sanitizer_placement_new.h"
 #include "sanitizer_procmaps.h"
 
+#if SANITIZER_NETBSD
+#define _RTLD_SOURCE  // for __lwp_gettcb_fast() / __lwp_getprivate_fast()
+#endif
+
 #include <dlfcn.h>  // for dlsym()
 #include <link.h>
 #include <pthread.h>
 #include <signal.h>
+#include <sys/mman.h>
 #include <sys/resource.h>
 #include <syslog.h>
 
@@ -44,11 +49,10 @@
 #include <osreldate.h>
 #include <sys/sysctl.h>
 #define pthread_getattr_np pthread_attr_get_np
-#endif
-
-#if SANITIZER_OPENBSD
-#include <pthread_np.h>
-#include <sys/sysctl.h>
+// The MAP_NORESERVE define has been removed in FreeBSD 11.x, and even before
+// that, it was never implemented. So just define it to zero.
+#undef MAP_NORESERVE
+#define MAP_NORESERVE 0
 #endif
 
 #if SANITIZER_NETBSD
@@ -138,18 +142,13 @@ void GetThreadStackTopAndBottom(bool at_initialization, uptr *stack_top,
   CHECK_EQ(thr_stksegment(&ss), 0);
   stacksize = ss.ss_size;
   stackaddr = (char *)ss.ss_sp - stacksize;
-#elif SANITIZER_OPENBSD
-  stack_t sattr;
-  CHECK_EQ(pthread_stackseg_np(pthread_self(), &sattr), 0);
-  stackaddr = sattr.ss_sp;
-  stacksize = sattr.ss_size;
 #else  // !SANITIZER_SOLARIS
   pthread_attr_t attr;
   pthread_attr_init(&attr);
   CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
   my_pthread_attr_getstack(&attr, &stackaddr, &stacksize);
   pthread_attr_destroy(&attr);
-#endif // SANITIZER_SOLARIS
+#endif  // SANITIZER_SOLARIS
 
   *stack_top = (uptr)stackaddr + stacksize;
   *stack_bottom = (uptr)stackaddr;
@@ -189,86 +188,35 @@ __attribute__((unused)) static bool GetLibcVersion(int *major, int *minor,
 #endif
 }
 
-#if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO &&               \
-    !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_SOLARIS
-static uptr g_tls_size;
-
-#ifdef __i386__
-# define CHECK_GET_TLS_STATIC_INFO_VERSION (!__GLIBC_PREREQ(2, 27))
-#else
-# define CHECK_GET_TLS_STATIC_INFO_VERSION 0
-#endif
-
-#if CHECK_GET_TLS_STATIC_INFO_VERSION
-# define DL_INTERNAL_FUNCTION __attribute__((regparm(3), stdcall))
-#else
-# define DL_INTERNAL_FUNCTION
-#endif
-
-namespace {
-struct GetTlsStaticInfoCall {
-  typedef void (*get_tls_func)(size_t*, size_t*);
-};
-struct GetTlsStaticInfoRegparmCall {
-  typedef void (*get_tls_func)(size_t*, size_t*) DL_INTERNAL_FUNCTION;
-};
-
-template <typename T>
-void CallGetTls(void* ptr, size_t* size, size_t* align) {
-  typename T::get_tls_func get_tls;
-  CHECK_EQ(sizeof(get_tls), sizeof(ptr));
-  internal_memcpy(&get_tls, &ptr, sizeof(ptr));
-  CHECK_NE(get_tls, 0);
-  get_tls(size, align);
-}
-
-bool CmpLibcVersion(int major, int minor, int patch) {
-  int ma;
-  int mi;
-  int pa;
-  if (!GetLibcVersion(&ma, &mi, &pa))
-    return false;
-  if (ma > major)
-    return true;
-  if (ma < major)
-    return false;
-  if (mi > minor)
-    return true;
-  if (mi < minor)
-    return false;
-  return pa >= patch;
-}
-
-}  // namespace
+// True if we can use dlpi_tls_data. glibc before 2.25 may leave NULL (BZ
+// #19826) so dlpi_tls_data cannot be used.
+//
+// musl before 1.2.3 and FreeBSD as of 12.2 incorrectly set dlpi_tls_data to
+// the TLS initialization image
+// https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=254774
+__attribute__((unused)) static int g_use_dlpi_tls_data;
 
+#if SANITIZER_GLIBC && !SANITIZER_GO
+__attribute__((unused)) static size_t g_tls_size;
 void InitTlsSize() {
-  // all current supported platforms have 16 bytes stack alignment
-  const size_t kStackAlign = 16;
-  void *get_tls_static_info_ptr = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
-  size_t tls_size = 0;
-  size_t tls_align = 0;
-  // On i?86, _dl_get_tls_static_info used to be internal_function, i.e.
-  // __attribute__((regparm(3), stdcall)) before glibc 2.27 and is normal
-  // function in 2.27 and later.
-  if (CHECK_GET_TLS_STATIC_INFO_VERSION && !CmpLibcVersion(2, 27, 0))
-    CallGetTls<GetTlsStaticInfoRegparmCall>(get_tls_static_info_ptr,
-                                            &tls_size, &tls_align);
-  else
-    CallGetTls<GetTlsStaticInfoCall>(get_tls_static_info_ptr,
-                                     &tls_size, &tls_align);
-  if (tls_align < kStackAlign)
-    tls_align = kStackAlign;
-  g_tls_size = RoundUpTo(tls_size, tls_align);
+  int major, minor, patch;
+  g_use_dlpi_tls_data =
+      GetLibcVersion(&major, &minor, &patch) && major == 2 && minor >= 25;
+
+#if defined(__aarch64__) || defined(__x86_64__) || defined(__powerpc64__)
+  void *get_tls_static_info = dlsym(RTLD_NEXT, "_dl_get_tls_static_info");
+  size_t tls_align;
+  ((void (*)(size_t *, size_t *))get_tls_static_info)(&g_tls_size, &tls_align);
+#endif
 }
 #else
 void InitTlsSize() { }
-#endif  // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO &&
-        // !SANITIZER_NETBSD && !SANITIZER_SOLARIS
+#endif  // SANITIZER_GLIBC && !SANITIZER_GO
 
-#if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) ||          \
-     defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) ||    \
-     defined(__arm__)) &&                                                      \
-    SANITIZER_LINUX && !SANITIZER_ANDROID
+// On glibc x86_64, ThreadDescriptorSize() needs to be precise due to the usage
+// of g_tls_size. On other targets, ThreadDescriptorSize() is only used by lsan
+// to get the pointer to thread-specific data keys in the thread control block.
+#if (SANITIZER_FREEBSD || SANITIZER_LINUX) && !SANITIZER_ANDROID
 // sizeof(struct pthread) from glibc.
 static atomic_uintptr_t thread_descriptor_size;
 
@@ -301,41 +249,58 @@ uptr ThreadDescriptorSize() {
       val = FIRST_32_SECOND_64(1168, 2288);
     else if (minor <= 14)
       val = FIRST_32_SECOND_64(1168, 2304);
-    else
+    else if (minor < 32)  // Unknown version
       val = FIRST_32_SECOND_64(1216, 2304);
+    else  // minor == 32
+      val = FIRST_32_SECOND_64(1344, 2496);
   }
+#elif defined(__s390__) || defined(__sparc__)
+  // The size of a prefix of TCB including pthread::{specific_1stblock,specific}
+  // suffices. Just return offsetof(struct pthread, specific_used), which hasn't
+  // changed since 2007-05. Technically this applies to i386/x86_64 as well but
+  // we call _dl_get_tls_static_info and need the precise size of struct
+  // pthread.
+  return FIRST_32_SECOND_64(524, 1552);
 #elif defined(__mips__)
   // TODO(sagarthakur): add more values as per different glibc versions.
   val = FIRST_32_SECOND_64(1152, 1776);
+#elif SANITIZER_RISCV64
+  int major;
+  int minor;
+  int patch;
+  if (GetLibcVersion(&major, &minor, &patch) && major == 2) {
+    // TODO: consider adding an optional runtime check for an unknown (untested)
+    // glibc version
+    if (minor <= 28)  // WARNING: the highest tested version is 2.29
+      val = 1772;     // no guarantees for this one
+    else if (minor <= 31)
+      val = 1772;  // tested against glibc 2.29, 2.31
+    else
+      val = 1936;  // tested against glibc 2.32
+  }
+
 #elif defined(__aarch64__)
   // The sizeof (struct pthread) is the same from GLIBC 2.17 to 2.22.
   val = 1776;
 #elif defined(__powerpc64__)
   val = 1776; // from glibc.ppc64le 2.20-8.fc21
-#elif defined(__s390__)
-  val = FIRST_32_SECOND_64(1152, 1776); // valid for glibc 2.22
 #endif
   if (val)
     atomic_store_relaxed(&thread_descriptor_size, val);
   return val;
 }
 
-// The offset at which pointer to self is located in the thread descriptor.
-const uptr kThreadSelfOffset = FIRST_32_SECOND_64(8, 16);
-
-uptr ThreadSelfOffset() {
-  return kThreadSelfOffset;
-}
-
-#if defined(__mips__) || defined(__powerpc64__)
+#if defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64
 // TlsPreTcbSize includes size of struct pthread_descr and size of tcb
 // head structure. It lies before the static tls blocks.
 static uptr TlsPreTcbSize() {
-# if defined(__mips__)
+#if defined(__mips__)
   const uptr kTcbHead = 16; // sizeof (tcbhead_t)
-# elif defined(__powerpc64__)
+#elif defined(__powerpc64__)
   const uptr kTcbHead = 88; // sizeof (tcbhead_t)
-# endif
+#elif SANITIZER_RISCV64
+  const uptr kTcbHead = 16;  // sizeof (tcbhead_t)
+#endif
   const uptr kTlsAlign = 16;
   const uptr kTlsPreTcbSize =
       RoundUpTo(ThreadDescriptorSize() + kTcbHead, kTlsAlign);
@@ -343,68 +308,107 @@ static uptr TlsPreTcbSize() {
 }
 #endif
 
-uptr ThreadSelf() {
-  uptr descr_addr;
-# if defined(__i386__)
-  asm("mov %%gs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
-# elif defined(__x86_64__)
-  asm("mov %%fs:%c1,%0" : "=r"(descr_addr) : "i"(kThreadSelfOffset));
-# elif defined(__mips__)
-  // MIPS uses TLS variant I. The thread pointer (in hardware register $29)
-  // points to the end of the TCB + 0x7000. The pthread_descr structure is
-  // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
-  // TCB and the size of pthread_descr.
-  const uptr kTlsTcbOffset = 0x7000;
-  uptr thread_pointer;
-  asm volatile(".set push;\
-                .set mips64r2;\
-                rdhwr %0,$29;\
-                .set pop" : "=r" (thread_pointer));
-  descr_addr = thread_pointer - kTlsTcbOffset - TlsPreTcbSize();
-# elif defined(__aarch64__) || defined(__arm__)
-  descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) -
-                                      ThreadDescriptorSize();
-# elif defined(__s390__)
-  descr_addr = reinterpret_cast<uptr>(__builtin_thread_pointer());
-# elif defined(__powerpc64__)
-  // PPC64LE uses TLS variant I. The thread pointer (in GPR 13)
-  // points to the end of the TCB + 0x7000. The pthread_descr structure is
-  // immediately in front of the TCB. TlsPreTcbSize() includes the size of the
-  // TCB and the size of pthread_descr.
-  const uptr kTlsTcbOffset = 0x7000;
-  uptr thread_pointer;
-  asm("addi %0,13,%1" : "=r"(thread_pointer) : "I"(-kTlsTcbOffset));
-  descr_addr = thread_pointer - TlsPreTcbSize();
-# else
-#  error "unsupported CPU arch"
-# endif
-  return descr_addr;
-}
-#endif  // (x86_64 || i386 || MIPS) && SANITIZER_LINUX
+#if !SANITIZER_GO
+namespace {
+struct TlsBlock {
+  uptr begin, end, align;
+  size_t tls_modid;
+  bool operator<(const TlsBlock &rhs) const { return begin < rhs.begin; }
+};
+}  // namespace
 
-#if SANITIZER_FREEBSD
-static void **ThreadSelfSegbase() {
-  void **segbase = 0;
-# if defined(__i386__)
-  // sysarch(I386_GET_GSBASE, segbase);
-  __asm __volatile("mov %%gs:0, %0" : "=r" (segbase));
-# elif defined(__x86_64__)
-  // sysarch(AMD64_GET_FSBASE, segbase);
-  __asm __volatile("movq %%fs:0, %0" : "=r" (segbase));
-# else
-#  error "unsupported CPU arch"
-# endif
-  return segbase;
+#ifdef __s390__
+extern "C" uptr __tls_get_offset(void *arg);
+
+static uptr TlsGetOffset(uptr ti_module, uptr ti_offset) {
+  // The __tls_get_offset ABI requires %r12 to point to GOT and %r2 to be an
+  // offset of a struct tls_index inside GOT. We don't possess either of the
+  // two, so violate the letter of the "ELF Handling For Thread-Local
+  // Storage" document and assume that the implementation just dereferences
+  // %r2 + %r12.
+  uptr tls_index[2] = {ti_module, ti_offset};
+  register uptr r2 asm("2") = 0;
+  register void *r12 asm("12") = tls_index;
+  asm("basr %%r14, %[__tls_get_offset]"
+      : "+r"(r2)
+      : [__tls_get_offset] "r"(__tls_get_offset), "r"(r12)
+      : "memory", "cc", "0", "1", "3", "4", "5", "14");
+  return r2;
 }
+#else
+extern "C" void *__tls_get_addr(size_t *);
+#endif
 
-uptr ThreadSelf() {
-  return (uptr)ThreadSelfSegbase()[2];
+static int CollectStaticTlsBlocks(struct dl_phdr_info *info, size_t size,
+                                  void *data) {
+  if (!info->dlpi_tls_modid)
+    return 0;
+  uptr begin = (uptr)info->dlpi_tls_data;
+  if (!g_use_dlpi_tls_data) {
+    // Call __tls_get_addr as a fallback. This forces TLS allocation on glibc
+    // and FreeBSD.
+#ifdef __s390__
+    begin = (uptr)__builtin_thread_pointer() +
+            TlsGetOffset(info->dlpi_tls_modid, 0);
+#else
+    size_t mod_and_off[2] = {info->dlpi_tls_modid, 0};
+    begin = (uptr)__tls_get_addr(mod_and_off);
+#endif
+  }
+  for (unsigned i = 0; i != info->dlpi_phnum; ++i)
+    if (info->dlpi_phdr[i].p_type == PT_TLS) {
+      static_cast<InternalMmapVector<TlsBlock> *>(data)->push_back(
+          TlsBlock{begin, begin + info->dlpi_phdr[i].p_memsz,
+                   info->dlpi_phdr[i].p_align, info->dlpi_tls_modid});
+      break;
+    }
+  return 0;
 }
-#endif  // SANITIZER_FREEBSD
+
+__attribute__((unused)) static void GetStaticTlsBoundary(uptr *addr, uptr *size,
+                                                         uptr *align) {
+  InternalMmapVector<TlsBlock> ranges;
+  dl_iterate_phdr(CollectStaticTlsBlocks, &ranges);
+  uptr len = ranges.size();
+  Sort(ranges.begin(), len);
+  // Find the range with tls_modid=1. For glibc, because libc.so uses PT_TLS,
+  // this module is guaranteed to exist and is one of the initially loaded
+  // modules.
+  uptr one = 0;
+  while (one != len && ranges[one].tls_modid != 1) ++one;
+  if (one == len) {
+    // This may happen with musl if no module uses PT_TLS.
+    *addr = 0;
+    *size = 0;
+    *align = 1;
+    return;
+  }
+  // Find the maximum consecutive ranges. We consider two modules consecutive if
+  // the gap is smaller than the alignment. The dynamic loader places static TLS
+  // blocks this way not to waste space.
+  uptr l = one;
+  *align = ranges[l].align;
+  while (l != 0 && ranges[l].begin < ranges[l - 1].end + ranges[l - 1].align)
+    *align = Max(*align, ranges[--l].align);
+  uptr r = one + 1;
+  while (r != len && ranges[r].begin < ranges[r - 1].end + ranges[r - 1].align)
+    *align = Max(*align, ranges[r++].align);
+  *addr = ranges[l].begin;
+  *size = ranges[r - 1].end - ranges[l].begin;
+}
+#endif  // !SANITIZER_GO
+#endif  // (x86_64 || i386 || mips || ...) && (SANITIZER_FREEBSD ||
+        // SANITIZER_LINUX) && !SANITIZER_ANDROID
 
 #if SANITIZER_NETBSD
 static struct tls_tcb * ThreadSelfTlsTcb() {
-  return (struct tls_tcb *)_lwp_getprivate();
+  struct tls_tcb *tcb = nullptr;
+#ifdef __HAVE___LWP_GETTCB_FAST
+  tcb = (struct tls_tcb *)__lwp_gettcb_fast();
+#elif defined(__HAVE___LWP_GETPRIVATE_FAST)
+  tcb = (struct tls_tcb *)__lwp_getprivate_fast();
+#endif
+  return tcb;
 }
 
 uptr ThreadSelf() {
@@ -425,35 +429,91 @@ int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
 }
 #endif  // SANITIZER_NETBSD
 
+#if SANITIZER_ANDROID
+// Bionic provides this API since S.
+extern "C" SANITIZER_WEAK_ATTRIBUTE void __libc_get_static_tls_bounds(void **,
+                                                                      void **);
+#endif
+
 #if !SANITIZER_GO
 static void GetTls(uptr *addr, uptr *size) {
-#if SANITIZER_LINUX && !SANITIZER_ANDROID
-# if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
-  *addr = ThreadSelf();
-  *size = GetTlsSize();
+#if SANITIZER_ANDROID
+  if (&__libc_get_static_tls_bounds) {
+    void *start_addr;
+    void *end_addr;
+    __libc_get_static_tls_bounds(&start_addr, &end_addr);
+    *addr = reinterpret_cast<uptr>(start_addr);
+    *size =
+        reinterpret_cast<uptr>(end_addr) - reinterpret_cast<uptr>(start_addr);
+  } else {
+    *addr = 0;
+    *size = 0;
+  }
+#elif SANITIZER_GLIBC && defined(__x86_64__)
+  // For aarch64 and x86-64, use an O(1) approach which requires relatively
+  // precise ThreadDescriptorSize. g_tls_size was initialized in InitTlsSize.
+  asm("mov %%fs:16,%0" : "=r"(*addr));
+  *size = g_tls_size;
   *addr -= *size;
   *addr += ThreadDescriptorSize();
-# elif defined(__mips__) || defined(__aarch64__) || defined(__powerpc64__) \
-    || defined(__arm__)
-  *addr = ThreadSelf();
-  *size = GetTlsSize();
-# else
-  *addr = 0;
-  *size = 0;
-# endif
-#elif SANITIZER_FREEBSD
-  void** segbase = ThreadSelfSegbase();
-  *addr = 0;
-  *size = 0;
-  if (segbase != 0) {
-    // tcbalign = 16
-    // tls_size = round(tls_static_space, tcbalign);
-    // dtv = segbase[1];
-    // dtv[2] = segbase - tls_static_space;
-    void **dtv = (void**) segbase[1];
-    *addr = (uptr) dtv[2];
-    *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
+#elif SANITIZER_GLIBC && defined(__aarch64__)
+  *addr = reinterpret_cast<uptr>(__builtin_thread_pointer()) -
+          ThreadDescriptorSize();
+  *size = g_tls_size + ThreadDescriptorSize();
+#elif SANITIZER_GLIBC && defined(__powerpc64__)
+  // Workaround for glibc<2.25(?). 2.27 is known to not need this.
+  uptr tp;
+  asm("addi %0,13,-0x7000" : "=r"(tp));
+  const uptr pre_tcb_size = TlsPreTcbSize();
+  *addr = tp - pre_tcb_size;
+  *size = g_tls_size + pre_tcb_size;
+#elif SANITIZER_FREEBSD || SANITIZER_LINUX
+  uptr align;
+  GetStaticTlsBoundary(addr, size, &align);
+#if defined(__x86_64__) || defined(__i386__) || defined(__s390__) || \
+    defined(__sparc__)
+  if (SANITIZER_GLIBC) {
+#if defined(__x86_64__) || defined(__i386__)
+    align = Max<uptr>(align, 64);
+#else
+    align = Max<uptr>(align, 16);
+#endif
   }
+  const uptr tp = RoundUpTo(*addr + *size, align);
+
+  // lsan requires the range to additionally cover the static TLS surplus
+  // (elf/dl-tls.c defines 1664). Otherwise there may be false positives for
+  // allocations only referenced by tls in dynamically loaded modules.
+  if (SANITIZER_GLIBC)
+    *size += 1644;
+  else if (SANITIZER_FREEBSD)
+    *size += 128;  // RTLD_STATIC_TLS_EXTRA
+
+  // Extend the range to include the thread control block. On glibc, lsan needs
+  // the range to include pthread::{specific_1stblock,specific} so that
+  // allocations only referenced by pthread_setspecific can be scanned. This may
+  // underestimate by at most TLS_TCB_ALIGN-1 bytes but it should be fine
+  // because the number of bytes after pthread::specific is larger.
+  *addr = tp - RoundUpTo(*size, align);
+  *size = tp - *addr + ThreadDescriptorSize();
+#else
+  if (SANITIZER_GLIBC)
+    *size += 1664;
+  else if (SANITIZER_FREEBSD)
+    *size += 128;  // RTLD_STATIC_TLS_EXTRA
+#if defined(__mips__) || defined(__powerpc64__) || SANITIZER_RISCV64
+  const uptr pre_tcb_size = TlsPreTcbSize();
+  *addr -= pre_tcb_size;
+  *size += pre_tcb_size;
+#else
+  // arm and aarch64 reserve two words at TP, so this underestimates the range.
+  // However, this is sufficient for the purpose of finding the pointers to
+  // thread-specific data keys.
+  const uptr tcb_size = ThreadDescriptorSize();
+  *addr -= tcb_size;
+  *size += tcb_size;
+#endif
+#endif
 #elif SANITIZER_NETBSD
   struct tls_tcb * const tcb = ThreadSelfTlsTcb();
   *addr = 0;
@@ -468,33 +528,25 @@ static void GetTls(uptr *addr, uptr *size) {
       *addr = (uptr)tcb->tcb_dtv[1];
     }
   }
-#elif SANITIZER_OPENBSD
-  *addr = 0;
-  *size = 0;
-#elif SANITIZER_ANDROID
-  *addr = 0;
-  *size = 0;
 #elif SANITIZER_SOLARIS
   // FIXME
   *addr = 0;
   *size = 0;
 #else
-# error "Unknown OS"
+#error "Unknown OS"
 #endif
 }
 #endif
 
 #if !SANITIZER_GO
 uptr GetTlsSize() {
-#if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NETBSD ||              \
-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
+#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD || \
+    SANITIZER_SOLARIS
   uptr addr, size;
   GetTls(&addr, &size);
   return size;
-#elif defined(__mips__) || defined(__powerpc64__)
-  return RoundUpTo(g_tls_size + TlsPreTcbSize(), 16);
 #else
-  return g_tls_size;
+  return 0;
 #endif
 }
 #endif
@@ -515,42 +567,33 @@ void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
   if (!main) {
     // If stack and tls intersect, make them non-intersecting.
     if (*tls_addr > *stk_addr && *tls_addr < *stk_addr + *stk_size) {
-      CHECK_GT(*tls_addr + *tls_size, *stk_addr);
-      CHECK_LE(*tls_addr + *tls_size, *stk_addr + *stk_size);
-      *stk_size -= *tls_size;
-      *tls_addr = *stk_addr + *stk_size;
+      if (*stk_addr + *stk_size < *tls_addr + *tls_size)
+        *tls_size = *stk_addr + *stk_size - *tls_addr;
+      *stk_size = *tls_addr - *stk_addr;
     }
   }
 #endif
 }
 
-#if !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
+#if !SANITIZER_FREEBSD
 typedef ElfW(Phdr) Elf_Phdr;
-#elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001 // v9.2
+#elif SANITIZER_WORDSIZE == 32 && __FreeBSD_version <= 902001  // v9.2
 #define Elf_Phdr XElf32_Phdr
 #define dl_phdr_info xdl_phdr_info
 #define dl_iterate_phdr(c, b) xdl_iterate_phdr((c), (b))
-#endif // !SANITIZER_FREEBSD && !SANITIZER_OPENBSD
+#endif  // !SANITIZER_FREEBSD
 
 struct DlIteratePhdrData {
   InternalMmapVectorNoCtor<LoadedModule> *modules;
   bool first;
 };
 
-static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
-  DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
-  InternalScopedString module_name(kMaxPathLength);
-  if (data->first) {
-    data->first = false;
-    // First module is the binary itself.
-    ReadBinaryNameCached(module_name.data(), module_name.size());
-  } else if (info->dlpi_name) {
-    module_name.append("%s", info->dlpi_name);
-  }
+static int AddModuleSegments(const char *module_name, dl_phdr_info *info,
+                             InternalMmapVectorNoCtor<LoadedModule> *modules) {
   if (module_name[0] == '\0')
     return 0;
   LoadedModule cur_module;
-  cur_module.set(module_name.data(), info->dlpi_addr);
+  cur_module.set(module_name, info->dlpi_addr);
   for (int i = 0; i < (int)info->dlpi_phnum; i++) {
     const Elf_Phdr *phdr = &info->dlpi_phdr[i];
     if (phdr->p_type == PT_LOAD) {
@@ -562,7 +605,26 @@ static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
                                  writable);
     }
   }
-  data->modules->push_back(cur_module);
+  modules->push_back(cur_module);
+  return 0;
+}
+
+static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
+  DlIteratePhdrData *data = (DlIteratePhdrData *)arg;
+  if (data->first) {
+    InternalMmapVector<char> module_name(kMaxPathLength);
+    data->first = false;
+    // First module is the binary itself.
+    ReadBinaryNameCached(module_name.data(), module_name.size());
+    return AddModuleSegments(module_name.data(), info, data->modules);
+  }
+
+  if (info->dlpi_name) {
+    InternalScopedString module_name;
+    module_name.append("%s", info->dlpi_name);
+    return AddModuleSegments(module_name.data(), info, data->modules);
+  }
+
   return 0;
 }
 
@@ -650,7 +712,7 @@ uptr GetRSS() {
 // sysconf(_SC_NPROCESSORS_{CONF,ONLN}) cannot be used on most platforms as
 // they allocate memory.
 u32 GetNumberOfCPUs() {
-#if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
+#if SANITIZER_FREEBSD || SANITIZER_NETBSD
   u32 ncpu;
   int req[2];
   uptr len = sizeof(ncpu);
@@ -705,7 +767,7 @@ u32 GetNumberOfCPUs() {
 
 #if SANITIZER_LINUX
 
-# if SANITIZER_ANDROID
+#if SANITIZER_ANDROID
 static atomic_uint8_t android_log_initialized;
 
 void AndroidLogInit() {
@@ -749,7 +811,7 @@ void SetAbortMessage(const char *str) {
   if (&android_set_abort_message)
     android_set_abort_message(str);
 }
-# else
+#else
 void AndroidLogInit() {}
 
 static bool ShouldLogAfterPrintf() { return true; }
@@ -757,7 +819,7 @@ static bool ShouldLogAfterPrintf() { return true; }
 void WriteOneLineToSyslog(const char *s) { syslog(LOG_INFO, "%s", s); }
 
 void SetAbortMessage(const char *str) {}
-# endif  // SANITIZER_ANDROID
+#endif  // SANITIZER_ANDROID
 
 void LogMessageOnPrintf(const char *str) {
   if (common_flags()->log_to_syslog && ShouldLogAfterPrintf())
@@ -766,20 +828,13 @@ void LogMessageOnPrintf(const char *str) {
 
 #endif  // SANITIZER_LINUX
 
-#if SANITIZER_LINUX && !SANITIZER_GO
+#if SANITIZER_GLIBC && !SANITIZER_GO
 // glibc crashes when using clock_gettime from a preinit_array function as the
 // vDSO function pointers haven't been initialized yet. __progname is
 // initialized after the vDSO function pointers, so if it exists, is not null
 // and is not empty, we can use clock_gettime.
 extern "C" SANITIZER_WEAK_ATTRIBUTE char *__progname;
-INLINE bool CanUseVDSO() {
-  // Bionic is safe, it checks for the vDSO function pointers to be initialized.
-  if (SANITIZER_ANDROID)
-    return true;
-  if (&__progname && __progname && *__progname)
-    return true;
-  return false;
-}
+inline bool CanUseVDSO() { return &__progname && __progname && *__progname; }
 
 // MonotonicNanoTime is a timing function that can leverage the vDSO by calling
 // clock_gettime. real_clock_gettime only exists if clock_gettime is
@@ -799,15 +854,14 @@ u64 MonotonicNanoTime() {
   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
 }
 #else
-// Non-Linux & Go always use the syscall.
+// Non-glibc & Go always use the regular function.
 u64 MonotonicNanoTime() {
   timespec ts;
-  internal_clock_gettime(CLOCK_MONOTONIC, &ts);
+  clock_gettime(CLOCK_MONOTONIC, &ts);
   return (u64)ts.tv_sec * (1000ULL * 1000 * 1000) + ts.tv_nsec;
 }
-#endif  // SANITIZER_LINUX && !SANITIZER_GO
+#endif  // SANITIZER_GLIBC && !SANITIZER_GO
 
-#if !SANITIZER_OPENBSD
 void ReExec() {
   const char *pathname = "/proc/self/exe";
 
@@ -839,7 +893,107 @@ void ReExec() {
   Printf("execve failed, errno %d\n", rverrno);
   Die();
 }
-#endif  // !SANITIZER_OPENBSD
+
+void UnmapFromTo(uptr from, uptr to) {
+  if (to == from)
+    return;
+  CHECK(to >= from);
+  uptr res = internal_munmap(reinterpret_cast<void *>(from), to - from);
+  if (UNLIKELY(internal_iserror(res))) {
+    Report("ERROR: %s failed to unmap 0x%zx (%zd) bytes at address %p\n",
+           SanitizerToolName, to - from, to - from, (void *)from);
+    CHECK("unable to unmap" && 0);
+  }
+}
+
+uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
+                      uptr min_shadow_base_alignment,
+                      UNUSED uptr &high_mem_end) {
+  const uptr granularity = GetMmapGranularity();
+  const uptr alignment =
+      Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
+  const uptr left_padding =
+      Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
+
+  const uptr shadow_size = RoundUpTo(shadow_size_bytes, granularity);
+  const uptr map_size = shadow_size + left_padding + alignment;
+
+  const uptr map_start = (uptr)MmapNoAccess(map_size);
+  CHECK_NE(map_start, ~(uptr)0);
+
+  const uptr shadow_start = RoundUpTo(map_start + left_padding, alignment);
+
+  UnmapFromTo(map_start, shadow_start - left_padding);
+  UnmapFromTo(shadow_start + shadow_size, map_start + map_size);
+
+  return shadow_start;
+}
+
+static uptr MmapSharedNoReserve(uptr addr, uptr size) {
+  return internal_mmap(
+      reinterpret_cast<void *>(addr), size, PROT_READ | PROT_WRITE,
+      MAP_FIXED | MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
+}
+
+static uptr MremapCreateAlias(uptr base_addr, uptr alias_addr,
+                              uptr alias_size) {
+#if SANITIZER_LINUX
+  return internal_mremap(reinterpret_cast<void *>(base_addr), 0, alias_size,
+                         MREMAP_MAYMOVE | MREMAP_FIXED,
+                         reinterpret_cast<void *>(alias_addr));
+#else
+  CHECK(false && "mremap is not supported outside of Linux");
+  return 0;
+#endif
+}
+
+static void CreateAliases(uptr start_addr, uptr alias_size, uptr num_aliases) {
+  uptr total_size = alias_size * num_aliases;
+  uptr mapped = MmapSharedNoReserve(start_addr, total_size);
+  CHECK_EQ(mapped, start_addr);
+
+  for (uptr i = 1; i < num_aliases; ++i) {
+    uptr alias_addr = start_addr + i * alias_size;
+    CHECK_EQ(MremapCreateAlias(start_addr, alias_addr, alias_size), alias_addr);
+  }
+}
+
+uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
+                                uptr num_aliases, uptr ring_buffer_size) {
+  CHECK_EQ(alias_size & (alias_size - 1), 0);
+  CHECK_EQ(num_aliases & (num_aliases - 1), 0);
+  CHECK_EQ(ring_buffer_size & (ring_buffer_size - 1), 0);
+
+  const uptr granularity = GetMmapGranularity();
+  shadow_size = RoundUpTo(shadow_size, granularity);
+  CHECK_EQ(shadow_size & (shadow_size - 1), 0);
+
+  const uptr alias_region_size = alias_size * num_aliases;
+  const uptr alignment =
+      2 * Max(Max(shadow_size, alias_region_size), ring_buffer_size);
+  const uptr left_padding = ring_buffer_size;
+
+  const uptr right_size = alignment;
+  const uptr map_size = left_padding + 2 * alignment;
+
+  const uptr map_start = reinterpret_cast<uptr>(MmapNoAccess(map_size));
+  CHECK_NE(map_start, static_cast<uptr>(-1));
+  const uptr right_start = RoundUpTo(map_start + left_padding, alignment);
+
+  UnmapFromTo(map_start, right_start - left_padding);
+  UnmapFromTo(right_start + right_size, map_start + map_size);
+
+  CreateAliases(right_start + right_size / 2, alias_size, num_aliases);
+
+  return right_start;
+}
+
+void InitializePlatformCommonFlags(CommonFlags *cf) {
+#if SANITIZER_ANDROID
+  if (&__libc_get_static_tls_bounds == nullptr)
+    cf->detect_leaks = false;
+#endif
+}
 
 } // namespace __sanitizer
 
lib/tsan/sanitizer_common/sanitizer_local_address_space_view.h
@@ -7,7 +7,7 @@
 //===----------------------------------------------------------------------===//
 //
 // `LocalAddressSpaceView` provides the local (i.e. target and current address
-// space are the same) implementation of the `AddressSpaveView` interface which
+// space are the same) implementation of the `AddressSpaceView` interface which
 // provides a simple interface to load memory from another process (i.e.
 // out-of-process)
 //
lib/tsan/sanitizer_common/sanitizer_mac.cpp
@@ -44,6 +44,14 @@ extern char **environ;
 #define SANITIZER_OS_TRACE 0
 #endif
 
+// import new crash reporting api
+#if defined(__has_include) && __has_include(<CrashReporterClient.h>)
+#define HAVE_CRASHREPORTERCLIENT_H 1
+#include <CrashReporterClient.h>
+#else
+#define HAVE_CRASHREPORTERCLIENT_H 0
+#endif
+
 #if !SANITIZER_IOS
 #include <crt_externs.h>  // for _NSGetArgv and _NSGetEnviron
 #else
@@ -62,6 +70,7 @@ extern "C" {
 #include <mach/mach_time.h>
 #include <mach/vm_statistics.h>
 #include <malloc/malloc.h>
+#include <os/log.h>
 #include <pthread.h>
 #include <sched.h>
 #include <signal.h>
@@ -133,10 +142,20 @@ uptr internal_munmap(void *addr, uptr length) {
   return munmap(addr, length);
 }
 
+uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
+                     void *new_address) {
+  CHECK(false && "internal_mremap is unimplemented on Mac");
+  return 0;
+}
+
 int internal_mprotect(void *addr, uptr length, int prot) {
   return mprotect(addr, length, prot);
 }
 
+int internal_madvise(uptr addr, uptr length, int advice) {
+  return madvise((void *)addr, length, advice);
+}
+
 uptr internal_close(fd_t fd) {
   return close(fd);
 }
@@ -200,9 +219,7 @@ void internal__exit(int exitcode) {
   _exit(exitcode);
 }
 
-unsigned int internal_sleep(unsigned int seconds) {
-  return sleep(seconds);
-}
+void internal_usleep(u64 useconds) { usleep(useconds); }
 
 uptr internal_getpid() {
   return getpid();
@@ -440,7 +457,7 @@ uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
   // On OS X the executable path is saved to the stack by dyld. Reading it
   // from there is much faster than calling dladdr, especially for large
   // binaries with symbols.
-  InternalScopedString exe_path(kMaxPathLength);
+  InternalMmapVector<char> exe_path(kMaxPathLength);
   uint32_t size = exe_path.size();
   if (_NSGetExecutablePath(exe_path.data(), &size) == 0 &&
       realpath(exe_path.data(), buf) != 0) {
@@ -492,6 +509,13 @@ void MprotectMallocZones(void *addr, int prot) {
   }
 }
 
+void FutexWait(atomic_uint32_t *p, u32 cmp) {
+  // FIXME: implement actual blocking.
+  sched_yield();
+}
+
+void FutexWake(atomic_uint32_t *p, u32 count) {}
+
 BlockingMutex::BlockingMutex() {
   internal_memset(this, 0, sizeof(*this));
 }
@@ -507,8 +531,8 @@ void BlockingMutex::Unlock() {
   OSSpinLockUnlock((OSSpinLock*)&opaque_storage_);
 }
 
-void BlockingMutex::CheckLocked() {
-  CHECK_NE(*(OSSpinLock*)&opaque_storage_, 0);
+void BlockingMutex::CheckLocked() const {
+  CHECK_NE(*(const OSSpinLock*)&opaque_storage_, 0);
 }
 
 u64 NanoTime() {
@@ -606,21 +630,103 @@ HandleSignalMode GetHandleSignalMode(int signum) {
   return result;
 }
 
-// This corresponds to Triple::getMacOSXVersion() in the Clang driver.
-static MacosVersion GetMacosAlignedVersionInternal() {
+// Offset example:
+// XNU 17 -- macOS 10.13 -- iOS 11 -- tvOS 11 -- watchOS 4
+constexpr u16 GetOSMajorKernelOffset() {
+  if (TARGET_OS_OSX) return 4;
+  if (TARGET_OS_IOS || TARGET_OS_TV) return 6;
+  if (TARGET_OS_WATCH) return 13;
+}
+
+using VersStr = char[64];
+
+static uptr ApproximateOSVersionViaKernelVersion(VersStr vers) {
   u16 kernel_major = GetDarwinKernelVersion().major;
-  // Darwin 0-3  -> unsupported
-  // Darwin 4-19 -> macOS 10.x
-  // Darwin 20+  -> macOS 11+
-  CHECK_GE(kernel_major, 4);
-  u16 major, minor;
-  if (kernel_major < 20) {
-    major = 10;
-    minor = kernel_major - 4;
+  u16 offset = GetOSMajorKernelOffset();
+  CHECK_GE(kernel_major, offset);
+  u16 os_major = kernel_major - offset;
+
+  const char *format = "%d.0";
+  if (TARGET_OS_OSX) {
+    if (os_major >= 16) {  // macOS 11+
+      os_major -= 5;
+    } else {  // macOS 10.15 and below
+      format = "10.%d";
+    }
+  }
+  return internal_snprintf(vers, sizeof(VersStr), format, os_major);
+}
+
+static void GetOSVersion(VersStr vers) {
+  uptr len = sizeof(VersStr);
+  if (SANITIZER_IOSSIM) {
+    const char *vers_env = GetEnv("SIMULATOR_RUNTIME_VERSION");
+    if (!vers_env) {
+      Report("ERROR: Running in simulator but SIMULATOR_RUNTIME_VERSION env "
+          "var is not set.\n");
+      Die();
+    }
+    len = internal_strlcpy(vers, vers_env, len);
   } else {
-    major = 11 + kernel_major - 20;
-    minor = 0;
+    int res =
+        internal_sysctlbyname("kern.osproductversion", vers, &len, nullptr, 0);
+
+    // XNU 17 (macOS 10.13) and below do not provide the sysctl
+    // `kern.osproductversion` entry (res != 0).
+    bool no_os_version = res != 0;
+
+    // For launchd, sanitizer initialization runs before sysctl is setup
+    // (res == 0 && len != strlen(vers), vers is not a valid version).  However,
+    // the kernel version `kern.osrelease` is available.
+    bool launchd = (res == 0 && internal_strlen(vers) < 3);
+    if (launchd) CHECK_EQ(internal_getpid(), 1);
+
+    if (no_os_version || launchd) {
+      len = ApproximateOSVersionViaKernelVersion(vers);
+    }
+  }
+  CHECK_LT(len, sizeof(VersStr));
+}
+
+void ParseVersion(const char *vers, u16 *major, u16 *minor) {
+  // Format: <major>.<minor>[.<patch>]\0
+  CHECK_GE(internal_strlen(vers), 3);
+  const char *p = vers;
+  *major = internal_simple_strtoll(p, &p, /*base=*/10);
+  CHECK_EQ(*p, '.');
+  p += 1;
+  *minor = internal_simple_strtoll(p, &p, /*base=*/10);
+}
+
+// Aligned versions example:
+// macOS 10.15 -- iOS 13 -- tvOS 13 -- watchOS 6
+static void MapToMacos(u16 *major, u16 *minor) {
+  if (TARGET_OS_OSX)
+    return;
+
+  if (TARGET_OS_IOS || TARGET_OS_TV)
+    *major += 2;
+  else if (TARGET_OS_WATCH)
+    *major += 9;
+  else
+    UNREACHABLE("unsupported platform");
+
+  if (*major >= 16) {  // macOS 11+
+    *major -= 5;
+  } else {  // macOS 10.15 and below
+    *minor = *major;
+    *major = 10;
   }
+}
+
+static MacosVersion GetMacosAlignedVersionInternal() {
+  VersStr vers = {};
+  GetOSVersion(vers);
+
+  u16 major, minor;
+  ParseVersion(vers, &major, &minor);
+  MapToMacos(&major, &minor);
+
   return MacosVersion(major, minor);
 }
 
@@ -639,24 +745,15 @@ MacosVersion GetMacosAlignedVersion() {
   return *reinterpret_cast<MacosVersion *>(&result);
 }
 
-void ParseVersion(const char *vers, u16 *major, u16 *minor) {
-  // Format: <major>.<minor>.<patch>\0
-  CHECK_GE(internal_strlen(vers), 5);
-  const char *p = vers;
-  *major = internal_simple_strtoll(p, &p, /*base=*/10);
-  CHECK_EQ(*p, '.');
-  p += 1;
-  *minor = internal_simple_strtoll(p, &p, /*base=*/10);
-}
-
 DarwinKernelVersion GetDarwinKernelVersion() {
-  char buf[100];
-  size_t len = sizeof(buf);
-  int res = internal_sysctlbyname("kern.osrelease", buf, &len, nullptr, 0);
+  VersStr vers = {};
+  uptr len = sizeof(VersStr);
+  int res = internal_sysctlbyname("kern.osrelease", vers, &len, nullptr, 0);
   CHECK_EQ(res, 0);
+  CHECK_LT(len, sizeof(VersStr));
 
   u16 major, minor;
-  ParseVersion(buf, &major, &minor);
+  ParseVersion(vers, &major, &minor);
 
   return DarwinKernelVersion(major, minor);
 }
@@ -693,7 +790,51 @@ static BlockingMutex syslog_lock(LINKER_INITIALIZED);
 void WriteOneLineToSyslog(const char *s) {
 #if !SANITIZER_GO
   syslog_lock.CheckLocked();
-  asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", s);
+  if (GetMacosAlignedVersion() >= MacosVersion(10, 12)) {
+    os_log_error(OS_LOG_DEFAULT, "%{public}s", s);
+  } else {
+    asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", s);
+  }
+#endif
+}
+
+// buffer to store crash report application information
+static char crashreporter_info_buff[__sanitizer::kErrorMessageBufferSize] = {};
+static BlockingMutex crashreporter_info_mutex(LINKER_INITIALIZED);
+
+extern "C" {
+// Integrate with crash reporter libraries.
+#if HAVE_CRASHREPORTERCLIENT_H
+CRASH_REPORTER_CLIENT_HIDDEN
+struct crashreporter_annotations_t gCRAnnotations
+    __attribute__((section("__DATA," CRASHREPORTER_ANNOTATIONS_SECTION))) = {
+        CRASHREPORTER_ANNOTATIONS_VERSION,
+        0,
+        0,
+        0,
+        0,
+        0,
+        0,
+#if CRASHREPORTER_ANNOTATIONS_VERSION > 4
+        0,
+#endif
+};
+
+#else
+// fall back to old crashreporter api
+static const char *__crashreporter_info__ __attribute__((__used__)) =
+    &crashreporter_info_buff[0];
+asm(".desc ___crashreporter_info__, 0x10");
+#endif
+
+}  // extern "C"
+
+static void CRAppendCrashLogMessage(const char *msg) {
+  BlockingMutexLock l(&crashreporter_info_mutex);
+  internal_strlcat(crashreporter_info_buff, msg,
+                   sizeof(crashreporter_info_buff));
+#if HAVE_CRASHREPORTERCLIENT_H
+  (void)CRSetCrashLogMessage(crashreporter_info_buff);
 #endif
 }
 
@@ -796,6 +937,19 @@ void SignalContext::InitPcSpBp() {
   GetPcSpBp(context, &pc, &sp, &bp);
 }
 
+// ASan/TSan use mmap in a way that creates โ€œdeallocation gapsโ€ which triggers
+// EXC_GUARD exceptions on macOS 10.15+ (XNU 19.0+).
+static void DisableMmapExcGuardExceptions() {
+  using task_exc_guard_behavior_t = uint32_t;
+  using task_set_exc_guard_behavior_t =
+      kern_return_t(task_t task, task_exc_guard_behavior_t behavior);
+  auto *set_behavior = (task_set_exc_guard_behavior_t *)dlsym(
+      RTLD_DEFAULT, "task_set_exc_guard_behavior");
+  if (set_behavior == nullptr) return;
+  const task_exc_guard_behavior_t task_exc_guard_none = 0;
+  set_behavior(mach_task_self(), task_exc_guard_none);
+}
+
 void InitializePlatformEarly() {
   // Only use xnu_fast_mmap when on x86_64 and the kernel supports it.
   use_xnu_fast_mmap =
@@ -804,6 +958,8 @@ void InitializePlatformEarly() {
 #else
       false;
 #endif
+  if (GetDarwinKernelVersion() >= DarwinKernelVersion(19, 0))
+    DisableMmapExcGuardExceptions();
 }
 
 #if !SANITIZER_GO
@@ -844,20 +1000,10 @@ bool ReexecDisabled() {
   return false;
 }
 
-extern "C" SANITIZER_WEAK_ATTRIBUTE double dyldVersionNumber;
-static const double kMinDyldVersionWithAutoInterposition = 360.0;
-
-bool DyldNeedsEnvVariable() {
-  // Although sanitizer support was added to LLVM on OS X 10.7+, GCC users
-  // still may want use them on older systems. On older Darwin platforms, dyld
-  // doesn't export dyldVersionNumber symbol and we simply return true.
-  if (!&dyldVersionNumber) return true;
+static bool DyldNeedsEnvVariable() {
   // If running on OS X 10.11+ or iOS 9.0+, dyld will interpose even if
-  // DYLD_INSERT_LIBRARIES is not set. However, checking OS version via
-  // GetMacosAlignedVersion() doesn't work for the simulator. Let's instead
-  // check `dyldVersionNumber`, which is exported by dyld, against a known
-  // version number from the first OS release where this appeared.
-  return dyldVersionNumber < kMinDyldVersionWithAutoInterposition;
+  // DYLD_INSERT_LIBRARIES is not set.
+  return GetMacosAlignedVersion() < MacosVersion(10, 11);
 }
 
 void MaybeReexec() {
@@ -884,7 +1030,7 @@ void MaybeReexec() {
   if (DyldNeedsEnvVariable() && !lib_is_in_env) {
     // DYLD_INSERT_LIBRARIES is not set or does not contain the runtime
     // library.
-    InternalScopedString program_name(1024);
+    InternalMmapVector<char> program_name(1024);
     uint32_t buf_size = program_name.size();
     _NSGetExecutablePath(program_name.data(), &buf_size);
     char *new_env = const_cast<char*>(info.dli_fname);
@@ -1003,7 +1149,7 @@ char **GetArgv() {
   return *_NSGetArgv();
 }
 
-#if SANITIZER_IOS
+#if SANITIZER_IOS && !SANITIZER_IOSSIM
 // The task_vm_info struct is normally provided by the macOS SDK, but we need
 // fields only available in 10.12+. Declare the struct manually to be able to
 // build against older SDKs.
@@ -1043,26 +1189,35 @@ static uptr GetTaskInfoMaxAddress() {
 
 uptr GetMaxUserVirtualAddress() {
   static uptr max_vm = GetTaskInfoMaxAddress();
-  if (max_vm != 0)
-    return max_vm - 1;
+  if (max_vm != 0) {
+    const uptr ret_value = max_vm - 1;
+    CHECK_LE(ret_value, SANITIZER_MMAP_RANGE_SIZE);
+    return ret_value;
+  }
 
   // xnu cannot provide vm address limit
 # if SANITIZER_WORDSIZE == 32
-  return 0xffe00000 - 1;
+  constexpr uptr fallback_max_vm = 0xffe00000 - 1;
 # else
-  return 0x200000000 - 1;
+  constexpr uptr fallback_max_vm = 0x200000000 - 1;
 # endif
+  static_assert(fallback_max_vm <= SANITIZER_MMAP_RANGE_SIZE,
+                "Max virtual address must be less than mmap range size.");
+  return fallback_max_vm;
 }
 
 #else // !SANITIZER_IOS
 
 uptr GetMaxUserVirtualAddress() {
 # if SANITIZER_WORDSIZE == 64
-  return (1ULL << 47) - 1;  // 0x00007fffffffffffUL;
+  constexpr uptr max_vm = (1ULL << 47) - 1;  // 0x00007fffffffffffUL;
 # else // SANITIZER_WORDSIZE == 32
   static_assert(SANITIZER_WORDSIZE == 32, "Wrong wordsize");
-  return (1ULL << 32) - 1;  // 0xffffffff;
+  constexpr uptr max_vm = (1ULL << 32) - 1;  // 0xffffffff;
 # endif
+  static_assert(max_vm <= SANITIZER_MMAP_RANGE_SIZE,
+                "Max virtual address must be less than mmap range size.");
+  return max_vm;
 }
 #endif
 
@@ -1070,6 +1225,59 @@ uptr GetMaxVirtualAddress() {
   return GetMaxUserVirtualAddress();
 }
 
+uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
+                      uptr min_shadow_base_alignment, uptr &high_mem_end) {
+  const uptr granularity = GetMmapGranularity();
+  const uptr alignment =
+      Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
+  const uptr left_padding =
+      Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
+
+  uptr space_size = shadow_size_bytes + left_padding;
+
+  uptr largest_gap_found = 0;
+  uptr max_occupied_addr = 0;
+  VReport(2, "FindDynamicShadowStart, space_size = %p\n", space_size);
+  uptr shadow_start =
+      FindAvailableMemoryRange(space_size, alignment, granularity,
+                               &largest_gap_found, &max_occupied_addr);
+  // If the shadow doesn't fit, restrict the address space to make it fit.
+  if (shadow_start == 0) {
+    VReport(
+        2,
+        "Shadow doesn't fit, largest_gap_found = %p, max_occupied_addr = %p\n",
+        largest_gap_found, max_occupied_addr);
+    uptr new_max_vm = RoundDownTo(largest_gap_found << shadow_scale, alignment);
+    if (new_max_vm < max_occupied_addr) {
+      Report("Unable to find a memory range for dynamic shadow.\n");
+      Report(
+          "space_size = %p, largest_gap_found = %p, max_occupied_addr = %p, "
+          "new_max_vm = %p\n",
+          space_size, largest_gap_found, max_occupied_addr, new_max_vm);
+      CHECK(0 && "cannot place shadow");
+    }
+    RestrictMemoryToMaxAddress(new_max_vm);
+    high_mem_end = new_max_vm - 1;
+    space_size = (high_mem_end >> shadow_scale) + left_padding;
+    VReport(2, "FindDynamicShadowStart, space_size = %p\n", space_size);
+    shadow_start = FindAvailableMemoryRange(space_size, alignment, granularity,
+                                            nullptr, nullptr);
+    if (shadow_start == 0) {
+      Report("Unable to find a memory range after restricting VM.\n");
+      CHECK(0 && "cannot place shadow after restricting vm");
+    }
+  }
+  CHECK_NE((uptr)0, shadow_start);
+  CHECK(IsAligned(shadow_start, alignment));
+  return shadow_start;
+}
+
+uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
+                                uptr num_aliases, uptr ring_buffer_size) {
+  CHECK(false && "HWASan aliasing is unimplemented on Mac");
+  return 0;
+}
+
 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
                               uptr *largest_gap_found,
                               uptr *max_occupied_addr) {
@@ -1190,7 +1398,7 @@ void FormatUUID(char *out, uptr size, const u8 *uuid) {
                     uuid[12], uuid[13], uuid[14], uuid[15]);
 }
 
-void PrintModuleMap() {
+void DumpProcessMap() {
   Printf("Process module map:\n");
   MemoryMappingLayout memory_mapping(false);
   InternalMmapVector<LoadedModule> modules;
@@ -1223,6 +1431,8 @@ u32 GetNumberOfCPUs() {
   return (u32)sysconf(_SC_NPROCESSORS_ONLN);
 }
 
+void InitializePlatformCommonFlags(CommonFlags *cf) {}
+
 }  // namespace __sanitizer
 
 #endif  // SANITIZER_MAC
lib/tsan/sanitizer_common/sanitizer_mac.h
@@ -44,6 +44,7 @@ struct VersionBase {
     return major > other.major ||
            (major == other.major && minor >= other.minor);
   }
+  bool operator<(const VersionType &other) const { return !(*this >= other); }
 };
 
 struct MacosVersion : VersionBase<MacosVersion> {
@@ -63,22 +64,5 @@ void RestrictMemoryToMaxAddress(uptr max_address);
 
 }  // namespace __sanitizer
 
-extern "C" {
-static char __crashreporter_info_buff__[__sanitizer::kErrorMessageBufferSize] =
-  {};
-static const char *__crashreporter_info__ __attribute__((__used__)) =
-  &__crashreporter_info_buff__[0];
-asm(".desc ___crashreporter_info__, 0x10");
-} // extern "C"
-
-namespace __sanitizer {
-static BlockingMutex crashreporter_info_mutex(LINKER_INITIALIZED);
-
-INLINE void CRAppendCrashLogMessage(const char *msg) {
-  BlockingMutexLock l(&crashreporter_info_mutex);
-  internal_strlcat(__crashreporter_info_buff__, msg,
-                   sizeof(__crashreporter_info_buff__)); }
-}  // namespace __sanitizer
-
 #endif  // SANITIZER_MAC
 #endif  // SANITIZER_MAC_H
lib/tsan/sanitizer_common/sanitizer_malloc_mac.inc
@@ -120,11 +120,7 @@ INTERCEPTOR(int, malloc_make_nonpurgeable, void *ptr) {
 
 INTERCEPTOR(void, malloc_set_zone_name, malloc_zone_t *zone, const char *name) {
   COMMON_MALLOC_ENTER();
-  // Allocate |sizeof(COMMON_MALLOC_ZONE_NAME "-") + internal_strlen(name)|
-  // bytes.
-  size_t buflen =
-      sizeof(COMMON_MALLOC_ZONE_NAME "-") + (name ? internal_strlen(name) : 0);
-  InternalScopedString new_name(buflen);
+  InternalScopedString new_name;
   if (name && zone->introspect == sanitizer_zone.introspect) {
     new_name.append(COMMON_MALLOC_ZONE_NAME "-%s", name);
     name = new_name.data();
lib/tsan/sanitizer_common/sanitizer_mutex.cpp
@@ -0,0 +1,225 @@
+//===-- sanitizer_mutex.cpp -----------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is shared between AddressSanitizer and ThreadSanitizer
+// run-time libraries.
+//===----------------------------------------------------------------------===//
+
+#include "sanitizer_mutex.h"
+
+#include "sanitizer_common.h"
+
+namespace __sanitizer {
+
+void StaticSpinMutex::LockSlow() {
+  for (int i = 0;; i++) {
+    if (i < 100)
+      proc_yield(1);
+    else
+      internal_sched_yield();
+    if (atomic_load(&state_, memory_order_relaxed) == 0 &&
+        atomic_exchange(&state_, 1, memory_order_acquire) == 0)
+      return;
+  }
+}
+
+void Semaphore::Wait() {
+  u32 count = atomic_load(&state_, memory_order_relaxed);
+  for (;;) {
+    if (count == 0) {
+      FutexWait(&state_, 0);
+      count = atomic_load(&state_, memory_order_relaxed);
+      continue;
+    }
+    if (atomic_compare_exchange_weak(&state_, &count, count - 1,
+                                     memory_order_acquire))
+      break;
+  }
+}
+
+void Semaphore::Post(u32 count) {
+  CHECK_NE(count, 0);
+  atomic_fetch_add(&state_, count, memory_order_release);
+  FutexWake(&state_, count);
+}
+
+#if SANITIZER_CHECK_DEADLOCKS
+// An empty mutex meta table, it effectively disables deadlock detection.
+// Each tool can override the table to define own mutex hierarchy and
+// enable deadlock detection.
+// The table defines a static mutex type hierarchy (what mutex types can be locked
+// under what mutex types). This table is checked to be acyclic and then
+// actual mutex lock/unlock operations are checked to adhere to this hierarchy.
+// The checking happens on mutex types rather than on individual mutex instances
+// because doing it on mutex instances will both significantly complicate
+// the implementation, worsen performance and memory overhead and is mostly
+// unnecessary (we almost never lock multiple mutexes of the same type recursively).
+static constexpr int kMutexTypeMax = 20;
+SANITIZER_WEAK_ATTRIBUTE MutexMeta mutex_meta[kMutexTypeMax] = {};
+SANITIZER_WEAK_ATTRIBUTE void PrintMutexPC(uptr pc) {}
+static StaticSpinMutex mutex_meta_mtx;
+static int mutex_type_count = -1;
+// Adjacency matrix of what mutexes can be locked under what mutexes.
+static bool mutex_can_lock[kMutexTypeMax][kMutexTypeMax];
+// Mutex types with MutexMulti mark.
+static bool mutex_multi[kMutexTypeMax];
+
+void DebugMutexInit() {
+  // Build adjacency matrix.
+  bool leaf[kMutexTypeMax];
+  internal_memset(&leaf, 0, sizeof(leaf));
+  int cnt[kMutexTypeMax] = {};
+  internal_memset(&cnt, 0, sizeof(cnt));
+  for (int t = 0; t < kMutexTypeMax; t++) {
+    mutex_type_count = t;
+    if (!mutex_meta[t].name)
+      break;
+    CHECK_EQ(t, mutex_meta[t].type);
+    for (uptr j = 0; j < ARRAY_SIZE(mutex_meta[t].can_lock); j++) {
+      MutexType z = mutex_meta[t].can_lock[j];
+      if (z == MutexInvalid)
+        break;
+      if (z == MutexLeaf) {
+        CHECK(!leaf[t]);
+        leaf[t] = true;
+        continue;
+      }
+      if (z == MutexMulti) {
+        mutex_multi[t] = true;
+        continue;
+      }
+      CHECK_LT(z, kMutexTypeMax);
+      CHECK(!mutex_can_lock[t][z]);
+      mutex_can_lock[t][z] = true;
+      cnt[t]++;
+    }
+  }
+  // Indicates the array is not properly terminated.
+  CHECK_LT(mutex_type_count, kMutexTypeMax);
+  // Add leaf mutexes.
+  for (int t = 0; t < mutex_type_count; t++) {
+    if (!leaf[t])
+      continue;
+    CHECK_EQ(cnt[t], 0);
+    for (int z = 0; z < mutex_type_count; z++) {
+      if (z == MutexInvalid || t == z || leaf[z])
+        continue;
+      CHECK(!mutex_can_lock[z][t]);
+      mutex_can_lock[z][t] = true;
+    }
+  }
+  // Build the transitive closure and check that the graphs is acyclic.
+  u32 trans[kMutexTypeMax];
+  static_assert(sizeof(trans[0]) * 8 >= kMutexTypeMax,
+                "kMutexTypeMax does not fit into u32, switch to u64");
+  internal_memset(&trans, 0, sizeof(trans));
+  for (int i = 0; i < mutex_type_count; i++) {
+    for (int j = 0; j < mutex_type_count; j++)
+      if (mutex_can_lock[i][j])
+        trans[i] |= 1 << j;
+  }
+  for (int k = 0; k < mutex_type_count; k++) {
+    for (int i = 0; i < mutex_type_count; i++) {
+      if (trans[i] & (1 << k))
+        trans[i] |= trans[k];
+    }
+  }
+  for (int i = 0; i < mutex_type_count; i++) {
+    if (trans[i] & (1 << i)) {
+      Printf("Mutex %s participates in a cycle\n", mutex_meta[i].name);
+      Die();
+    }
+  }
+}
+
+struct InternalDeadlockDetector {
+  struct LockDesc {
+    u64 seq;
+    uptr pc;
+    int recursion;
+  };
+  int initialized;
+  u64 sequence;
+  LockDesc locked[kMutexTypeMax];
+
+  void Lock(MutexType type, uptr pc) {
+    if (!Initialize(type))
+      return;
+    CHECK_LT(type, mutex_type_count);
+    // Find the last locked mutex type.
+    // This is the type we will use for hierarchy checks.
+    u64 max_seq = 0;
+    MutexType max_idx = MutexInvalid;
+    for (int i = 0; i != mutex_type_count; i++) {
+      if (locked[i].seq == 0)
+        continue;
+      CHECK_NE(locked[i].seq, max_seq);
+      if (max_seq < locked[i].seq) {
+        max_seq = locked[i].seq;
+        max_idx = (MutexType)i;
+      }
+    }
+    if (max_idx == type && mutex_multi[type]) {
+      // Recursive lock of the same type.
+      CHECK_EQ(locked[type].seq, max_seq);
+      CHECK(locked[type].pc);
+      locked[type].recursion++;
+      return;
+    }
+    if (max_idx != MutexInvalid && !mutex_can_lock[max_idx][type]) {
+      Printf("%s: internal deadlock: can't lock %s under %s mutex\n", SanitizerToolName,
+             mutex_meta[type].name, mutex_meta[max_idx].name);
+      PrintMutexPC(pc);
+      CHECK(0);
+    }
+    locked[type].seq = ++sequence;
+    locked[type].pc = pc;
+    locked[type].recursion = 1;
+  }
+
+  void Unlock(MutexType type) {
+    if (!Initialize(type))
+      return;
+    CHECK_LT(type, mutex_type_count);
+    CHECK(locked[type].seq);
+    CHECK_GT(locked[type].recursion, 0);
+    if (--locked[type].recursion)
+      return;
+    locked[type].seq = 0;
+    locked[type].pc = 0;
+  }
+
+  void CheckNoLocks() {
+    for (int i = 0; i < mutex_type_count; i++) CHECK_EQ(locked[i].recursion, 0);
+  }
+
+  bool Initialize(MutexType type) {
+    if (type == MutexUnchecked || type == MutexInvalid)
+      return false;
+    CHECK_GT(type, MutexInvalid);
+    if (initialized != 0)
+      return initialized > 0;
+    initialized = -1;
+    SpinMutexLock lock(&mutex_meta_mtx);
+    if (mutex_type_count < 0)
+      DebugMutexInit();
+    initialized = mutex_type_count ? 1 : -1;
+    return initialized > 0;
+  }
+};
+
+static THREADLOCAL InternalDeadlockDetector deadlock_detector;
+
+void CheckedMutex::LockImpl(uptr pc) { deadlock_detector.Lock(type_, pc); }
+
+void CheckedMutex::UnlockImpl() { deadlock_detector.Unlock(type_); }
+
+void CheckedMutex::CheckNoLocksImpl() { deadlock_detector.CheckNoLocks(); }
+#endif
+
+}  // namespace __sanitizer
lib/tsan/sanitizer_common/sanitizer_mutex.h
@@ -16,67 +16,335 @@
 #include "sanitizer_atomic.h"
 #include "sanitizer_internal_defs.h"
 #include "sanitizer_libc.h"
+#include "sanitizer_thread_safety.h"
 
 namespace __sanitizer {
 
-class StaticSpinMutex {
+class MUTEX StaticSpinMutex {
  public:
   void Init() {
     atomic_store(&state_, 0, memory_order_relaxed);
   }
 
-  void Lock() {
-    if (TryLock())
+  void Lock() ACQUIRE() {
+    if (LIKELY(TryLock()))
       return;
     LockSlow();
   }
 
-  bool TryLock() {
+  bool TryLock() TRY_ACQUIRE(true) {
     return atomic_exchange(&state_, 1, memory_order_acquire) == 0;
   }
 
-  void Unlock() {
-    atomic_store(&state_, 0, memory_order_release);
-  }
+  void Unlock() RELEASE() { atomic_store(&state_, 0, memory_order_release); }
 
-  void CheckLocked() {
+  void CheckLocked() const CHECK_LOCKED() {
     CHECK_EQ(atomic_load(&state_, memory_order_relaxed), 1);
   }
 
  private:
   atomic_uint8_t state_;
 
-  void NOINLINE LockSlow() {
-    for (int i = 0;; i++) {
-      if (i < 10)
-        proc_yield(10);
-      else
-        internal_sched_yield();
-      if (atomic_load(&state_, memory_order_relaxed) == 0
-          && atomic_exchange(&state_, 1, memory_order_acquire) == 0)
-        return;
-    }
-  }
+  void LockSlow();
 };
 
-class SpinMutex : public StaticSpinMutex {
+class MUTEX SpinMutex : public StaticSpinMutex {
  public:
   SpinMutex() {
     Init();
   }
 
+  SpinMutex(const SpinMutex &) = delete;
+  void operator=(const SpinMutex &) = delete;
+};
+
+// Semaphore provides an OS-dependent way to park/unpark threads.
+// The last thread returned from Wait can destroy the object
+// (destruction-safety).
+class Semaphore {
+ public:
+  constexpr Semaphore() {}
+  Semaphore(const Semaphore &) = delete;
+  void operator=(const Semaphore &) = delete;
+
+  void Wait();
+  void Post(u32 count = 1);
+
  private:
-  SpinMutex(const SpinMutex&);
-  void operator=(const SpinMutex&);
+  atomic_uint32_t state_ = {0};
 };
 
-class BlockingMutex {
+typedef int MutexType;
+
+enum {
+  // Used as sentinel and to catch unassigned types
+  // (should not be used as real Mutex type).
+  MutexInvalid = 0,
+  MutexThreadRegistry,
+  // Each tool own mutexes must start at this number.
+  MutexLastCommon,
+  // Type for legacy mutexes that are not checked for deadlocks.
+  MutexUnchecked = -1,
+  // Special marks that can be used in MutexMeta::can_lock table.
+  // The leaf mutexes can be locked under any other non-leaf mutex,
+  // but no other mutex can be locked while under a leaf mutex.
+  MutexLeaf = -1,
+  // Multiple mutexes of this type can be locked at the same time.
+  MutexMulti = -3,
+};
+
+// Go linker does not support THREADLOCAL variables,
+// so we can't use per-thread state.
+#define SANITIZER_CHECK_DEADLOCKS (SANITIZER_DEBUG && !SANITIZER_GO)
+
+#if SANITIZER_CHECK_DEADLOCKS
+struct MutexMeta {
+  MutexType type;
+  const char *name;
+  // The table fixes what mutexes can be locked under what mutexes.
+  // If the entry for MutexTypeFoo contains MutexTypeBar,
+  // then Bar mutex can be locked while under Foo mutex.
+  // Can also contain the special MutexLeaf/MutexMulti marks.
+  MutexType can_lock[10];
+};
+#endif
+
+class CheckedMutex {
+ public:
+  constexpr CheckedMutex(MutexType type)
+#if SANITIZER_CHECK_DEADLOCKS
+      : type_(type)
+#endif
+  {
+  }
+
+  ALWAYS_INLINE void Lock() {
+#if SANITIZER_CHECK_DEADLOCKS
+    LockImpl(GET_CALLER_PC());
+#endif
+  }
+
+  ALWAYS_INLINE void Unlock() {
+#if SANITIZER_CHECK_DEADLOCKS
+    UnlockImpl();
+#endif
+  }
+
+  // Checks that the current thread does not hold any mutexes
+  // (e.g. when returning from a runtime function to user code).
+  static void CheckNoLocks() {
+#if SANITIZER_CHECK_DEADLOCKS
+    CheckNoLocksImpl();
+#endif
+  }
+
+ private:
+#if SANITIZER_CHECK_DEADLOCKS
+  const MutexType type_;
+
+  void LockImpl(uptr pc);
+  void UnlockImpl();
+  static void CheckNoLocksImpl();
+#endif
+};
+
+// Reader-writer mutex.
+// Derive from CheckedMutex for the purposes of EBO.
+// We could make it a field marked with [[no_unique_address]],
+// but this attribute is not supported by some older compilers.
+class MUTEX Mutex : CheckedMutex {
+ public:
+  constexpr Mutex(MutexType type = MutexUnchecked) : CheckedMutex(type) {}
+
+  void Lock() ACQUIRE() {
+    CheckedMutex::Lock();
+    u64 reset_mask = ~0ull;
+    u64 state = atomic_load_relaxed(&state_);
+    const uptr kMaxSpinIters = 1500;
+    for (uptr spin_iters = 0;; spin_iters++) {
+      u64 new_state;
+      bool locked = (state & (kWriterLock | kReaderLockMask)) != 0;
+      if (LIKELY(!locked)) {
+        // The mutex is not read-/write-locked, try to lock.
+        new_state = (state | kWriterLock) & reset_mask;
+      } else if (spin_iters > kMaxSpinIters) {
+        // We've spun enough, increment waiting writers count and block.
+        // The counter will be decremented by whoever wakes us.
+        new_state = (state + kWaitingWriterInc) & reset_mask;
+      } else if ((state & kWriterSpinWait) == 0) {
+        // Active spinning, but denote our presence so that unlocking
+        // thread does not wake up other threads.
+        new_state = state | kWriterSpinWait;
+      } else {
+        // Active spinning.
+        state = atomic_load(&state_, memory_order_relaxed);
+        continue;
+      }
+      if (UNLIKELY(!atomic_compare_exchange_weak(&state_, &state, new_state,
+                                                 memory_order_acquire)))
+        continue;
+      if (LIKELY(!locked))
+        return;  // We've locked the mutex.
+      if (spin_iters > kMaxSpinIters) {
+        // We've incremented waiting writers, so now block.
+        writers_.Wait();
+        spin_iters = 0;
+        state = atomic_load(&state_, memory_order_relaxed);
+        DCHECK_NE(state & kWriterSpinWait, 0);
+      } else {
+        // We've set kWriterSpinWait, but we are still in active spinning.
+      }
+      // We either blocked and were unblocked,
+      // or we just spun but set kWriterSpinWait.
+      // Either way we need to reset kWriterSpinWait
+      // next time we take the lock or block again.
+      reset_mask = ~kWriterSpinWait;
+    }
+  }
+
+  void Unlock() RELEASE() {
+    CheckedMutex::Unlock();
+    bool wake_writer;
+    u64 wake_readers;
+    u64 new_state;
+    u64 state = atomic_load_relaxed(&state_);
+    do {
+      DCHECK_NE(state & kWriterLock, 0);
+      DCHECK_EQ(state & kReaderLockMask, 0);
+      new_state = state & ~kWriterLock;
+      wake_writer =
+          (state & kWriterSpinWait) == 0 && (state & kWaitingWriterMask) != 0;
+      if (wake_writer)
+        new_state = (new_state - kWaitingWriterInc) | kWriterSpinWait;
+      wake_readers =
+          (state & (kWriterSpinWait | kWaitingWriterMask)) != 0
+              ? 0
+              : ((state & kWaitingReaderMask) >> kWaitingReaderShift);
+      if (wake_readers)
+        new_state = (new_state & ~kWaitingReaderMask) +
+                    (wake_readers << kReaderLockShift);
+    } while (UNLIKELY(!atomic_compare_exchange_weak(&state_, &state, new_state,
+                                                    memory_order_release)));
+    if (UNLIKELY(wake_writer))
+      writers_.Post();
+    else if (UNLIKELY(wake_readers))
+      readers_.Post(wake_readers);
+  }
+
+  void ReadLock() ACQUIRE_SHARED() {
+    CheckedMutex::Lock();
+    bool locked;
+    u64 new_state;
+    u64 state = atomic_load_relaxed(&state_);
+    do {
+      locked =
+          (state & kReaderLockMask) == 0 &&
+          (state & (kWriterLock | kWriterSpinWait | kWaitingWriterMask)) != 0;
+      if (LIKELY(!locked))
+        new_state = state + kReaderLockInc;
+      else
+        new_state = state + kWaitingReaderInc;
+    } while (UNLIKELY(!atomic_compare_exchange_weak(&state_, &state, new_state,
+                                                    memory_order_acquire)));
+    if (UNLIKELY(locked))
+      readers_.Wait();
+    DCHECK_EQ(atomic_load_relaxed(&state_) & kWriterLock, 0);
+    DCHECK_NE(atomic_load_relaxed(&state_) & kReaderLockMask, 0);
+  }
+
+  void ReadUnlock() RELEASE_SHARED() {
+    CheckedMutex::Unlock();
+    bool wake;
+    u64 new_state;
+    u64 state = atomic_load_relaxed(&state_);
+    do {
+      DCHECK_NE(state & kReaderLockMask, 0);
+      DCHECK_EQ(state & (kWaitingReaderMask | kWriterLock), 0);
+      new_state = state - kReaderLockInc;
+      wake = (new_state & (kReaderLockMask | kWriterSpinWait)) == 0 &&
+             (new_state & kWaitingWriterMask) != 0;
+      if (wake)
+        new_state = (new_state - kWaitingWriterInc) | kWriterSpinWait;
+    } while (UNLIKELY(!atomic_compare_exchange_weak(&state_, &state, new_state,
+                                                    memory_order_release)));
+    if (UNLIKELY(wake))
+      writers_.Post();
+  }
+
+  // This function does not guarantee an explicit check that the calling thread
+  // is the thread which owns the mutex. This behavior, while more strictly
+  // correct, causes problems in cases like StopTheWorld, where a parent thread
+  // owns the mutex but a child checks that it is locked. Rather than
+  // maintaining complex state to work around those situations, the check only
+  // checks that the mutex is owned.
+  void CheckWriteLocked() const CHECK_LOCKED() {
+    CHECK(atomic_load(&state_, memory_order_relaxed) & kWriterLock);
+  }
+
+  void CheckLocked() const CHECK_LOCKED() { CheckWriteLocked(); }
+
+  void CheckReadLocked() const CHECK_LOCKED() {
+    CHECK(atomic_load(&state_, memory_order_relaxed) & kReaderLockMask);
+  }
+
+ private:
+  atomic_uint64_t state_ = {0};
+  Semaphore writers_;
+  Semaphore readers_;
+
+  // The state has 3 counters:
+  //  - number of readers holding the lock,
+  //    if non zero, the mutex is read-locked
+  //  - number of waiting readers,
+  //    if not zero, the mutex is write-locked
+  //  - number of waiting writers,
+  //    if non zero, the mutex is read- or write-locked
+  // And 2 flags:
+  //  - writer lock
+  //    if set, the mutex is write-locked
+  //  - a writer is awake and spin-waiting
+  //    the flag is used to prevent thundering herd problem
+  //    (new writers are not woken if this flag is set)
+  //
+  // Writer support active spinning, readers does not.
+  // But readers are more aggressive and always take the mutex
+  // if there are any other readers.
+  // Writers hand off the mutex to readers: after wake up readers
+  // already assume ownership of the mutex (don't need to do any
+  // state updates). But the mutex is not handed off to writers,
+  // after wake up writers compete to lock the mutex again.
+  // This is needed to allow repeated write locks even in presence
+  // of other blocked writers.
+  static constexpr u64 kCounterWidth = 20;
+  static constexpr u64 kReaderLockShift = 0;
+  static constexpr u64 kReaderLockInc = 1ull << kReaderLockShift;
+  static constexpr u64 kReaderLockMask = ((1ull << kCounterWidth) - 1)
+                                         << kReaderLockShift;
+  static constexpr u64 kWaitingReaderShift = kCounterWidth;
+  static constexpr u64 kWaitingReaderInc = 1ull << kWaitingReaderShift;
+  static constexpr u64 kWaitingReaderMask = ((1ull << kCounterWidth) - 1)
+                                            << kWaitingReaderShift;
+  static constexpr u64 kWaitingWriterShift = 2 * kCounterWidth;
+  static constexpr u64 kWaitingWriterInc = 1ull << kWaitingWriterShift;
+  static constexpr u64 kWaitingWriterMask = ((1ull << kCounterWidth) - 1)
+                                            << kWaitingWriterShift;
+  static constexpr u64 kWriterLock = 1ull << (3 * kCounterWidth);
+  static constexpr u64 kWriterSpinWait = 1ull << (3 * kCounterWidth + 1);
+
+  Mutex(const Mutex &) = delete;
+  void operator=(const Mutex &) = delete;
+};
+
+void FutexWait(atomic_uint32_t *p, u32 cmp);
+void FutexWake(atomic_uint32_t *p, u32 count);
+
+class MUTEX BlockingMutex {
  public:
   explicit constexpr BlockingMutex(LinkerInitialized)
       : opaque_storage_ {0, }, owner_ {0} {}
   BlockingMutex();
-  void Lock();
-  void Unlock();
+  void Lock() ACQUIRE();
+  void Unlock() RELEASE();
 
   // This function does not guarantee an explicit check that the calling thread
   // is the thread which owns the mutex. This behavior, while more strictly
@@ -85,7 +353,7 @@ class BlockingMutex {
   // maintaining complex state to work around those situations, the check only
   // checks that the mutex is owned, and assumes callers to be generally
   // well-behaved.
-  void CheckLocked();
+  void CheckLocked() const CHECK_LOCKED();
 
  private:
   // Solaris mutex_t has a member that requires 64-bit alignment.
@@ -94,7 +362,7 @@ class BlockingMutex {
 };
 
 // Reader-writer spin mutex.
-class RWMutex {
+class MUTEX RWMutex {
  public:
   RWMutex() {
     atomic_store(&state_, kUnlocked, memory_order_relaxed);
@@ -104,7 +372,7 @@ class RWMutex {
     CHECK_EQ(atomic_load(&state_, memory_order_relaxed), kUnlocked);
   }
 
-  void Lock() {
+  void Lock() ACQUIRE() {
     u32 cmp = kUnlocked;
     if (atomic_compare_exchange_strong(&state_, &cmp, kWriteLock,
                                        memory_order_acquire))
@@ -112,27 +380,27 @@ class RWMutex {
     LockSlow();
   }
 
-  void Unlock() {
+  void Unlock() RELEASE() {
     u32 prev = atomic_fetch_sub(&state_, kWriteLock, memory_order_release);
     DCHECK_NE(prev & kWriteLock, 0);
     (void)prev;
   }
 
-  void ReadLock() {
+  void ReadLock() ACQUIRE_SHARED() {
     u32 prev = atomic_fetch_add(&state_, kReadLock, memory_order_acquire);
     if ((prev & kWriteLock) == 0)
       return;
     ReadLockSlow();
   }
 
-  void ReadUnlock() {
+  void ReadUnlock() RELEASE_SHARED() {
     u32 prev = atomic_fetch_sub(&state_, kReadLock, memory_order_release);
     DCHECK_EQ(prev & kWriteLock, 0);
     DCHECK_GT(prev & ~kWriteLock, 0);
     (void)prev;
   }
 
-  void CheckLocked() {
+  void CheckLocked() const CHECK_LOCKED() {
     CHECK_NE(atomic_load(&state_, memory_order_relaxed), kUnlocked);
   }
 
@@ -171,52 +439,48 @@ class RWMutex {
     }
   }
 
-  RWMutex(const RWMutex&);
-  void operator = (const RWMutex&);
+  RWMutex(const RWMutex &) = delete;
+  void operator=(const RWMutex &) = delete;
 };
 
-template<typename MutexType>
-class GenericScopedLock {
+template <typename MutexType>
+class SCOPED_LOCK GenericScopedLock {
  public:
-  explicit GenericScopedLock(MutexType *mu)
-      : mu_(mu) {
+  explicit GenericScopedLock(MutexType *mu) ACQUIRE(mu) : mu_(mu) {
     mu_->Lock();
   }
 
-  ~GenericScopedLock() {
-    mu_->Unlock();
-  }
+  ~GenericScopedLock() RELEASE() { mu_->Unlock(); }
 
  private:
   MutexType *mu_;
 
-  GenericScopedLock(const GenericScopedLock&);
-  void operator=(const GenericScopedLock&);
+  GenericScopedLock(const GenericScopedLock &) = delete;
+  void operator=(const GenericScopedLock &) = delete;
 };
 
-template<typename MutexType>
-class GenericScopedReadLock {
+template <typename MutexType>
+class SCOPED_LOCK GenericScopedReadLock {
  public:
-  explicit GenericScopedReadLock(MutexType *mu)
-      : mu_(mu) {
+  explicit GenericScopedReadLock(MutexType *mu) ACQUIRE(mu) : mu_(mu) {
     mu_->ReadLock();
   }
 
-  ~GenericScopedReadLock() {
-    mu_->ReadUnlock();
-  }
+  ~GenericScopedReadLock() RELEASE() { mu_->ReadUnlock(); }
 
  private:
   MutexType *mu_;
 
-  GenericScopedReadLock(const GenericScopedReadLock&);
-  void operator=(const GenericScopedReadLock&);
+  GenericScopedReadLock(const GenericScopedReadLock &) = delete;
+  void operator=(const GenericScopedReadLock &) = delete;
 };
 
 typedef GenericScopedLock<StaticSpinMutex> SpinMutexLock;
 typedef GenericScopedLock<BlockingMutex> BlockingMutexLock;
 typedef GenericScopedLock<RWMutex> RWMutexLock;
 typedef GenericScopedReadLock<RWMutex> RWMutexReadLock;
+typedef GenericScopedLock<Mutex> Lock;
+typedef GenericScopedReadLock<Mutex> ReadLock;
 
 }  // namespace __sanitizer
 
lib/tsan/sanitizer_common/sanitizer_netbsd.cpp
@@ -105,11 +105,22 @@ uptr internal_munmap(void *addr, uptr length) {
   return _REAL(munmap, addr, length);
 }
 
+uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
+                     void *new_address) {
+  CHECK(false && "internal_mremap is unimplemented on NetBSD");
+  return 0;
+}
+
 int internal_mprotect(void *addr, uptr length, int prot) {
   DEFINE__REAL(int, mprotect, void *a, uptr b, int c);
   return _REAL(mprotect, addr, length, prot);
 }
 
+int internal_madvise(uptr addr, uptr length, int advice) {
+  DEFINE__REAL(int, madvise, void *a, uptr b, int c);
+  return _REAL(madvise, (void *)addr, length, advice);
+}
+
 uptr internal_close(fd_t fd) {
   CHECK(&_sys_close);
   return _sys_close(fd);
@@ -204,15 +215,12 @@ void internal__exit(int exitcode) {
   Die();  // Unreachable.
 }
 
-unsigned int internal_sleep(unsigned int seconds) {
+void internal_usleep(u64 useconds) {
   struct timespec ts;
-  ts.tv_sec = seconds;
-  ts.tv_nsec = 0;
+  ts.tv_sec = useconds / 1000000;
+  ts.tv_nsec = (useconds % 1000000) * 1000;
   CHECK(&_sys___nanosleep50);
-  int res = _sys___nanosleep50(&ts, &ts);
-  if (res)
-    return ts.tv_sec;
-  return 0;
+  _sys___nanosleep50(&ts, &ts);
 }
 
 uptr internal_execve(const char *filename, char *const argv[],
lib/tsan/sanitizer_common/sanitizer_openbsd.cpp
@@ -1,115 +0,0 @@
-//===-- sanitizer_openbsd.cpp ---------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is shared between various sanitizers' runtime libraries and
-// implements Solaris-specific functions.
-//===----------------------------------------------------------------------===//
-
-#include "sanitizer_platform.h"
-#if SANITIZER_OPENBSD
-
-#include <stdio.h>
-
-#include "sanitizer_common.h"
-#include "sanitizer_flags.h"
-#include "sanitizer_internal_defs.h"
-#include "sanitizer_libc.h"
-#include "sanitizer_placement_new.h"
-#include "sanitizer_platform_limits_posix.h"
-#include "sanitizer_procmaps.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <pthread.h>
-#include <sched.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/mman.h>
-#include <sys/shm.h>
-#include <sys/sysctl.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-extern char **environ;
-
-namespace __sanitizer {
-
-uptr internal_mmap(void *addr, size_t length, int prot, int flags, int fd,
-                   u64 offset) {
-  return (uptr)mmap(addr, length, prot, flags, fd, offset);
-}
-
-uptr internal_munmap(void *addr, uptr length) { return munmap(addr, length); }
-
-int internal_mprotect(void *addr, uptr length, int prot) {
-  return mprotect(addr, length, prot);
-}
-
-int internal_sysctlbyname(const char *sname, void *oldp, uptr *oldlenp,
-                          const void *newp, uptr newlen) {
-  Printf("internal_sysctlbyname not implemented for OpenBSD");
-  Die();
-  return 0;
-}
-
-uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
-  // On OpenBSD we cannot get the full path
-  struct kinfo_proc kp;
-  uptr kl;
-  const int Mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
-  if (internal_sysctl(Mib, ARRAY_SIZE(Mib), &kp, &kl, NULL, 0) != -1)
-    return internal_snprintf(buf,
-                             (KI_MAXCOMLEN < buf_len ? KI_MAXCOMLEN : buf_len),
-                             "%s", kp.p_comm);
-  return (uptr)0;
-}
-
-static void GetArgsAndEnv(char ***argv, char ***envp) {
-  uptr nargv;
-  uptr nenv;
-  int argvmib[4] = {CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV};
-  int envmib[4] = {CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ENV};
-  if (internal_sysctl(argvmib, 4, NULL, &nargv, NULL, 0) == -1) {
-    Printf("sysctl KERN_PROC_NARGV failed\n");
-    Die();
-  }
-  if (internal_sysctl(envmib, 4, NULL, &nenv, NULL, 0) == -1) {
-    Printf("sysctl KERN_PROC_NENV failed\n");
-    Die();
-  }
-  if (internal_sysctl(argvmib, 4, &argv, &nargv, NULL, 0) == -1) {
-    Printf("sysctl KERN_PROC_ARGV failed\n");
-    Die();
-  }
-  if (internal_sysctl(envmib, 4, &envp, &nenv, NULL, 0) == -1) {
-    Printf("sysctl KERN_PROC_ENV failed\n");
-    Die();
-  }
-}
-
-char **GetArgv() {
-  char **argv, **envp;
-  GetArgsAndEnv(&argv, &envp);
-  return argv;
-}
-
-char **GetEnviron() {
-  char **argv, **envp;
-  GetArgsAndEnv(&argv, &envp);
-  return envp;
-}
-
-void ReExec() {
-  UNIMPLEMENTED();
-}
-
-}  // namespace __sanitizer
-
-#endif  // SANITIZER_OPENBSD
lib/tsan/sanitizer_common/sanitizer_platform.h
@@ -13,10 +13,16 @@
 #define SANITIZER_PLATFORM_H
 
 #if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && \
-  !defined(__OpenBSD__) && !defined(__APPLE__) && !defined(_WIN32) && \
-  !defined(__Fuchsia__) && !defined(__rtems__) && \
-  !(defined(__sun__) && defined(__svr4__))
-# error "This operating system is not supported"
+    !defined(__APPLE__) && !defined(_WIN32) && !defined(__Fuchsia__) &&     \
+    !(defined(__sun__) && defined(__svr4__))
+#  error "This operating system is not supported"
+#endif
+
+// Get __GLIBC__ on a glibc platform. Exclude Android: features.h includes C
+// function declarations into a .S file which doesn't compile.
+// https://crbug.com/1162741
+#if __has_include(<features.h>) && !defined(__ANDROID__)
+#include <features.h>
 #endif
 
 #if defined(__linux__)
@@ -25,6 +31,12 @@
 # define SANITIZER_LINUX   0
 #endif
 
+#if defined(__GLIBC__)
+# define SANITIZER_GLIBC   1
+#else
+# define SANITIZER_GLIBC   0
+#endif
+
 #if defined(__FreeBSD__)
 # define SANITIZER_FREEBSD 1
 #else
@@ -37,12 +49,6 @@
 # define SANITIZER_NETBSD 0
 #endif
 
-#if defined(__OpenBSD__)
-# define SANITIZER_OPENBSD 1
-#else
-# define SANITIZER_OPENBSD 0
-#endif
-
 #if defined(__sun__) && defined(__svr4__)
 # define SANITIZER_SOLARIS 1
 #else
@@ -52,6 +58,11 @@
 #if defined(__APPLE__)
 # define SANITIZER_MAC     1
 # include <TargetConditionals.h>
+# if TARGET_OS_OSX
+#  define SANITIZER_OSX    1
+# else
+#  define SANITIZER_OSX    0
+# endif
 # if TARGET_OS_IPHONE
 #  define SANITIZER_IOS    1
 # else
@@ -66,6 +77,7 @@
 # define SANITIZER_MAC     0
 # define SANITIZER_IOS     0
 # define SANITIZER_IOSSIM  0
+# define SANITIZER_OSX     0
 #endif
 
 #if defined(__APPLE__) && TARGET_OS_IPHONE && TARGET_OS_WATCH
@@ -104,15 +116,9 @@
 # define SANITIZER_FUCHSIA 0
 #endif
 
-#if defined(__rtems__)
-# define SANITIZER_RTEMS 1
-#else
-# define SANITIZER_RTEMS 0
-#endif
-
 #define SANITIZER_POSIX \
   (SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_MAC || \
-    SANITIZER_NETBSD || SANITIZER_OPENBSD || SANITIZER_SOLARIS)
+    SANITIZER_NETBSD || SANITIZER_SOLARIS)
 
 #if __LP64__ || defined(_WIN64)
 #  define SANITIZER_WORDSIZE 64
@@ -213,10 +219,10 @@
 # define SANITIZER_SOLARIS32 0
 #endif
 
-#if defined(__myriad2__)
-# define SANITIZER_MYRIAD2 1
+#if defined(__riscv) && (__riscv_xlen == 64)
+#define SANITIZER_RISCV64 1
 #else
-# define SANITIZER_MYRIAD2 0
+#define SANITIZER_RISCV64 0
 #endif
 
 // By default we allow to use SizeClassAllocator64 on 64-bit platform.
@@ -238,11 +244,21 @@
 // FIXME: this value should be different on different platforms.  Larger values
 // will still work but will consume more memory for TwoLevelByteMap.
 #if defined(__mips__)
+#if SANITIZER_GO && defined(__mips64)
+#define SANITIZER_MMAP_RANGE_SIZE FIRST_32_SECOND_64(1ULL << 32, 1ULL << 47)
+#else
 # define SANITIZER_MMAP_RANGE_SIZE FIRST_32_SECOND_64(1ULL << 32, 1ULL << 40)
+#endif
+#elif SANITIZER_RISCV64
+#define SANITIZER_MMAP_RANGE_SIZE FIRST_32_SECOND_64(1ULL << 32, 1ULL << 38)
 #elif defined(__aarch64__)
 # if SANITIZER_MAC
-// Darwin iOS/ARM64 has a 36-bit VMA, 64GiB VM
-#  define SANITIZER_MMAP_RANGE_SIZE FIRST_32_SECOND_64(1ULL << 32, 1ULL << 36)
+#  if SANITIZER_OSX || SANITIZER_IOSSIM
+#   define SANITIZER_MMAP_RANGE_SIZE FIRST_32_SECOND_64(1ULL << 32, 1ULL << 47)
+#  else
+    // Darwin iOS/ARM64 has a 36-bit VMA, 64GiB VM
+#   define SANITIZER_MMAP_RANGE_SIZE FIRST_32_SECOND_64(1ULL << 32, 1ULL << 36)
+#  endif
 # else
 #  define SANITIZER_MMAP_RANGE_SIZE FIRST_32_SECOND_64(1ULL << 32, 1ULL << 48)
 # endif
@@ -331,7 +347,7 @@
 #endif
 
 #if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_NETBSD || \
-  SANITIZER_OPENBSD || SANITIZER_SOLARIS
+  SANITIZER_SOLARIS
 # define SANITIZER_MADVISE_DONTNEED MADV_FREE
 #else
 # define SANITIZER_MADVISE_DONTNEED MADV_DONTNEED
@@ -345,9 +361,9 @@
 # define SANITIZER_CACHE_LINE_SIZE 64
 #endif
 
-// Enable offline markup symbolizer for Fuchsia and RTEMS.
-#if SANITIZER_FUCHSIA || SANITIZER_RTEMS
-#define SANITIZER_SYMBOLIZER_MARKUP 1
+// Enable offline markup symbolizer for Fuchsia.
+#if SANITIZER_FUCHSIA
+#  define SANITIZER_SYMBOLIZER_MARKUP 1
 #else
 #define SANITIZER_SYMBOLIZER_MARKUP 0
 #endif
lib/tsan/sanitizer_common/sanitizer_platform_interceptors.h
@@ -15,133 +15,127 @@
 
 #include "sanitizer_glibc_version.h"
 #include "sanitizer_internal_defs.h"
+#include "sanitizer_platform.h"
 
 #if SANITIZER_POSIX
-# define SI_POSIX 1
+#define SI_POSIX 1
 #else
-# define SI_POSIX 0
+#define SI_POSIX 0
 #endif
 
 #if !SANITIZER_WINDOWS
-# define SI_WINDOWS 0
+#define SI_WINDOWS 0
 #else
-# define SI_WINDOWS 1
+#define SI_WINDOWS 1
 #endif
 
 #if SI_WINDOWS && SI_POSIX
-# error "Windows is not POSIX!"
+#error "Windows is not POSIX!"
 #endif
 
 #if SI_POSIX
-# include "sanitizer_platform_limits_freebsd.h"
-# include "sanitizer_platform_limits_netbsd.h"
-# include "sanitizer_platform_limits_openbsd.h"
-# include "sanitizer_platform_limits_posix.h"
-# include "sanitizer_platform_limits_solaris.h"
+#include "sanitizer_platform_limits_freebsd.h"
+#include "sanitizer_platform_limits_netbsd.h"
+#include "sanitizer_platform_limits_posix.h"
+#include "sanitizer_platform_limits_solaris.h"
 #endif
 
 #if SANITIZER_LINUX && !SANITIZER_ANDROID
-# define SI_LINUX_NOT_ANDROID 1
+#define SI_LINUX_NOT_ANDROID 1
 #else
-# define SI_LINUX_NOT_ANDROID 0
+#define SI_LINUX_NOT_ANDROID 0
 #endif
 
-#if SANITIZER_ANDROID
-# define SI_ANDROID 1
+#if SANITIZER_GLIBC
+#define SI_GLIBC 1
 #else
-# define SI_ANDROID 0
+#define SI_GLIBC 0
 #endif
 
-#if SANITIZER_FREEBSD
-# define SI_FREEBSD 1
+#if SANITIZER_ANDROID
+#define SI_ANDROID 1
 #else
-# define SI_FREEBSD 0
+#define SI_ANDROID 0
 #endif
 
-#if SANITIZER_NETBSD
-# define SI_NETBSD 1
+#if SANITIZER_FREEBSD
+#define SI_FREEBSD 1
 #else
-# define SI_NETBSD 0
+#define SI_FREEBSD 0
 #endif
 
-#if SANITIZER_OPENBSD
-#define SI_OPENBSD 1
+#if SANITIZER_NETBSD
+#define SI_NETBSD 1
 #else
-#define SI_OPENBSD 0
+#define SI_NETBSD 0
 #endif
 
 #if SANITIZER_LINUX
-# define SI_LINUX 1
+#define SI_LINUX 1
 #else
-# define SI_LINUX 0
+#define SI_LINUX 0
 #endif
 
 #if SANITIZER_MAC
-# define SI_MAC 1
-# define SI_NOT_MAC 0
+#define SI_MAC 1
+#define SI_NOT_MAC 0
 #else
-# define SI_MAC 0
-# define SI_NOT_MAC 1
+#define SI_MAC 0
+#define SI_NOT_MAC 1
 #endif
 
 #if SANITIZER_IOS
-# define SI_IOS 1
+#define SI_IOS 1
 #else
-# define SI_IOS 0
+#define SI_IOS 0
 #endif
 
 #if SANITIZER_IOSSIM
-# define SI_IOSSIM 1
+#define SI_IOSSIM 1
 #else
-# define SI_IOSSIM 0
+#define SI_IOSSIM 0
 #endif
 
 #if SANITIZER_WATCHOS
-# define SI_WATCHOS 1
+#define SI_WATCHOS 1
 #else
-# define SI_WATCHOS 0
+#define SI_WATCHOS 0
 #endif
 
 #if SANITIZER_TVOS
-# define SI_TVOS 1
+#define SI_TVOS 1
 #else
-# define SI_TVOS 0
+#define SI_TVOS 0
 #endif
 
 #if SANITIZER_FUCHSIA
-# define SI_NOT_FUCHSIA 0
-#else
-# define SI_NOT_FUCHSIA 1
-#endif
-
-#if SANITIZER_RTEMS
-# define SI_NOT_RTEMS 0
+#define SI_NOT_FUCHSIA 0
 #else
-# define SI_NOT_RTEMS 1
+#define SI_NOT_FUCHSIA 1
 #endif
 
 #if SANITIZER_SOLARIS
-# define SI_SOLARIS 1
+#define SI_SOLARIS 1
 #else
-# define SI_SOLARIS 0
+#define SI_SOLARIS 0
 #endif
 
 #if SANITIZER_SOLARIS32
-# define SI_SOLARIS32 1
+#define SI_SOLARIS32 1
 #else
-# define SI_SOLARIS32 0
+#define SI_SOLARIS32 0
 #endif
 
 #if SANITIZER_POSIX && !SANITIZER_MAC
-# define SI_POSIX_NOT_MAC 1
+#define SI_POSIX_NOT_MAC 1
 #else
-# define SI_POSIX_NOT_MAC 0
+#define SI_POSIX_NOT_MAC 0
 #endif
 
 #if SANITIZER_LINUX && !SANITIZER_FREEBSD
-# define SI_LINUX_NOT_FREEBSD 1
-# else
-# define SI_LINUX_NOT_FREEBSD 0
+#define SI_LINUX_NOT_FREEBSD 1
+#else
+#define SI_LINUX_NOT_FREEBSD 0
 #endif
 
 #define SANITIZER_INTERCEPT_STRLEN SI_NOT_FUCHSIA
@@ -163,21 +157,20 @@
 #define SANITIZER_INTERCEPT_MEMCMP SI_NOT_FUCHSIA
 #define SANITIZER_INTERCEPT_BCMP \
   SANITIZER_INTERCEPT_MEMCMP &&  \
-      ((SI_POSIX && _GNU_SOURCE) || SI_NETBSD || SI_OPENBSD || SI_FREEBSD)
+      ((SI_POSIX && _GNU_SOURCE) || SI_NETBSD || SI_FREEBSD)
 #define SANITIZER_INTERCEPT_STRNDUP SI_POSIX
-#define SANITIZER_INTERCEPT___STRNDUP SI_LINUX_NOT_FREEBSD
+#define SANITIZER_INTERCEPT___STRNDUP SI_GLIBC
 #if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \
     __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070
-# define SI_MAC_DEPLOYMENT_BELOW_10_7 1
+#define SI_MAC_DEPLOYMENT_BELOW_10_7 1
 #else
-# define SI_MAC_DEPLOYMENT_BELOW_10_7 0
+#define SI_MAC_DEPLOYMENT_BELOW_10_7 0
 #endif
 // memmem on Darwin doesn't exist on 10.6
 // FIXME: enable memmem on Windows.
 #define SANITIZER_INTERCEPT_MEMMEM (SI_POSIX && !SI_MAC_DEPLOYMENT_BELOW_10_7)
 #define SANITIZER_INTERCEPT_MEMCHR SI_NOT_FUCHSIA
-#define SANITIZER_INTERCEPT_MEMRCHR \
-  (SI_FREEBSD || SI_LINUX || SI_NETBSD || SI_OPENBSD)
+#define SANITIZER_INTERCEPT_MEMRCHR (SI_FREEBSD || SI_LINUX || SI_NETBSD)
 
 #define SANITIZER_INTERCEPT_READ SI_POSIX
 #define SANITIZER_INTERCEPT_PREAD SI_POSIX
@@ -190,64 +183,60 @@
 #define SANITIZER_INTERCEPT_FPUTS SI_POSIX
 #define SANITIZER_INTERCEPT_PUTS SI_POSIX
 
-#define SANITIZER_INTERCEPT_PREAD64 SI_LINUX_NOT_ANDROID || SI_SOLARIS32
-#define SANITIZER_INTERCEPT_PWRITE64 SI_LINUX_NOT_ANDROID || SI_SOLARIS32
+#define SANITIZER_INTERCEPT_PREAD64 (SI_GLIBC || SI_SOLARIS32)
+#define SANITIZER_INTERCEPT_PWRITE64 (SI_GLIBC || SI_SOLARIS32)
 
 #define SANITIZER_INTERCEPT_READV SI_POSIX
 #define SANITIZER_INTERCEPT_WRITEV SI_POSIX
 
 #define SANITIZER_INTERCEPT_PREADV \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID)
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID)
 #define SANITIZER_INTERCEPT_PWRITEV SI_LINUX_NOT_ANDROID
-#define SANITIZER_INTERCEPT_PREADV64 SI_LINUX_NOT_ANDROID
-#define SANITIZER_INTERCEPT_PWRITEV64 SI_LINUX_NOT_ANDROID
+#define SANITIZER_INTERCEPT_PREADV64 SI_GLIBC
+#define SANITIZER_INTERCEPT_PWRITEV64 SI_GLIBC
 
-#define SANITIZER_INTERCEPT_PRCTL   SI_LINUX
+#define SANITIZER_INTERCEPT_PRCTL SI_LINUX
 
 #define SANITIZER_INTERCEPT_LOCALTIME_AND_FRIENDS SI_POSIX
 #define SANITIZER_INTERCEPT_STRPTIME SI_POSIX
 
 #define SANITIZER_INTERCEPT_SCANF SI_POSIX
-#define SANITIZER_INTERCEPT_ISOC99_SCANF SI_LINUX_NOT_ANDROID
+#define SANITIZER_INTERCEPT_ISOC99_SCANF SI_GLIBC
 
 #ifndef SANITIZER_INTERCEPT_PRINTF
-# define SANITIZER_INTERCEPT_PRINTF SI_POSIX
-# define SANITIZER_INTERCEPT_PRINTF_L (SI_FREEBSD || SI_NETBSD)
-# define SANITIZER_INTERCEPT_ISOC99_PRINTF SI_LINUX_NOT_ANDROID
+#define SANITIZER_INTERCEPT_PRINTF SI_POSIX
+#define SANITIZER_INTERCEPT_PRINTF_L (SI_FREEBSD || SI_NETBSD)
+#define SANITIZER_INTERCEPT_ISOC99_PRINTF SI_GLIBC
 #endif
 
 #define SANITIZER_INTERCEPT___PRINTF_CHK \
-  (SANITIZER_INTERCEPT_PRINTF && SI_LINUX_NOT_ANDROID)
+  (SANITIZER_INTERCEPT_PRINTF && SI_GLIBC)
 
 #define SANITIZER_INTERCEPT_FREXP SI_NOT_FUCHSIA
 #define SANITIZER_INTERCEPT_FREXPF_FREXPL SI_POSIX
 
 #define SANITIZER_INTERCEPT_GETPWNAM_AND_FRIENDS SI_POSIX
-#define SANITIZER_INTERCEPT_GETPWNAM_R_AND_FRIENDS                            \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_MAC || SI_LINUX_NOT_ANDROID || \
-  SI_SOLARIS)
-#define SANITIZER_INTERCEPT_GETPWENT                                          \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_MAC || SI_LINUX_NOT_ANDROID || \
-  SI_SOLARIS)
-#define SANITIZER_INTERCEPT_FGETGRENT_R                                       \
-  (SI_FREEBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_GETPWNAM_R_AND_FRIENDS \
+  (SI_FREEBSD || SI_NETBSD || SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_GETPWENT \
+  (SI_FREEBSD || SI_NETBSD || SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_FGETGRENT_R (SI_GLIBC || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_FGETPWENT SI_LINUX_NOT_ANDROID || SI_SOLARIS
 #define SANITIZER_INTERCEPT_GETPWENT_R \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
-#define SANITIZER_INTERCEPT_FGETPWENT_R \
-  (SI_FREEBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+  (SI_FREEBSD || SI_NETBSD || SI_GLIBC || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_FGETPWENT_R (SI_FREEBSD || SI_GLIBC || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_SETPWENT \
   (SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_CLOCK_GETTIME \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX || SI_SOLARIS)
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_CLOCK_GETCPUCLOCKID SI_LINUX
 #define SANITIZER_INTERCEPT_GETITIMER SI_POSIX
 #define SANITIZER_INTERCEPT_TIME SI_POSIX
-#define SANITIZER_INTERCEPT_GLOB SI_LINUX_NOT_ANDROID || SI_SOLARIS
-#define SANITIZER_INTERCEPT_GLOB64 SI_LINUX_NOT_ANDROID
+#define SANITIZER_INTERCEPT_GLOB (SI_GLIBC || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_GLOB64 SI_GLIBC
 #define SANITIZER_INTERCEPT_WAIT SI_POSIX
 #define SANITIZER_INTERCEPT_INET SI_POSIX
-#define SANITIZER_INTERCEPT_PTHREAD_GETSCHEDPARAM (SI_POSIX && !SI_OPENBSD)
+#define SANITIZER_INTERCEPT_PTHREAD_GETSCHEDPARAM SI_POSIX
 #define SANITIZER_INTERCEPT_GETADDRINFO SI_POSIX
 #define SANITIZER_INTERCEPT_GETNAMEINFO SI_POSIX
 #define SANITIZER_INTERCEPT_GETSOCKNAME SI_POSIX
@@ -259,12 +248,10 @@
   (SI_FREEBSD || SI_LINUX_NOT_ANDROID)
 #define SANITIZER_INTERCEPT_GETHOSTBYADDR_R \
   (SI_FREEBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
-#define SANITIZER_INTERCEPT_GETHOSTENT_R \
-  (SI_FREEBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_GETHOSTENT_R (SI_FREEBSD || SI_GLIBC || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_GETSOCKOPT SI_POSIX
 #define SANITIZER_INTERCEPT_ACCEPT SI_POSIX
-#define SANITIZER_INTERCEPT_ACCEPT4 \
-  (SI_LINUX_NOT_ANDROID || SI_NETBSD || SI_OPENBSD)
+#define SANITIZER_INTERCEPT_ACCEPT4 (SI_LINUX_NOT_ANDROID || SI_NETBSD)
 #define SANITIZER_INTERCEPT_PACCEPT SI_NETBSD
 #define SANITIZER_INTERCEPT_MODF SI_POSIX
 #define SANITIZER_INTERCEPT_RECVMSG SI_POSIX
@@ -278,10 +265,10 @@
 #define SANITIZER_INTERCEPT_SYSINFO SI_LINUX
 #define SANITIZER_INTERCEPT_READDIR SI_POSIX
 #define SANITIZER_INTERCEPT_READDIR64 SI_LINUX_NOT_ANDROID || SI_SOLARIS32
-#if SI_LINUX_NOT_ANDROID && \
-  (defined(__i386) || defined(__x86_64) || defined(__mips64) || \
-    defined(__powerpc64__) || defined(__aarch64__) || defined(__arm__) || \
-    defined(__s390__))
+#if SI_LINUX_NOT_ANDROID &&                                                \
+    (defined(__i386) || defined(__x86_64) || defined(__mips64) ||          \
+     defined(__powerpc64__) || defined(__aarch64__) || defined(__arm__) || \
+     defined(__s390__) || SANITIZER_RISCV64)
 #define SANITIZER_INTERCEPT_PTRACE 1
 #else
 #define SANITIZER_INTERCEPT_PTRACE 0
@@ -298,46 +285,42 @@
 #define SANITIZER_INTERCEPT___STRXFRM_L SI_LINUX
 #define SANITIZER_INTERCEPT_WCSXFRM SI_POSIX
 #define SANITIZER_INTERCEPT___WCSXFRM_L SI_LINUX
-#define SANITIZER_INTERCEPT_WCSNRTOMBS                                        \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_MAC || SI_LINUX_NOT_ANDROID || \
-  SI_SOLARIS)
-#define SANITIZER_INTERCEPT_WCRTOMB                                           \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_MAC || SI_LINUX_NOT_ANDROID || \
-  SI_SOLARIS)
-#define SANITIZER_INTERCEPT_WCTOMB                                           \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_MAC || SI_LINUX_NOT_ANDROID || \
-  SI_SOLARIS)
+#define SANITIZER_INTERCEPT_WCSNRTOMBS \
+  (SI_FREEBSD || SI_NETBSD || SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_WCRTOMB \
+  (SI_FREEBSD || SI_NETBSD || SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_WCTOMB \
+  (SI_FREEBSD || SI_NETBSD || SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_TCGETATTR SI_LINUX_NOT_ANDROID || SI_SOLARIS
 #define SANITIZER_INTERCEPT_REALPATH SI_POSIX
-#define SANITIZER_INTERCEPT_CANONICALIZE_FILE_NAME \
-  (SI_LINUX_NOT_ANDROID || SI_SOLARIS)
-#define SANITIZER_INTERCEPT_CONFSTR                                           \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_MAC || SI_LINUX_NOT_ANDROID || \
-  SI_SOLARIS)
+#define SANITIZER_INTERCEPT_CANONICALIZE_FILE_NAME (SI_GLIBC || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_CONFSTR \
+  (SI_FREEBSD || SI_NETBSD || SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_SCHED_GETAFFINITY SI_LINUX_NOT_ANDROID
 #define SANITIZER_INTERCEPT_SCHED_GETPARAM SI_LINUX_NOT_ANDROID || SI_SOLARIS
 #define SANITIZER_INTERCEPT_STRERROR SI_POSIX
 #define SANITIZER_INTERCEPT_STRERROR_R SI_POSIX
 #define SANITIZER_INTERCEPT_XPG_STRERROR_R SI_LINUX_NOT_ANDROID
 #define SANITIZER_INTERCEPT_SCANDIR \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_SCANDIR64 SI_LINUX_NOT_ANDROID || SI_SOLARIS32
 #define SANITIZER_INTERCEPT_GETGROUPS SI_POSIX
 #define SANITIZER_INTERCEPT_POLL SI_POSIX
 #define SANITIZER_INTERCEPT_PPOLL SI_LINUX_NOT_ANDROID || SI_SOLARIS
-#define SANITIZER_INTERCEPT_WORDEXP \
+#define SANITIZER_INTERCEPT_WORDEXP                                          \
   (SI_FREEBSD || SI_NETBSD || (SI_MAC && !SI_IOS) || SI_LINUX_NOT_ANDROID || \
-    SI_SOLARIS)
+   SI_SOLARIS)  // NOLINT
 #define SANITIZER_INTERCEPT_SIGWAIT SI_POSIX
 #define SANITIZER_INTERCEPT_SIGWAITINFO SI_LINUX_NOT_ANDROID || SI_SOLARIS
 #define SANITIZER_INTERCEPT_SIGTIMEDWAIT SI_LINUX_NOT_ANDROID || SI_SOLARIS
 #define SANITIZER_INTERCEPT_SIGSETOPS \
   (SI_FREEBSD || SI_NETBSD || SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_SIGSET_LOGICOPS SI_LINUX_NOT_ANDROID
 #define SANITIZER_INTERCEPT_SIGPENDING SI_POSIX
 #define SANITIZER_INTERCEPT_SIGPROCMASK SI_POSIX
 #define SANITIZER_INTERCEPT_PTHREAD_SIGMASK SI_POSIX
 #define SANITIZER_INTERCEPT_BACKTRACE \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+  (SI_FREEBSD || SI_NETBSD || SI_GLIBC || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_GETMNTENT SI_LINUX
 #define SANITIZER_INTERCEPT_GETMNTENT_R SI_LINUX_NOT_ANDROID
 #define SANITIZER_INTERCEPT_STATFS \
@@ -345,25 +328,25 @@
 #define SANITIZER_INTERCEPT_STATFS64 \
   (((SI_MAC && !TARGET_CPU_ARM64) && !SI_IOS) || SI_LINUX_NOT_ANDROID)
 #define SANITIZER_INTERCEPT_STATVFS \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID)
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID)
 #define SANITIZER_INTERCEPT_STATVFS64 SI_LINUX_NOT_ANDROID
 #define SANITIZER_INTERCEPT_INITGROUPS SI_POSIX
-#define SANITIZER_INTERCEPT_ETHER_NTOA_ATON (SI_POSIX && !SI_OPENBSD)
+#define SANITIZER_INTERCEPT_ETHER_NTOA_ATON SI_POSIX
 #define SANITIZER_INTERCEPT_ETHER_HOST \
   (SI_FREEBSD || SI_MAC || SI_LINUX_NOT_ANDROID)
 #define SANITIZER_INTERCEPT_ETHER_R (SI_FREEBSD || SI_LINUX_NOT_ANDROID)
 #define SANITIZER_INTERCEPT_SHMCTL                                       \
   (((SI_FREEBSD || SI_LINUX_NOT_ANDROID) && SANITIZER_WORDSIZE == 64) || \
-   SI_NETBSD || SI_OPENBSD || SI_SOLARIS)  // NOLINT
-#define SANITIZER_INTERCEPT_RANDOM_R SI_LINUX_NOT_ANDROID
+   SI_NETBSD || SI_SOLARIS)  // NOLINT
+#define SANITIZER_INTERCEPT_RANDOM_R SI_GLIBC
 #define SANITIZER_INTERCEPT_PTHREAD_ATTR_GET SI_POSIX
 #define SANITIZER_INTERCEPT_PTHREAD_ATTR_GETINHERITSCHED \
   (SI_FREEBSD || SI_NETBSD || SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
-#define SANITIZER_INTERCEPT_PTHREAD_ATTR_GETAFFINITY_NP SI_LINUX_NOT_ANDROID
-#define SANITIZER_INTERCEPT_PTHREAD_ATTR_GET_SCHED (SI_POSIX && !SI_OPENBSD)
+#define SANITIZER_INTERCEPT_PTHREAD_ATTR_GETAFFINITY_NP SI_GLIBC
+#define SANITIZER_INTERCEPT_PTHREAD_ATTR_GET_SCHED SI_POSIX
 #define SANITIZER_INTERCEPT_PTHREAD_MUTEXATTR_GETPSHARED \
-  (SI_POSIX && !SI_NETBSD && !SI_OPENBSD)
-#define SANITIZER_INTERCEPT_PTHREAD_MUTEXATTR_GETTYPE (SI_POSIX && !SI_OPENBSD)
+  (SI_POSIX && !SI_NETBSD)
+#define SANITIZER_INTERCEPT_PTHREAD_MUTEXATTR_GETTYPE SI_POSIX
 #define SANITIZER_INTERCEPT_PTHREAD_MUTEXATTR_GETPROTOCOL \
   (SI_MAC || SI_NETBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_PTHREAD_MUTEXATTR_GETPRIOCEILING \
@@ -372,17 +355,18 @@
   (SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_PTHREAD_MUTEXATTR_GETROBUST_NP SI_LINUX_NOT_ANDROID
 #define SANITIZER_INTERCEPT_PTHREAD_RWLOCKATTR_GETPSHARED \
-  (SI_POSIX && !SI_NETBSD && !SI_OPENBSD)
-#define SANITIZER_INTERCEPT_PTHREAD_RWLOCKATTR_GETKIND_NP SI_LINUX_NOT_ANDROID
-#define SANITIZER_INTERCEPT_PTHREAD_CONDATTR_GETPSHARED \
-  (SI_POSIX && !SI_NETBSD && !SI_OPENBSD)
+  (SI_POSIX && !SI_NETBSD)
+#define SANITIZER_INTERCEPT_PTHREAD_RWLOCKATTR_GETKIND_NP SI_GLIBC
+#define SANITIZER_INTERCEPT_PTHREAD_CONDATTR_GETPSHARED (SI_POSIX && !SI_NETBSD)
 #define SANITIZER_INTERCEPT_PTHREAD_CONDATTR_GETCLOCK \
   (SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_PTHREAD_BARRIERATTR_GETPSHARED \
-  (SI_LINUX_NOT_ANDROID && !SI_NETBSD && !SI_OPENBSD)
+  (SI_LINUX_NOT_ANDROID && !SI_NETBSD)
 #define SANITIZER_INTERCEPT_THR_EXIT SI_FREEBSD
 #define SANITIZER_INTERCEPT_TMPNAM SI_POSIX
-#define SANITIZER_INTERCEPT_TMPNAM_R SI_LINUX_NOT_ANDROID || SI_SOLARIS
+#define SANITIZER_INTERCEPT_TMPNAM_R (SI_GLIBC || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_PTSNAME SI_LINUX
+#define SANITIZER_INTERCEPT_PTSNAME_R SI_LINUX
 #define SANITIZER_INTERCEPT_TTYNAME SI_POSIX
 #define SANITIZER_INTERCEPT_TTYNAME_R SI_POSIX
 #define SANITIZER_INTERCEPT_TEMPNAM SI_POSIX
@@ -393,71 +377,67 @@
 #define SANITIZER_INTERCEPT_LGAMMAL (SI_POSIX && !SI_NETBSD)
 #define SANITIZER_INTERCEPT_LGAMMA_R (SI_FREEBSD || SI_LINUX || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_LGAMMAL_R SI_LINUX_NOT_ANDROID || SI_SOLARIS
-#define SANITIZER_INTERCEPT_DRAND48_R SI_LINUX_NOT_ANDROID
-#define SANITIZER_INTERCEPT_RAND_R                                            \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_MAC || SI_LINUX_NOT_ANDROID || \
-  SI_SOLARIS)
+#define SANITIZER_INTERCEPT_DRAND48_R SI_GLIBC
+#define SANITIZER_INTERCEPT_RAND_R \
+  (SI_FREEBSD || SI_NETBSD || SI_MAC || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_ICONV \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_TIMES SI_POSIX
 
 // FIXME: getline seems to be available on OSX 10.7
 #define SANITIZER_INTERCEPT_GETLINE \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 
 #define SANITIZER_INTERCEPT__EXIT \
-  (SI_LINUX || SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_MAC || SI_SOLARIS)
+  (SI_LINUX || SI_FREEBSD || SI_NETBSD || SI_MAC || SI_SOLARIS)
 
 #define SANITIZER_INTERCEPT_PTHREAD_MUTEX SI_POSIX
-#define SANITIZER_INTERCEPT___PTHREAD_MUTEX SI_LINUX_NOT_ANDROID
+#define SANITIZER_INTERCEPT___PTHREAD_MUTEX SI_GLIBC
 #define SANITIZER_INTERCEPT___LIBC_MUTEX SI_NETBSD
 #define SANITIZER_INTERCEPT_PTHREAD_SETNAME_NP \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+  (SI_FREEBSD || SI_NETBSD || SI_GLIBC || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_PTHREAD_GETNAME_NP \
-  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+  (SI_FREEBSD || SI_NETBSD || SI_GLIBC || SI_SOLARIS)
 
 #define SANITIZER_INTERCEPT_TLS_GET_ADDR \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID || SI_SOLARIS)
 
 #define SANITIZER_INTERCEPT_LISTXATTR SI_LINUX
 #define SANITIZER_INTERCEPT_GETXATTR SI_LINUX
 #define SANITIZER_INTERCEPT_GETRESID SI_LINUX
-#define SANITIZER_INTERCEPT_GETIFADDRS                                        \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_MAC || \
-  SI_SOLARIS)
-#define SANITIZER_INTERCEPT_IF_INDEXTONAME                                    \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_MAC || \
-  SI_SOLARIS)
+#define SANITIZER_INTERCEPT_GETIFADDRS \
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID || SI_MAC || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_IF_INDEXTONAME \
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID || SI_MAC || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_CAPGET SI_LINUX_NOT_ANDROID
 #if SI_LINUX && defined(__arm__)
 #define SANITIZER_INTERCEPT_AEABI_MEM 1
 #else
 #define SANITIZER_INTERCEPT_AEABI_MEM 0
 #endif
-#define SANITIZER_INTERCEPT___BZERO SI_MAC || SI_LINUX_NOT_ANDROID
+#define SANITIZER_INTERCEPT___BZERO SI_MAC || SI_GLIBC
 #define SANITIZER_INTERCEPT_BZERO SI_LINUX_NOT_ANDROID
-#define SANITIZER_INTERCEPT_FTIME \
-  (!SI_FREEBSD && !SI_NETBSD && !SI_OPENBSD && SI_POSIX)
-#define SANITIZER_INTERCEPT_XDR SI_LINUX_NOT_ANDROID || SI_SOLARIS
+#define SANITIZER_INTERCEPT_FTIME (!SI_FREEBSD && !SI_NETBSD && SI_POSIX)
+#define SANITIZER_INTERCEPT_XDR (SI_GLIBC || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_XDRREC SI_GLIBC
 #define SANITIZER_INTERCEPT_TSEARCH \
-  (SI_LINUX_NOT_ANDROID || SI_MAC || SI_NETBSD || SI_OPENBSD || SI_SOLARIS)
-#define SANITIZER_INTERCEPT_LIBIO_INTERNALS SI_LINUX_NOT_ANDROID
+  (SI_LINUX_NOT_ANDROID || SI_MAC || SI_NETBSD || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_LIBIO_INTERNALS SI_GLIBC
 #define SANITIZER_INTERCEPT_FOPEN SI_POSIX
-#define SANITIZER_INTERCEPT_FOPEN64 SI_LINUX_NOT_ANDROID || SI_SOLARIS32
+#define SANITIZER_INTERCEPT_FOPEN64 (SI_GLIBC || SI_SOLARIS32)
 #define SANITIZER_INTERCEPT_OPEN_MEMSTREAM \
-  (SI_LINUX_NOT_ANDROID || SI_NETBSD || SI_OPENBSD || SI_SOLARIS)
-#define SANITIZER_INTERCEPT_OBSTACK SI_LINUX_NOT_ANDROID
+  (SI_LINUX_NOT_ANDROID || SI_NETBSD || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_OBSTACK SI_GLIBC
 #define SANITIZER_INTERCEPT_FFLUSH SI_POSIX
 #define SANITIZER_INTERCEPT_FCLOSE SI_POSIX
 
 #ifndef SANITIZER_INTERCEPT_DLOPEN_DLCLOSE
-#define SANITIZER_INTERCEPT_DLOPEN_DLCLOSE                                    \
-  (SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_LINUX_NOT_ANDROID || SI_MAC || \
-  SI_SOLARIS)
+#define SANITIZER_INTERCEPT_DLOPEN_DLCLOSE \
+  (SI_FREEBSD || SI_NETBSD || SI_LINUX_NOT_ANDROID || SI_MAC || SI_SOLARIS)
 #endif
 
 #define SANITIZER_INTERCEPT_GETPASS \
-  (SI_LINUX_NOT_ANDROID || SI_MAC || SI_NETBSD || SI_OPENBSD)
+  (SI_LINUX_NOT_ANDROID || SI_MAC || SI_NETBSD)
 #define SANITIZER_INTERCEPT_TIMERFD SI_LINUX_NOT_ANDROID
 
 #define SANITIZER_INTERCEPT_MLOCKX SI_POSIX
@@ -465,21 +445,20 @@
 #define SANITIZER_INTERCEPT_SEM \
   (SI_LINUX || SI_FREEBSD || SI_NETBSD || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_PTHREAD_SETCANCEL SI_POSIX
-#define SANITIZER_INTERCEPT_MINCORE \
-  (SI_LINUX || SI_NETBSD || SI_OPENBSD || SI_SOLARIS)
+#define SANITIZER_INTERCEPT_MINCORE (SI_LINUX || SI_NETBSD || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_PROCESS_VM_READV SI_LINUX
 #define SANITIZER_INTERCEPT_CTERMID \
-  (SI_LINUX || SI_MAC || SI_FREEBSD || SI_NETBSD || SI_OPENBSD || SI_SOLARIS)
+  (SI_LINUX || SI_MAC || SI_FREEBSD || SI_NETBSD || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_CTERMID_R (SI_MAC || SI_FREEBSD || SI_SOLARIS)
 
 #define SANITIZER_INTERCEPTOR_HOOKS \
-  (SI_LINUX || SI_MAC || SI_WINDOWS || SI_NETBSD)
+  (SI_LINUX || SI_MAC || SI_WINDOWS || SI_FREEBSD || SI_NETBSD || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_RECV_RECVFROM SI_POSIX
 #define SANITIZER_INTERCEPT_SEND_SENDTO SI_POSIX
 #define SANITIZER_INTERCEPT_EVENTFD_READ_WRITE SI_LINUX
 
 #define SANITIZER_INTERCEPT_STAT \
-  (SI_FREEBSD || SI_MAC || SI_ANDROID || SI_NETBSD || SI_OPENBSD || SI_SOLARIS)
+  (SI_FREEBSD || SI_MAC || SI_ANDROID || SI_NETBSD || SI_SOLARIS)
 #define SANITIZER_INTERCEPT_LSTAT (SI_NETBSD || SI_FREEBSD)
 #define SANITIZER_INTERCEPT___XSTAT (!SANITIZER_INTERCEPT_STAT && SI_POSIX)
 #define SANITIZER_INTERCEPT___XSTAT64 SI_LINUX_NOT_ANDROID
@@ -492,41 +471,34 @@
   (SI_LINUX_NOT_ANDROID || SI_MAC || SI_FREEBSD || SI_NETBSD)
 
 #define SANITIZER_INTERCEPT_GETLOADAVG \
-  (SI_LINUX_NOT_ANDROID || SI_MAC || SI_FREEBSD || SI_NETBSD || SI_OPENBSD)
+  (SI_LINUX_NOT_ANDROID || SI_MAC || SI_FREEBSD || SI_NETBSD)
 
 #define SANITIZER_INTERCEPT_MMAP SI_POSIX
 #define SANITIZER_INTERCEPT_MMAP64 SI_LINUX_NOT_ANDROID
-#define SANITIZER_INTERCEPT_MALLOPT_AND_MALLINFO \
-  (!SI_FREEBSD && !SI_MAC && !SI_NETBSD && !SI_OPENBSD && SI_NOT_FUCHSIA && \
-  SI_NOT_RTEMS)
-#define SANITIZER_INTERCEPT_MEMALIGN \
-  (!SI_FREEBSD && !SI_MAC && !SI_NETBSD && !SI_OPENBSD && SI_NOT_RTEMS)
-#define SANITIZER_INTERCEPT_PVALLOC \
-  (!SI_FREEBSD && !SI_MAC && !SI_NETBSD && !SI_OPENBSD && SI_NOT_FUCHSIA && \
-  SI_NOT_RTEMS)
-#define SANITIZER_INTERCEPT_CFREE \
-  (!SI_FREEBSD && !SI_MAC && !SI_NETBSD && !SI_OPENBSD && SI_NOT_FUCHSIA && \
-  SI_NOT_RTEMS)
+#define SANITIZER_INTERCEPT_MALLOPT_AND_MALLINFO (SI_GLIBC || SI_ANDROID)
+#define SANITIZER_INTERCEPT_MEMALIGN (!SI_FREEBSD && !SI_MAC && !SI_NETBSD)
+#define SANITIZER_INTERCEPT___LIBC_MEMALIGN SI_GLIBC
+#define SANITIZER_INTERCEPT_PVALLOC (SI_GLIBC || SI_ANDROID)
+#define SANITIZER_INTERCEPT_CFREE (SI_GLIBC && !SANITIZER_RISCV64)
 #define SANITIZER_INTERCEPT_REALLOCARRAY SI_POSIX
-#define SANITIZER_INTERCEPT_ALIGNED_ALLOC (!SI_MAC && SI_NOT_RTEMS)
-#define SANITIZER_INTERCEPT_MALLOC_USABLE_SIZE \
-  (!SI_MAC && !SI_OPENBSD && !SI_NETBSD)
+#define SANITIZER_INTERCEPT_ALIGNED_ALLOC (!SI_MAC)
+#define SANITIZER_INTERCEPT_MALLOC_USABLE_SIZE (!SI_MAC && !SI_NETBSD)
 #define SANITIZER_INTERCEPT_MCHECK_MPROBE SI_LINUX_NOT_ANDROID
 #define SANITIZER_INTERCEPT_WCSCAT SI_POSIX
 #define SANITIZER_INTERCEPT_WCSDUP SI_POSIX
 #define SANITIZER_INTERCEPT_SIGNAL_AND_SIGACTION (!SI_WINDOWS && SI_NOT_FUCHSIA)
 #define SANITIZER_INTERCEPT_BSD_SIGNAL SI_ANDROID
 
-#define SANITIZER_INTERCEPT_ACCT (SI_NETBSD || SI_OPENBSD || SI_FREEBSD)
+#define SANITIZER_INTERCEPT_ACCT (SI_NETBSD || SI_FREEBSD)
 #define SANITIZER_INTERCEPT_USER_FROM_UID SI_NETBSD
 #define SANITIZER_INTERCEPT_UID_FROM_USER SI_NETBSD
 #define SANITIZER_INTERCEPT_GROUP_FROM_GID SI_NETBSD
 #define SANITIZER_INTERCEPT_GID_FROM_GROUP SI_NETBSD
-#define SANITIZER_INTERCEPT_ACCESS (SI_NETBSD || SI_OPENBSD || SI_FREEBSD)
-#define SANITIZER_INTERCEPT_FACCESSAT (SI_NETBSD || SI_OPENBSD || SI_FREEBSD)
-#define SANITIZER_INTERCEPT_GETGROUPLIST (SI_NETBSD || SI_OPENBSD)
-#define SANITIZER_INTERCEPT_STRLCPY                                            \
-  (SI_NETBSD || SI_FREEBSD || SI_OPENBSD || SI_MAC || SI_ANDROID)
+#define SANITIZER_INTERCEPT_ACCESS (SI_NETBSD || SI_FREEBSD)
+#define SANITIZER_INTERCEPT_FACCESSAT (SI_NETBSD || SI_FREEBSD)
+#define SANITIZER_INTERCEPT_GETGROUPLIST SI_NETBSD
+#define SANITIZER_INTERCEPT_STRLCPY \
+  (SI_NETBSD || SI_FREEBSD || SI_MAC || SI_ANDROID)
 
 #define SANITIZER_INTERCEPT_NAME_TO_HANDLE_AT SI_LINUX_NOT_ANDROID
 #define SANITIZER_INTERCEPT_OPEN_BY_HANDLE_AT SI_LINUX_NOT_ANDROID
@@ -534,23 +506,23 @@
 #define SANITIZER_INTERCEPT_READLINK SI_POSIX
 #if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && \
     __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 101000
-# define SI_MAC_DEPLOYMENT_BELOW_10_10 1
+#define SI_MAC_DEPLOYMENT_BELOW_10_10 1
 #else
-# define SI_MAC_DEPLOYMENT_BELOW_10_10 0
+#define SI_MAC_DEPLOYMENT_BELOW_10_10 0
 #endif
 #define SANITIZER_INTERCEPT_READLINKAT \
   (SI_POSIX && !SI_MAC_DEPLOYMENT_BELOW_10_10)
 
-#define SANITIZER_INTERCEPT_DEVNAME (SI_NETBSD || SI_OPENBSD || SI_FREEBSD)
+#define SANITIZER_INTERCEPT_DEVNAME (SI_NETBSD || SI_FREEBSD)
 #define SANITIZER_INTERCEPT_DEVNAME_R (SI_NETBSD || SI_FREEBSD)
 #define SANITIZER_INTERCEPT_FGETLN (SI_NETBSD || SI_FREEBSD)
 #define SANITIZER_INTERCEPT_STRMODE (SI_NETBSD || SI_FREEBSD)
 #define SANITIZER_INTERCEPT_TTYENT SI_NETBSD
 #define SANITIZER_INTERCEPT_PROTOENT (SI_NETBSD || SI_LINUX)
-#define SANITIZER_INTERCEPT_PROTOENT_R (SI_LINUX_NOT_ANDROID)
+#define SANITIZER_INTERCEPT_PROTOENT_R SI_GLIBC
 #define SANITIZER_INTERCEPT_NETENT SI_NETBSD
-#define SANITIZER_INTERCEPT_SETVBUF (SI_NETBSD || SI_FREEBSD || \
-  SI_LINUX || SI_MAC)
+#define SANITIZER_INTERCEPT_SETVBUF \
+  (SI_NETBSD || SI_FREEBSD || SI_LINUX || SI_MAC)
 #define SANITIZER_INTERCEPT_GETMNTINFO (SI_NETBSD || SI_FREEBSD || SI_MAC)
 #define SANITIZER_INTERCEPT_MI_VECTOR_HASH SI_NETBSD
 #define SANITIZER_INTERCEPT_GETVFSSTAT SI_NETBSD
@@ -598,12 +570,34 @@
 #define SANITIZER_INTERCEPT_GETENTROPY SI_FREEBSD
 #define SANITIZER_INTERCEPT_QSORT \
   (SI_POSIX && !SI_IOSSIM && !SI_WATCHOS && !SI_TVOS && !SI_ANDROID)
-#define SANITIZER_INTERCEPT_QSORT_R (SI_LINUX && !SI_ANDROID)
+#define SANITIZER_INTERCEPT_QSORT_R SI_GLIBC
 // sigaltstack on i386 macOS cannot be intercepted due to setjmp()
 // calling it and assuming that it does not clobber registers.
 #define SANITIZER_INTERCEPT_SIGALTSTACK \
   (SI_POSIX && !(SANITIZER_MAC && SANITIZER_I386))
 #define SANITIZER_INTERCEPT_UNAME (SI_POSIX && !SI_FREEBSD)
 #define SANITIZER_INTERCEPT___XUNAME SI_FREEBSD
+#define SANITIZER_INTERCEPT_FLOPEN SI_FREEBSD
+
+// This macro gives a way for downstream users to override the above
+// interceptor macros irrespective of the platform they are on. They have
+// to do two things:
+// 1. Build compiler-rt with -DSANITIZER_OVERRIDE_INTERCEPTORS.
+// 2. Provide a header file named sanitizer_intercept_overriders.h in the
+//    include path for their compiler-rt build.
+// An example of an overrider for strlen interceptor that one can list in
+// sanitizer_intercept_overriders.h is as follows:
+//
+// #ifdef SANITIZER_INTERCEPT_STRLEN
+// #undef SANITIZER_INTERCEPT_STRLEN
+// #define SANITIZER_INTERCEPT_STRLEN <value of choice>
+// #endif
+//
+// This "feature" is useful for downstream users who do not want some of
+// their libc funtions to be intercepted. They can selectively disable
+// interception of those functions.
+#ifdef SANITIZER_OVERRIDE_INTERCEPTORS
+#include <sanitizer_intercept_overriders.h>
+#endif
 
 #endif  // #ifndef SANITIZER_PLATFORM_INTERCEPTORS_H
lib/tsan/sanitizer_common/sanitizer_platform_limits_freebsd.cpp
@@ -35,7 +35,10 @@
 #include <sys/stat.h>
 #include <sys/statvfs.h>
 #include <sys/time.h>
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-W#warnings"
 #include <sys/timeb.h>
+#pragma clang diagnostic pop
 #include <sys/times.h>
 #include <sys/timespec.h>
 #include <sys/types.h>
@@ -81,8 +84,6 @@
 #include <sys/shm.h>
 #undef _KERNEL
 
-#undef INLINE  // to avoid clashes with sanitizers' definitions
-
 #undef IOC_DIRMASK
 
 // Include these after system headers to avoid name clashes and ambiguities.
lib/tsan/sanitizer_common/sanitizer_platform_limits_netbsd.cpp
@@ -34,6 +34,7 @@
 #include <sys/chio.h>
 #include <sys/clockctl.h>
 #include <sys/cpuio.h>
+#include <sys/dkbad.h>
 #include <sys/dkio.h>
 #include <sys/drvctlio.h>
 #include <sys/dvdio.h>
@@ -83,6 +84,7 @@
 
 #include <sys/resource.h>
 #include <sys/sem.h>
+#include <sys/scsiio.h>
 #include <sys/sha1.h>
 #include <sys/sha2.h>
 #include <sys/shm.h>
@@ -139,7 +141,158 @@
 #include <dev/ir/irdaio.h>
 #include <dev/isa/isvio.h>
 #include <dev/isa/wtreg.h>
+#if __has_include(<dev/iscsi/iscsi_ioctl.h>)
 #include <dev/iscsi/iscsi_ioctl.h>
+#else
+/* Fallback for MKISCSI=no */
+
+typedef struct {
+  uint32_t status;
+  uint32_t session_id;
+  uint32_t connection_id;
+} iscsi_conn_status_parameters_t;
+
+typedef struct {
+  uint32_t status;
+  uint16_t interface_version;
+  uint16_t major;
+  uint16_t minor;
+  uint8_t version_string[224];
+} iscsi_get_version_parameters_t;
+
+typedef struct {
+  uint32_t status;
+  uint32_t session_id;
+  uint32_t connection_id;
+  struct {
+    unsigned int immediate : 1;
+  } options;
+  uint64_t lun;
+  scsireq_t req; /* from <sys/scsiio.h> */
+} iscsi_iocommand_parameters_t;
+
+typedef enum {
+  ISCSI_AUTH_None = 0,
+  ISCSI_AUTH_CHAP = 1,
+  ISCSI_AUTH_KRB5 = 2,
+  ISCSI_AUTH_SRP = 3
+} iscsi_auth_types_t;
+
+typedef enum {
+  ISCSI_LOGINTYPE_DISCOVERY = 0,
+  ISCSI_LOGINTYPE_NOMAP = 1,
+  ISCSI_LOGINTYPE_MAP = 2
+} iscsi_login_session_type_t;
+
+typedef enum { ISCSI_DIGEST_None = 0, ISCSI_DIGEST_CRC32C = 1 } iscsi_digest_t;
+
+typedef enum {
+  ISCSI_SESSION_TERMINATED = 1,
+  ISCSI_CONNECTION_TERMINATED,
+  ISCSI_RECOVER_CONNECTION,
+  ISCSI_DRIVER_TERMINATING
+} iscsi_event_t;
+
+typedef struct {
+  unsigned int mutual_auth : 1;
+  unsigned int is_secure : 1;
+  unsigned int auth_number : 4;
+  iscsi_auth_types_t auth_type[4];
+} iscsi_auth_info_t;
+
+typedef struct {
+  uint32_t status;
+  int socket;
+  struct {
+    unsigned int HeaderDigest : 1;
+    unsigned int DataDigest : 1;
+    unsigned int MaxConnections : 1;
+    unsigned int DefaultTime2Wait : 1;
+    unsigned int DefaultTime2Retain : 1;
+    unsigned int MaxRecvDataSegmentLength : 1;
+    unsigned int auth_info : 1;
+    unsigned int user_name : 1;
+    unsigned int password : 1;
+    unsigned int target_password : 1;
+    unsigned int TargetName : 1;
+    unsigned int TargetAlias : 1;
+    unsigned int ErrorRecoveryLevel : 1;
+  } is_present;
+  iscsi_auth_info_t auth_info;
+  iscsi_login_session_type_t login_type;
+  iscsi_digest_t HeaderDigest;
+  iscsi_digest_t DataDigest;
+  uint32_t session_id;
+  uint32_t connection_id;
+  uint32_t MaxRecvDataSegmentLength;
+  uint16_t MaxConnections;
+  uint16_t DefaultTime2Wait;
+  uint16_t DefaultTime2Retain;
+  uint16_t ErrorRecoveryLevel;
+  void *user_name;
+  void *password;
+  void *target_password;
+  void *TargetName;
+  void *TargetAlias;
+} iscsi_login_parameters_t;
+
+typedef struct {
+  uint32_t status;
+  uint32_t session_id;
+} iscsi_logout_parameters_t;
+
+typedef struct {
+  uint32_t status;
+  uint32_t event_id;
+} iscsi_register_event_parameters_t;
+
+typedef struct {
+  uint32_t status;
+  uint32_t session_id;
+  uint32_t connection_id;
+} iscsi_remove_parameters_t;
+
+typedef struct {
+  uint32_t status;
+  uint32_t session_id;
+  void *response_buffer;
+  uint32_t response_size;
+  uint32_t response_used;
+  uint32_t response_total;
+  uint8_t key[224];
+} iscsi_send_targets_parameters_t;
+
+typedef struct {
+  uint32_t status;
+  uint8_t InitiatorName[224];
+  uint8_t InitiatorAlias[224];
+  uint8_t ISID[6];
+} iscsi_set_node_name_parameters_t;
+
+typedef struct {
+  uint32_t status;
+  uint32_t event_id;
+  iscsi_event_t event_kind;
+  uint32_t session_id;
+  uint32_t connection_id;
+  uint32_t reason;
+} iscsi_wait_event_parameters_t;
+
+#define ISCSI_GET_VERSION _IOWR(0, 1, iscsi_get_version_parameters_t)
+#define ISCSI_LOGIN _IOWR(0, 2, iscsi_login_parameters_t)
+#define ISCSI_LOGOUT _IOWR(0, 3, iscsi_logout_parameters_t)
+#define ISCSI_ADD_CONNECTION _IOWR(0, 4, iscsi_login_parameters_t)
+#define ISCSI_RESTORE_CONNECTION _IOWR(0, 5, iscsi_login_parameters_t)
+#define ISCSI_REMOVE_CONNECTION _IOWR(0, 6, iscsi_remove_parameters_t)
+#define ISCSI_CONNECTION_STATUS _IOWR(0, 7, iscsi_conn_status_parameters_t)
+#define ISCSI_SEND_TARGETS _IOWR(0, 8, iscsi_send_targets_parameters_t)
+#define ISCSI_SET_NODE_NAME _IOWR(0, 9, iscsi_set_node_name_parameters_t)
+#define ISCSI_IO_COMMAND _IOWR(0, 10, iscsi_iocommand_parameters_t)
+#define ISCSI_REGISTER_EVENT _IOWR(0, 11, iscsi_register_event_parameters_t)
+#define ISCSI_DEREGISTER_EVENT _IOWR(0, 12, iscsi_register_event_parameters_t)
+#define ISCSI_WAIT_EVENT _IOWR(0, 13, iscsi_wait_event_parameters_t)
+#define ISCSI_POLL_EVENT _IOWR(0, 14, iscsi_wait_event_parameters_t)
+#endif
 #include <dev/ofw/openfirmio.h>
 #include <dev/pci/amrio.h>
 #include <dev/pci/mlyreg.h>
@@ -372,7 +525,7 @@ struct urio_command {
 #include "sanitizer_platform_limits_netbsd.h"
 
 namespace __sanitizer {
-void *__sanitizer_get_link_map_by_dlopen_handle(void* handle) {
+void *__sanitizer_get_link_map_by_dlopen_handle(void *handle) {
   void *p = nullptr;
   return internal_dlinfo(handle, RTLD_DI_LINKMAP, &p) == 0 ? p : nullptr;
 }
lib/tsan/sanitizer_common/sanitizer_platform_limits_netbsd.h
@@ -21,8 +21,8 @@
 
 namespace __sanitizer {
 void *__sanitizer_get_link_map_by_dlopen_handle(void *handle);
-# define GET_LINK_MAP_BY_DLOPEN_HANDLE(handle) \
-    (link_map *)__sanitizer_get_link_map_by_dlopen_handle(handle)
+#define GET_LINK_MAP_BY_DLOPEN_HANDLE(handle) \
+  (link_map *)__sanitizer_get_link_map_by_dlopen_handle(handle)
 
 extern unsigned struct_utsname_sz;
 extern unsigned struct_stat_sz;
@@ -1024,12 +1024,10 @@ extern unsigned struct_RF_ProgressInfo_sz;
 extern unsigned struct_nvlist_ref_sz;
 extern unsigned struct_StringList_sz;
 
-
 // A special value to mark ioctls that are not present on the target platform,
 // when it can not be determined without including any system headers.
 extern const unsigned IOCTL_NOT_PRESENT;
 
-
 extern unsigned IOCTL_AFM_ADDFMAP;
 extern unsigned IOCTL_AFM_DELFMAP;
 extern unsigned IOCTL_AFM_CLEANFMAP;
lib/tsan/sanitizer_common/sanitizer_platform_limits_openbsd.cpp
@@ -1,279 +0,0 @@
-//===-- sanitizer_platform_limits_openbsd.cpp -----------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is a part of Sanitizer common code.
-//
-// Sizes and layouts of platform-specific NetBSD data structures.
-//===----------------------------------------------------------------------===//
-
-#include "sanitizer_platform.h"
-
-#if SANITIZER_OPENBSD
-#include <arpa/inet.h>
-#include <dirent.h>
-#include <glob.h>
-#include <grp.h>
-#include <ifaddrs.h>
-#include <limits.h>
-#include <link_elf.h>
-#include <sys/socket.h>
-#include <net/if.h>
-#include <net/ppp_defs.h>
-#include <net/route.h>
-#include <netdb.h>
-#include <netinet/in.h>
-#include <netinet/ip_mroute.h>
-#include <poll.h>
-#include <pthread.h>
-#include <pwd.h>
-#include <semaphore.h>
-#include <signal.h>
-#include <soundcard.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/filio.h>
-#include <sys/ipc.h>
-#include <sys/mman.h>
-#include <sys/mount.h>
-#include <sys/msg.h>
-#include <sys/mtio.h>
-#include <sys/ptrace.h>
-#include <sys/resource.h>
-#include <sys/shm.h>
-#include <sys/signal.h>
-#include <sys/sockio.h>
-#include <sys/stat.h>
-#include <sys/statvfs.h>
-#include <sys/time.h>
-#include <sys/times.h>
-#include <sys/types.h>
-#include <sys/utsname.h>
-#include <term.h>
-#include <time.h>
-#include <utime.h>
-#include <utmp.h>
-#include <wchar.h>
-
-// Include these after system headers to avoid name clashes and ambiguities.
-#include "sanitizer_internal_defs.h"
-#include "sanitizer_platform_limits_openbsd.h"
-
-namespace __sanitizer {
-unsigned struct_utsname_sz = sizeof(struct utsname);
-unsigned struct_stat_sz = sizeof(struct stat);
-unsigned struct_rusage_sz = sizeof(struct rusage);
-unsigned struct_tm_sz = sizeof(struct tm);
-unsigned struct_passwd_sz = sizeof(struct passwd);
-unsigned struct_group_sz = sizeof(struct group);
-unsigned siginfo_t_sz = sizeof(siginfo_t);
-unsigned struct_sigaction_sz = sizeof(struct sigaction);
-unsigned struct_stack_t_sz = sizeof(stack_t);
-unsigned struct_itimerval_sz = sizeof(struct itimerval);
-unsigned pthread_t_sz = sizeof(pthread_t);
-unsigned pthread_mutex_t_sz = sizeof(pthread_mutex_t);
-unsigned pthread_cond_t_sz = sizeof(pthread_cond_t);
-unsigned pid_t_sz = sizeof(pid_t);
-unsigned timeval_sz = sizeof(timeval);
-unsigned uid_t_sz = sizeof(uid_t);
-unsigned gid_t_sz = sizeof(gid_t);
-unsigned mbstate_t_sz = sizeof(mbstate_t);
-unsigned sigset_t_sz = sizeof(sigset_t);
-unsigned struct_timezone_sz = sizeof(struct timezone);
-unsigned struct_tms_sz = sizeof(struct tms);
-unsigned struct_sched_param_sz = sizeof(struct sched_param);
-unsigned struct_sockaddr_sz = sizeof(struct sockaddr);
-unsigned struct_rlimit_sz = sizeof(struct rlimit);
-unsigned struct_timespec_sz = sizeof(struct timespec);
-unsigned struct_utimbuf_sz = sizeof(struct utimbuf);
-unsigned struct_itimerspec_sz = sizeof(struct itimerspec);
-unsigned struct_msqid_ds_sz = sizeof(struct msqid_ds);
-unsigned struct_statvfs_sz = sizeof(struct statvfs);
-
-const uptr sig_ign = (uptr)SIG_IGN;
-const uptr sig_dfl = (uptr)SIG_DFL;
-const uptr sig_err = (uptr)SIG_ERR;
-const uptr sa_siginfo = (uptr)SA_SIGINFO;
-
-int shmctl_ipc_stat = (int)IPC_STAT;
-
-unsigned struct_utmp_sz = sizeof(struct utmp);
-
-int map_fixed = MAP_FIXED;
-
-int af_inet = (int)AF_INET;
-int af_inet6 = (int)AF_INET6;
-
-uptr __sanitizer_in_addr_sz(int af) {
-  if (af == AF_INET)
-    return sizeof(struct in_addr);
-  else if (af == AF_INET6)
-    return sizeof(struct in6_addr);
-  else
-    return 0;
-}
-
-unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
-
-int glob_nomatch = GLOB_NOMATCH;
-int glob_altdirfunc = GLOB_ALTDIRFUNC;
-
-unsigned path_max = PATH_MAX;
-
-const int si_SEGV_MAPERR = SEGV_MAPERR;
-const int si_SEGV_ACCERR = SEGV_ACCERR;
-}  // namespace __sanitizer
-
-using namespace __sanitizer;
-
-COMPILER_CHECK(sizeof(__sanitizer_pthread_attr_t) >= sizeof(pthread_attr_t));
-
-COMPILER_CHECK(sizeof(socklen_t) == sizeof(unsigned));
-CHECK_TYPE_SIZE(pthread_key_t);
-
-CHECK_TYPE_SIZE(dl_phdr_info);
-CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_addr);
-CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_name);
-CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phdr);
-CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phnum);
-
-CHECK_TYPE_SIZE(glob_t);
-CHECK_SIZE_AND_OFFSET(glob_t, gl_pathc);
-CHECK_SIZE_AND_OFFSET(glob_t, gl_pathv);
-CHECK_SIZE_AND_OFFSET(glob_t, gl_offs);
-CHECK_SIZE_AND_OFFSET(glob_t, gl_flags);
-CHECK_SIZE_AND_OFFSET(glob_t, gl_closedir);
-CHECK_SIZE_AND_OFFSET(glob_t, gl_readdir);
-CHECK_SIZE_AND_OFFSET(glob_t, gl_opendir);
-CHECK_SIZE_AND_OFFSET(glob_t, gl_lstat);
-CHECK_SIZE_AND_OFFSET(glob_t, gl_stat);
-
-CHECK_TYPE_SIZE(addrinfo);
-CHECK_SIZE_AND_OFFSET(addrinfo, ai_flags);
-CHECK_SIZE_AND_OFFSET(addrinfo, ai_family);
-CHECK_SIZE_AND_OFFSET(addrinfo, ai_socktype);
-CHECK_SIZE_AND_OFFSET(addrinfo, ai_protocol);
-CHECK_SIZE_AND_OFFSET(addrinfo, ai_addrlen);
-CHECK_SIZE_AND_OFFSET(addrinfo, ai_addr);
-CHECK_SIZE_AND_OFFSET(addrinfo, ai_canonname);
-CHECK_SIZE_AND_OFFSET(addrinfo, ai_next);
-
-CHECK_TYPE_SIZE(hostent);
-CHECK_SIZE_AND_OFFSET(hostent, h_name);
-CHECK_SIZE_AND_OFFSET(hostent, h_aliases);
-CHECK_SIZE_AND_OFFSET(hostent, h_addrtype);
-CHECK_SIZE_AND_OFFSET(hostent, h_length);
-CHECK_SIZE_AND_OFFSET(hostent, h_addr_list);
-
-CHECK_TYPE_SIZE(iovec);
-CHECK_SIZE_AND_OFFSET(iovec, iov_base);
-CHECK_SIZE_AND_OFFSET(iovec, iov_len);
-
-CHECK_TYPE_SIZE(msghdr);
-CHECK_SIZE_AND_OFFSET(msghdr, msg_name);
-CHECK_SIZE_AND_OFFSET(msghdr, msg_namelen);
-CHECK_SIZE_AND_OFFSET(msghdr, msg_iov);
-CHECK_SIZE_AND_OFFSET(msghdr, msg_iovlen);
-CHECK_SIZE_AND_OFFSET(msghdr, msg_control);
-CHECK_SIZE_AND_OFFSET(msghdr, msg_controllen);
-CHECK_SIZE_AND_OFFSET(msghdr, msg_flags);
-
-CHECK_TYPE_SIZE(cmsghdr);
-CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_len);
-CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_level);
-CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_type);
-
-COMPILER_CHECK(sizeof(__sanitizer_dirent) <= sizeof(dirent));
-CHECK_SIZE_AND_OFFSET(dirent, d_fileno);
-CHECK_SIZE_AND_OFFSET(dirent, d_off);
-CHECK_SIZE_AND_OFFSET(dirent, d_reclen);
-
-CHECK_TYPE_SIZE(ifconf);
-CHECK_SIZE_AND_OFFSET(ifconf, ifc_len);
-CHECK_SIZE_AND_OFFSET(ifconf, ifc_ifcu);
-
-CHECK_TYPE_SIZE(pollfd);
-CHECK_SIZE_AND_OFFSET(pollfd, fd);
-CHECK_SIZE_AND_OFFSET(pollfd, events);
-CHECK_SIZE_AND_OFFSET(pollfd, revents);
-
-CHECK_TYPE_SIZE(nfds_t);
-
-CHECK_TYPE_SIZE(sigset_t);
-
-COMPILER_CHECK(sizeof(__sanitizer_sigaction) == sizeof(struct sigaction));
-// Can't write checks for sa_handler and sa_sigaction due to them being
-// preprocessor macros.
-CHECK_STRUCT_SIZE_AND_OFFSET(sigaction, sa_mask);
-
-CHECK_TYPE_SIZE(tm);
-CHECK_SIZE_AND_OFFSET(tm, tm_sec);
-CHECK_SIZE_AND_OFFSET(tm, tm_min);
-CHECK_SIZE_AND_OFFSET(tm, tm_hour);
-CHECK_SIZE_AND_OFFSET(tm, tm_mday);
-CHECK_SIZE_AND_OFFSET(tm, tm_mon);
-CHECK_SIZE_AND_OFFSET(tm, tm_year);
-CHECK_SIZE_AND_OFFSET(tm, tm_wday);
-CHECK_SIZE_AND_OFFSET(tm, tm_yday);
-CHECK_SIZE_AND_OFFSET(tm, tm_isdst);
-CHECK_SIZE_AND_OFFSET(tm, tm_gmtoff);
-CHECK_SIZE_AND_OFFSET(tm, tm_zone);
-
-CHECK_TYPE_SIZE(ipc_perm);
-CHECK_SIZE_AND_OFFSET(ipc_perm, cuid);
-CHECK_SIZE_AND_OFFSET(ipc_perm, cgid);
-CHECK_SIZE_AND_OFFSET(ipc_perm, uid);
-CHECK_SIZE_AND_OFFSET(ipc_perm, gid);
-CHECK_SIZE_AND_OFFSET(ipc_perm, mode);
-CHECK_SIZE_AND_OFFSET(ipc_perm, seq);
-CHECK_SIZE_AND_OFFSET(ipc_perm, key);
-
-CHECK_TYPE_SIZE(shmid_ds);
-CHECK_SIZE_AND_OFFSET(shmid_ds, shm_perm);
-CHECK_SIZE_AND_OFFSET(shmid_ds, shm_segsz);
-CHECK_SIZE_AND_OFFSET(shmid_ds, shm_atime);
-CHECK_SIZE_AND_OFFSET(shmid_ds, __shm_atimensec);
-CHECK_SIZE_AND_OFFSET(shmid_ds, shm_dtime);
-CHECK_SIZE_AND_OFFSET(shmid_ds, __shm_dtimensec);
-CHECK_SIZE_AND_OFFSET(shmid_ds, shm_ctime);
-CHECK_SIZE_AND_OFFSET(shmid_ds, __shm_ctimensec);
-CHECK_SIZE_AND_OFFSET(shmid_ds, shm_cpid);
-CHECK_SIZE_AND_OFFSET(shmid_ds, shm_lpid);
-CHECK_SIZE_AND_OFFSET(shmid_ds, shm_nattch);
-
-CHECK_TYPE_SIZE(clock_t);
-
-CHECK_TYPE_SIZE(ifaddrs);
-CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_next);
-CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_name);
-CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_addr);
-CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_netmask);
-// Compare against the union, because we can't reach into the union in a
-// compliant way.
-#ifdef ifa_dstaddr
-#undef ifa_dstaddr
-#endif
-CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_dstaddr);
-CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_data);
-
-CHECK_TYPE_SIZE(passwd);
-CHECK_SIZE_AND_OFFSET(passwd, pw_name);
-CHECK_SIZE_AND_OFFSET(passwd, pw_passwd);
-CHECK_SIZE_AND_OFFSET(passwd, pw_uid);
-CHECK_SIZE_AND_OFFSET(passwd, pw_gid);
-CHECK_SIZE_AND_OFFSET(passwd, pw_dir);
-CHECK_SIZE_AND_OFFSET(passwd, pw_shell);
-
-CHECK_SIZE_AND_OFFSET(passwd, pw_gecos);
-
-CHECK_TYPE_SIZE(group);
-CHECK_SIZE_AND_OFFSET(group, gr_name);
-CHECK_SIZE_AND_OFFSET(group, gr_passwd);
-CHECK_SIZE_AND_OFFSET(group, gr_gid);
-CHECK_SIZE_AND_OFFSET(group, gr_mem);
-
-#endif  // SANITIZER_OPENBSD
lib/tsan/sanitizer_common/sanitizer_platform_limits_openbsd.h
@@ -1,382 +0,0 @@
-//===-- sanitizer_platform_limits_openbsd.h -------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is a part of Sanitizer common code.
-//
-// Sizes and layouts of platform-specific OpenBSD data structures.
-//===----------------------------------------------------------------------===//
-
-#ifndef SANITIZER_PLATFORM_LIMITS_OPENBSD_H
-#define SANITIZER_PLATFORM_LIMITS_OPENBSD_H
-
-#if SANITIZER_OPENBSD
-
-#include "sanitizer_internal_defs.h"
-#include "sanitizer_platform.h"
-
-#define _GET_LINK_MAP_BY_DLOPEN_HANDLE(handle, shift) \
-  ((link_map *)((handle) == nullptr ? nullptr : ((char *)(handle) + (shift))))
-
-#if defined(__x86_64__)
-#define GET_LINK_MAP_BY_DLOPEN_HANDLE(handle) \
-  _GET_LINK_MAP_BY_DLOPEN_HANDLE(handle, 312)
-#elif defined(__i386__)
-#define GET_LINK_MAP_BY_DLOPEN_HANDLE(handle) \
-  _GET_LINK_MAP_BY_DLOPEN_HANDLE(handle, 164)
-#endif
-
-#define RLIMIT_AS RLIMIT_DATA
-
-namespace __sanitizer {
-extern unsigned struct_utsname_sz;
-extern unsigned struct_stat_sz;
-extern unsigned struct_rusage_sz;
-extern unsigned siginfo_t_sz;
-extern unsigned struct_itimerval_sz;
-extern unsigned pthread_t_sz;
-extern unsigned pthread_mutex_t_sz;
-extern unsigned pthread_cond_t_sz;
-extern unsigned pid_t_sz;
-extern unsigned timeval_sz;
-extern unsigned uid_t_sz;
-extern unsigned gid_t_sz;
-extern unsigned mbstate_t_sz;
-extern unsigned struct_timezone_sz;
-extern unsigned struct_tms_sz;
-extern unsigned struct_itimerspec_sz;
-extern unsigned struct_sigevent_sz;
-extern unsigned struct_stack_t_sz;
-extern unsigned struct_statfs_sz;
-extern unsigned struct_sockaddr_sz;
-
-extern unsigned struct_rlimit_sz;
-extern unsigned struct_utimbuf_sz;
-extern unsigned struct_timespec_sz;
-
-struct __sanitizer_iocb {
-  u64 aio_offset;
-  uptr aio_buf;
-  long aio_nbytes;
-  u32 aio_fildes;
-  u32 aio_lio_opcode;
-  long aio_reqprio;
-#if SANITIZER_WORDSIZE == 64
-  u8 aio_sigevent[32];
-#else
-  u8 aio_sigevent[20];
-#endif
-  u32 _state;
-  u32 _errno;
-  long _retval;
-};
-
-struct __sanitizer___sysctl_args {
-  int *name;
-  int nlen;
-  void *oldval;
-  uptr *oldlenp;
-  void *newval;
-  uptr newlen;
-};
-
-struct __sanitizer_sem_t {
-  uptr data[5];
-};
-
-struct __sanitizer_ipc_perm {
-  u32 cuid;
-  u32 cgid;
-  u32 uid;
-  u32 gid;
-  u32 mode;
-  unsigned short seq;
-  long key;
-};
-
-struct __sanitizer_shmid_ds {
-  __sanitizer_ipc_perm shm_perm;
-  int shm_segsz;
-  u32 shm_lpid;
-  u32 shm_cpid;
-  short shm_nattch;
-  u64 shm_atime;
-  long __shm_atimensec;
-  u64 shm_dtime;
-  long __shm_dtimensec;
-  u64 shm_ctime;
-  long __shm_ctimensec;
-  void *_shm_internal;
-};
-
-extern unsigned struct_msqid_ds_sz;
-extern unsigned struct_mq_attr_sz;
-extern unsigned struct_timex_sz;
-extern unsigned struct_statvfs_sz;
-
-struct __sanitizer_iovec {
-  void *iov_base;
-  uptr iov_len;
-};
-
-struct __sanitizer_ifaddrs {
-  struct __sanitizer_ifaddrs *ifa_next;
-  char *ifa_name;
-  unsigned int ifa_flags;
-  struct __sanitizer_sockaddr *ifa_addr;     // (struct sockaddr *)
-  struct __sanitizer_sockaddr *ifa_netmask;  // (struct sockaddr *)
-  struct __sanitizer_sockaddr *ifa_dstaddr;  // (struct sockaddr *)
-  void *ifa_data;
-};
-
-typedef unsigned __sanitizer_pthread_key_t;
-
-typedef long long __sanitizer_time_t;
-typedef int __sanitizer_suseconds_t;
-
-struct __sanitizer_timeval {
-  __sanitizer_time_t tv_sec;
-  __sanitizer_suseconds_t tv_usec;
-};
-
-struct __sanitizer_itimerval {
-  struct __sanitizer_timeval it_interval;
-  struct __sanitizer_timeval it_value;
-};
-
-struct __sanitizer_passwd {
-  char *pw_name;
-  char *pw_passwd;
-  int pw_uid;
-  int pw_gid;
-  __sanitizer_time_t pw_change;
-  char *pw_class;
-  char *pw_gecos;
-  char *pw_dir;
-  char *pw_shell;
-  __sanitizer_time_t pw_expire;
-};
-
-struct __sanitizer_group {
-  char *gr_name;
-  char *gr_passwd;
-  int gr_gid;
-  char **gr_mem;
-};
-
-struct __sanitizer_ether_addr {
-  u8 octet[6];
-};
-
-struct __sanitizer_tm {
-  int tm_sec;
-  int tm_min;
-  int tm_hour;
-  int tm_mday;
-  int tm_mon;
-  int tm_year;
-  int tm_wday;
-  int tm_yday;
-  int tm_isdst;
-  long int tm_gmtoff;
-  const char *tm_zone;
-};
-
-struct __sanitizer_msghdr {
-  void *msg_name;
-  unsigned msg_namelen;
-  struct __sanitizer_iovec *msg_iov;
-  unsigned msg_iovlen;
-  void *msg_control;
-  unsigned msg_controllen;
-  int msg_flags;
-};
-struct __sanitizer_cmsghdr {
-  unsigned cmsg_len;
-  int cmsg_level;
-  int cmsg_type;
-};
-
-struct __sanitizer_dirent {
-  u64 d_fileno;
-  u64 d_off;
-  u16 d_reclen;
-};
-
-typedef u64 __sanitizer_clock_t;
-typedef u32 __sanitizer_clockid_t;
-
-typedef u32 __sanitizer___kernel_uid_t;
-typedef u32 __sanitizer___kernel_gid_t;
-typedef u64 __sanitizer___kernel_off_t;
-typedef struct {
-  u32 fds_bits[8];
-} __sanitizer___kernel_fd_set;
-
-typedef struct {
-  unsigned int pta_magic;
-  int pta_flags;
-  void *pta_private;
-} __sanitizer_pthread_attr_t;
-
-typedef unsigned int __sanitizer_sigset_t;
-
-struct __sanitizer_siginfo {
-  // The size is determined by looking at sizeof of real siginfo_t on linux.
-  u64 opaque[128 / sizeof(u64)];
-};
-
-using __sanitizer_sighandler_ptr = void (*)(int sig);
-using __sanitizer_sigactionhandler_ptr = void (*)(int sig,
-                                                  __sanitizer_siginfo *siginfo,
-                                                  void *uctx);
-
-struct __sanitizer_sigaction {
-  union {
-    __sanitizer_sighandler_ptr handler;
-    __sanitizer_sigactionhandler_ptr sigaction;
-  };
-  __sanitizer_sigset_t sa_mask;
-  int sa_flags;
-};
-
-typedef __sanitizer_sigset_t __sanitizer_kernel_sigset_t;
-
-struct __sanitizer_kernel_sigaction_t {
-  union {
-    void (*handler)(int signo);
-    void (*sigaction)(int signo, void *info, void *ctx);
-  };
-  unsigned long sa_flags;
-  void (*sa_restorer)(void);
-  __sanitizer_kernel_sigset_t sa_mask;
-};
-
-extern const uptr sig_ign;
-extern const uptr sig_dfl;
-extern const uptr sig_err;
-extern const uptr sa_siginfo;
-
-extern int af_inet;
-extern int af_inet6;
-uptr __sanitizer_in_addr_sz(int af);
-
-struct __sanitizer_dl_phdr_info {
-#if SANITIZER_WORDSIZE == 64
-  u64 dlpi_addr;
-#else
-  u32 dlpi_addr;
-#endif
-  const char *dlpi_name;
-  const void *dlpi_phdr;
-#if SANITIZER_WORDSIZE == 64
-  u32 dlpi_phnum;
-#else
-  u16 dlpi_phnum;
-#endif
-};
-
-extern unsigned struct_ElfW_Phdr_sz;
-
-struct __sanitizer_addrinfo {
-  int ai_flags;
-  int ai_family;
-  int ai_socktype;
-  int ai_protocol;
-  unsigned ai_addrlen;
-  struct __sanitizer_sockaddr *ai_addr;
-  char *ai_canonname;
-  struct __sanitizer_addrinfo *ai_next;
-};
-
-struct __sanitizer_hostent {
-  char *h_name;
-  char **h_aliases;
-  int h_addrtype;
-  int h_length;
-  char **h_addr_list;
-};
-
-struct __sanitizer_pollfd {
-  int fd;
-  short events;
-  short revents;
-};
-
-typedef unsigned __sanitizer_nfds_t;
-
-struct __sanitizer_glob_t {
-  int gl_pathc;
-  int gl_matchc;
-  int gl_offs;
-  int gl_flags;
-  char **gl_pathv;
-  void **gl_statv;
-  int (*gl_errfunc)(const char *, int);
-  void (*gl_closedir)(void *dirp);
-  struct dirent *(*gl_readdir)(void *dirp);
-  void *(*gl_opendir)(const char *);
-  int (*gl_lstat)(const char *, void * /* struct stat* */);
-  int (*gl_stat)(const char *, void * /* struct stat* */);
-};
-
-extern int glob_nomatch;
-extern int glob_altdirfunc;
-
-extern unsigned path_max;
-
-typedef char __sanitizer_FILE;
-#define SANITIZER_HAS_STRUCT_FILE 0
-
-extern int shmctl_ipc_stat;
-
-// This simplifies generic code
-#define struct_shminfo_sz -1
-#define struct_shm_info_sz -1
-#define shmctl_shm_stat -1
-#define shmctl_ipc_info -1
-#define shmctl_shm_info -1
-
-extern unsigned struct_utmp_sz;
-extern unsigned struct_utmpx_sz;
-
-extern int map_fixed;
-
-// ioctl arguments
-struct __sanitizer_ifconf {
-  int ifc_len;
-  union {
-    void *ifcu_req;
-  } ifc_ifcu;
-};
-
-extern const int si_SEGV_MAPERR;
-extern const int si_SEGV_ACCERR;
-}  // namespace __sanitizer
-
-#define CHECK_TYPE_SIZE(TYPE) \
-  COMPILER_CHECK(sizeof(__sanitizer_##TYPE) == sizeof(TYPE))
-
-#define CHECK_SIZE_AND_OFFSET(CLASS, MEMBER)                      \
-  COMPILER_CHECK(sizeof(((__sanitizer_##CLASS *)NULL)->MEMBER) == \
-                 sizeof(((CLASS *)NULL)->MEMBER));                \
-  COMPILER_CHECK(offsetof(__sanitizer_##CLASS, MEMBER) ==         \
-                 offsetof(CLASS, MEMBER))
-
-// For sigaction, which is a function and struct at the same time,
-// and thus requires explicit "struct" in sizeof() expression.
-#define CHECK_STRUCT_SIZE_AND_OFFSET(CLASS, MEMBER)                      \
-  COMPILER_CHECK(sizeof(((struct __sanitizer_##CLASS *)NULL)->MEMBER) == \
-                 sizeof(((struct CLASS *)NULL)->MEMBER));                \
-  COMPILER_CHECK(offsetof(struct __sanitizer_##CLASS, MEMBER) ==         \
-                 offsetof(struct CLASS, MEMBER))
-
-#define SIGACTION_SYMNAME __sigaction14
-
-#endif  // SANITIZER_OPENBSD
-
-#endif
lib/tsan/sanitizer_common/sanitizer_platform_limits_posix.cpp
@@ -11,18 +11,19 @@
 // Sizes and layouts of platform-specific POSIX data structures.
 //===----------------------------------------------------------------------===//
 
-#include "sanitizer_platform.h"
-
-#if SANITIZER_LINUX || SANITIZER_MAC
+#if defined(__linux__) || defined(__APPLE__)
 // Tests in this file assume that off_t-dependent data structures match the
 // libc ABI. For example, struct dirent here is what readdir() function (as
 // exported from libc) returns, and not the user-facing "dirent", which
 // depends on _FILE_OFFSET_BITS setting.
 // To get this "true" dirent definition, we undefine _FILE_OFFSET_BITS below.
-#ifdef _FILE_OFFSET_BITS
 #undef _FILE_OFFSET_BITS
 #endif
 
+// Must go after undef _FILE_OFFSET_BITS.
+#include "sanitizer_platform.h"
+
+#if SANITIZER_LINUX || SANITIZER_MAC
 // Must go after undef _FILE_OFFSET_BITS.
 #include "sanitizer_glibc_version.h"
 
@@ -37,6 +38,7 @@
 #include <pwd.h>
 #include <signal.h>
 #include <stddef.h>
+#include <stdio.h>
 #include <sys/mman.h>
 #include <sys/resource.h>
 #include <sys/socket.h>
@@ -58,7 +60,6 @@
 #endif
 
 #if !SANITIZER_ANDROID
-#include <fstab.h>
 #include <sys/mount.h>
 #include <sys/timeb.h>
 #include <utmpx.h>
@@ -90,7 +91,8 @@
 #if SANITIZER_LINUX
 # include <utime.h>
 # include <sys/ptrace.h>
-# if defined(__mips64) || defined(__aarch64__) || defined(__arm__)
+#if defined(__mips64) || defined(__aarch64__) || defined(__arm__) || \
+    SANITIZER_RISCV64
 #  include <asm/ptrace.h>
 #  ifdef __arm__
 typedef struct user_fpregs elf_fpregset_t;
@@ -109,20 +111,31 @@ typedef struct user_fpregs elf_fpregset_t;
 #include <wordexp.h>
 #endif
 
-#if SANITIZER_LINUX && !SANITIZER_ANDROID
-#include <glob.h>
-#include <obstack.h>
-#include <mqueue.h>
+#if SANITIZER_LINUX
+#if SANITIZER_GLIBC
+#include <fstab.h>
 #include <net/if_ppp.h>
 #include <netax25/ax25.h>
 #include <netipx/ipx.h>
 #include <netrom/netrom.h>
+#include <obstack.h>
 #if HAVE_RPC_XDR_H
 # include <rpc/xdr.h>
 #endif
 #include <scsi/scsi.h>
-#include <sys/mtio.h>
+#else
+#include <linux/if_ppp.h>
+#include <linux/kd.h>
+#include <linux/ppp_defs.h>
+#endif  // SANITIZER_GLIBC
+
+#if SANITIZER_ANDROID
+#include <linux/mtio.h>
+#else
+#include <glob.h>
+#include <mqueue.h>
 #include <sys/kd.h>
+#include <sys/mtio.h>
 #include <sys/shm.h>
 #include <sys/statvfs.h>
 #include <sys/timex.h>
@@ -130,7 +143,6 @@ typedef struct user_fpregs elf_fpregset_t;
 # include <sys/procfs.h>
 #endif
 #include <sys/user.h>
-#include <linux/cyclades.h>
 #include <linux/if_eql.h>
 #include <linux/if_plip.h>
 #include <linux/lp.h>
@@ -141,20 +153,14 @@ typedef struct user_fpregs elf_fpregset_t;
 #include <sys/msg.h>
 #include <sys/ipc.h>
 #include <crypt.h>
-#endif // SANITIZER_LINUX && !SANITIZER_ANDROID
+#endif  // SANITIZER_ANDROID
 
-#if SANITIZER_ANDROID
-#include <linux/kd.h>
-#include <linux/mtio.h>
-#include <linux/ppp_defs.h>
-#include <linux/if_ppp.h>
-#endif
-
-#if SANITIZER_LINUX
 #include <link.h>
 #include <sys/vfs.h>
 #include <sys/epoll.h>
 #include <linux/capability.h>
+#else
+#include <fstab.h>
 #endif // SANITIZER_LINUX
 
 #if SANITIZER_MAC
@@ -201,8 +207,11 @@ namespace __sanitizer {
   unsigned struct_statfs64_sz = sizeof(struct statfs64);
 #endif // (SANITIZER_MAC && !TARGET_CPU_ARM64) && !SANITIZER_IOS
 
-#if !SANITIZER_ANDROID
+#if SANITIZER_GLIBC || SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_MAC
   unsigned struct_fstab_sz = sizeof(struct fstab);
+#endif  // SANITIZER_GLIBC || SANITIZER_FREEBSD || SANITIZER_NETBSD ||
+        // SANITIZER_MAC
+#if !SANITIZER_ANDROID
   unsigned struct_statfs_sz = sizeof(struct statfs);
   unsigned struct_sockaddr_sz = sizeof(struct sockaddr);
   unsigned ucontext_t_sz = sizeof(ucontext_t);
@@ -229,9 +238,9 @@ namespace __sanitizer {
 #if SANITIZER_LINUX && !SANITIZER_ANDROID
   // Use pre-computed size of struct ustat to avoid <sys/ustat.h> which
   // has been removed from glibc 2.28.
-#if defined(__aarch64__) || defined(__s390x__) || defined (__mips64) \
-  || defined(__powerpc64__) || defined(__arch64__) || defined(__sparcv9) \
-  || defined(__x86_64__) || (defined(__riscv) && __riscv_xlen == 64)
+#if defined(__aarch64__) || defined(__s390x__) || defined(__mips64) ||     \
+    defined(__powerpc64__) || defined(__arch64__) || defined(__sparcv9) || \
+    defined(__x86_64__) || SANITIZER_RISCV64
 #define SIZEOF_STRUCT_USTAT 32
 #elif defined(__arm__) || defined(__i386__) || defined(__mips__) \
   || defined(__powerpc__) || defined(__s390__) || defined(__sparc__)
@@ -298,18 +307,21 @@ unsigned struct_ElfW_Phdr_sz = sizeof(ElfW(Phdr));
 unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
 #endif
 
-#if SANITIZER_LINUX && !SANITIZER_ANDROID
+#if SANITIZER_GLIBC
   int glob_nomatch = GLOB_NOMATCH;
   int glob_altdirfunc = GLOB_ALTDIRFUNC;
 #endif
 
-#if SANITIZER_LINUX && !SANITIZER_ANDROID && \
-    (defined(__i386) || defined(__x86_64) || defined(__mips64) || \
-      defined(__powerpc64__) || defined(__aarch64__) || defined(__arm__) || \
-      defined(__s390__))
+#if SANITIZER_LINUX && !SANITIZER_ANDROID &&                               \
+    (defined(__i386) || defined(__x86_64) || defined(__mips64) ||          \
+     defined(__powerpc64__) || defined(__aarch64__) || defined(__arm__) || \
+     defined(__s390__) || SANITIZER_RISCV64)
 #if defined(__mips64) || defined(__powerpc64__) || defined(__arm__)
   unsigned struct_user_regs_struct_sz = sizeof(struct pt_regs);
   unsigned struct_user_fpregs_struct_sz = sizeof(elf_fpregset_t);
+#elif SANITIZER_RISCV64
+  unsigned struct_user_regs_struct_sz = sizeof(struct user_regs_struct);
+  unsigned struct_user_fpregs_struct_sz = sizeof(struct __riscv_q_ext_state);
 #elif defined(__aarch64__)
   unsigned struct_user_regs_struct_sz = sizeof(struct user_pt_regs);
   unsigned struct_user_fpregs_struct_sz = sizeof(struct user_fpsimd_state);
@@ -321,7 +333,8 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
   unsigned struct_user_fpregs_struct_sz = sizeof(struct user_fpregs_struct);
 #endif // __mips64 || __powerpc64__ || __aarch64__
 #if defined(__x86_64) || defined(__mips64) || defined(__powerpc64__) || \
-    defined(__aarch64__) || defined(__arm__) || defined(__s390__)
+    defined(__aarch64__) || defined(__arm__) || defined(__s390__) ||    \
+    SANITIZER_RISCV64
   unsigned struct_user_fpxregs_struct_sz = 0;
 #else
   unsigned struct_user_fpxregs_struct_sz = sizeof(struct user_fpxregs_struct);
@@ -417,7 +430,9 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
   unsigned struct_input_id_sz = sizeof(struct input_id);
   unsigned struct_mtpos_sz = sizeof(struct mtpos);
   unsigned struct_rtentry_sz = sizeof(struct rtentry);
+#if SANITIZER_GLIBC || SANITIZER_ANDROID
   unsigned struct_termio_sz = sizeof(struct termio);
+#endif
   unsigned struct_vt_consize_sz = sizeof(struct vt_consize);
   unsigned struct_vt_sizes_sz = sizeof(struct vt_sizes);
   unsigned struct_vt_stat_sz = sizeof(struct vt_stat);
@@ -442,9 +457,8 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
   unsigned struct_vt_mode_sz = sizeof(struct vt_mode);
 #endif // SANITIZER_LINUX
 
-#if SANITIZER_LINUX && !SANITIZER_ANDROID
+#if SANITIZER_GLIBC
   unsigned struct_ax25_parms_struct_sz = sizeof(struct ax25_parms_struct);
-  unsigned struct_cyclades_monitor_sz = sizeof(struct cyclades_monitor);
 #if EV_VERSION > (0x010000)
   unsigned struct_input_keymap_entry_sz = sizeof(struct input_keymap_entry);
 #else
@@ -465,12 +479,10 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
   unsigned struct_sockaddr_ax25_sz = sizeof(struct sockaddr_ax25);
   unsigned struct_unimapdesc_sz = sizeof(struct unimapdesc);
   unsigned struct_unimapinit_sz = sizeof(struct unimapinit);
-#endif // SANITIZER_LINUX && !SANITIZER_ANDROID
 
-#if SANITIZER_LINUX && !SANITIZER_ANDROID
   unsigned struct_audio_buf_info_sz = sizeof(struct audio_buf_info);
   unsigned struct_ppp_stats_sz = sizeof(struct ppp_stats);
-#endif // (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
+#endif  // SANITIZER_GLIBC
 
 #if !SANITIZER_ANDROID && !SANITIZER_MAC
   unsigned struct_sioc_sg_req_sz = sizeof(struct sioc_sg_req);
@@ -810,15 +822,6 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
 #endif // SANITIZER_LINUX
 
 #if SANITIZER_LINUX && !SANITIZER_ANDROID
-  unsigned IOCTL_CYGETDEFTHRESH = CYGETDEFTHRESH;
-  unsigned IOCTL_CYGETDEFTIMEOUT = CYGETDEFTIMEOUT;
-  unsigned IOCTL_CYGETMON = CYGETMON;
-  unsigned IOCTL_CYGETTHRESH = CYGETTHRESH;
-  unsigned IOCTL_CYGETTIMEOUT = CYGETTIMEOUT;
-  unsigned IOCTL_CYSETDEFTHRESH = CYSETDEFTHRESH;
-  unsigned IOCTL_CYSETDEFTIMEOUT = CYSETDEFTIMEOUT;
-  unsigned IOCTL_CYSETTHRESH = CYSETTHRESH;
-  unsigned IOCTL_CYSETTIMEOUT = CYSETTIMEOUT;
   unsigned IOCTL_EQL_EMANCIPATE = EQL_EMANCIPATE;
   unsigned IOCTL_EQL_ENSLAVE = EQL_ENSLAVE;
   unsigned IOCTL_EQL_GETMASTRCFG = EQL_GETMASTRCFG;
@@ -876,6 +879,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
   unsigned IOCTL_PIO_UNIMAP = PIO_UNIMAP;
   unsigned IOCTL_PIO_UNIMAPCLR = PIO_UNIMAPCLR;
   unsigned IOCTL_PIO_UNISCRNMAP = PIO_UNISCRNMAP;
+#if SANITIZER_GLIBC
   unsigned IOCTL_SCSI_IOCTL_GET_IDLUN = SCSI_IOCTL_GET_IDLUN;
   unsigned IOCTL_SCSI_IOCTL_PROBE_HOST = SCSI_IOCTL_PROBE_HOST;
   unsigned IOCTL_SCSI_IOCTL_TAGGED_DISABLE = SCSI_IOCTL_TAGGED_DISABLE;
@@ -894,6 +898,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
   unsigned IOCTL_SIOCNRGETPARMS = SIOCNRGETPARMS;
   unsigned IOCTL_SIOCNRRTCTL = SIOCNRRTCTL;
   unsigned IOCTL_SIOCNRSETPARMS = SIOCNRSETPARMS;
+#endif
   unsigned IOCTL_TIOCGSERIAL = TIOCGSERIAL;
   unsigned IOCTL_TIOCSERGETMULTI = TIOCSERGETMULTI;
   unsigned IOCTL_TIOCSERSETMULTI = TIOCSERSETMULTI;
@@ -964,7 +969,7 @@ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phdr);
 CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phnum);
 #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
 
-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
+#if SANITIZER_GLIBC || SANITIZER_FREEBSD
 CHECK_TYPE_SIZE(glob_t);
 CHECK_SIZE_AND_OFFSET(glob_t, gl_pathc);
 CHECK_SIZE_AND_OFFSET(glob_t, gl_pathv);
@@ -975,7 +980,7 @@ CHECK_SIZE_AND_OFFSET(glob_t, gl_readdir);
 CHECK_SIZE_AND_OFFSET(glob_t, gl_opendir);
 CHECK_SIZE_AND_OFFSET(glob_t, gl_lstat);
 CHECK_SIZE_AND_OFFSET(glob_t, gl_stat);
-#endif
+#endif  // SANITIZER_GLIBC || SANITIZER_FREEBSD
 
 CHECK_TYPE_SIZE(addrinfo);
 CHECK_SIZE_AND_OFFSET(addrinfo, ai_flags);
@@ -998,17 +1003,27 @@ CHECK_TYPE_SIZE(iovec);
 CHECK_SIZE_AND_OFFSET(iovec, iov_base);
 CHECK_SIZE_AND_OFFSET(iovec, iov_len);
 
+// In POSIX, int msg_iovlen; socklen_t msg_controllen; socklen_t cmsg_len; but
+// many implementations don't conform to the standard. Since we pick the
+// non-conforming glibc definition, exclude the checks for musl (incompatible
+// sizes but compatible offsets).
 CHECK_TYPE_SIZE(msghdr);
 CHECK_SIZE_AND_OFFSET(msghdr, msg_name);
 CHECK_SIZE_AND_OFFSET(msghdr, msg_namelen);
 CHECK_SIZE_AND_OFFSET(msghdr, msg_iov);
+#if SANITIZER_GLIBC || SANITIZER_ANDROID
 CHECK_SIZE_AND_OFFSET(msghdr, msg_iovlen);
+#endif
 CHECK_SIZE_AND_OFFSET(msghdr, msg_control);
+#if SANITIZER_GLIBC || SANITIZER_ANDROID
 CHECK_SIZE_AND_OFFSET(msghdr, msg_controllen);
+#endif
 CHECK_SIZE_AND_OFFSET(msghdr, msg_flags);
 
 CHECK_TYPE_SIZE(cmsghdr);
+#if SANITIZER_GLIBC || SANITIZER_ANDROID
 CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_len);
+#endif
 CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_level);
 CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_type);
 
@@ -1116,7 +1131,7 @@ CHECK_SIZE_AND_OFFSET(mntent, mnt_passno);
 
 CHECK_TYPE_SIZE(ether_addr);
 
-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
+#if SANITIZER_GLIBC || SANITIZER_FREEBSD
 CHECK_TYPE_SIZE(ipc_perm);
 # if SANITIZER_FREEBSD
 CHECK_SIZE_AND_OFFSET(ipc_perm, key);
@@ -1178,7 +1193,7 @@ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_dstaddr);
 CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_data);
 #endif
 
-#if SANITIZER_LINUX
+#if SANITIZER_GLIBC || SANITIZER_ANDROID
 COMPILER_CHECK(sizeof(__sanitizer_struct_mallinfo) == sizeof(struct mallinfo));
 #endif
 
@@ -1228,7 +1243,7 @@ COMPILER_CHECK(__sanitizer_XDR_DECODE == XDR_DECODE);
 COMPILER_CHECK(__sanitizer_XDR_FREE == XDR_FREE);
 #endif
 
-#if SANITIZER_LINUX && !SANITIZER_ANDROID
+#if SANITIZER_GLIBC
 COMPILER_CHECK(sizeof(__sanitizer_FILE) <= sizeof(FILE));
 CHECK_SIZE_AND_OFFSET(FILE, _flags);
 CHECK_SIZE_AND_OFFSET(FILE, _IO_read_ptr);
@@ -1245,9 +1260,7 @@ CHECK_SIZE_AND_OFFSET(FILE, _IO_save_end);
 CHECK_SIZE_AND_OFFSET(FILE, _markers);
 CHECK_SIZE_AND_OFFSET(FILE, _chain);
 CHECK_SIZE_AND_OFFSET(FILE, _fileno);
-#endif
 
-#if SANITIZER_LINUX && !SANITIZER_ANDROID
 COMPILER_CHECK(sizeof(__sanitizer__obstack_chunk) <= sizeof(_obstack_chunk));
 CHECK_SIZE_AND_OFFSET(_obstack_chunk, limit);
 CHECK_SIZE_AND_OFFSET(_obstack_chunk, prev);
@@ -1262,7 +1275,7 @@ CHECK_SIZE_AND_OFFSET(cookie_io_functions_t, read);
 CHECK_SIZE_AND_OFFSET(cookie_io_functions_t, write);
 CHECK_SIZE_AND_OFFSET(cookie_io_functions_t, seek);
 CHECK_SIZE_AND_OFFSET(cookie_io_functions_t, close);
-#endif
+#endif  // SANITIZER_GLIBC
 
 #if SANITIZER_LINUX || SANITIZER_FREEBSD
 CHECK_TYPE_SIZE(sem_t);
lib/tsan/sanitizer_common/sanitizer_platform_limits_posix.h
@@ -99,9 +99,9 @@ const unsigned struct_kernel_stat64_sz = 144;
 const unsigned struct___old_kernel_stat_sz = 0;
 const unsigned struct_kernel_stat_sz = 64;
 const unsigned struct_kernel_stat64_sz = 104;
-#elif defined(__riscv) && __riscv_xlen == 64
+#elif SANITIZER_RISCV64
 const unsigned struct_kernel_stat_sz = 128;
-const unsigned struct_kernel_stat64_sz = 104;
+const unsigned struct_kernel_stat64_sz = 0;  // RISCV64 does not use stat64
 #endif
 struct __sanitizer_perf_event_attr {
   unsigned type;
@@ -443,6 +443,8 @@ struct __sanitizer_cmsghdr {
   int cmsg_type;
 };
 #else
+// In POSIX, int msg_iovlen; socklen_t msg_controllen; socklen_t cmsg_len; but
+// many implementations don't conform to the standard.
 struct __sanitizer_msghdr {
   void *msg_name;
   unsigned msg_namelen;
@@ -648,14 +650,14 @@ struct __sanitizer_sigaction {
 #endif // !SANITIZER_ANDROID
 
 #if defined(__mips__)
-struct __sanitizer_kernel_sigset_t {
-  uptr sig[2];
-};
+#define __SANITIZER_KERNEL_NSIG 128
 #else
+#define __SANITIZER_KERNEL_NSIG 64
+#endif
+
 struct __sanitizer_kernel_sigset_t {
-  u8 sig[8];
+  uptr sig[__SANITIZER_KERNEL_NSIG / (sizeof(uptr) * 8)];
 };
-#endif
 
 // Linux system headers define the 'sa_handler' and 'sa_sigaction' macros.
 #if SANITIZER_MIPS
@@ -804,7 +806,7 @@ typedef void __sanitizer_FILE;
 #if SANITIZER_LINUX && !SANITIZER_ANDROID &&                               \
     (defined(__i386) || defined(__x86_64) || defined(__mips64) ||          \
      defined(__powerpc64__) || defined(__aarch64__) || defined(__arm__) || \
-     defined(__s390__))
+     defined(__s390__) || SANITIZER_RISCV64)
 extern unsigned struct_user_regs_struct_sz;
 extern unsigned struct_user_fpregs_struct_sz;
 extern unsigned struct_user_fpxregs_struct_sz;
@@ -981,7 +983,6 @@ extern unsigned struct_vt_mode_sz;
 
 #if SANITIZER_LINUX && !SANITIZER_ANDROID
 extern unsigned struct_ax25_parms_struct_sz;
-extern unsigned struct_cyclades_monitor_sz;
 extern unsigned struct_input_keymap_entry_sz;
 extern unsigned struct_ipx_config_data_sz;
 extern unsigned struct_kbdiacrs_sz;
@@ -1326,15 +1327,6 @@ extern unsigned IOCTL_VT_WAITACTIVE;
 #endif  // SANITIZER_LINUX
 
 #if SANITIZER_LINUX && !SANITIZER_ANDROID
-extern unsigned IOCTL_CYGETDEFTHRESH;
-extern unsigned IOCTL_CYGETDEFTIMEOUT;
-extern unsigned IOCTL_CYGETMON;
-extern unsigned IOCTL_CYGETTHRESH;
-extern unsigned IOCTL_CYGETTIMEOUT;
-extern unsigned IOCTL_CYSETDEFTHRESH;
-extern unsigned IOCTL_CYSETDEFTIMEOUT;
-extern unsigned IOCTL_CYSETTHRESH;
-extern unsigned IOCTL_CYSETTIMEOUT;
 extern unsigned IOCTL_EQL_EMANCIPATE;
 extern unsigned IOCTL_EQL_ENSLAVE;
 extern unsigned IOCTL_EQL_GETMASTRCFG;
lib/tsan/sanitizer_common/sanitizer_platform_limits_solaris.cpp
@@ -202,7 +202,8 @@ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_name);
 CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phdr);
 CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phnum);
 
-CHECK_TYPE_SIZE(glob_t);
+// There are additional fields we are not interested in.
+COMPILER_CHECK(sizeof(__sanitizer_glob_t) <= sizeof(glob_t));
 CHECK_SIZE_AND_OFFSET(glob_t, gl_pathc);
 CHECK_SIZE_AND_OFFSET(glob_t, gl_pathv);
 CHECK_SIZE_AND_OFFSET(glob_t, gl_offs);
lib/tsan/sanitizer_common/sanitizer_posix.cpp
@@ -239,6 +239,7 @@ bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
   return true;
 }
 
+#if !SANITIZER_MAC
 void DumpProcessMap() {
   MemoryMappingLayout proc_maps(/*cache_enabled*/true);
   const sptr kBufSize = 4095;
@@ -252,6 +253,7 @@ void DumpProcessMap() {
   Report("End of process memory map.\n");
   UnmapOrDie(filename, kBufSize);
 }
+#endif
 
 const char *GetPwd() {
   return GetEnv("PWD");
@@ -273,8 +275,8 @@ void ReportFile::Write(const char *buffer, uptr length) {
 
 bool GetCodeRangeForFile(const char *module, uptr *start, uptr *end) {
   MemoryMappingLayout proc_maps(/*cache_enabled*/false);
-  InternalScopedString buff(kMaxPathLength);
-  MemoryMappedSegment segment(buff.data(), kMaxPathLength);
+  InternalMmapVector<char> buff(kMaxPathLength);
+  MemoryMappedSegment segment(buff.data(), buff.size());
   while (proc_maps.Next(&segment)) {
     if (segment.IsExecutable() &&
         internal_strcmp(module, segment.filename) == 0) {
@@ -293,7 +295,7 @@ uptr SignalContext::GetAddress() const {
 
 bool SignalContext::IsMemoryAccess() const {
   auto si = static_cast<const siginfo_t *>(siginfo);
-  return si->si_signo == SIGSEGV;
+  return si->si_signo == SIGSEGV || si->si_signo == SIGBUS;
 }
 
 int SignalContext::GetType() const {
@@ -354,11 +356,11 @@ int GetNamedMappingFd(const char *name, uptr size, int *flags) {
   int fd = ReserveStandardFds(
       internal_open(shmname, O_RDWR | O_CREAT | O_TRUNC | o_cloexec, S_IRWXU));
   CHECK_GE(fd, 0);
-  if (!o_cloexec) {
-    int res = fcntl(fd, F_SETFD, FD_CLOEXEC);
-    CHECK_EQ(0, res);
-  }
   int res = internal_ftruncate(fd, size);
+#if !defined(O_CLOEXEC)
+  res = fcntl(fd, F_SETFD, FD_CLOEXEC);
+  CHECK_EQ(0, res);
+#endif
   CHECK_EQ(0, res);
   res = internal_unlink(shmname);
   CHECK_EQ(0, res);
lib/tsan/sanitizer_common/sanitizer_posix.h
@@ -17,7 +17,6 @@
 #include "sanitizer_internal_defs.h"
 #include "sanitizer_platform_limits_freebsd.h"
 #include "sanitizer_platform_limits_netbsd.h"
-#include "sanitizer_platform_limits_openbsd.h"
 #include "sanitizer_platform_limits_posix.h"
 #include "sanitizer_platform_limits_solaris.h"
 
@@ -41,7 +40,12 @@ uptr internal_write(fd_t fd, const void *buf, uptr count);
 uptr internal_mmap(void *addr, uptr length, int prot, int flags,
                    int fd, u64 offset);
 uptr internal_munmap(void *addr, uptr length);
+#if SANITIZER_LINUX
+uptr internal_mremap(void *old_address, uptr old_size, uptr new_size, int flags,
+                     void *new_address);
+#endif
 int internal_mprotect(void *addr, uptr length, int prot);
+int internal_madvise(uptr addr, uptr length, int advice);
 
 // OS
 uptr internal_filesize(fd_t fd);  // -1 on error.
lib/tsan/sanitizer_common/sanitizer_posix_libcdep.cpp
@@ -18,7 +18,6 @@
 #include "sanitizer_common.h"
 #include "sanitizer_flags.h"
 #include "sanitizer_platform_limits_netbsd.h"
-#include "sanitizer_platform_limits_openbsd.h"
 #include "sanitizer_platform_limits_posix.h"
 #include "sanitizer_platform_limits_solaris.h"
 #include "sanitizer_posix.h"
@@ -61,27 +60,24 @@ void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
   uptr beg_aligned = RoundUpTo(beg, page_size);
   uptr end_aligned = RoundDownTo(end, page_size);
   if (beg_aligned < end_aligned)
-    // In the default Solaris compilation environment, madvise() is declared
-    // to take a caddr_t arg; casting it to void * results in an invalid
-    // conversion error, so use char * instead.
-    madvise((char *)beg_aligned, end_aligned - beg_aligned,
-            SANITIZER_MADVISE_DONTNEED);
+    internal_madvise(beg_aligned, end_aligned - beg_aligned,
+                     SANITIZER_MADVISE_DONTNEED);
 }
 
 void SetShadowRegionHugePageMode(uptr addr, uptr size) {
 #ifdef MADV_NOHUGEPAGE  // May not be defined on old systems.
   if (common_flags()->no_huge_pages_for_shadow)
-    madvise((char *)addr, size, MADV_NOHUGEPAGE);
+    internal_madvise(addr, size, MADV_NOHUGEPAGE);
   else
-    madvise((char *)addr, size, MADV_HUGEPAGE);
+    internal_madvise(addr, size, MADV_HUGEPAGE);
 #endif  // MADV_NOHUGEPAGE
 }
 
 bool DontDumpShadowMemory(uptr addr, uptr length) {
 #if defined(MADV_DONTDUMP)
-  return madvise((char *)addr, length, MADV_DONTDUMP) == 0;
+  return internal_madvise(addr, length, MADV_DONTDUMP) == 0;
 #elif defined(MADV_NOCORE)
-  return madvise((char *)addr, length, MADV_NOCORE) == 0;
+  return internal_madvise(addr, length, MADV_NOCORE) == 0;
 #else
   return true;
 #endif  // MADV_DONTDUMP
@@ -132,14 +128,6 @@ void SetAddressSpaceUnlimited() {
   CHECK(AddressSpaceIsUnlimited());
 }
 
-void SleepForSeconds(int seconds) {
-  sleep(seconds);
-}
-
-void SleepForMillis(int millis) {
-  usleep(millis * 1000);
-}
-
 void Abort() {
 #if !SANITIZER_GO
   // If we are handling SIGABRT, unhandle it first.
@@ -147,7 +135,7 @@ void Abort() {
   if (GetHandleSignalMode(SIGABRT) != kHandleSignalNo) {
     struct sigaction sigact;
     internal_memset(&sigact, 0, sizeof(sigact));
-    sigact.sa_sigaction = (sa_sigaction_t)SIG_DFL;
+    sigact.sa_handler = SIG_DFL;
     internal_sigaction(SIGABRT, &sigact, nullptr);
   }
 #endif
@@ -169,7 +157,12 @@ bool SupportsColoredOutput(fd_t fd) {
 
 #if !SANITIZER_GO
 // TODO(glider): different tools may require different altstack size.
-static const uptr kAltStackSize = SIGSTKSZ * 4;  // SIGSTKSZ is not enough.
+static uptr GetAltStackSize() {
+  // Note: since GLIBC_2.31, SIGSTKSZ may be a function call, so this may be
+  // more costly that you think. However GetAltStackSize is only call 2-3 times
+  // per thread so don't cache the evaluation.
+  return SIGSTKSZ * 4;
+}
 
 void SetAlternateSignalStack() {
   stack_t altstack, oldstack;
@@ -180,10 +173,9 @@ void SetAlternateSignalStack() {
   // TODO(glider): the mapped stack should have the MAP_STACK flag in the
   // future. It is not required by man 2 sigaltstack now (they're using
   // malloc()).
-  void* base = MmapOrDie(kAltStackSize, __func__);
-  altstack.ss_sp = (char*) base;
+  altstack.ss_size = GetAltStackSize();
+  altstack.ss_sp = (char *)MmapOrDie(altstack.ss_size, __func__);
   altstack.ss_flags = 0;
-  altstack.ss_size = kAltStackSize;
   CHECK_EQ(0, sigaltstack(&altstack, nullptr));
 }
 
@@ -191,7 +183,7 @@ void UnsetAlternateSignalStack() {
   stack_t altstack, oldstack;
   altstack.ss_sp = nullptr;
   altstack.ss_flags = SS_DISABLE;
-  altstack.ss_size = kAltStackSize;  // Some sane value required on Darwin.
+  altstack.ss_size = GetAltStackSize();  // Some sane value required on Darwin.
   CHECK_EQ(0, sigaltstack(&altstack, &oldstack));
   UnmapOrDie(oldstack.ss_sp, oldstack.ss_size);
 }
lib/tsan/sanitizer_common/sanitizer_printf.cpp
@@ -20,6 +20,10 @@
 #include <stdio.h>
 #include <stdarg.h>
 
+#if defined(__x86_64__)
+#  include <emmintrin.h>
+#endif
+
 #if SANITIZER_WINDOWS && defined(_MSC_VER) && _MSC_VER < 1800 &&               \
       !defined(va_copy)
 # define va_copy(dst, src) ((dst) = (src))
@@ -128,7 +132,7 @@ static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
 int VSNPrintf(char *buff, int buff_length,
               const char *format, va_list args) {
   static const char *kPrintfFormatsHelp =
-      "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x,X}; %p; "
+      "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x,X,V}; %p; "
       "%[-]([0-9]*)?(\\.\\*)?s; %c\n";
   RAW_CHECK(format);
   RAW_CHECK(buff_length > 0);
@@ -162,17 +166,15 @@ int VSNPrintf(char *buff, int buff_length,
     cur += have_z;
     bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
     cur += have_ll * 2;
-    s64 dval;
-    u64 uval;
     const bool have_length = have_z || have_ll;
     const bool have_flags = have_width || have_length;
     // At the moment only %s supports precision and left-justification.
     CHECK(!((precision >= 0 || left_justified) && *cur != 's'));
     switch (*cur) {
       case 'd': {
-        dval = have_ll ? va_arg(args, s64)
-             : have_z ? va_arg(args, sptr)
-             : va_arg(args, int);
+        s64 dval = have_ll  ? va_arg(args, s64)
+                   : have_z ? va_arg(args, sptr)
+                            : va_arg(args, int);
         result += AppendSignedDecimal(&buff, buff_end, dval, width,
                                       pad_with_zero);
         break;
@@ -180,14 +182,21 @@ int VSNPrintf(char *buff, int buff_length,
       case 'u':
       case 'x':
       case 'X': {
-        uval = have_ll ? va_arg(args, u64)
-             : have_z ? va_arg(args, uptr)
-             : va_arg(args, unsigned);
+        u64 uval = have_ll  ? va_arg(args, u64)
+                   : have_z ? va_arg(args, uptr)
+                            : va_arg(args, unsigned);
         bool uppercase = (*cur == 'X');
         result += AppendUnsigned(&buff, buff_end, uval, (*cur == 'u') ? 10 : 16,
                                  width, pad_with_zero, uppercase);
         break;
       }
+      case 'V': {
+        for (uptr i = 0; i < 16; i++) {
+          unsigned x = va_arg(args, unsigned);
+          result += AppendUnsigned(&buff, buff_end, x, 16, 2, true, false);
+        }
+        break;
+      }
       case 'p': {
         RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
         result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
@@ -249,26 +258,21 @@ static void NOINLINE SharedPrintfCodeNoBuffer(bool append_pid,
                                               va_list args) {
   va_list args2;
   va_copy(args2, args);
-  const int kLen = 16 * 1024;
-  int needed_length;
+  InternalMmapVector<char> v;
+  int needed_length = 0;
   char *buffer = local_buffer;
   // First try to print a message using a local buffer, and then fall back to
   // mmaped buffer.
-  for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
+  for (int use_mmap = 0;; use_mmap++) {
     if (use_mmap) {
       va_end(args);
       va_copy(args, args2);
-      buffer = (char*)MmapOrDie(kLen, "Report");
-      buffer_size = kLen;
+      v.resize(needed_length + 1);
+      buffer_size = v.capacity();
+      v.resize(buffer_size);
+      buffer = &v[0];
     }
     needed_length = 0;
-    // Check that data fits into the current buffer.
-#   define CHECK_NEEDED_LENGTH \
-      if (needed_length >= buffer_size) { \
-        if (!use_mmap) continue; \
-        RAW_CHECK_MSG(needed_length < kLen, \
-                      "Buffer in Report is too short!\n"); \
-      }
     // Fuchsia's logging infrastructure always keeps track of the logging
     // process, thread, and timestamp, so never prepend such information.
     if (!SANITIZER_FUCHSIA && append_pid) {
@@ -277,18 +281,20 @@ static void NOINLINE SharedPrintfCodeNoBuffer(bool append_pid,
       if (common_flags()->log_exe_name && exe_name) {
         needed_length += internal_snprintf(buffer, buffer_size,
                                            "==%s", exe_name);
-        CHECK_NEEDED_LENGTH
+        if (needed_length >= buffer_size)
+          continue;
       }
       needed_length += internal_snprintf(
           buffer + needed_length, buffer_size - needed_length, "==%d==", pid);
-      CHECK_NEEDED_LENGTH
+      if (needed_length >= buffer_size)
+        continue;
     }
     needed_length += VSNPrintf(buffer + needed_length,
                                buffer_size - needed_length, format, args);
-    CHECK_NEEDED_LENGTH
+    if (needed_length >= buffer_size)
+      continue;
     // If the message fit into the buffer, print it and exit.
     break;
-#   undef CHECK_NEEDED_LENGTH
   }
   RawWrite(buffer);
 
@@ -297,9 +303,6 @@ static void NOINLINE SharedPrintfCodeNoBuffer(bool append_pid,
   CallPrintfAndReportCallback(buffer);
   LogMessageOnPrintf(buffer);
 
-  // If we had mapped any memory, clean up.
-  if (buffer != local_buffer)
-    UnmapOrDie((void *)buffer, buffer_size);
   va_end(args2);
 }
 
@@ -346,13 +349,24 @@ int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
 
 FORMAT(2, 3)
 void InternalScopedString::append(const char *format, ...) {
-  CHECK_LT(length_, size());
-  va_list args;
-  va_start(args, format);
-  VSNPrintf(data() + length_, size() - length_, format, args);
-  va_end(args);
-  length_ += internal_strlen(data() + length_);
-  CHECK_LT(length_, size());
+  uptr prev_len = length();
+
+  while (true) {
+    buffer_.resize(buffer_.capacity());
+
+    va_list args;
+    va_start(args, format);
+    uptr sz = VSNPrintf(buffer_.data() + prev_len, buffer_.size() - prev_len,
+                        format, args);
+    va_end(args);
+    if (sz < buffer_.size() - prev_len) {
+      buffer_.resize(prev_len + sz + 1);
+      break;
+    }
+
+    buffer_.reserve(buffer_.capacity() * 2);
+  }
+  CHECK_EQ(buffer_[length()], '\0');
 }
 
 } // namespace __sanitizer
lib/tsan/sanitizer_common/sanitizer_procmaps.h
@@ -16,7 +16,7 @@
 #include "sanitizer_platform.h"
 
 #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD || \
-    SANITIZER_OPENBSD || SANITIZER_MAC || SANITIZER_SOLARIS ||  \
+    SANITIZER_MAC || SANITIZER_SOLARIS ||  \
     SANITIZER_FUCHSIA
 
 #include "sanitizer_common.h"
lib/tsan/sanitizer_common/sanitizer_procmaps_bsd.cpp
@@ -7,11 +7,11 @@
 //===----------------------------------------------------------------------===//
 //
 // Information about the process mappings
-// (FreeBSD, OpenBSD and NetBSD-specific parts).
+// (FreeBSD and NetBSD-specific parts).
 //===----------------------------------------------------------------------===//
 
 #include "sanitizer_platform.h"
-#if SANITIZER_FREEBSD || SANITIZER_NETBSD || SANITIZER_OPENBSD
+#if SANITIZER_FREEBSD || SANITIZER_NETBSD
 #include "sanitizer_common.h"
 #if SANITIZER_FREEBSD
 #include "sanitizer_freebsd.h"
@@ -28,11 +28,6 @@
 #endif
 
 #include <limits.h>
-#if SANITIZER_OPENBSD
-#define KVME_PROT_READ KVE_PROT_READ
-#define KVME_PROT_WRITE KVE_PROT_WRITE
-#define KVME_PROT_EXEC KVE_PROT_EXEC
-#endif
 
 // Fix 'kinfo_vmentry' definition on FreeBSD prior v9.2 in 32-bit mode.
 #if SANITIZER_FREEBSD && (SANITIZER_WORDSIZE == 32)
@@ -51,10 +46,6 @@ void ReadProcMaps(ProcSelfMapsBuff *proc_maps) {
     KERN_PROC,
     KERN_PROC_VMMAP,
     getpid()
-#elif SANITIZER_OPENBSD
-    CTL_KERN,
-    KERN_PROC_VMMAP,
-    getpid()
 #elif SANITIZER_NETBSD
     CTL_VM,
     VM_PROC,
@@ -71,28 +62,12 @@ void ReadProcMaps(ProcSelfMapsBuff *proc_maps) {
   CHECK_EQ(Err, 0);
   CHECK_GT(Size, 0);
 
-#if !SANITIZER_OPENBSD
   size_t MmapedSize = Size * 4 / 3;
   void *VmMap = MmapOrDie(MmapedSize, "ReadProcMaps()");
   Size = MmapedSize;
   Err = internal_sysctl(Mib, ARRAY_SIZE(Mib), VmMap, &Size, NULL, 0);
   CHECK_EQ(Err, 0);
   proc_maps->data = (char *)VmMap;
-#else
-  size_t PageSize = GetPageSize();
-  size_t MmapedSize = Size;
-  MmapedSize = ((MmapedSize - 1) / PageSize + 1) * PageSize;
-  char *Mem = (char *)MmapOrDie(MmapedSize, "ReadProcMaps()");
-  Size = 2 * Size + 10 * sizeof(struct kinfo_vmentry);
-  if (Size > 0x10000)
-    Size = 0x10000;
-  Size = (Size / sizeof(struct kinfo_vmentry)) * sizeof(struct kinfo_vmentry);
-  Err = internal_sysctl(Mib, ARRAY_SIZE(Mib), Mem, &Size, NULL, 0);
-  CHECK_EQ(Err, 0);
-  MmapedSize = Size;
-  proc_maps->data = Mem;
-#endif
-
   proc_maps->mmaped_size = MmapedSize;
   proc_maps->len = Size;
 }
@@ -117,13 +92,11 @@ bool MemoryMappingLayout::Next(MemoryMappedSegment *segment) {
   if ((VmEntry->kve_protection & KVME_PROT_EXEC) != 0)
     segment->protection |= kProtectionExecute;
 
-#if !SANITIZER_OPENBSD
   if (segment->filename != NULL && segment->filename_size > 0) {
     internal_snprintf(segment->filename,
                       Min(segment->filename_size, (uptr)PATH_MAX), "%s",
                       VmEntry->kve_path);
   }
-#endif
 
 #if SANITIZER_FREEBSD
   data_.current += VmEntry->kve_structsize;
lib/tsan/sanitizer_common/sanitizer_procmaps_common.cpp
@@ -12,7 +12,7 @@
 #include "sanitizer_platform.h"
 
 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD ||                \
-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
+    SANITIZER_SOLARIS
 
 #include "sanitizer_common.h"
 #include "sanitizer_placement_new.h"
@@ -120,7 +120,7 @@ void MemoryMappingLayout::LoadFromCache() {
 void MemoryMappingLayout::DumpListOfModules(
     InternalMmapVectorNoCtor<LoadedModule> *modules) {
   Reset();
-  InternalScopedString module_name(kMaxPathLength);
+  InternalMmapVector<char> module_name(kMaxPathLength);
   MemoryMappedSegment segment(module_name.data(), module_name.size());
   for (uptr i = 0; Next(&segment); i++) {
     const char *cur_name = segment.filename;
lib/tsan/sanitizer_common/sanitizer_procmaps_mac.cpp
@@ -354,8 +354,8 @@ bool MemoryMappingLayout::Next(MemoryMappedSegment *segment) {
 void MemoryMappingLayout::DumpListOfModules(
     InternalMmapVectorNoCtor<LoadedModule> *modules) {
   Reset();
-  InternalScopedString module_name(kMaxPathLength);
-  MemoryMappedSegment segment(module_name.data(), kMaxPathLength);
+  InternalMmapVector<char> module_name(kMaxPathLength);
+  MemoryMappedSegment segment(module_name.data(), module_name.size());
   MemoryMappedSegmentData data;
   segment.data_ = &data;
   while (Next(&segment)) {
lib/tsan/sanitizer_common/sanitizer_procmaps_solaris.cpp
@@ -9,13 +9,13 @@
 // Information about the process mappings (Solaris-specific parts).
 //===----------------------------------------------------------------------===//
 
+// Before Solaris 11.4, <procfs.h> doesn't work in a largefile environment.
+#undef _FILE_OFFSET_BITS
 #include "sanitizer_platform.h"
 #if SANITIZER_SOLARIS
 #include "sanitizer_common.h"
 #include "sanitizer_procmaps.h"
 
-// Before Solaris 11.4, <procfs.h> doesn't work in a largefile environment.
-#undef _FILE_OFFSET_BITS
 #include <procfs.h>
 #include <limits.h>
 
@@ -35,7 +35,8 @@ bool MemoryMappingLayout::Next(MemoryMappedSegment *segment) {
   char *last = data_.proc_self_maps.data + data_.proc_self_maps.len;
   if (data_.current >= last) return false;
 
-  prxmap_t *xmapentry = (prxmap_t*)data_.current;
+  prxmap_t *xmapentry =
+      const_cast<prxmap_t *>(reinterpret_cast<const prxmap_t *>(data_.current));
 
   segment->start = (uptr)xmapentry->pr_vaddr;
   segment->end = (uptr)(xmapentry->pr_vaddr + xmapentry->pr_size);
lib/tsan/sanitizer_common/sanitizer_ptrauth.h
@@ -11,6 +11,24 @@
 
 #if __has_feature(ptrauth_calls)
 #include <ptrauth.h>
+#elif defined(__ARM_FEATURE_PAC_DEFAULT) && !defined(__APPLE__)
+inline unsigned long ptrauth_strip(void* __value, unsigned int __key) {
+  // On the stack the link register is protected with Pointer
+  // Authentication Code when compiled with -mbranch-protection.
+  // Let's stripping the PAC unconditionally because xpaclri is in
+  // the NOP space so will do nothing when it is not enabled or not available.
+  unsigned long ret;
+  asm volatile(
+      "mov x30, %1\n\t"
+      "hint #7\n\t"  // xpaclri
+      "mov %0, x30\n\t"
+      : "=r"(ret)
+      : "r"(__value)
+      : "x30");
+  return ret;
+}
+#define ptrauth_auth_data(__value, __old_key, __old_data) __value
+#define ptrauth_string_discriminator(__string) ((int)0)
 #else
 // Copied from <ptrauth.h>
 #define ptrauth_strip(__value, __key) __value
@@ -18,4 +36,6 @@
 #define ptrauth_string_discriminator(__string) ((int)0)
 #endif
 
+#define STRIP_PAC_PC(pc) ((uptr)ptrauth_strip(pc, 0))
+
 #endif // SANITIZER_PTRAUTH_H
lib/tsan/sanitizer_common/sanitizer_quarantine.h
@@ -149,7 +149,8 @@ class Quarantine {
   Cache cache_;
   char pad2_[kCacheLineSize];
 
-  void NOINLINE Recycle(uptr min_size, Callback cb) {
+  void NOINLINE Recycle(uptr min_size, Callback cb) REQUIRES(recycle_mutex_)
+      RELEASE(recycle_mutex_) {
     Cache tmp;
     {
       SpinMutexLock l(&cache_mutex_);
lib/tsan/sanitizer_common/sanitizer_rtems.cpp
@@ -1,283 +0,0 @@
-//===-- sanitizer_rtems.cpp -----------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is shared between various sanitizers' runtime libraries and
-// implements RTEMS-specific functions.
-//===----------------------------------------------------------------------===//
-
-#include "sanitizer_rtems.h"
-#if SANITIZER_RTEMS
-
-#define posix_memalign __real_posix_memalign
-#define free __real_free
-#define memset __real_memset
-
-#include "sanitizer_file.h"
-#include "sanitizer_symbolizer.h"
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <sched.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-// There is no mmap on RTEMS.  Use memalign, etc.
-#define __mmap_alloc_aligned posix_memalign
-#define __mmap_free free
-#define __mmap_memset memset
-
-namespace __sanitizer {
-
-#include "sanitizer_syscall_generic.inc"
-
-void NORETURN internal__exit(int exitcode) {
-  _exit(exitcode);
-}
-
-uptr internal_sched_yield() {
-  return sched_yield();
-}
-
-uptr internal_getpid() {
-  return getpid();
-}
-
-int internal_dlinfo(void *handle, int request, void *p) {
-  UNIMPLEMENTED();
-}
-
-bool FileExists(const char *filename) {
-  struct stat st;
-  if (stat(filename, &st))
-    return false;
-  // Sanity check: filename is a regular file.
-  return S_ISREG(st.st_mode);
-}
-
-uptr GetThreadSelf() { return static_cast<uptr>(pthread_self()); }
-
-tid_t GetTid() { return GetThreadSelf(); }
-
-void Abort() { abort(); }
-
-int Atexit(void (*function)(void)) { return atexit(function); }
-
-void SleepForSeconds(int seconds) { sleep(seconds); }
-
-void SleepForMillis(int millis) { usleep(millis * 1000); }
-
-bool SupportsColoredOutput(fd_t fd) { return false; }
-
-void GetThreadStackTopAndBottom(bool at_initialization,
-                                uptr *stack_top, uptr *stack_bottom) {
-  pthread_attr_t attr;
-  pthread_attr_init(&attr);
-  CHECK_EQ(pthread_getattr_np(pthread_self(), &attr), 0);
-  void *base = nullptr;
-  size_t size = 0;
-  CHECK_EQ(pthread_attr_getstack(&attr, &base, &size), 0);
-  CHECK_EQ(pthread_attr_destroy(&attr), 0);
-
-  *stack_bottom = reinterpret_cast<uptr>(base);
-  *stack_top = *stack_bottom + size;
-}
-
-void GetThreadStackAndTls(bool main, uptr *stk_addr, uptr *stk_size,
-                          uptr *tls_addr, uptr *tls_size) {
-  uptr stack_top, stack_bottom;
-  GetThreadStackTopAndBottom(main, &stack_top, &stack_bottom);
-  *stk_addr = stack_bottom;
-  *stk_size = stack_top - stack_bottom;
-  *tls_addr = *tls_size = 0;
-}
-
-void InitializePlatformEarly() {}
-void MaybeReexec() {}
-void CheckASLR() {}
-void CheckMPROTECT() {}
-void DisableCoreDumperIfNecessary() {}
-void InstallDeadlySignalHandlers(SignalHandlerType handler) {}
-void SetAlternateSignalStack() {}
-void UnsetAlternateSignalStack() {}
-void InitTlsSize() {}
-
-void PrintModuleMap() {}
-
-void SignalContext::DumpAllRegisters(void *context) {}
-const char *DescribeSignalOrException(int signo) { UNIMPLEMENTED(); }
-
-enum MutexState { MtxUnlocked = 0, MtxLocked = 1, MtxSleeping = 2 };
-
-BlockingMutex::BlockingMutex() {
-  internal_memset(this, 0, sizeof(*this));
-}
-
-void BlockingMutex::Lock() {
-  CHECK_EQ(owner_, 0);
-  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
-  if (atomic_exchange(m, MtxLocked, memory_order_acquire) == MtxUnlocked)
-    return;
-  while (atomic_exchange(m, MtxSleeping, memory_order_acquire) != MtxUnlocked) {
-    internal_sched_yield();
-  }
-}
-
-void BlockingMutex::Unlock() {
-  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
-  u32 v = atomic_exchange(m, MtxUnlocked, memory_order_release);
-  CHECK_NE(v, MtxUnlocked);
-}
-
-void BlockingMutex::CheckLocked() {
-  atomic_uint32_t *m = reinterpret_cast<atomic_uint32_t *>(&opaque_storage_);
-  CHECK_NE(MtxUnlocked, atomic_load(m, memory_order_relaxed));
-}
-
-uptr GetPageSize() { return getpagesize(); }
-
-uptr GetMmapGranularity() { return GetPageSize(); }
-
-uptr GetMaxVirtualAddress() {
-  return (1ULL << 32) - 1;  // 0xffffffff
-}
-
-void *MmapOrDie(uptr size, const char *mem_type, bool raw_report) {
-  void* ptr = 0;
-  int res = __mmap_alloc_aligned(&ptr, GetPageSize(), size);
-  if (UNLIKELY(res))
-    ReportMmapFailureAndDie(size, mem_type, "allocate", res, raw_report);
-  __mmap_memset(ptr, 0, size);
-  IncreaseTotalMmap(size);
-  return ptr;
-}
-
-void *MmapOrDieOnFatalError(uptr size, const char *mem_type) {
-  void* ptr = 0;
-  int res = __mmap_alloc_aligned(&ptr, GetPageSize(), size);
-  if (UNLIKELY(res)) {
-    if (res == ENOMEM)
-      return nullptr;
-    ReportMmapFailureAndDie(size, mem_type, "allocate", false);
-  }
-  __mmap_memset(ptr, 0, size);
-  IncreaseTotalMmap(size);
-  return ptr;
-}
-
-void *MmapAlignedOrDieOnFatalError(uptr size, uptr alignment,
-                                   const char *mem_type) {
-  CHECK(IsPowerOfTwo(size));
-  CHECK(IsPowerOfTwo(alignment));
-  void* ptr = 0;
-  int res = __mmap_alloc_aligned(&ptr, alignment, size);
-  if (res)
-    ReportMmapFailureAndDie(size, mem_type, "align allocate", res, false);
-  __mmap_memset(ptr, 0, size);
-  IncreaseTotalMmap(size);
-  return ptr;
-}
-
-void *MmapNoReserveOrDie(uptr size, const char *mem_type) {
-  return MmapOrDie(size, mem_type, false);
-}
-
-void UnmapOrDie(void *addr, uptr size) {
-  if (!addr || !size) return;
-  __mmap_free(addr);
-  DecreaseTotalMmap(size);
-}
-
-fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *errno_p) {
-  int flags;
-  switch (mode) {
-    case RdOnly: flags = O_RDONLY; break;
-    case WrOnly: flags = O_WRONLY | O_CREAT | O_TRUNC; break;
-    case RdWr: flags = O_RDWR | O_CREAT; break;
-  }
-  fd_t res = open(filename, flags, 0660);
-  if (internal_iserror(res, errno_p))
-    return kInvalidFd;
-  return res;
-}
-
-void CloseFile(fd_t fd) {
-  close(fd);
-}
-
-bool ReadFromFile(fd_t fd, void *buff, uptr buff_size, uptr *bytes_read,
-                  error_t *error_p) {
-  uptr res = read(fd, buff, buff_size);
-  if (internal_iserror(res, error_p))
-    return false;
-  if (bytes_read)
-    *bytes_read = res;
-  return true;
-}
-
-bool WriteToFile(fd_t fd, const void *buff, uptr buff_size, uptr *bytes_written,
-                 error_t *error_p) {
-  uptr res = write(fd, buff, buff_size);
-  if (internal_iserror(res, error_p))
-    return false;
-  if (bytes_written)
-    *bytes_written = res;
-  return true;
-}
-
-void ReleaseMemoryPagesToOS(uptr beg, uptr end) {}
-void DumpProcessMap() {}
-
-// There is no page protection so everything is "accessible."
-bool IsAccessibleMemoryRange(uptr beg, uptr size) {
-  return true;
-}
-
-char **GetArgv() { return nullptr; }
-char **GetEnviron() { return nullptr; }
-
-const char *GetEnv(const char *name) {
-  return getenv(name);
-}
-
-uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
-  internal_strncpy(buf, "StubBinaryName", buf_len);
-  return internal_strlen(buf);
-}
-
-uptr ReadLongProcessName(/*out*/ char *buf, uptr buf_len) {
-  internal_strncpy(buf, "StubProcessName", buf_len);
-  return internal_strlen(buf);
-}
-
-bool IsPathSeparator(const char c) {
-  return c == '/';
-}
-
-bool IsAbsolutePath(const char *path) {
-  return path != nullptr && IsPathSeparator(path[0]);
-}
-
-void ReportFile::Write(const char *buffer, uptr length) {
-  SpinMutexLock l(mu);
-  static const char *kWriteError =
-      "ReportFile::Write() can't output requested buffer!\n";
-  ReopenIfNecessary();
-  if (length != write(fd, buffer, length)) {
-    write(fd, kWriteError, internal_strlen(kWriteError));
-    Die();
-  }
-}
-
-uptr MainThreadStackBase, MainThreadStackSize;
-uptr MainThreadTlsBase, MainThreadTlsSize;
-
-} // namespace __sanitizer
-
-#endif  // SANITIZER_RTEMS
lib/tsan/sanitizer_common/sanitizer_rtems.h
@@ -1,20 +0,0 @@
-//===-- sanitizer_rtems.h ---------------------------------------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is shared between various sanitizers' runtime libraries and
-// provides definitions for RTEMS-specific functions.
-//===----------------------------------------------------------------------===//
-#ifndef SANITIZER_RTEMS_H
-#define SANITIZER_RTEMS_H
-
-#include "sanitizer_platform.h"
-#if SANITIZER_RTEMS
-#include "sanitizer_common.h"
-
-#endif  // SANITIZER_RTEMS
-#endif  // SANITIZER_RTEMS_H
lib/tsan/sanitizer_common/sanitizer_signal_interceptors.inc
@@ -53,7 +53,10 @@ INTERCEPTOR(uptr, signal, int signum, uptr handler) {
 
 INTERCEPTOR(int, sigaction_symname, int signum,
             const __sanitizer_sigaction *act, __sanitizer_sigaction *oldact) {
-  if (GetHandleSignalMode(signum) == kHandleSignalExclusive) return 0;
+  if (GetHandleSignalMode(signum) == kHandleSignalExclusive) {
+    if (!oldact) return 0;
+    act = nullptr;
+  }
   SIGNAL_INTERCEPTOR_SIGACTION_IMPL(signum, act, oldact);
 }
 #define INIT_SIGACTION COMMON_INTERCEPT_FUNCTION(sigaction_symname)
lib/tsan/sanitizer_common/sanitizer_solaris.cpp
@@ -74,6 +74,20 @@ DECLARE__REAL_AND_INTERNAL(int, mprotect, void *addr, uptr length, int prot) {
   return _REAL(mprotect)(addr, length, prot);
 }
 
+// Illumos' declaration of madvise cannot be made visible if _XOPEN_SOURCE
+// is defined as g++ does on Solaris.
+//
+// This declaration is consistent with Solaris 11.4. Both Illumos and Solaris
+// versions older than 11.4 declared madvise with a caddr_t as the first
+// argument, but we don't currently support Solaris versions older than 11.4,
+// and as mentioned above the declaration is not visible on Illumos so we can
+// use any declaration we like on Illumos.
+extern "C" int madvise(void *, size_t, int);
+
+int internal_madvise(uptr addr, uptr length, int advice) {
+  return madvise((void *)addr, length, advice);
+}
+
 DECLARE__REAL_AND_INTERNAL(uptr, close, fd_t fd) {
   return _REAL(close)(fd);
 }
@@ -146,8 +160,11 @@ DECLARE__REAL_AND_INTERNAL(uptr, sched_yield, void) {
   return sched_yield();
 }
 
-DECLARE__REAL_AND_INTERNAL(void, _exit, int exitcode) {
-  _exit(exitcode);
+DECLARE__REAL_AND_INTERNAL(void, usleep, u64 useconds) {
+  struct timespec ts;
+  ts.tv_sec = useconds / 1000000;
+  ts.tv_nsec = (useconds % 1000000) * 1000;
+  nanosleep(&ts, nullptr);
 }
 
 DECLARE__REAL_AND_INTERNAL(uptr, execve, const char *filename,
@@ -201,6 +218,13 @@ uptr internal_clock_gettime(__sanitizer_clockid_t clk_id, void *tp) {
 }
 
 // ----------------- sanitizer_common.h
+void FutexWait(atomic_uint32_t *p, u32 cmp) {
+  // FIXME: implement actual blocking.
+  sched_yield();
+}
+
+void FutexWake(atomic_uint32_t *p, u32 count) {}
+
 BlockingMutex::BlockingMutex() {
   CHECK(sizeof(mutex_t) <= sizeof(opaque_storage_));
   internal_memset(this, 0, sizeof(*this));
@@ -221,9 +245,7 @@ void BlockingMutex::Unlock() {
   CHECK_EQ(mutex_unlock((mutex_t *)&opaque_storage_), 0);
 }
 
-void BlockingMutex::CheckLocked() {
-  CHECK_EQ((uptr)thr_self(), owner_);
-}
+void BlockingMutex::CheckLocked() const { CHECK_EQ((uptr)thr_self(), owner_); }
 
 }  // namespace __sanitizer
 
lib/tsan/sanitizer_common/sanitizer_stackdepot.cpp
@@ -115,6 +115,12 @@ void StackDepotUnlockAll() {
   theDepot.UnlockAll();
 }
 
+void StackDepotPrintAll() {
+#if !SANITIZER_GO
+  theDepot.PrintAll();
+#endif
+}
+
 bool StackDepotReverseMap::IdDescPair::IdComparator(
     const StackDepotReverseMap::IdDescPair &a,
     const StackDepotReverseMap::IdDescPair &b) {
@@ -139,8 +145,7 @@ StackTrace StackDepotReverseMap::Get(u32 id) {
   if (!map_.size())
     return StackTrace();
   IdDescPair pair = {id, nullptr};
-  uptr idx =
-      InternalLowerBound(map_, 0, map_.size(), pair, IdDescPair::IdComparator);
+  uptr idx = InternalLowerBound(map_, pair, IdDescPair::IdComparator);
   if (idx > map_.size() || map_[idx].id != id)
     return StackTrace();
   return map_[idx].desc->load();
lib/tsan/sanitizer_common/sanitizer_stackdepot.h
@@ -41,6 +41,7 @@ StackTrace StackDepotGet(u32 id);
 
 void StackDepotLockAll();
 void StackDepotUnlockAll();
+void StackDepotPrintAll();
 
 // Instantiating this class creates a snapshot of StackDepot which can be
 // efficiently queried with StackDepotGet(). You can use it concurrently with
lib/tsan/sanitizer_common/sanitizer_stackdepotbase.h
@@ -13,9 +13,11 @@
 #ifndef SANITIZER_STACKDEPOTBASE_H
 #define SANITIZER_STACKDEPOTBASE_H
 
+#include <stdio.h>
+
+#include "sanitizer_atomic.h"
 #include "sanitizer_internal_defs.h"
 #include "sanitizer_mutex.h"
-#include "sanitizer_atomic.h"
 #include "sanitizer_persistent_allocator.h"
 
 namespace __sanitizer {
@@ -34,6 +36,7 @@ class StackDepotBase {
 
   void LockAll();
   void UnlockAll();
+  void PrintAll();
 
  private:
   static Node *find(Node *s, args_type args, u32 hash);
@@ -172,6 +175,21 @@ void StackDepotBase<Node, kReservedBits, kTabSizeLog>::UnlockAll() {
   }
 }
 
+template <class Node, int kReservedBits, int kTabSizeLog>
+void StackDepotBase<Node, kReservedBits, kTabSizeLog>::PrintAll() {
+  for (int i = 0; i < kTabSize; ++i) {
+    atomic_uintptr_t *p = &tab[i];
+    lock(p);
+    uptr v = atomic_load(p, memory_order_relaxed);
+    Node *s = (Node *)(v & ~1UL);
+    for (; s; s = s->link) {
+      Printf("Stack for id %u:\n", s->id);
+      s->load().Print();
+    }
+    unlock(p, s);
+  }
+}
+
 } // namespace __sanitizer
 
 #endif // SANITIZER_STACKDEPOTBASE_H
lib/tsan/sanitizer_common/sanitizer_stacktrace.cpp
@@ -10,9 +10,12 @@
 // run-time libraries.
 //===----------------------------------------------------------------------===//
 
+#include "sanitizer_stacktrace.h"
+
 #include "sanitizer_common.h"
 #include "sanitizer_flags.h"
-#include "sanitizer_stacktrace.h"
+#include "sanitizer_platform.h"
+#include "sanitizer_ptrauth.h"
 
 namespace __sanitizer {
 
@@ -21,6 +24,28 @@ uptr StackTrace::GetNextInstructionPc(uptr pc) {
   return pc + 8;
 #elif defined(__powerpc__) || defined(__arm__) || defined(__aarch64__)
   return pc + 4;
+#elif SANITIZER_RISCV64
+  // Current check order is 4 -> 2 -> 6 -> 8
+  u8 InsnByte = *(u8 *)(pc);
+  if (((InsnByte & 0x3) == 0x3) && ((InsnByte & 0x1c) != 0x1c)) {
+    // xxxxxxxxxxxbbb11 | 32 bit | bbb != 111
+    return pc + 4;
+  }
+  if ((InsnByte & 0x3) != 0x3) {
+    // xxxxxxxxxxxxxxaa | 16 bit | aa != 11
+    return pc + 2;
+  }
+  // RISC-V encoding allows instructions to be up to 8 bytes long
+  if ((InsnByte & 0x3f) == 0x1f) {
+    // xxxxxxxxxx011111 | 48 bit |
+    return pc + 6;
+  }
+  if ((InsnByte & 0x7f) == 0x3f) {
+    // xxxxxxxxx0111111 | 64 bit |
+    return pc + 8;
+  }
+  // bail-out if could not figure out the instruction size
+  return 0;
 #else
   return pc + 1;
 #endif
@@ -94,8 +119,11 @@ void BufferedStackTrace::UnwindFast(uptr pc, uptr bp, uptr stack_top,
     uhwptr pc1 = caller_frame[2];
 #elif defined(__s390__)
     uhwptr pc1 = frame[14];
+#elif defined(__riscv)
+    // frame[-1] contains the return address
+    uhwptr pc1 = frame[-1];
 #else
-    uhwptr pc1 = frame[1];
+    uhwptr pc1 = STRIP_PAC_PC((void *)frame[1]);
 #endif
     // Let's assume that any pointer in the 0th page (i.e. <0x1000 on i386 and
     // x86_64) is invalid and stop unwinding here.  If we're adding support for
@@ -106,7 +134,13 @@ void BufferedStackTrace::UnwindFast(uptr pc, uptr bp, uptr stack_top,
       trace_buffer[size++] = (uptr) pc1;
     }
     bottom = (uptr)frame;
-    frame = GetCanonicFrame((uptr)frame[0], stack_top, bottom);
+#if defined(__riscv)
+    // frame[-2] contain fp of the previous frame
+    uptr new_bp = (uptr)frame[-2];
+#else
+    uptr new_bp = (uptr)frame[0];
+#endif
+    frame = GetCanonicFrame(new_bp, stack_top, bottom);
   }
 }
 
lib/tsan/sanitizer_common/sanitizer_stacktrace.h
@@ -12,7 +12,9 @@
 #ifndef SANITIZER_STACKTRACE_H
 #define SANITIZER_STACKTRACE_H
 
+#include "sanitizer_common.h"
 #include "sanitizer_internal_defs.h"
+#include "sanitizer_platform.h"
 
 namespace __sanitizer {
 
@@ -24,8 +26,6 @@ static const u32 kStackTraceMax = 256;
 # define SANITIZER_CAN_FAST_UNWIND 0
 #elif SANITIZER_WINDOWS
 # define SANITIZER_CAN_FAST_UNWIND 0
-#elif SANITIZER_OPENBSD
-# define SANITIZER_CAN_FAST_UNWIND 0
 #else
 # define SANITIZER_CAN_FAST_UNWIND 1
 #endif
@@ -33,8 +33,8 @@ static const u32 kStackTraceMax = 256;
 // Fast unwind is the only option on Mac for now; we will need to
 // revisit this macro when slow unwind works on Mac, see
 // https://github.com/google/sanitizers/issues/137
-#if SANITIZER_MAC || SANITIZER_OPENBSD || SANITIZER_RTEMS
-# define SANITIZER_CAN_SLOW_UNWIND 0
+#if SANITIZER_MAC
+#  define SANITIZER_CAN_SLOW_UNWIND 0
 #else
 # define SANITIZER_CAN_SLOW_UNWIND 1
 #endif
@@ -57,6 +57,16 @@ struct StackTrace {
   // Prints a symbolized stacktrace, followed by an empty line.
   void Print() const;
 
+  // Prints a symbolized stacktrace to the output string, followed by an empty
+  // line.
+  void PrintTo(InternalScopedString *output) const;
+
+  // Prints a symbolized stacktrace to the output buffer, followed by an empty
+  // line. Returns the number of symbols that should have been written to buffer
+  // (not including trailing '\0'). Thus, the string is truncated iff return
+  // value is not less than "out_buf_size".
+  uptr PrintTo(char *out_buf, uptr out_buf_size) const;
+
   static bool WillUseFastUnwind(bool request_fast_unwind) {
     if (!SANITIZER_CAN_FAST_UNWIND)
       return false;
@@ -68,8 +78,6 @@ struct StackTrace {
   static uptr GetCurrentPc();
   static inline uptr GetPreviousInstructionPc(uptr pc);
   static uptr GetNextInstructionPc(uptr pc);
-  typedef bool (*SymbolizeCallback)(const void *pc, char *out_buffer,
-                                    int out_size);
 };
 
 // Performance-critical, must be in the header.
@@ -85,6 +93,14 @@ uptr StackTrace::GetPreviousInstructionPc(uptr pc) {
   return pc - 4;
 #elif defined(__sparc__) || defined(__mips__)
   return pc - 8;
+#elif SANITIZER_RISCV64
+  // RV-64 has variable instruciton length...
+  // C extentions gives us 2-byte instructoins
+  // RV-64 has 4-byte instructions
+  // + RISCV architecture allows instructions up to 8 bytes
+  // It seems difficult to figure out the exact instruction length -
+  // pc - 2 seems like a safe option for the purposes of stack tracing
+  return pc - 2;
 #else
   return pc - 1;
 #endif
@@ -143,9 +159,17 @@ struct BufferedStackTrace : public StackTrace {
   friend class FastUnwindTest;
 };
 
+#if defined(__s390x__)
+static const uptr kFrameSize = 160;
+#elif defined(__s390__)
+static const uptr kFrameSize = 96;
+#else
+static const uptr kFrameSize = 2 * sizeof(uhwptr);
+#endif
+
 // Check if given pointer points into allocated stack area.
 static inline bool IsValidFrame(uptr frame, uptr stack_top, uptr stack_bottom) {
-  return frame > stack_bottom && frame < stack_top - 2 * sizeof (uhwptr);
+  return frame > stack_bottom && frame < stack_top - kFrameSize;
 }
 
 }  // namespace __sanitizer
@@ -172,5 +196,26 @@ static inline bool IsValidFrame(uptr frame, uptr stack_top, uptr stack_bottom) {
   uptr local_stack;                           \
   uptr sp = (uptr)&local_stack
 
+// GET_CURRENT_PC() is equivalent to StackTrace::GetCurrentPc().
+// Optimized x86 version is faster than GetCurrentPc because
+// it does not involve a function call, instead it reads RIP register.
+// Reads of RIP by an instruction return RIP pointing to the next
+// instruction, which is exactly what we want here, thus 0 offset.
+// It needs to be a macro because otherwise we will get the name
+// of this function on the top of most stacks. Attribute artificial
+// does not do what it claims to do, unfortunatley. And attribute
+// __nodebug__ is clang-only. If we would have an attribute that
+// would remove this function from debug info, we could simply make
+// StackTrace::GetCurrentPc() faster.
+#if defined(__x86_64__)
+#  define GET_CURRENT_PC()                \
+    ({                                    \
+      uptr pc;                            \
+      asm("lea 0(%%rip), %0" : "=r"(pc)); \
+      pc;                                 \
+    })
+#else
+#  define GET_CURRENT_PC() StackTrace::GetCurrentPc()
+#endif
 
 #endif  // SANITIZER_STACKTRACE_H
lib/tsan/sanitizer_common/sanitizer_stacktrace_libcdep.cpp
@@ -18,40 +18,119 @@
 
 namespace __sanitizer {
 
-void StackTrace::Print() const {
+namespace {
+
+class StackTraceTextPrinter {
+ public:
+  StackTraceTextPrinter(const char *stack_trace_fmt, char frame_delimiter,
+                        InternalScopedString *output,
+                        InternalScopedString *dedup_token)
+      : stack_trace_fmt_(stack_trace_fmt),
+        frame_delimiter_(frame_delimiter),
+        output_(output),
+        dedup_token_(dedup_token),
+        symbolize_(RenderNeedsSymbolization(stack_trace_fmt)) {}
+
+  bool ProcessAddressFrames(uptr pc) {
+    SymbolizedStack *frames = symbolize_
+                                  ? Symbolizer::GetOrInit()->SymbolizePC(pc)
+                                  : SymbolizedStack::New(pc);
+    if (!frames)
+      return false;
+
+    for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
+      uptr prev_len = output_->length();
+      RenderFrame(output_, stack_trace_fmt_, frame_num_++, cur->info.address,
+                  symbolize_ ? &cur->info : nullptr,
+                  common_flags()->symbolize_vs_style,
+                  common_flags()->strip_path_prefix);
+
+      if (prev_len != output_->length())
+        output_->append("%c", frame_delimiter_);
+
+      ExtendDedupToken(cur);
+    }
+    frames->ClearAll();
+    return true;
+  }
+
+ private:
+  // Extend the dedup token by appending a new frame.
+  void ExtendDedupToken(SymbolizedStack *stack) {
+    if (!dedup_token_)
+      return;
+
+    if (dedup_frames_-- > 0) {
+      if (dedup_token_->length())
+        dedup_token_->append("--");
+      if (stack->info.function != nullptr)
+        dedup_token_->append(stack->info.function);
+    }
+  }
+
+  const char *stack_trace_fmt_;
+  const char frame_delimiter_;
+  int dedup_frames_ = common_flags()->dedup_token_length;
+  uptr frame_num_ = 0;
+  InternalScopedString *output_;
+  InternalScopedString *dedup_token_;
+  const bool symbolize_ = false;
+};
+
+static void CopyStringToBuffer(const InternalScopedString &str, char *out_buf,
+                               uptr out_buf_size) {
+  if (!out_buf_size)
+    return;
+
+  CHECK_GT(out_buf_size, 0);
+  uptr copy_size = Min(str.length(), out_buf_size - 1);
+  internal_memcpy(out_buf, str.data(), copy_size);
+  out_buf[copy_size] = '\0';
+}
+
+}  // namespace
+
+void StackTrace::PrintTo(InternalScopedString *output) const {
+  CHECK(output);
+
+  InternalScopedString dedup_token;
+  StackTraceTextPrinter printer(common_flags()->stack_trace_format, '\n',
+                                output, &dedup_token);
+
   if (trace == nullptr || size == 0) {
-    Printf("    <empty stack>\n\n");
+    output->append("    <empty stack>\n\n");
     return;
   }
-  InternalScopedString frame_desc(GetPageSizeCached() * 2);
-  InternalScopedString dedup_token(GetPageSizeCached());
-  int dedup_frames = common_flags()->dedup_token_length;
-  uptr frame_num = 0;
+
   for (uptr i = 0; i < size && trace[i]; i++) {
     // PCs in stack traces are actually the return addresses, that is,
     // addresses of the next instructions after the call.
     uptr pc = GetPreviousInstructionPc(trace[i]);
-    SymbolizedStack *frames = Symbolizer::GetOrInit()->SymbolizePC(pc);
-    CHECK(frames);
-    for (SymbolizedStack *cur = frames; cur; cur = cur->next) {
-      frame_desc.clear();
-      RenderFrame(&frame_desc, common_flags()->stack_trace_format, frame_num++,
-                  cur->info, common_flags()->symbolize_vs_style,
-                  common_flags()->strip_path_prefix);
-      Printf("%s\n", frame_desc.data());
-      if (dedup_frames-- > 0) {
-        if (dedup_token.length())
-          dedup_token.append("--");
-        if (cur->info.function != nullptr)
-          dedup_token.append(cur->info.function);
-      }
-    }
-    frames->ClearAll();
+    CHECK(printer.ProcessAddressFrames(pc));
   }
-  // Always print a trailing empty line after stack trace.
-  Printf("\n");
+
+  // Always add a trailing empty line after stack trace.
+  output->append("\n");
+
+  // Append deduplication token, if non-empty.
   if (dedup_token.length())
-    Printf("DEDUP_TOKEN: %s\n", dedup_token.data());
+    output->append("DEDUP_TOKEN: %s\n", dedup_token.data());
+}
+
+uptr StackTrace::PrintTo(char *out_buf, uptr out_buf_size) const {
+  CHECK(out_buf);
+
+  InternalScopedString output;
+  PrintTo(&output);
+  CopyStringToBuffer(output, out_buf, out_buf_size);
+
+  return output.length();
+}
+
+void StackTrace::Print() const {
+  InternalScopedString output;
+  PrintTo(&output);
+  Printf("%s", output.data());
 }
 
 void BufferedStackTrace::Unwind(u32 max_depth, uptr pc, uptr bp, void *context,
@@ -76,12 +155,15 @@ void BufferedStackTrace::Unwind(u32 max_depth, uptr pc, uptr bp, void *context,
       UnwindSlow(pc, context, max_depth);
     else
       UnwindSlow(pc, max_depth);
+    // If there are too few frames, the program may be built with
+    // -fno-asynchronous-unwind-tables. Fall back to fast unwinder below.
+    if (size > 2 || size >= max_depth)
+      return;
 #else
     UNREACHABLE("slow unwind requested but not available");
 #endif
-  } else {
-    UnwindFast(pc, bp, stack_top, stack_bottom, max_depth);
   }
+  UnwindFast(pc, bp, stack_top, stack_bottom, max_depth);
 }
 
 static int GetModuleAndOffsetForPc(uptr pc, char *module_name,
@@ -106,34 +188,18 @@ extern "C" {
 SANITIZER_INTERFACE_ATTRIBUTE
 void __sanitizer_symbolize_pc(uptr pc, const char *fmt, char *out_buf,
                               uptr out_buf_size) {
-  if (!out_buf_size) return;
-  pc = StackTrace::GetPreviousInstructionPc(pc);
-  SymbolizedStack *frame = Symbolizer::GetOrInit()->SymbolizePC(pc);
-  if (!frame) {
-    internal_strncpy(out_buf, "<can't symbolize>", out_buf_size);
-    out_buf[out_buf_size - 1] = 0;
+  if (!out_buf_size)
     return;
+
+  pc = StackTrace::GetPreviousInstructionPc(pc);
+
+  InternalScopedString output;
+  StackTraceTextPrinter printer(fmt, '\0', &output, nullptr);
+  if (!printer.ProcessAddressFrames(pc)) {
+    output.clear();
+    output.append("<can't symbolize>");
   }
-  InternalScopedString frame_desc(GetPageSizeCached());
-  uptr frame_num = 0;
-  // Reserve one byte for the final 0.
-  char *out_end = out_buf + out_buf_size - 1;
-  for (SymbolizedStack *cur = frame; cur && out_buf < out_end;
-       cur = cur->next) {
-    frame_desc.clear();
-    RenderFrame(&frame_desc, fmt, frame_num++, cur->info,
-                common_flags()->symbolize_vs_style,
-                common_flags()->strip_path_prefix);
-    if (!frame_desc.length())
-      continue;
-    // Reserve one byte for the terminating 0.
-    uptr n = out_end - out_buf - 1;
-    internal_strncpy(out_buf, frame_desc.data(), n);
-    out_buf += __sanitizer::Min<uptr>(n, frame_desc.length());
-    *out_buf++ = 0;
-  }
-  CHECK(out_buf <= out_end);
-  *out_buf = 0;
+  CopyStringToBuffer(output, out_buf, out_buf_size);
 }
 
 SANITIZER_INTERFACE_ATTRIBUTE
@@ -143,7 +209,7 @@ void __sanitizer_symbolize_global(uptr data_addr, const char *fmt,
   out_buf[0] = 0;
   DataInfo DI;
   if (!Symbolizer::GetOrInit()->SymbolizeData(data_addr, &DI)) return;
-  InternalScopedString data_desc(GetPageSizeCached());
+  InternalScopedString data_desc;
   RenderData(&data_desc, fmt, &DI, common_flags()->strip_path_prefix);
   internal_strncpy(out_buf, data_desc.data(), out_buf_size);
   out_buf[out_buf_size - 1] = 0;
lib/tsan/sanitizer_common/sanitizer_stacktrace_printer.cpp
@@ -107,8 +107,14 @@ static const char *DemangleFunctionName(const char *function) {
 static const char kDefaultFormat[] = "    #%n %p %F %L";
 
 void RenderFrame(InternalScopedString *buffer, const char *format, int frame_no,
-                 const AddressInfo &info, bool vs_style,
+                 uptr address, const AddressInfo *info, bool vs_style,
                  const char *strip_path_prefix, const char *strip_func_prefix) {
+  // info will be null in the case where symbolization is not needed for the
+  // given format. This ensures that the code below will get a hard failure
+  // rather than print incorrect information in case RenderNeedsSymbolization
+  // ever ends up out of sync with this function. If non-null, the addresses
+  // should match.
+  CHECK(!info || address == info->address);
   if (0 == internal_strcmp(format, "DEFAULT"))
     format = kDefaultFormat;
   for (const char *p = format; *p != '\0'; p++) {
@@ -126,71 +132,70 @@ void RenderFrame(InternalScopedString *buffer, const char *format, int frame_no,
       buffer->append("%zu", frame_no);
       break;
     case 'p':
-      buffer->append("0x%zx", info.address);
+      buffer->append("0x%zx", address);
       break;
     case 'm':
-      buffer->append("%s", StripPathPrefix(info.module, strip_path_prefix));
+      buffer->append("%s", StripPathPrefix(info->module, strip_path_prefix));
       break;
     case 'o':
-      buffer->append("0x%zx", info.module_offset);
+      buffer->append("0x%zx", info->module_offset);
       break;
     case 'f':
-      buffer->append("%s",
-        DemangleFunctionName(
-          StripFunctionName(info.function, strip_func_prefix)));
+      buffer->append("%s", DemangleFunctionName(StripFunctionName(
+                               info->function, strip_func_prefix)));
       break;
     case 'q':
-      buffer->append("0x%zx", info.function_offset != AddressInfo::kUnknown
-                                  ? info.function_offset
+      buffer->append("0x%zx", info->function_offset != AddressInfo::kUnknown
+                                  ? info->function_offset
                                   : 0x0);
       break;
     case 's':
-      buffer->append("%s", StripPathPrefix(info.file, strip_path_prefix));
+      buffer->append("%s", StripPathPrefix(info->file, strip_path_prefix));
       break;
     case 'l':
-      buffer->append("%d", info.line);
+      buffer->append("%d", info->line);
       break;
     case 'c':
-      buffer->append("%d", info.column);
+      buffer->append("%d", info->column);
       break;
     // Smarter special cases.
     case 'F':
       // Function name and offset, if file is unknown.
-      if (info.function) {
-        buffer->append("in %s",
-                       DemangleFunctionName(
-                         StripFunctionName(info.function, strip_func_prefix)));
-        if (!info.file && info.function_offset != AddressInfo::kUnknown)
-          buffer->append("+0x%zx", info.function_offset);
+      if (info->function) {
+        buffer->append("in %s", DemangleFunctionName(StripFunctionName(
+                                    info->function, strip_func_prefix)));
+        if (!info->file && info->function_offset != AddressInfo::kUnknown)
+          buffer->append("+0x%zx", info->function_offset);
       }
       break;
     case 'S':
       // File/line information.
-      RenderSourceLocation(buffer, info.file, info.line, info.column, vs_style,
-                           strip_path_prefix);
+      RenderSourceLocation(buffer, info->file, info->line, info->column,
+                           vs_style, strip_path_prefix);
       break;
     case 'L':
       // Source location, or module location.
-      if (info.file) {
-        RenderSourceLocation(buffer, info.file, info.line, info.column,
+      if (info->file) {
+        RenderSourceLocation(buffer, info->file, info->line, info->column,
                              vs_style, strip_path_prefix);
-      } else if (info.module) {
-        RenderModuleLocation(buffer, info.module, info.module_offset,
-                             info.module_arch, strip_path_prefix);
+      } else if (info->module) {
+        RenderModuleLocation(buffer, info->module, info->module_offset,
+                             info->module_arch, strip_path_prefix);
       } else {
         buffer->append("(<unknown module>)");
       }
       break;
     case 'M':
       // Module basename and offset, or PC.
-      if (info.address & kExternalPCBit)
-        {} // There PCs are not meaningful.
-      else if (info.module)
+      if (address & kExternalPCBit) {
+        // There PCs are not meaningful.
+      } else if (info->module) {
         // Always strip the module name for %M.
-        RenderModuleLocation(buffer, StripModuleName(info.module),
-                             info.module_offset, info.module_arch, "");
-      else
-        buffer->append("(%p)", (void *)info.address);
+        RenderModuleLocation(buffer, StripModuleName(info->module),
+                             info->module_offset, info->module_arch, "");
+      } else {
+        buffer->append("(%p)", (void *)address);
+      }
       break;
     default:
       Report("Unsupported specifier in stack frame format: %c (0x%zx)!\n", *p,
@@ -200,6 +205,29 @@ void RenderFrame(InternalScopedString *buffer, const char *format, int frame_no,
   }
 }
 
+bool RenderNeedsSymbolization(const char *format) {
+  if (0 == internal_strcmp(format, "DEFAULT"))
+    format = kDefaultFormat;
+  for (const char *p = format; *p != '\0'; p++) {
+    if (*p != '%')
+      continue;
+    p++;
+    switch (*p) {
+      case '%':
+        break;
+      case 'n':
+        // frame_no
+        break;
+      case 'p':
+        // address
+        break;
+      default:
+        return true;
+    }
+  }
+  return false;
+}
+
 void RenderData(InternalScopedString *buffer, const char *format,
                 const DataInfo *DI, const char *strip_path_prefix) {
   for (const char *p = format; *p != '\0'; p++) {
lib/tsan/sanitizer_common/sanitizer_stacktrace_printer.h
@@ -47,10 +47,12 @@ namespace __sanitizer {
 //        module+offset if it is known, or (<unknown module>) string.
 //   %M - prints module basename and offset, if it is known, or PC.
 void RenderFrame(InternalScopedString *buffer, const char *format, int frame_no,
-                 const AddressInfo &info, bool vs_style,
+                 uptr address, const AddressInfo *info, bool vs_style,
                  const char *strip_path_prefix = "",
                  const char *strip_func_prefix = "");
 
+bool RenderNeedsSymbolization(const char *format);
+
 void RenderSourceLocation(InternalScopedString *buffer, const char *file,
                           int line, int column, bool vs_style,
                           const char *strip_path_prefix);
lib/tsan/sanitizer_common/sanitizer_stoptheworld.h
@@ -32,20 +32,21 @@ class SuspendedThreadsList {
 
   // Can't declare pure virtual functions in sanitizer runtimes:
   // __cxa_pure_virtual might be unavailable. Use UNIMPLEMENTED() instead.
-  virtual PtraceRegistersStatus GetRegistersAndSP(uptr index, uptr *buffer,
-                                                  uptr *sp) const {
+  virtual PtraceRegistersStatus GetRegistersAndSP(
+      uptr index, InternalMmapVector<uptr> *buffer, uptr *sp) const {
     UNIMPLEMENTED();
   }
 
-  // The buffer in GetRegistersAndSP should be at least this big.
-  virtual uptr RegisterCount() const { UNIMPLEMENTED(); }
   virtual uptr ThreadCount() const { UNIMPLEMENTED(); }
   virtual tid_t GetThreadID(uptr index) const { UNIMPLEMENTED(); }
 
+ protected:
+  ~SuspendedThreadsList() {}
+
  private:
   // Prohibit copy and assign.
-  SuspendedThreadsList(const SuspendedThreadsList&);
-  void operator=(const SuspendedThreadsList&);
+  SuspendedThreadsList(const SuspendedThreadsList &) = delete;
+  void operator=(const SuspendedThreadsList &) = delete;
 };
 
 typedef void (*StopTheWorldCallback)(
lib/tsan/sanitizer_common/sanitizer_stoptheworld_fuchsia.cpp
@@ -17,6 +17,7 @@
 #include <zircon/sanitizer.h>
 
 #include "sanitizer_stoptheworld.h"
+#include "sanitizer_stoptheworld_fuchsia.h"
 
 namespace __sanitizer {
 
@@ -32,7 +33,7 @@ void StopTheWorld(StopTheWorldCallback callback, void *argument) {
       nullptr, nullptr, nullptr, nullptr,
       [](zx_status_t, void *data) {
         auto params = reinterpret_cast<Params *>(data);
-        params->callback({}, params->argument);
+        params->callback(SuspendedThreadsListFuchsia(), params->argument);
       },
       &params);
 }
lib/tsan/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cpp
@@ -13,10 +13,10 @@
 
 #include "sanitizer_platform.h"
 
-#if SANITIZER_LINUX && (defined(__x86_64__) || defined(__mips__) || \
-                        defined(__aarch64__) || defined(__powerpc64__) || \
-                        defined(__s390__) || defined(__i386__) || \
-                        defined(__arm__))
+#if SANITIZER_LINUX &&                                                   \
+    (defined(__x86_64__) || defined(__mips__) || defined(__aarch64__) || \
+     defined(__powerpc64__) || defined(__s390__) || defined(__i386__) || \
+     defined(__arm__) || SANITIZER_RISCV64)
 
 #include "sanitizer_stoptheworld.h"
 
@@ -31,7 +31,7 @@
 #include <sys/types.h> // for pid_t
 #include <sys/uio.h> // for iovec
 #include <elf.h> // for NT_PRSTATUS
-#if defined(__aarch64__) && !SANITIZER_ANDROID
+#if (defined(__aarch64__) || SANITIZER_RISCV64) && !SANITIZER_ANDROID
 // GLIBC 2.20+ sys/user does not include asm/ptrace.h
 # include <asm/ptrace.h>
 #endif
@@ -85,18 +85,18 @@
 
 namespace __sanitizer {
 
-class SuspendedThreadsListLinux : public SuspendedThreadsList {
+class SuspendedThreadsListLinux final : public SuspendedThreadsList {
  public:
   SuspendedThreadsListLinux() { thread_ids_.reserve(1024); }
 
-  tid_t GetThreadID(uptr index) const;
-  uptr ThreadCount() const;
+  tid_t GetThreadID(uptr index) const override;
+  uptr ThreadCount() const override;
   bool ContainsTid(tid_t thread_id) const;
   void Append(tid_t tid);
 
-  PtraceRegistersStatus GetRegistersAndSP(uptr index, uptr *buffer,
-                                          uptr *sp) const;
-  uptr RegisterCount() const;
+  PtraceRegistersStatus GetRegistersAndSP(uptr index,
+                                          InternalMmapVector<uptr> *buffer,
+                                          uptr *sp) const override;
 
  private:
   InternalMmapVector<tid_t> thread_ids_;
@@ -485,6 +485,16 @@ typedef user_regs_struct regs_struct;
 #else
 #define REG_SP rsp
 #endif
+#define ARCH_IOVEC_FOR_GETREGSET
+// Support ptrace extensions even when compiled without required kernel support
+#ifndef NT_X86_XSTATE
+#define NT_X86_XSTATE 0x202
+#endif
+#ifndef PTRACE_GETREGSET
+#define PTRACE_GETREGSET 0x4204
+#endif
+// Compiler may use FP registers to store pointers.
+static constexpr uptr kExtraRegs[] = {NT_X86_XSTATE, NT_FPREGSET};
 
 #elif defined(__powerpc__) || defined(__powerpc64__)
 typedef pt_regs regs_struct;
@@ -501,11 +511,21 @@ typedef struct user regs_struct;
 #elif defined(__aarch64__)
 typedef struct user_pt_regs regs_struct;
 #define REG_SP sp
+static constexpr uptr kExtraRegs[] = {0};
+#define ARCH_IOVEC_FOR_GETREGSET
+
+#elif SANITIZER_RISCV64
+typedef struct user_regs_struct regs_struct;
+// sys/ucontext.h already defines REG_SP as 2. Undefine it first.
+#undef REG_SP
+#define REG_SP sp
+static constexpr uptr kExtraRegs[] = {0};
 #define ARCH_IOVEC_FOR_GETREGSET
 
 #elif defined(__s390__)
 typedef _user_regs_struct regs_struct;
 #define REG_SP gprs[15]
+static constexpr uptr kExtraRegs[] = {0};
 #define ARCH_IOVEC_FOR_GETREGSET
 
 #else
@@ -533,24 +553,58 @@ void SuspendedThreadsListLinux::Append(tid_t tid) {
 }
 
 PtraceRegistersStatus SuspendedThreadsListLinux::GetRegistersAndSP(
-    uptr index, uptr *buffer, uptr *sp) const {
+    uptr index, InternalMmapVector<uptr> *buffer, uptr *sp) const {
   pid_t tid = GetThreadID(index);
-  regs_struct regs;
+  constexpr uptr uptr_sz = sizeof(uptr);
   int pterrno;
 #ifdef ARCH_IOVEC_FOR_GETREGSET
-  struct iovec regset_io;
-  regset_io.iov_base = &regs;
-  regset_io.iov_len = sizeof(regs_struct);
-  bool isErr = internal_iserror(internal_ptrace(PTRACE_GETREGSET, tid,
-                                (void*)NT_PRSTATUS, (void*)&regset_io),
-                                &pterrno);
+  auto append = [&](uptr regset) {
+    uptr size = buffer->size();
+    // NT_X86_XSTATE requires 64bit alignment.
+    uptr size_up = RoundUpTo(size, 8 / uptr_sz);
+    buffer->reserve(Max<uptr>(1024, size_up));
+    struct iovec regset_io;
+    for (;; buffer->resize(buffer->capacity() * 2)) {
+      buffer->resize(buffer->capacity());
+      uptr available_bytes = (buffer->size() - size_up) * uptr_sz;
+      regset_io.iov_base = buffer->data() + size_up;
+      regset_io.iov_len = available_bytes;
+      bool fail =
+          internal_iserror(internal_ptrace(PTRACE_GETREGSET, tid,
+                                           (void *)regset, (void *)&regset_io),
+                           &pterrno);
+      if (fail) {
+        VReport(1, "Could not get regset %p from thread %d (errno %d).\n",
+                (void *)regset, tid, pterrno);
+        buffer->resize(size);
+        return false;
+      }
+
+      // Far enough from the buffer size, no need to resize and repeat.
+      if (regset_io.iov_len + 64 < available_bytes)
+        break;
+    }
+    buffer->resize(size_up + RoundUpTo(regset_io.iov_len, uptr_sz) / uptr_sz);
+    return true;
+  };
+
+  buffer->clear();
+  bool fail = !append(NT_PRSTATUS);
+  if (!fail) {
+    // Accept the first available and do not report errors.
+    for (uptr regs : kExtraRegs)
+      if (regs && append(regs))
+        break;
+  }
 #else
-  bool isErr = internal_iserror(internal_ptrace(PTRACE_GETREGS, tid, nullptr,
-                                &regs), &pterrno);
-#endif
-  if (isErr) {
+  buffer->resize(RoundUpTo(sizeof(regs_struct), uptr_sz) / uptr_sz);
+  bool fail = internal_iserror(
+      internal_ptrace(PTRACE_GETREGS, tid, nullptr, buffer->data()), &pterrno);
+  if (fail)
     VReport(1, "Could not get registers from thread %d (errno %d).\n", tid,
             pterrno);
+#endif
+  if (fail) {
     // ESRCH means that the given thread is not suspended or already dead.
     // Therefore it's unsafe to inspect its data (e.g. walk through stack) and
     // we should notify caller about this.
@@ -558,14 +612,10 @@ PtraceRegistersStatus SuspendedThreadsListLinux::GetRegistersAndSP(
                             : REGISTERS_UNAVAILABLE;
   }
 
-  *sp = regs.REG_SP;
-  internal_memcpy(buffer, &regs, sizeof(regs));
+  *sp = reinterpret_cast<regs_struct *>(buffer->data())[0].REG_SP;
   return REGISTERS_AVAILABLE;
 }
 
-uptr SuspendedThreadsListLinux::RegisterCount() const {
-  return sizeof(regs_struct) / sizeof(uptr);
-}
 } // namespace __sanitizer
 
 #endif  // SANITIZER_LINUX && (defined(__x86_64__) || defined(__mips__)
lib/tsan/sanitizer_common/sanitizer_stoptheworld_mac.cpp
@@ -27,19 +27,19 @@ typedef struct {
   thread_t thread;
 } SuspendedThreadInfo;
 
-class SuspendedThreadsListMac : public SuspendedThreadsList {
+class SuspendedThreadsListMac final : public SuspendedThreadsList {
  public:
   SuspendedThreadsListMac() : threads_(1024) {}
 
-  tid_t GetThreadID(uptr index) const;
+  tid_t GetThreadID(uptr index) const override;
   thread_t GetThread(uptr index) const;
-  uptr ThreadCount() const;
+  uptr ThreadCount() const override;
   bool ContainsThread(thread_t thread) const;
   void Append(thread_t thread);
 
-  PtraceRegistersStatus GetRegistersAndSP(uptr index, uptr *buffer,
-                                          uptr *sp) const;
-  uptr RegisterCount() const;
+  PtraceRegistersStatus GetRegistersAndSP(uptr index,
+                                          InternalMmapVector<uptr> *buffer,
+                                          uptr *sp) const override;
 
  private:
   InternalMmapVector<SuspendedThreadInfo> threads_;
@@ -142,7 +142,7 @@ void SuspendedThreadsListMac::Append(thread_t thread) {
 }
 
 PtraceRegistersStatus SuspendedThreadsListMac::GetRegistersAndSP(
-    uptr index, uptr *buffer, uptr *sp) const {
+    uptr index, InternalMmapVector<uptr> *buffer, uptr *sp) const {
   thread_t thread = GetThread(index);
   regs_struct regs;
   int err;
@@ -159,7 +159,8 @@ PtraceRegistersStatus SuspendedThreadsListMac::GetRegistersAndSP(
                                         : REGISTERS_UNAVAILABLE;
   }
 
-  internal_memcpy(buffer, &regs, sizeof(regs));
+  buffer->resize(RoundUpTo(sizeof(regs), sizeof(uptr)) / sizeof(uptr));
+  internal_memcpy(buffer->data(), &regs, sizeof(regs));
 #if defined(__aarch64__) && defined(arm_thread_state64_get_sp)
   *sp = arm_thread_state64_get_sp(regs);
 #else
@@ -173,9 +174,6 @@ PtraceRegistersStatus SuspendedThreadsListMac::GetRegistersAndSP(
   return REGISTERS_AVAILABLE;
 }
 
-uptr SuspendedThreadsListMac::RegisterCount() const {
-  return MACHINE_THREAD_STATE_COUNT;
-}
 } // namespace __sanitizer
 
 #endif  // SANITIZER_MAC && (defined(__x86_64__) || defined(__aarch64__)) ||
lib/tsan/sanitizer_common/sanitizer_stoptheworld_netbsd_libcdep.cpp
@@ -48,7 +48,7 @@
 
 namespace __sanitizer {
 
-class SuspendedThreadsListNetBSD : public SuspendedThreadsList {
+class SuspendedThreadsListNetBSD final : public SuspendedThreadsList {
  public:
   SuspendedThreadsListNetBSD() { thread_ids_.reserve(1024); }
 
@@ -57,9 +57,9 @@ class SuspendedThreadsListNetBSD : public SuspendedThreadsList {
   bool ContainsTid(tid_t thread_id) const;
   void Append(tid_t tid);
 
-  PtraceRegistersStatus GetRegistersAndSP(uptr index, uptr *buffer,
+  PtraceRegistersStatus GetRegistersAndSP(uptr index,
+                                          InternalMmapVector<uptr> *buffer,
                                           uptr *sp) const;
-  uptr RegisterCount() const;
 
  private:
   InternalMmapVector<tid_t> thread_ids_;
@@ -131,7 +131,7 @@ bool ThreadSuspender::SuspendAllThreads() {
   pl.pl_lwpid = 0;
 
   int val;
-  while ((val = ptrace(op, pid_, (void *)&pl, sizeof(pl))) != -1 &&
+  while ((val = internal_ptrace(op, pid_, (void *)&pl, sizeof(pl))) != -1 &&
          pl.pl_lwpid != 0) {
     suspended_threads_list_.Append(pl.pl_lwpid);
     VReport(2, "Appended thread %d in process %d.\n", pl.pl_lwpid, pid_);
@@ -335,7 +335,7 @@ void SuspendedThreadsListNetBSD::Append(tid_t tid) {
 }
 
 PtraceRegistersStatus SuspendedThreadsListNetBSD::GetRegistersAndSP(
-    uptr index, uptr *buffer, uptr *sp) const {
+    uptr index, InternalMmapVector<uptr> *buffer, uptr *sp) const {
   lwpid_t tid = GetThreadID(index);
   pid_t ppid = internal_getppid();
   struct reg regs;
@@ -351,14 +351,12 @@ PtraceRegistersStatus SuspendedThreadsListNetBSD::GetRegistersAndSP(
   }
 
   *sp = PTRACE_REG_SP(&regs);
-  internal_memcpy(buffer, &regs, sizeof(regs));
+  buffer->resize(RoundUpTo(sizeof(regs), sizeof(uptr)) / sizeof(uptr));
+  internal_memcpy(buffer->data(), &regs, sizeof(regs));
 
   return REGISTERS_AVAILABLE;
 }
 
-uptr SuspendedThreadsListNetBSD::RegisterCount() const {
-  return sizeof(struct reg) / sizeof(uptr);
-}
 }  // namespace __sanitizer
 
 #endif
lib/tsan/sanitizer_common/sanitizer_suppressions.cpp
@@ -34,7 +34,7 @@ SuppressionContext::SuppressionContext(const char *suppression_types[],
 static bool GetPathAssumingFileIsRelativeToExec(const char *file_path,
                                                 /*out*/char *new_file_path,
                                                 uptr new_file_path_size) {
-  InternalScopedString exec(kMaxPathLength);
+  InternalMmapVector<char> exec(kMaxPathLength);
   if (ReadBinaryNameCached(exec.data(), exec.size())) {
     const char *file_name_pos = StripModuleName(exec.data());
     uptr path_to_exec_len = file_name_pos - exec.data();
@@ -69,7 +69,7 @@ void SuppressionContext::ParseFromFile(const char *filename) {
   if (filename[0] == '\0')
     return;
 
-  InternalScopedString new_file_path(kMaxPathLength);
+  InternalMmapVector<char> new_file_path(kMaxPathLength);
   filename = FindFile(filename, new_file_path.data(), new_file_path.size());
 
   // Read the file.
lib/tsan/sanitizer_common/sanitizer_symbolizer_internal.h
@@ -74,6 +74,9 @@ class SymbolizerTool {
   // Usually this is a safe place to call code that might need to use user
   // memory allocators.
   virtual void LateInitialize() {}
+
+ protected:
+  ~SymbolizerTool() {}
 };
 
 // SymbolizerProcess encapsulates communication between the tool and
@@ -85,6 +88,8 @@ class SymbolizerProcess {
   const char *SendCommand(const char *command);
 
  protected:
+  ~SymbolizerProcess() {}
+
   /// The maximum number of arguments required to invoke a tool process.
   static const unsigned kArgVMax = 6;
 
@@ -128,7 +133,7 @@ class LLVMSymbolizerProcess;
 
 // This tool invokes llvm-symbolizer in a subprocess. It should be as portable
 // as the llvm-symbolizer tool is.
-class LLVMSymbolizer : public SymbolizerTool {
+class LLVMSymbolizer final : public SymbolizerTool {
  public:
   explicit LLVMSymbolizer(const char *path, LowLevelAllocator *allocator);
 
lib/tsan/sanitizer_common/sanitizer_symbolizer_libbacktrace.h
@@ -28,7 +28,7 @@
 
 namespace __sanitizer {
 
-class LibbacktraceSymbolizer : public SymbolizerTool {
+class LibbacktraceSymbolizer final : public SymbolizerTool {
  public:
   static LibbacktraceSymbolizer *get(LowLevelAllocator *alloc);
 
lib/tsan/sanitizer_common/sanitizer_symbolizer_libcdep.cpp
@@ -12,6 +12,7 @@
 
 #include "sanitizer_allocator_internal.h"
 #include "sanitizer_internal_defs.h"
+#include "sanitizer_platform.h"
 #include "sanitizer_symbolizer_internal.h"
 
 namespace __sanitizer {
@@ -236,7 +237,7 @@ const LoadedModule *Symbolizer::FindModuleForAddress(uptr address) {
 //   <file_name>:<line_number>:<column_number>
 //   ...
 //   <empty line>
-class LLVMSymbolizerProcess : public SymbolizerProcess {
+class LLVMSymbolizerProcess final : public SymbolizerProcess {
  public:
   explicit LLVMSymbolizerProcess(const char *path)
       : SymbolizerProcess(path, /*use_posix_spawn=*/SANITIZER_MAC) {}
@@ -258,6 +259,8 @@ class LLVMSymbolizerProcess : public SymbolizerProcess {
     const char* const kSymbolizerArch = "--default-arch=x86_64";
 #elif defined(__i386__)
     const char* const kSymbolizerArch = "--default-arch=i386";
+#elif SANITIZER_RISCV64
+    const char *const kSymbolizerArch = "--default-arch=riscv64";
 #elif defined(__aarch64__)
     const char* const kSymbolizerArch = "--default-arch=arm64";
 #elif defined(__arm__)
@@ -275,8 +278,8 @@ class LLVMSymbolizerProcess : public SymbolizerProcess {
 #endif
 
     const char *const inline_flag = common_flags()->symbolize_inline_frames
-                                        ? "--inlining=true"
-                                        : "--inlining=false";
+                                        ? "--inlines"
+                                        : "--no-inlines";
     int i = 0;
     argv[i++] = path_to_binary;
     argv[i++] = inline_flag;
@@ -353,7 +356,7 @@ void ParseSymbolizePCOutput(const char *str, SymbolizedStack *res) {
       InternalFree(info->function);
       info->function = 0;
     }
-    if (0 == internal_strcmp(info->file, "??")) {
+    if (info->file && 0 == internal_strcmp(info->file, "??")) {
       InternalFree(info->file);
       info->file = 0;
     }
lib/tsan/sanitizer_common/sanitizer_symbolizer_mac.cpp
@@ -33,8 +33,15 @@ bool DlAddrSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {
   int result = dladdr((const void *)addr, &info);
   if (!result) return false;
 
-  CHECK(addr >= reinterpret_cast<uptr>(info.dli_saddr));
-  stack->info.function_offset = addr - reinterpret_cast<uptr>(info.dli_saddr);
+  // Compute offset if possible. `dladdr()` doesn't always ensure that `addr >=
+  // sym_addr` so only compute the offset when this holds. Failure to find the
+  // function offset is not treated as a failure because it might still be
+  // possible to get the symbol name.
+  uptr sym_addr = reinterpret_cast<uptr>(info.dli_saddr);
+  if (addr >= sym_addr) {
+    stack->info.function_offset = addr - sym_addr;
+  }
+
   const char *demangled = DemangleSwiftAndCXX(info.dli_sname);
   if (!demangled) return false;
   stack->info.function = internal_strdup(demangled);
@@ -58,7 +65,7 @@ bool DlAddrSymbolizer::SymbolizeData(uptr addr, DataInfo *datainfo) {
 // kAsanInternalHeapMagic.
 static char kAtosMachPortEnvEntry[] = K_ATOS_ENV_VAR "=000000000000000";
 
-class AtosSymbolizerProcess : public SymbolizerProcess {
+class AtosSymbolizerProcess final : public SymbolizerProcess {
  public:
   explicit AtosSymbolizerProcess(const char *path)
       : SymbolizerProcess(path, /*use_posix_spawn*/ true) {
@@ -219,10 +226,10 @@ bool AtosSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {
       start_address = reinterpret_cast<uptr>(info.dli_saddr);
   }
 
-  // Only assig to `function_offset` if we were able to get the function's
-  // start address.
-  if (start_address != AddressInfo::kUnknown) {
-    CHECK(addr >= start_address);
+  // Only assign to `function_offset` if we were able to get the function's
+  // start address and we got a sensible `start_address` (dladdr doesn't always
+  // ensure that `addr >= sym_addr`).
+  if (start_address != AddressInfo::kUnknown && addr >= start_address) {
     stack->info.function_offset = addr - start_address;
   }
   return true;
lib/tsan/sanitizer_common/sanitizer_symbolizer_mac.h
@@ -21,7 +21,7 @@
 
 namespace __sanitizer {
 
-class DlAddrSymbolizer : public SymbolizerTool {
+class DlAddrSymbolizer final : public SymbolizerTool {
  public:
   bool SymbolizePC(uptr addr, SymbolizedStack *stack) override;
   bool SymbolizeData(uptr addr, DataInfo *info) override;
@@ -29,7 +29,7 @@ class DlAddrSymbolizer : public SymbolizerTool {
 
 class AtosSymbolizerProcess;
 
-class AtosSymbolizer : public SymbolizerTool {
+class AtosSymbolizer final : public SymbolizerTool {
  public:
   explicit AtosSymbolizer(const char *path, LowLevelAllocator *allocator);
 
lib/tsan/sanitizer_common/sanitizer_symbolizer_markup.cpp
@@ -16,14 +16,13 @@
 
 #if SANITIZER_FUCHSIA
 #include "sanitizer_symbolizer_fuchsia.h"
-#elif SANITIZER_RTEMS
-#include "sanitizer_symbolizer_rtems.h"
-#endif
-#include "sanitizer_stacktrace.h"
-#include "sanitizer_symbolizer.h"
+#  endif
 
-#include <limits.h>
-#include <unwind.h>
+#  include <limits.h>
+#  include <unwind.h>
+
+#  include "sanitizer_stacktrace.h"
+#  include "sanitizer_symbolizer.h"
 
 namespace __sanitizer {
 
@@ -54,6 +53,10 @@ bool Symbolizer::GetModuleNameAndOffsetForPC(uptr pc, const char **module_name,
   return false;
 }
 
+// This is mainly used by hwasan for online symbolization. This isn't needed
+// since hwasan can always just dump stack frames for offline symbolization.
+bool Symbolizer::SymbolizeFrame(uptr addr, FrameInfo *info) { return false; }
+
 // This is used in some places for suppression checking, which we
 // don't really support for Fuchsia.  It's also used in UBSan to
 // identify a PC location to a function name, so we always fill in
@@ -83,11 +86,14 @@ void RenderData(InternalScopedString *buffer, const char *format,
   buffer->append(kFormatData, DI->start);
 }
 
+bool RenderNeedsSymbolization(const char *format) { return false; }
+
 // We don't support the stack_trace_format flag at all.
 void RenderFrame(InternalScopedString *buffer, const char *format, int frame_no,
-                 const AddressInfo &info, bool vs_style,
+                 uptr address, const AddressInfo *info, bool vs_style,
                  const char *strip_path_prefix, const char *strip_func_prefix) {
-  buffer->append(kFormatFrame, frame_no, info.address);
+  CHECK(!RenderNeedsSymbolization(format));
+  buffer->append(kFormatFrame, frame_no, address);
 }
 
 Symbolizer *Symbolizer::PlatformInit() {
lib/tsan/sanitizer_common/sanitizer_symbolizer_posix_libcdep.cpp
@@ -201,7 +201,7 @@ bool SymbolizerProcess::StartSymbolizerSubprocess() {
   return true;
 }
 
-class Addr2LineProcess : public SymbolizerProcess {
+class Addr2LineProcess final : public SymbolizerProcess {
  public:
   Addr2LineProcess(const char *path, const char *module_name)
       : SymbolizerProcess(path), module_name_(internal_strdup(module_name)) {}
@@ -261,7 +261,7 @@ bool Addr2LineProcess::ReachedEndOfOutput(const char *buffer,
                           output_terminator_, kTerminatorLen);
 }
 
-class Addr2LinePool : public SymbolizerTool {
+class Addr2LinePool final : public SymbolizerTool {
  public:
   explicit Addr2LinePool(const char *addr2line_path,
                          LowLevelAllocator *allocator)
@@ -328,7 +328,7 @@ int __sanitizer_symbolize_demangle(const char *Name, char *Buffer,
                                    int MaxLength);
 }  // extern "C"
 
-class InternalSymbolizer : public SymbolizerTool {
+class InternalSymbolizer final : public SymbolizerTool {
  public:
   static InternalSymbolizer *get(LowLevelAllocator *alloc) {
     if (__sanitizer_symbolize_code != 0 &&
@@ -387,7 +387,7 @@ class InternalSymbolizer : public SymbolizerTool {
 };
 #else  // SANITIZER_SUPPORTS_WEAK_HOOKS
 
-class InternalSymbolizer : public SymbolizerTool {
+class InternalSymbolizer final : public SymbolizerTool {
  public:
   static InternalSymbolizer *get(LowLevelAllocator *alloc) { return 0; }
 };
@@ -400,11 +400,20 @@ const char *Symbolizer::PlatformDemangle(const char *name) {
 
 static SymbolizerTool *ChooseExternalSymbolizer(LowLevelAllocator *allocator) {
   const char *path = common_flags()->external_symbolizer_path;
+
+  if (path && internal_strchr(path, '%')) {
+    char *new_path = (char *)InternalAlloc(kMaxPathLength);
+    SubstituteForFlagValue(path, new_path, kMaxPathLength);
+    path = new_path;
+  }
+
   const char *binary_name = path ? StripModuleName(path) : "";
+  static const char kLLVMSymbolizerPrefix[] = "llvm-symbolizer";
   if (path && path[0] == '\0') {
     VReport(2, "External symbolizer is explicitly disabled.\n");
     return nullptr;
-  } else if (!internal_strcmp(binary_name, "llvm-symbolizer")) {
+  } else if (!internal_strncmp(binary_name, kLLVMSymbolizerPrefix,
+                               internal_strlen(kLLVMSymbolizerPrefix))) {
     VReport(2, "Using llvm-symbolizer at user-specified path: %s\n", path);
     return new(*allocator) LLVMSymbolizer(path, allocator);
   } else if (!internal_strcmp(binary_name, "atos")) {
lib/tsan/sanitizer_common/sanitizer_symbolizer_report.cpp
@@ -31,9 +31,10 @@ namespace __sanitizer {
 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
                         const char *alt_tool_name) {
   if (!common_flags()->print_summary) return;
-  InternalScopedString buff(kMaxSummaryLength);
+  InternalScopedString buff;
   buff.append("%s ", error_type);
-  RenderFrame(&buff, "%L %F", 0, info, common_flags()->symbolize_vs_style,
+  RenderFrame(&buff, "%L %F", 0, info.address, &info,
+              common_flags()->symbolize_vs_style,
               common_flags()->strip_path_prefix);
   ReportErrorSummary(buff.data(), alt_tool_name);
 }
@@ -47,14 +48,14 @@ bool ReportFile::SupportsColors() {
   return SupportsColoredOutput(fd);
 }
 
-static INLINE bool ReportSupportsColors() {
+static inline bool ReportSupportsColors() {
   return report_file.SupportsColors();
 }
 
 #else  // SANITIZER_FUCHSIA
 
 // Fuchsia's logs always go through post-processing that handles colorization.
-static INLINE bool ReportSupportsColors() { return true; }
+static inline bool ReportSupportsColors() { return true; }
 
 #endif  // !SANITIZER_FUCHSIA
 
@@ -119,7 +120,7 @@ void ReportMmapWriteExec(int prot) {
 #endif
 }
 
-#if !SANITIZER_FUCHSIA && !SANITIZER_RTEMS && !SANITIZER_GO
+#if !SANITIZER_FUCHSIA && !SANITIZER_GO
 void StartReportDeadlySignal() {
   // Write the first message using fd=2, just in case.
   // It may actually fail to write in case stderr is closed.
@@ -149,7 +150,7 @@ static void PrintMemoryByte(InternalScopedString *str, const char *before,
 static void MaybeDumpInstructionBytes(uptr pc) {
   if (!common_flags()->dump_instruction_bytes || (pc < GetPageSizeCached()))
     return;
-  InternalScopedString str(1024);
+  InternalScopedString str;
   str.append("First 16 instruction bytes at pc: ");
   if (IsAccessibleMemoryRange(pc, 16)) {
     for (int i = 0; i < 16; ++i) {
@@ -210,7 +211,7 @@ static void ReportDeadlySignalImpl(const SignalContext &sig, u32 tid,
     Report("The signal is caused by a %s memory access.\n", access_type);
     if (!sig.is_true_faulting_addr)
       Report("Hint: this fault was caused by a dereference of a high value "
-             "address (see register values below).  Dissassemble the provided "
+             "address (see register values below).  Disassemble the provided "
              "pc to learn which register was used.\n");
     else if (sig.addr < GetPageSizeCached())
       Report("Hint: address points to the zero page.\n");
@@ -249,17 +250,17 @@ void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
 
 #endif  // !SANITIZER_FUCHSIA && !SANITIZER_GO
 
-static atomic_uintptr_t reporting_thread = {0};
-static StaticSpinMutex CommonSanitizerReportMutex;
+atomic_uintptr_t ScopedErrorReportLock::reporting_thread_ = {0};
+StaticSpinMutex ScopedErrorReportLock::mutex_;
 
-ScopedErrorReportLock::ScopedErrorReportLock() {
+void ScopedErrorReportLock::Lock() {
   uptr current = GetThreadSelf();
   for (;;) {
     uptr expected = 0;
-    if (atomic_compare_exchange_strong(&reporting_thread, &expected, current,
+    if (atomic_compare_exchange_strong(&reporting_thread_, &expected, current,
                                        memory_order_relaxed)) {
       // We've claimed reporting_thread so proceed.
-      CommonSanitizerReportMutex.Lock();
+      mutex_.Lock();
       return;
     }
 
@@ -281,13 +282,11 @@ ScopedErrorReportLock::ScopedErrorReportLock() {
   }
 }
 
-ScopedErrorReportLock::~ScopedErrorReportLock() {
-  CommonSanitizerReportMutex.Unlock();
-  atomic_store_relaxed(&reporting_thread, 0);
+void ScopedErrorReportLock::Unlock() {
+  mutex_.Unlock();
+  atomic_store_relaxed(&reporting_thread_, 0);
 }
 
-void ScopedErrorReportLock::CheckLocked() {
-  CommonSanitizerReportMutex.CheckLocked();
-}
+void ScopedErrorReportLock::CheckLocked() { mutex_.CheckLocked(); }
 
 }  // namespace __sanitizer
lib/tsan/sanitizer_common/sanitizer_symbolizer_rtems.h
@@ -1,40 +0,0 @@
-//===-- sanitizer_symbolizer_rtems.h -----------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is shared between various sanitizers' runtime libraries.
-//
-// Define RTEMS's string formats and limits for the markup symbolizer.
-//===----------------------------------------------------------------------===//
-#ifndef SANITIZER_SYMBOLIZER_RTEMS_H
-#define SANITIZER_SYMBOLIZER_RTEMS_H
-
-#include "sanitizer_internal_defs.h"
-
-namespace __sanitizer {
-
-// The Myriad RTEMS symbolizer currently only parses backtrace lines,
-// so use a format that the symbolizer understands.  For other
-// markups, keep them the same as the Fuchsia's.
-
-// This is used by UBSan for type names, and by ASan for global variable names.
-constexpr const char *kFormatDemangle = "{{{symbol:%s}}}";
-constexpr uptr kFormatDemangleMax = 1024;  // Arbitrary.
-
-// Function name or equivalent from PC location.
-constexpr const char *kFormatFunction = "{{{pc:%p}}}";
-constexpr uptr kFormatFunctionMax = 64;  // More than big enough for 64-bit hex.
-
-// Global variable name or equivalent from data memory address.
-constexpr const char *kFormatData = "{{{data:%p}}}";
-
-// One frame in a backtrace (printed on a line by itself).
-constexpr const char *kFormatFrame = "    [%u] IP: %p";
-
-}  // namespace __sanitizer
-
-#endif  // SANITIZER_SYMBOLIZER_RTEMS_H
lib/tsan/sanitizer_common/sanitizer_symbolizer_win.cpp
@@ -33,7 +33,7 @@ decltype(::UnDecorateSymbolName) *UnDecorateSymbolName;
 
 namespace {
 
-class WinSymbolizerTool : public SymbolizerTool {
+class WinSymbolizerTool final : public SymbolizerTool {
  public:
   // The constructor is provided to avoid synthesized memsets.
   WinSymbolizerTool() {}
@@ -136,9 +136,10 @@ void InitializeDbgHelpIfNeeded() {
 bool WinSymbolizerTool::SymbolizePC(uptr addr, SymbolizedStack *frame) {
   InitializeDbgHelpIfNeeded();
 
-  // See http://msdn.microsoft.com/en-us/library/ms680578(VS.85).aspx
-  char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(CHAR)];
-  PSYMBOL_INFO symbol = (PSYMBOL_INFO)buffer;
+  // See https://docs.microsoft.com/en-us/windows/win32/debug/retrieving-symbol-information-by-address
+  InternalMmapVector<char> buffer(sizeof(SYMBOL_INFO) +
+                                  MAX_SYM_NAME * sizeof(CHAR));
+  PSYMBOL_INFO symbol = (PSYMBOL_INFO)&buffer[0];
   symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
   symbol->MaxNameLen = MAX_SYM_NAME;
   DWORD64 offset = 0;
@@ -223,7 +224,7 @@ bool SymbolizerProcess::StartSymbolizerSubprocess() {
   // Compute the command line. Wrap double quotes around everything.
   const char *argv[kArgVMax];
   GetArgV(path_, argv);
-  InternalScopedString command_line(kMaxPathLength * 3);
+  InternalScopedString command_line;
   for (int i = 0; argv[i]; i++) {
     const char *arg = argv[i];
     int arglen = internal_strlen(arg);
@@ -281,8 +282,15 @@ static void ChooseSymbolizerTools(IntrusiveList<SymbolizerTool> *list,
     return;
   }
 
-  // Add llvm-symbolizer in case the binary has dwarf.
+  // Add llvm-symbolizer.
   const char *user_path = common_flags()->external_symbolizer_path;
+
+  if (user_path && internal_strchr(user_path, '%')) {
+    char *new_path = (char *)InternalAlloc(kMaxPathLength);
+    SubstituteForFlagValue(user_path, new_path, kMaxPathLength);
+    user_path = new_path;
+  }
+
   const char *path =
       user_path ? user_path : FindPathToBinary("llvm-symbolizer.exe");
   if (path) {
lib/tsan/sanitizer_common/sanitizer_syscall_generic.inc
@@ -13,7 +13,7 @@
 // NetBSD uses libc calls directly
 #if !SANITIZER_NETBSD
 
-#if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_OPENBSD || SANITIZER_SOLARIS
+#if SANITIZER_FREEBSD || SANITIZER_MAC || SANITIZER_SOLARIS
 # define SYSCALL(name) SYS_ ## name
 #else
 # define SYSCALL(name) __NR_ ## name
lib/tsan/sanitizer_common/sanitizer_syscalls_netbsd.inc
@@ -42,8 +42,8 @@
 // DO NOT EDIT! THIS FILE HAS BEEN GENERATED!
 //
 // Generated with: generate_netbsd_syscalls.awk
-// Generated date: 2019-12-24
-// Generated from: syscalls.master,v 1.296 2019/09/22 22:59:39 christos Exp
+// Generated date: 2020-09-10
+// Generated from: syscalls.master,v 1.306 2020/08/14 00:53:16 riastradh Exp
 //
 //===----------------------------------------------------------------------===//
 
@@ -872,7 +872,13 @@ PRE_SYSCALL(dup2)(long long from_, long long to_) { /* Nothing to do */ }
 POST_SYSCALL(dup2)(long long res, long long from_, long long to_) {
   /* Nothing to do */
 }
-/* syscall 91 has been skipped */
+PRE_SYSCALL(getrandom)(void *buf_, long long buflen_, long long flags_) {
+  /* TODO */
+}
+POST_SYSCALL(getrandom)
+(long long res, void *buf_, long long buflen_, long long flags_) {
+  /* TODO */
+}
 PRE_SYSCALL(fcntl)(long long fd_, long long cmd_, void *arg_) {
   /* Nothing to do */
 }
@@ -1332,9 +1338,29 @@ PRE_SYSCALL(compat_09_ouname)(void *name_) { /* TODO */ }
 POST_SYSCALL(compat_09_ouname)(long long res, void *name_) { /* TODO */ }
 PRE_SYSCALL(sysarch)(long long op_, void *parms_) { /* TODO */ }
 POST_SYSCALL(sysarch)(long long res, long long op_, void *parms_) { /* TODO */ }
-/* syscall 166 has been skipped */
-/* syscall 167 has been skipped */
-/* syscall 168 has been skipped */
+PRE_SYSCALL(__futex)
+(void *uaddr_, long long op_, long long val_, void *timeout_, void *uaddr2_,
+  long long val2_, long long val3_) {
+  /* TODO */
+}
+POST_SYSCALL(__futex)
+(long long res, void *uaddr_, long long op_, long long val_, void *timeout_,
+  void *uaddr2_, long long val2_, long long val3_) {
+  /* TODO */
+}
+PRE_SYSCALL(__futex_set_robust_list)(void *head_, long long len_) { /* TODO */ }
+POST_SYSCALL(__futex_set_robust_list)
+(long long res, void *head_, long long len_) {
+  /* TODO */
+}
+PRE_SYSCALL(__futex_get_robust_list)
+(long long lwpid_, void **headp_, void *lenp_) {
+  /* TODO */
+}
+POST_SYSCALL(__futex_get_robust_list)
+(long long res, long long lwpid_, void **headp_, void *lenp_) {
+  /* TODO */
+}
 #if !defined(_LP64)
 PRE_SYSCALL(compat_10_osemsys)
 (long long which_, long long a2_, long long a3_, long long a4_, long long a5_) {
@@ -3824,6 +3850,87 @@ PRE_SYSCALL(__fhstatvfs190)
 }
 POST_SYSCALL(__fhstatvfs190)
 (long long res, void *fhp_, long long fh_size_, void *buf_, long long flags_) {}
+PRE_SYSCALL(__acl_get_link)(void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+POST_SYSCALL(__acl_get_link)
+(long long res, void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_set_link)(void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+POST_SYSCALL(__acl_set_link)
+(long long res, void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_delete_link)(void *path_, long long type_) { /* TODO */ }
+POST_SYSCALL(__acl_delete_link)(long long res, void *path_, long long type_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_aclcheck_link)(void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+POST_SYSCALL(__acl_aclcheck_link)
+(long long res, void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_get_file)(void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+POST_SYSCALL(__acl_get_file)
+(long long res, void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_set_file)(void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+POST_SYSCALL(__acl_set_file)
+(long long res, void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_get_fd)(long long filedes_, long long type_, void *aclp_) {
+  /* TODO */
+}
+POST_SYSCALL(__acl_get_fd)
+(long long res, long long filedes_, long long type_, void *aclp_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_set_fd)(long long filedes_, long long type_, void *aclp_) {
+  /* TODO */
+}
+POST_SYSCALL(__acl_set_fd)
+(long long res, long long filedes_, long long type_, void *aclp_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_delete_file)(void *path_, long long type_) { /* TODO */ }
+POST_SYSCALL(__acl_delete_file)(long long res, void *path_, long long type_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_delete_fd)(long long filedes_, long long type_) { /* TODO */ }
+POST_SYSCALL(__acl_delete_fd)
+(long long res, long long filedes_, long long type_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_aclcheck_file)(void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+POST_SYSCALL(__acl_aclcheck_file)
+(long long res, void *path_, long long type_, void *aclp_) {
+  /* TODO */
+}
+PRE_SYSCALL(__acl_aclcheck_fd)
+(long long filedes_, long long type_, void *aclp_) {
+  /* TODO */
+}
+POST_SYSCALL(__acl_aclcheck_fd)
+(long long res, long long filedes_, long long type_, void *aclp_) {
+  /* TODO */
+}
+PRE_SYSCALL(lpathconf)(void *path_, long long name_) { /* TODO */ }
+POST_SYSCALL(lpathconf)(long long res, void *path_, long long name_) {
+  /* TODO */
+}
 #undef SYS_MAXSYSARGS
 } // extern "C"
 
lib/tsan/sanitizer_common/sanitizer_termination.cpp
@@ -59,26 +59,31 @@ void NORETURN Die() {
   internal__exit(common_flags()->exitcode);
 }
 
-static CheckFailedCallbackType CheckFailedCallback;
-void SetCheckFailedCallback(CheckFailedCallbackType callback) {
-  CheckFailedCallback = callback;
+static void (*CheckUnwindCallback)();
+void SetCheckUnwindCallback(void (*callback)()) {
+  CheckUnwindCallback = callback;
 }
 
-const int kSecondsToSleepWhenRecursiveCheckFailed = 2;
-
 void NORETURN CheckFailed(const char *file, int line, const char *cond,
                           u64 v1, u64 v2) {
-  static atomic_uint32_t num_calls;
-  if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) > 10) {
-    SleepForSeconds(kSecondsToSleepWhenRecursiveCheckFailed);
+  u32 tid = GetTid();
+  Printf("%s: CHECK failed: %s:%d \"%s\" (0x%zx, 0x%zx) (tid=%u)\n",
+         SanitizerToolName, StripModuleName(file), line, cond, (uptr)v1,
+         (uptr)v2, tid);
+  static atomic_uint32_t first_tid;
+  u32 cmp = 0;
+  if (!atomic_compare_exchange_strong(&first_tid, &cmp, tid,
+                                      memory_order_relaxed)) {
+    if (cmp == tid) {
+      // Recursing into CheckFailed.
+    } else {
+      // Another thread fails already, let it print the stack and terminate.
+      SleepForSeconds(2);
+    }
     Trap();
   }
-
-  if (CheckFailedCallback) {
-    CheckFailedCallback(file, line, cond, v1, v2);
-  }
-  Report("Sanitizer CHECK failed: %s:%d %s (%lld, %lld)\n", file, line, cond,
-                                                            v1, v2);
+  if (CheckUnwindCallback)
+    CheckUnwindCallback();
   Die();
 }
 
lib/tsan/sanitizer_common/sanitizer_thread_registry.cpp
@@ -85,7 +85,7 @@ void ThreadContextBase::SetCreated(uptr _user_id, u64 _unique_id,
   unique_id = _unique_id;
   detached = _detached;
   // Parent tid makes no sense for the main thread.
-  if (tid != 0)
+  if (tid != kMainTid)
     parent_tid = _parent_tid;
   OnCreated(arg);
 }
@@ -99,7 +99,8 @@ void ThreadContextBase::Reset() {
 
 // ThreadRegistry implementation.
 
-const u32 ThreadRegistry::kUnknownTid = ~0U;
+ThreadRegistry::ThreadRegistry(ThreadContextFactory factory)
+    : ThreadRegistry(factory, UINT32_MAX, UINT32_MAX, 0) {}
 
 ThreadRegistry::ThreadRegistry(ThreadContextFactory factory, u32 max_threads,
                                u32 thread_quarantine_size, u32 max_reuse)
@@ -108,13 +109,10 @@ ThreadRegistry::ThreadRegistry(ThreadContextFactory factory, u32 max_threads,
       thread_quarantine_size_(thread_quarantine_size),
       max_reuse_(max_reuse),
       mtx_(),
-      n_contexts_(0),
       total_threads_(0),
       alive_threads_(0),
       max_alive_threads_(0),
       running_threads_(0) {
-  threads_ = (ThreadContextBase **)MmapOrDie(max_threads_ * sizeof(threads_[0]),
-                                             "ThreadRegistry");
   dead_threads_.clear();
   invalid_threads_.clear();
 }
@@ -122,7 +120,8 @@ ThreadRegistry::ThreadRegistry(ThreadContextFactory factory, u32 max_threads,
 void ThreadRegistry::GetNumberOfThreads(uptr *total, uptr *running,
                                         uptr *alive) {
   BlockingMutexLock l(&mtx_);
-  if (total) *total = n_contexts_;
+  if (total)
+    *total = threads_.size();
   if (running) *running = running_threads_;
   if (alive) *alive = alive_threads_;
 }
@@ -135,15 +134,15 @@ uptr ThreadRegistry::GetMaxAliveThreads() {
 u32 ThreadRegistry::CreateThread(uptr user_id, bool detached, u32 parent_tid,
                                  void *arg) {
   BlockingMutexLock l(&mtx_);
-  u32 tid = kUnknownTid;
+  u32 tid = kInvalidTid;
   ThreadContextBase *tctx = QuarantinePop();
   if (tctx) {
     tid = tctx->tid;
-  } else if (n_contexts_ < max_threads_) {
+  } else if (threads_.size() < max_threads_) {
     // Allocate new thread context and tid.
-    tid = n_contexts_++;
+    tid = threads_.size();
     tctx = context_factory_(tid);
-    threads_[tid] = tctx;
+    threads_.push_back(tctx);
   } else {
 #if !SANITIZER_GO
     Report("%s: Thread limit (%u threads) exceeded. Dying.\n",
@@ -155,7 +154,7 @@ u32 ThreadRegistry::CreateThread(uptr user_id, bool detached, u32 parent_tid,
     Die();
   }
   CHECK_NE(tctx, 0);
-  CHECK_NE(tid, kUnknownTid);
+  CHECK_NE(tid, kInvalidTid);
   CHECK_LT(tid, max_threads_);
   CHECK_EQ(tctx->status, ThreadStatusInvalid);
   alive_threads_++;
@@ -171,7 +170,7 @@ u32 ThreadRegistry::CreateThread(uptr user_id, bool detached, u32 parent_tid,
 void ThreadRegistry::RunCallbackForEachThreadLocked(ThreadCallback cb,
                                                     void *arg) {
   CheckLocked();
-  for (u32 tid = 0; tid < n_contexts_; tid++) {
+  for (u32 tid = 0; tid < threads_.size(); tid++) {
     ThreadContextBase *tctx = threads_[tid];
     if (tctx == 0)
       continue;
@@ -181,18 +180,18 @@ void ThreadRegistry::RunCallbackForEachThreadLocked(ThreadCallback cb,
 
 u32 ThreadRegistry::FindThread(FindThreadCallback cb, void *arg) {
   BlockingMutexLock l(&mtx_);
-  for (u32 tid = 0; tid < n_contexts_; tid++) {
+  for (u32 tid = 0; tid < threads_.size(); tid++) {
     ThreadContextBase *tctx = threads_[tid];
     if (tctx != 0 && cb(tctx, arg))
       return tctx->tid;
   }
-  return kUnknownTid;
+  return kInvalidTid;
 }
 
 ThreadContextBase *
 ThreadRegistry::FindThreadContextLocked(FindThreadCallback cb, void *arg) {
   CheckLocked();
-  for (u32 tid = 0; tid < n_contexts_; tid++) {
+  for (u32 tid = 0; tid < threads_.size(); tid++) {
     ThreadContextBase *tctx = threads_[tid];
     if (tctx != 0 && cb(tctx, arg))
       return tctx;
@@ -213,7 +212,6 @@ ThreadContextBase *ThreadRegistry::FindThreadContextByOsIDLocked(tid_t os_id) {
 
 void ThreadRegistry::SetThreadName(u32 tid, const char *name) {
   BlockingMutexLock l(&mtx_);
-  CHECK_LT(tid, n_contexts_);
   ThreadContextBase *tctx = threads_[tid];
   CHECK_NE(tctx, 0);
   CHECK_EQ(SANITIZER_FUCHSIA ? ThreadStatusCreated : ThreadStatusRunning,
@@ -223,7 +221,7 @@ void ThreadRegistry::SetThreadName(u32 tid, const char *name) {
 
 void ThreadRegistry::SetThreadNameByUserId(uptr user_id, const char *name) {
   BlockingMutexLock l(&mtx_);
-  for (u32 tid = 0; tid < n_contexts_; tid++) {
+  for (u32 tid = 0; tid < threads_.size(); tid++) {
     ThreadContextBase *tctx = threads_[tid];
     if (tctx != 0 && tctx->user_id == user_id &&
         tctx->status != ThreadStatusInvalid) {
@@ -235,7 +233,6 @@ void ThreadRegistry::SetThreadNameByUserId(uptr user_id, const char *name) {
 
 void ThreadRegistry::DetachThread(u32 tid, void *arg) {
   BlockingMutexLock l(&mtx_);
-  CHECK_LT(tid, n_contexts_);
   ThreadContextBase *tctx = threads_[tid];
   CHECK_NE(tctx, 0);
   if (tctx->status == ThreadStatusInvalid) {
@@ -256,7 +253,6 @@ void ThreadRegistry::JoinThread(u32 tid, void *arg) {
   do {
     {
       BlockingMutexLock l(&mtx_);
-      CHECK_LT(tid, n_contexts_);
       ThreadContextBase *tctx = threads_[tid];
       CHECK_NE(tctx, 0);
       if (tctx->status == ThreadStatusInvalid) {
@@ -278,14 +274,14 @@ void ThreadRegistry::JoinThread(u32 tid, void *arg) {
 // really started.  We just did CreateThread for a prospective new
 // thread before trying to create it, and then failed to actually
 // create it, and so never called StartThread.
-void ThreadRegistry::FinishThread(u32 tid) {
+ThreadStatus ThreadRegistry::FinishThread(u32 tid) {
   BlockingMutexLock l(&mtx_);
   CHECK_GT(alive_threads_, 0);
   alive_threads_--;
-  CHECK_LT(tid, n_contexts_);
   ThreadContextBase *tctx = threads_[tid];
   CHECK_NE(tctx, 0);
   bool dead = tctx->detached;
+  ThreadStatus prev_status = tctx->status;
   if (tctx->status == ThreadStatusRunning) {
     CHECK_GT(running_threads_, 0);
     running_threads_--;
@@ -300,13 +296,13 @@ void ThreadRegistry::FinishThread(u32 tid) {
     QuarantinePush(tctx);
   }
   tctx->SetDestroyed();
+  return prev_status;
 }
 
 void ThreadRegistry::StartThread(u32 tid, tid_t os_id, ThreadType thread_type,
                                  void *arg) {
   BlockingMutexLock l(&mtx_);
   running_threads_++;
-  CHECK_LT(tid, n_contexts_);
   ThreadContextBase *tctx = threads_[tid];
   CHECK_NE(tctx, 0);
   CHECK_EQ(ThreadStatusCreated, tctx->status);
@@ -339,7 +335,6 @@ ThreadContextBase *ThreadRegistry::QuarantinePop() {
 
 void ThreadRegistry::SetThreadUserId(u32 tid, uptr user_id) {
   BlockingMutexLock l(&mtx_);
-  CHECK_LT(tid, n_contexts_);
   ThreadContextBase *tctx = threads_[tid];
   CHECK_NE(tctx, 0);
   CHECK_NE(tctx->status, ThreadStatusInvalid);
lib/tsan/sanitizer_common/sanitizer_thread_registry.h
@@ -39,8 +39,6 @@ enum class ThreadType {
 class ThreadContextBase {
  public:
   explicit ThreadContextBase(u32 tid);
-  ~ThreadContextBase();  // Should never be called.
-
   const u32 tid;  // Thread ID. Main thread should have tid = 0.
   u64 unique_id;  // Unique thread ID.
   u32 reuse_count;  // Number of times this tid was reused.
@@ -80,28 +78,29 @@ class ThreadContextBase {
   virtual void OnCreated(void *arg) {}
   virtual void OnReset() {}
   virtual void OnDetached(void *arg) {}
+
+ protected:
+  ~ThreadContextBase();
 };
 
 typedef ThreadContextBase* (*ThreadContextFactory)(u32 tid);
 
-class ThreadRegistry {
+class MUTEX ThreadRegistry {
  public:
-  static const u32 kUnknownTid;
-
+  ThreadRegistry(ThreadContextFactory factory);
   ThreadRegistry(ThreadContextFactory factory, u32 max_threads,
-                 u32 thread_quarantine_size, u32 max_reuse = 0);
+                 u32 thread_quarantine_size, u32 max_reuse);
   void GetNumberOfThreads(uptr *total = nullptr, uptr *running = nullptr,
                           uptr *alive = nullptr);
   uptr GetMaxAliveThreads();
 
-  void Lock() { mtx_.Lock(); }
-  void CheckLocked() { mtx_.CheckLocked(); }
-  void Unlock() { mtx_.Unlock(); }
+  void Lock() ACQUIRE() { mtx_.Lock(); }
+  void CheckLocked() const CHECK_LOCKED() { mtx_.CheckLocked(); }
+  void Unlock() RELEASE() { mtx_.Unlock(); }
 
   // Should be guarded by ThreadRegistryLock.
   ThreadContextBase *GetThreadLocked(u32 tid) {
-    DCHECK_LT(tid, n_contexts_);
-    return threads_[tid];
+    return threads_.empty() ? nullptr : threads_[tid];
   }
 
   u32 CreateThread(uptr user_id, bool detached, u32 parent_tid, void *arg);
@@ -112,7 +111,7 @@ class ThreadRegistry {
   void RunCallbackForEachThreadLocked(ThreadCallback cb, void *arg);
 
   typedef bool (*FindThreadCallback)(ThreadContextBase *tctx, void *arg);
-  // Finds a thread using the provided callback. Returns kUnknownTid if no
+  // Finds a thread using the provided callback. Returns kInvalidTid if no
   // thread is found.
   u32 FindThread(FindThreadCallback cb, void *arg);
   // Should be guarded by ThreadRegistryLock. Return 0 if no thread
@@ -125,7 +124,8 @@ class ThreadRegistry {
   void SetThreadNameByUserId(uptr user_id, const char *name);
   void DetachThread(u32 tid, void *arg);
   void JoinThread(u32 tid, void *arg);
-  void FinishThread(u32 tid);
+  // Finishes thread and returns previous status.
+  ThreadStatus FinishThread(u32 tid);
   void StartThread(u32 tid, tid_t os_id, ThreadType thread_type, void *arg);
   void SetThreadUserId(u32 tid, uptr user_id);
 
@@ -137,15 +137,13 @@ class ThreadRegistry {
 
   BlockingMutex mtx_;
 
-  u32 n_contexts_;      // Number of created thread contexts,
-                        // at most max_threads_.
   u64 total_threads_;   // Total number of created threads. May be greater than
                         // max_threads_ if contexts were reused.
   uptr alive_threads_;  // Created or running.
   uptr max_alive_threads_;
   uptr running_threads_;
 
-  ThreadContextBase **threads_;  // Array of thread contexts is leaked.
+  InternalMmapVector<ThreadContextBase *> threads_;
   IntrusiveList<ThreadContextBase> dead_threads_;
   IntrusiveList<ThreadContextBase> invalid_threads_;
 
lib/tsan/sanitizer_common/sanitizer_thread_safety.h
@@ -0,0 +1,42 @@
+//===-- sanitizer_thread_safety.h -------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file is shared between sanitizer tools.
+//
+// Wrappers around thread safety annotations.
+// https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
+//===----------------------------------------------------------------------===//
+
+#ifndef SANITIZER_THREAD_SAFETY_H
+#define SANITIZER_THREAD_SAFETY_H
+
+#if defined(__clang__)
+#  define THREAD_ANNOTATION(x) __attribute__((x))
+#else
+#  define THREAD_ANNOTATION(x)
+#endif
+
+#define MUTEX THREAD_ANNOTATION(capability("mutex"))
+#define SCOPED_LOCK THREAD_ANNOTATION(scoped_lockable)
+#define GUARDED_BY(x) THREAD_ANNOTATION(guarded_by(x))
+#define PT_GUARDED_BY(x) THREAD_ANNOTATION(pt_guarded_by(x))
+#define REQUIRES(...) THREAD_ANNOTATION(requires_capability(__VA_ARGS__))
+#define REQUIRES_SHARED(...) \
+  THREAD_ANNOTATION(requires_shared_capability(__VA_ARGS__))
+#define ACQUIRE(...) THREAD_ANNOTATION(acquire_capability(__VA_ARGS__))
+#define ACQUIRE_SHARED(...) \
+  THREAD_ANNOTATION(acquire_shared_capability(__VA_ARGS__))
+#define TRY_ACQUIRE(...) THREAD_ANNOTATION(try_acquire_capability(__VA_ARGS__))
+#define RELEASE(...) THREAD_ANNOTATION(release_capability(__VA_ARGS__))
+#define RELEASE_SHARED(...) \
+  THREAD_ANNOTATION(release_shared_capability(__VA_ARGS__))
+#define EXCLUDES(...) THREAD_ANNOTATION(locks_excluded(__VA_ARGS__))
+#define CHECK_LOCKED(...) THREAD_ANNOTATION(assert_capability(__VA_ARGS__))
+#define NO_THREAD_SAFETY_ANALYSIS THREAD_ANNOTATION(no_thread_safety_analysis)
+
+#endif
lib/tsan/sanitizer_common/sanitizer_tls_get_addr.cpp
@@ -12,6 +12,7 @@
 
 #include "sanitizer_tls_get_addr.h"
 
+#include "sanitizer_atomic.h"
 #include "sanitizer_flags.h"
 #include "sanitizer_platform_interceptors.h"
 
@@ -42,46 +43,66 @@ static atomic_uintptr_t number_of_live_dtls;
 
 static const uptr kDestroyedThread = -1;
 
-static inline void DTLS_Deallocate(DTLS::DTV *dtv, uptr size) {
-  if (!size) return;
-  VReport(2, "__tls_get_addr: DTLS_Deallocate %p %zd\n", dtv, size);
-  UnmapOrDie(dtv, size * sizeof(DTLS::DTV));
+static void DTLS_Deallocate(DTLS::DTVBlock *block) {
+  VReport(2, "__tls_get_addr: DTLS_Deallocate %p %zd\n", block);
+  UnmapOrDie(block, sizeof(DTLS::DTVBlock));
   atomic_fetch_sub(&number_of_live_dtls, 1, memory_order_relaxed);
 }
 
-static inline void DTLS_Resize(uptr new_size) {
-  if (dtls.dtv_size >= new_size) return;
-  new_size = RoundUpToPowerOfTwo(new_size);
-  new_size = Max(new_size, 4096UL / sizeof(DTLS::DTV));
-  DTLS::DTV *new_dtv =
-      (DTLS::DTV *)MmapOrDie(new_size * sizeof(DTLS::DTV), "DTLS_Resize");
+static DTLS::DTVBlock *DTLS_NextBlock(atomic_uintptr_t *cur) {
+  uptr v = atomic_load(cur, memory_order_acquire);
+  if (v == kDestroyedThread)
+    return nullptr;
+  DTLS::DTVBlock *next = (DTLS::DTVBlock *)v;
+  if (next)
+    return next;
+  DTLS::DTVBlock *new_dtv =
+      (DTLS::DTVBlock *)MmapOrDie(sizeof(DTLS::DTVBlock), "DTLS_NextBlock");
+  uptr prev = 0;
+  if (!atomic_compare_exchange_strong(cur, &prev, (uptr)new_dtv,
+                                      memory_order_seq_cst)) {
+    UnmapOrDie(new_dtv, sizeof(DTLS::DTVBlock));
+    return (DTLS::DTVBlock *)prev;
+  }
   uptr num_live_dtls =
       atomic_fetch_add(&number_of_live_dtls, 1, memory_order_relaxed);
-  VReport(2, "__tls_get_addr: DTLS_Resize %p %zd\n", &dtls, num_live_dtls);
-  CHECK_LT(num_live_dtls, 1 << 20);
-  uptr old_dtv_size = dtls.dtv_size;
-  DTLS::DTV *old_dtv = dtls.dtv;
-  if (old_dtv_size)
-    internal_memcpy(new_dtv, dtls.dtv, dtls.dtv_size * sizeof(DTLS::DTV));
-  dtls.dtv = new_dtv;
-  dtls.dtv_size = new_size;
-  if (old_dtv_size)
-    DTLS_Deallocate(old_dtv, old_dtv_size);
+  VReport(2, "__tls_get_addr: DTLS_NextBlock %p %zd\n", &dtls, num_live_dtls);
+  return new_dtv;
+}
+
+static DTLS::DTV *DTLS_Find(uptr id) {
+  VReport(2, "__tls_get_addr: DTLS_Find %p %zd\n", &dtls, id);
+  static constexpr uptr kPerBlock = ARRAY_SIZE(DTLS::DTVBlock::dtvs);
+  DTLS::DTVBlock *cur = DTLS_NextBlock(&dtls.dtv_block);
+  if (!cur)
+    return nullptr;
+  for (; id >= kPerBlock; id -= kPerBlock) cur = DTLS_NextBlock(&cur->next);
+  return cur->dtvs + id;
 }
 
 void DTLS_Destroy() {
   if (!common_flags()->intercept_tls_get_addr) return;
-  VReport(2, "__tls_get_addr: DTLS_Destroy %p %zd\n", &dtls, dtls.dtv_size);
-  uptr s = dtls.dtv_size;
-  dtls.dtv_size = kDestroyedThread;  // Do this before unmap for AS-safety.
-  DTLS_Deallocate(dtls.dtv, s);
+  VReport(2, "__tls_get_addr: DTLS_Destroy %p\n", &dtls);
+  DTLS::DTVBlock *block = (DTLS::DTVBlock *)atomic_exchange(
+      &dtls.dtv_block, kDestroyedThread, memory_order_release);
+  while (block) {
+    DTLS::DTVBlock *next =
+        (DTLS::DTVBlock *)atomic_load(&block->next, memory_order_acquire);
+    DTLS_Deallocate(block);
+    block = next;
+  }
 }
 
 #if defined(__powerpc64__) || defined(__mips__)
 // This is glibc's TLS_DTV_OFFSET:
 // "Dynamic thread vector pointers point 0x8000 past the start of each
-//  TLS block."
+//  TLS block." (sysdeps/<arch>/dl-tls.h)
 static const uptr kDtvOffset = 0x8000;
+#elif defined(__riscv)
+// This is glibc's TLS_DTV_OFFSET:
+// "Dynamic thread vector pointers point 0x800 past the start of each
+// TLS block." (sysdeps/riscv/dl-tls.h)
+static const uptr kDtvOffset = 0x800;
 #else
 static const uptr kDtvOffset = 0;
 #endif
@@ -91,9 +112,9 @@ DTLS::DTV *DTLS_on_tls_get_addr(void *arg_void, void *res,
   if (!common_flags()->intercept_tls_get_addr) return 0;
   TlsGetAddrParam *arg = reinterpret_cast<TlsGetAddrParam *>(arg_void);
   uptr dso_id = arg->dso_id;
-  if (dtls.dtv_size == kDestroyedThread) return 0;
-  DTLS_Resize(dso_id + 1);
-  if (dtls.dtv[dso_id].beg) return 0;
+  DTLS::DTV *dtv = DTLS_Find(dso_id);
+  if (!dtv || dtv->beg)
+    return 0;
   uptr tls_size = 0;
   uptr tls_beg = reinterpret_cast<uptr>(res) - arg->offset - kDtvOffset;
   VReport(2, "__tls_get_addr: %p {%p,%p} => %p; tls_beg: %p; sp: %p "
@@ -121,9 +142,9 @@ DTLS::DTV *DTLS_on_tls_get_addr(void *arg_void, void *res,
     // This may happen inside the DTOR of main thread, so just ignore it.
     tls_size = 0;
   }
-  dtls.dtv[dso_id].beg = tls_beg;
-  dtls.dtv[dso_id].size = tls_size;
-  return dtls.dtv + dso_id;
+  dtv->beg = tls_beg;
+  dtv->size = tls_size;
+  return dtv;
 }
 
 void DTLS_on_libc_memalign(void *ptr, uptr size) {
@@ -136,7 +157,8 @@ void DTLS_on_libc_memalign(void *ptr, uptr size) {
 DTLS *DTLS_Get() { return &dtls; }
 
 bool DTLSInDestruction(DTLS *dtls) {
-  return dtls->dtv_size == kDestroyedThread;
+  return atomic_load(&dtls->dtv_block, memory_order_relaxed) ==
+         kDestroyedThread;
 }
 
 #else
lib/tsan/sanitizer_common/sanitizer_tls_get_addr.h
@@ -28,6 +28,7 @@
 #ifndef SANITIZER_TLS_GET_ADDR_H
 #define SANITIZER_TLS_GET_ADDR_H
 
+#include "sanitizer_atomic.h"
 #include "sanitizer_common.h"
 
 namespace __sanitizer {
@@ -38,15 +39,31 @@ struct DTLS {
   struct DTV {
     uptr beg, size;
   };
+  struct DTVBlock {
+    atomic_uintptr_t next;
+    DTV dtvs[(4096UL - sizeof(next)) / sizeof(DTLS::DTV)];
+  };
+
+  static_assert(sizeof(DTVBlock) <= 4096UL, "Unexpected block size");
 
-  uptr dtv_size;
-  DTV *dtv;  // dtv_size elements, allocated by MmapOrDie.
+  atomic_uintptr_t dtv_block;
 
   // Auxiliary fields, don't access them outside sanitizer_tls_get_addr.cpp
   uptr last_memalign_size;
   uptr last_memalign_ptr;
 };
 
+template <typename Fn>
+void ForEachDVT(DTLS *dtls, const Fn &fn) {
+  DTLS::DTVBlock *block =
+      (DTLS::DTVBlock *)atomic_load(&dtls->dtv_block, memory_order_acquire);
+  while (block) {
+    int id = 0;
+    for (auto &d : block->dtvs) fn(d, id++);
+    block = (DTLS::DTVBlock *)atomic_load(&block->next, memory_order_acquire);
+  }
+}
+
 // Returns pointer and size of a linker-allocated TLS block.
 // Each block is returned exactly once.
 DTLS::DTV *DTLS_on_tls_get_addr(void *arg, void *res, uptr static_tls_begin,
lib/tsan/sanitizer_common/sanitizer_unwind_win.cpp
@@ -37,8 +37,16 @@ void BufferedStackTrace::UnwindSlow(uptr pc, u32 max_depth) {
   // Skip the RTL frames by searching for the PC in the stacktrace.
   uptr pc_location = LocatePcInTrace(pc);
   PopStackFrames(pc_location);
+
+  // Replace the first frame with the PC because the frame in the
+  // stacktrace might be incorrect.
+  trace_buffer[0] = pc;
 }
 
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wframe-larger-than="
+#endif
 void BufferedStackTrace::UnwindSlow(uptr pc, void *context, u32 max_depth) {
   CHECK(context);
   CHECK_GE(max_depth, 2);
@@ -70,6 +78,9 @@ void BufferedStackTrace::UnwindSlow(uptr pc, void *context, u32 max_depth) {
     trace_buffer[size++] = (uptr)stack_frame.AddrPC.Offset;
   }
 }
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
 #endif  // #if !SANITIZER_GO
 
 #endif  // SANITIZER_WINDOWS
lib/tsan/sanitizer_common/sanitizer_win.cpp
@@ -44,6 +44,9 @@ TRACELOGGING_DEFINE_PROVIDER(g_asan_provider, "AddressSanitizerLoggingProvider",
 #define TraceLoggingUnregister(x)
 #endif
 
+// For WaitOnAddress
+#  pragma comment(lib, "synchronization.lib")
+
 // A macro to tell the compiler that this part of the code cannot be reached,
 // if the compiler supports this feature. Since we're using this in
 // code that is called when terminating the process, the expansion of the
@@ -334,8 +337,12 @@ bool MprotectNoAccess(uptr addr, uptr size) {
 }
 
 void ReleaseMemoryPagesToOS(uptr beg, uptr end) {
-  // This is almost useless on 32-bits.
-  // FIXME: add madvise-analog when we move to 64-bits.
+  uptr beg_aligned = RoundDownTo(beg, GetPageSizeCached()),
+       end_aligned = RoundDownTo(end, GetPageSizeCached());
+  CHECK(beg < end);                // make sure the region is sane
+  if (beg_aligned == end_aligned)  // make sure we're freeing at least 1 page;
+    return;
+  UnmapOrDie((void *)beg, end_aligned - beg_aligned);
 }
 
 void SetShadowRegionHugePageMode(uptr addr, uptr size) {
@@ -348,6 +355,22 @@ bool DontDumpShadowMemory(uptr addr, uptr length) {
   return true;
 }
 
+uptr MapDynamicShadow(uptr shadow_size_bytes, uptr shadow_scale,
+                      uptr min_shadow_base_alignment,
+                      UNUSED uptr &high_mem_end) {
+  const uptr granularity = GetMmapGranularity();
+  const uptr alignment =
+      Max<uptr>(granularity << shadow_scale, 1ULL << min_shadow_base_alignment);
+  const uptr left_padding =
+      Max<uptr>(granularity, 1ULL << min_shadow_base_alignment);
+  uptr space_size = shadow_size_bytes + left_padding;
+  uptr shadow_start = FindAvailableMemoryRange(space_size, alignment,
+                                               granularity, nullptr, nullptr);
+  CHECK_NE((uptr)0, shadow_start);
+  CHECK(IsAligned(shadow_start, alignment));
+  return shadow_start;
+}
+
 uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
                               uptr *largest_gap_found,
                               uptr *max_occupied_addr) {
@@ -370,6 +393,12 @@ uptr FindAvailableMemoryRange(uptr size, uptr alignment, uptr left_padding,
   return 0;
 }
 
+uptr MapDynamicShadowAndAliases(uptr shadow_size, uptr alias_size,
+                                uptr num_aliases, uptr ring_buffer_size) {
+  CHECK(false && "HWASan aliasing is unimplemented on Windows");
+  return 0;
+}
+
 bool MemoryRangeIsAvailable(uptr range_start, uptr range_end) {
   MEMORY_BASIC_INFORMATION mbi;
   CHECK(VirtualQuery((void *)range_start, &mbi, sizeof(mbi)));
@@ -475,8 +504,6 @@ void DumpProcessMap() {
 }
 #endif
 
-void PrintModuleMap() { }
-
 void DisableCoreDumperIfNecessary() {
   // Do nothing.
 }
@@ -517,13 +544,7 @@ bool IsAbsolutePath(const char *path) {
          IsPathSeparator(path[2]);
 }
 
-void SleepForSeconds(int seconds) {
-  Sleep(seconds * 1000);
-}
-
-void SleepForMillis(int millis) {
-  Sleep(millis);
-}
+void internal_usleep(u64 useconds) { Sleep(useconds / 1000); }
 
 u64 NanoTime() {
   static LARGE_INTEGER frequency = {};
@@ -550,7 +571,7 @@ void Abort() {
 // load the image at this address. Therefore, we call it the preferred base. Any
 // addresses in the DWARF typically assume that the object has been loaded at
 // this address.
-static uptr GetPreferredBase(const char *modname) {
+static uptr GetPreferredBase(const char *modname, char *buf, size_t buf_size) {
   fd_t fd = OpenFile(modname, RdOnly, nullptr);
   if (fd == kInvalidFd)
     return 0;
@@ -572,12 +593,10 @@ static uptr GetPreferredBase(const char *modname) {
   // IMAGE_FILE_HEADER
   // IMAGE_OPTIONAL_HEADER
   // Seek to e_lfanew and read all that data.
-  char buf[4 + sizeof(IMAGE_FILE_HEADER) + sizeof(IMAGE_OPTIONAL_HEADER)];
   if (::SetFilePointer(fd, dos_header.e_lfanew, nullptr, FILE_BEGIN) ==
       INVALID_SET_FILE_POINTER)
     return 0;
-  if (!ReadFromFile(fd, &buf[0], sizeof(buf), &bytes_read) ||
-      bytes_read != sizeof(buf))
+  if (!ReadFromFile(fd, buf, buf_size, &bytes_read) || bytes_read != buf_size)
     return 0;
 
   // Check for "PE\0\0" before the PE header.
@@ -619,6 +638,10 @@ void ListOfModules::init() {
     }
   }
 
+  InternalMmapVector<char> buf(4 + sizeof(IMAGE_FILE_HEADER) +
+                               sizeof(IMAGE_OPTIONAL_HEADER));
+  InternalMmapVector<wchar_t> modname_utf16(kMaxPathLength);
+  InternalMmapVector<char> module_name(kMaxPathLength);
   // |num_modules| is the number of modules actually present,
   size_t num_modules = bytes_required / sizeof(HMODULE);
   for (size_t i = 0; i < num_modules; ++i) {
@@ -628,15 +651,13 @@ void ListOfModules::init() {
       continue;
 
     // Get the UTF-16 path and convert to UTF-8.
-    wchar_t modname_utf16[kMaxPathLength];
     int modname_utf16_len =
-        GetModuleFileNameW(handle, modname_utf16, kMaxPathLength);
+        GetModuleFileNameW(handle, &modname_utf16[0], kMaxPathLength);
     if (modname_utf16_len == 0)
       modname_utf16[0] = '\0';
-    char module_name[kMaxPathLength];
-    int module_name_len =
-        ::WideCharToMultiByte(CP_UTF8, 0, modname_utf16, modname_utf16_len + 1,
-                              &module_name[0], kMaxPathLength, NULL, NULL);
+    int module_name_len = ::WideCharToMultiByte(
+        CP_UTF8, 0, &modname_utf16[0], modname_utf16_len + 1, &module_name[0],
+        kMaxPathLength, NULL, NULL);
     module_name[module_name_len] = '\0';
 
     uptr base_address = (uptr)mi.lpBaseOfDll;
@@ -646,15 +667,16 @@ void ListOfModules::init() {
     // RVA when computing the module offset. This helps llvm-symbolizer find the
     // right DWARF CU. In the common case that the image is loaded at it's
     // preferred address, we will now print normal virtual addresses.
-    uptr preferred_base = GetPreferredBase(&module_name[0]);
+    uptr preferred_base =
+        GetPreferredBase(&module_name[0], &buf[0], buf.size());
     uptr adjusted_base = base_address - preferred_base;
 
-    LoadedModule cur_module;
-    cur_module.set(module_name, adjusted_base);
+    modules_.push_back(LoadedModule());
+    LoadedModule &cur_module = modules_.back();
+    cur_module.set(&module_name[0], adjusted_base);
     // We add the whole module as one single address range.
     cur_module.addAddressRange(base_address, end_address, /*executable*/ true,
                                /*writable*/ true);
-    modules_.push_back(cur_module);
   }
   UnmapOrDie(hmodules, modules_buffer_size);
 }
@@ -794,6 +816,17 @@ uptr GetRSS() {
 void *internal_start_thread(void *(*func)(void *arg), void *arg) { return 0; }
 void internal_join_thread(void *th) { }
 
+void FutexWait(atomic_uint32_t *p, u32 cmp) {
+  WaitOnAddress(p, &cmp, sizeof(cmp), INFINITE);
+}
+
+void FutexWake(atomic_uint32_t *p, u32 count) {
+  if (count == 1)
+    WakeByAddressSingle(p);
+  else
+    WakeByAddressAll(p);
+}
+
 // ---------------------- BlockingMutex ---------------- {{{1
 
 BlockingMutex::BlockingMutex() {
@@ -813,9 +846,7 @@ void BlockingMutex::Unlock() {
   ReleaseSRWLockExclusive((PSRWLOCK)opaque_storage_);
 }
 
-void BlockingMutex::CheckLocked() {
-  CHECK_EQ(owner_, GetThreadSelf());
-}
+void BlockingMutex::CheckLocked() const { CHECK_EQ(owner_, GetThreadSelf()); }
 
 uptr GetTlsSize() {
   return 0;
@@ -942,22 +973,27 @@ void SignalContext::InitPcSpBp() {
 
 uptr SignalContext::GetAddress() const {
   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
-  return exception_record->ExceptionInformation[1];
+  if (exception_record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
+    return exception_record->ExceptionInformation[1];
+  return (uptr)exception_record->ExceptionAddress;
 }
 
 bool SignalContext::IsMemoryAccess() const {
-  return GetWriteFlag() != SignalContext::UNKNOWN;
+  return ((EXCEPTION_RECORD *)siginfo)->ExceptionCode ==
+         EXCEPTION_ACCESS_VIOLATION;
 }
 
-bool SignalContext::IsTrueFaultingAddress() const {
-  // FIXME: Provide real implementation for this. See Linux and Mac variants.
-  return IsMemoryAccess();
-}
+bool SignalContext::IsTrueFaultingAddress() const { return true; }
 
 SignalContext::WriteFlag SignalContext::GetWriteFlag() const {
   EXCEPTION_RECORD *exception_record = (EXCEPTION_RECORD *)siginfo;
+
+  // The write flag is only available for access violation exceptions.
+  if (exception_record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION)
+    return SignalContext::UNKNOWN;
+
   // The contents of this array are documented at
-  // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx
+  // https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-exception_record
   // The first element indicates read as 0, write as 1, or execute as 8.  The
   // second element is the faulting address.
   switch (exception_record->ExceptionInformation[0]) {
@@ -1023,10 +1059,24 @@ const char *SignalContext::Describe() const {
 }
 
 uptr ReadBinaryName(/*out*/char *buf, uptr buf_len) {
-  // FIXME: Actually implement this function.
-  CHECK_GT(buf_len, 0);
-  buf[0] = 0;
-  return 0;
+  if (buf_len == 0)
+    return 0;
+
+  // Get the UTF-16 path and convert to UTF-8.
+  InternalMmapVector<wchar_t> binname_utf16(kMaxPathLength);
+  int binname_utf16_len =
+      GetModuleFileNameW(NULL, &binname_utf16[0], kMaxPathLength);
+  if (binname_utf16_len == 0) {
+    buf[0] = '\0';
+    return 0;
+  }
+  int binary_name_len =
+      ::WideCharToMultiByte(CP_UTF8, 0, &binname_utf16[0], binname_utf16_len,
+                            buf, buf_len, NULL, NULL);
+  if ((unsigned)binary_name_len == buf_len)
+    --binary_name_len;
+  buf[binary_name_len] = '\0';
+  return binary_name_len;
 }
 
 uptr ReadLongProcessName(/*out*/char *buf, uptr buf_len) {
@@ -1124,6 +1174,8 @@ void LogFullErrorReport(const char *buffer) {
 }
 #endif // SANITIZER_WIN_TRACE
 
+void InitializePlatformCommonFlags(CommonFlags *cf) {}
+
 }  // namespace __sanitizer
 
 #endif  // _WIN32
lib/tsan/ubsan/ubsan_flags.h
@@ -34,8 +34,6 @@ inline Flags *flags() { return &ubsan_flags; }
 void InitializeFlags();
 void RegisterUbsanFlags(FlagParser *parser, Flags *f);
 
-const char *MaybeCallUbsanDefaultOptions();
-
 }  // namespace __ubsan
 
 extern "C" {
lib/tsan/ubsan/ubsan_platform.h
@@ -14,10 +14,10 @@
 
 // Other platforms should be easy to add, and probably work as-is.
 #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) ||        \
-    defined(__NetBSD__) || defined(__OpenBSD__) || \
-    (defined(__sun__) && defined(__svr4__)) || \
-    defined(_WIN32) || defined(__Fuchsia__) || defined(__rtems__)
-# define CAN_SANITIZE_UB 1
+    defined(__NetBSD__) || defined(__DragonFly__) ||                           \
+    (defined(__sun__) && defined(__svr4__)) || defined(_WIN32) ||              \
+    defined(__Fuchsia__)
+#define CAN_SANITIZE_UB 1
 #else
 # define CAN_SANITIZE_UB 0
 #endif
lib/tsan/tsan_clock.cpp
@@ -80,14 +80,6 @@
 //   release-store operation by the thread with release_store_tid_ index.
 // release_store_reused_ - reuse count of release_store_tid_.
 
-// We don't have ThreadState in these methods, so this is an ugly hack that
-// works only in C++.
-#if !SANITIZER_GO
-# define CPP_STAT_INC(typ) StatInc(cur_thread(), typ)
-#else
-# define CPP_STAT_INC(typ) (void)0
-#endif
-
 namespace __tsan {
 
 static atomic_uint32_t *ref_ptr(ClockBlock *cb) {
@@ -138,19 +130,16 @@ void ThreadClock::ResetCached(ClockCache *c) {
 void ThreadClock::acquire(ClockCache *c, SyncClock *src) {
   DCHECK_LE(nclk_, kMaxTid);
   DCHECK_LE(src->size_, kMaxTid);
-  CPP_STAT_INC(StatClockAcquire);
 
   // Check if it's empty -> no need to do anything.
   const uptr nclk = src->size_;
-  if (nclk == 0) {
-    CPP_STAT_INC(StatClockAcquireEmpty);
+  if (nclk == 0)
     return;
-  }
 
   bool acquired = false;
   for (unsigned i = 0; i < kDirtyTids; i++) {
     SyncClock::Dirty dirty = src->dirty_[i];
-    unsigned tid = dirty.tid;
+    unsigned tid = dirty.tid();
     if (tid != kInvalidTid) {
       if (clk_[tid] < dirty.epoch) {
         clk_[tid] = dirty.epoch;
@@ -162,7 +151,6 @@ void ThreadClock::acquire(ClockCache *c, SyncClock *src) {
   // Check if we've already acquired src after the last release operation on src
   if (tid_ >= nclk || src->elem(tid_).reused != reused_) {
     // O(N) acquire.
-    CPP_STAT_INC(StatClockAcquireFull);
     nclk_ = max(nclk_, nclk);
     u64 *dst_pos = &clk_[0];
     for (ClockElem &src_elem : *src) {
@@ -180,7 +168,6 @@ void ThreadClock::acquire(ClockCache *c, SyncClock *src) {
   }
 
   if (acquired) {
-    CPP_STAT_INC(StatClockAcquiredSomething);
     last_acquire_ = clk_[tid_];
     ResetCached(c);
   }
@@ -223,7 +210,6 @@ void ThreadClock::releaseStoreAcquire(ClockCache *c, SyncClock *sc) {
   sc->release_store_reused_ = 0;
 
   if (acquired) {
-    CPP_STAT_INC(StatClockAcquiredSomething);
     last_acquire_ = clk_[tid_];
     ResetCached(c);
   }
@@ -240,7 +226,6 @@ void ThreadClock::release(ClockCache *c, SyncClock *dst) {
     return;
   }
 
-  CPP_STAT_INC(StatClockRelease);
   // Check if we need to resize dst.
   if (dst->size_ < nclk_)
     dst->Resize(c, nclk_);
@@ -257,12 +242,9 @@ void ThreadClock::release(ClockCache *c, SyncClock *dst) {
   }
 
   // O(N) release.
-  CPP_STAT_INC(StatClockReleaseFull);
   dst->Unshare(c);
   // First, remember whether we've acquired dst.
   bool acquired = IsAlreadyAcquired(dst);
-  if (acquired)
-    CPP_STAT_INC(StatClockReleaseAcquired);
   // Update dst->clk_.
   dst->FlushDirty();
   uptr i = 0;
@@ -272,8 +254,6 @@ void ThreadClock::release(ClockCache *c, SyncClock *dst) {
     i++;
   }
   // Clear 'acquired' flag in the remaining elements.
-  if (nclk_ < dst->size_)
-    CPP_STAT_INC(StatClockReleaseClearTail);
   dst->release_store_tid_ = kInvalidTid;
   dst->release_store_reused_ = 0;
   // If we've acquired dst, remember this fact,
@@ -285,7 +265,6 @@ void ThreadClock::release(ClockCache *c, SyncClock *dst) {
 void ThreadClock::ReleaseStore(ClockCache *c, SyncClock *dst) {
   DCHECK_LE(nclk_, kMaxTid);
   DCHECK_LE(dst->size_, kMaxTid);
-  CPP_STAT_INC(StatClockStore);
 
   if (dst->size_ == 0 && cached_idx_ != 0) {
     // Reuse the cached clock.
@@ -299,10 +278,10 @@ void ThreadClock::ReleaseStore(ClockCache *c, SyncClock *dst) {
     dst->tab_idx_ = cached_idx_;
     dst->size_ = cached_size_;
     dst->blocks_ = cached_blocks_;
-    CHECK_EQ(dst->dirty_[0].tid, kInvalidTid);
+    CHECK_EQ(dst->dirty_[0].tid(), kInvalidTid);
     // The cached clock is shared (immutable),
     // so this is where we store the current clock.
-    dst->dirty_[0].tid = tid_;
+    dst->dirty_[0].set_tid(tid_);
     dst->dirty_[0].epoch = clk_[tid_];
     dst->release_store_tid_ = tid_;
     dst->release_store_reused_ = reused_;
@@ -320,13 +299,11 @@ void ThreadClock::ReleaseStore(ClockCache *c, SyncClock *dst) {
   if (dst->release_store_tid_ == tid_ &&
       dst->release_store_reused_ == reused_ &&
       !HasAcquiredAfterRelease(dst)) {
-    CPP_STAT_INC(StatClockStoreFast);
     UpdateCurrentThread(c, dst);
     return;
   }
 
   // O(N) release-store.
-  CPP_STAT_INC(StatClockStoreFull);
   dst->Unshare(c);
   // Note: dst can be larger than this ThreadClock.
   // This is fine since clk_ beyond size is all zeros.
@@ -336,8 +313,7 @@ void ThreadClock::ReleaseStore(ClockCache *c, SyncClock *dst) {
     ce.reused = 0;
     i++;
   }
-  for (uptr i = 0; i < kDirtyTids; i++)
-    dst->dirty_[i].tid = kInvalidTid;
+  for (uptr i = 0; i < kDirtyTids; i++) dst->dirty_[i].set_tid(kInvalidTid);
   dst->release_store_tid_ = tid_;
   dst->release_store_reused_ = reused_;
   // Rememeber that we don't need to acquire it in future.
@@ -359,7 +335,6 @@ void ThreadClock::ReleaseStore(ClockCache *c, SyncClock *dst) {
 }
 
 void ThreadClock::acq_rel(ClockCache *c, SyncClock *dst) {
-  CPP_STAT_INC(StatClockAcquireRelease);
   acquire(c, dst);
   ReleaseStore(c, dst);
 }
@@ -369,10 +344,9 @@ void ThreadClock::UpdateCurrentThread(ClockCache *c, SyncClock *dst) const {
   // Update the threads time, but preserve 'acquired' flag.
   for (unsigned i = 0; i < kDirtyTids; i++) {
     SyncClock::Dirty *dirty = &dst->dirty_[i];
-    const unsigned tid = dirty->tid;
+    const unsigned tid = dirty->tid();
     if (tid == tid_ || tid == kInvalidTid) {
-      CPP_STAT_INC(StatClockReleaseFast);
-      dirty->tid = tid_;
+      dirty->set_tid(tid_);
       dirty->epoch = clk_[tid_];
       return;
     }
@@ -380,7 +354,6 @@ void ThreadClock::UpdateCurrentThread(ClockCache *c, SyncClock *dst) const {
   // Reset all 'acquired' flags, O(N).
   // We are going to touch dst elements, so we need to unshare it.
   dst->Unshare(c);
-  CPP_STAT_INC(StatClockReleaseSlow);
   dst->elem(tid_).epoch = clk_[tid_];
   for (uptr i = 0; i < dst->size_; i++)
     dst->elem(i).reused = 0;
@@ -393,8 +366,8 @@ bool ThreadClock::IsAlreadyAcquired(const SyncClock *src) const {
     return false;
   for (unsigned i = 0; i < kDirtyTids; i++) {
     SyncClock::Dirty dirty = src->dirty_[i];
-    if (dirty.tid != kInvalidTid) {
-      if (clk_[dirty.tid] < dirty.epoch)
+    if (dirty.tid() != kInvalidTid) {
+      if (clk_[dirty.tid()] < dirty.epoch)
         return false;
     }
   }
@@ -453,12 +426,10 @@ void SyncClock::ResetImpl() {
   blocks_ = 0;
   release_store_tid_ = kInvalidTid;
   release_store_reused_ = 0;
-  for (uptr i = 0; i < kDirtyTids; i++)
-    dirty_[i].tid = kInvalidTid;
+  for (uptr i = 0; i < kDirtyTids; i++) dirty_[i].set_tid(kInvalidTid);
 }
 
 void SyncClock::Resize(ClockCache *c, uptr nclk) {
-  CPP_STAT_INC(StatClockReleaseResize);
   Unshare(c);
   if (nclk <= capacity()) {
     // Memory is already allocated, just increase the size.
@@ -503,10 +474,10 @@ void SyncClock::Resize(ClockCache *c, uptr nclk) {
 void SyncClock::FlushDirty() {
   for (unsigned i = 0; i < kDirtyTids; i++) {
     Dirty *dirty = &dirty_[i];
-    if (dirty->tid != kInvalidTid) {
-      CHECK_LT(dirty->tid, size_);
-      elem(dirty->tid).epoch = dirty->epoch;
-      dirty->tid = kInvalidTid;
+    if (dirty->tid() != kInvalidTid) {
+      CHECK_LT(dirty->tid(), size_);
+      elem(dirty->tid()).epoch = dirty->epoch;
+      dirty->set_tid(kInvalidTid);
     }
   }
 }
@@ -559,7 +530,7 @@ ALWAYS_INLINE bool SyncClock::Cachable() const {
   if (size_ == 0)
     return false;
   for (unsigned i = 0; i < kDirtyTids; i++) {
-    if (dirty_[i].tid != kInvalidTid)
+    if (dirty_[i].tid() != kInvalidTid)
       return false;
   }
   return atomic_load_relaxed(ref_ptr(tab_)) == 1;
@@ -606,7 +577,7 @@ ALWAYS_INLINE void SyncClock::append_block(u32 idx) {
 u64 SyncClock::get(unsigned tid) const {
   for (unsigned i = 0; i < kDirtyTids; i++) {
     Dirty dirty = dirty_[i];
-    if (dirty.tid == tid)
+    if (dirty.tid() == tid)
       return dirty.epoch;
   }
   return elem(tid).epoch;
@@ -625,9 +596,8 @@ void SyncClock::DebugDump(int(*printf)(const char *s, ...)) {
   for (uptr i = 0; i < size_; i++)
     printf("%s%llu", i == 0 ? "" : ",", elem(i).reused);
   printf("] release_store_tid=%d/%d dirty_tids=%d[%llu]/%d[%llu]",
-      release_store_tid_, release_store_reused_,
-      dirty_[0].tid, dirty_[0].epoch,
-      dirty_[1].tid, dirty_[1].epoch);
+         release_store_tid_, release_store_reused_, dirty_[0].tid(),
+         dirty_[0].epoch, dirty_[1].tid(), dirty_[1].epoch);
 }
 
 void SyncClock::Iter::Next() {
lib/tsan/tsan_clock.h
@@ -17,7 +17,7 @@
 
 namespace __tsan {
 
-typedef DenseSlabAlloc<ClockBlock, 1<<16, 1<<10> ClockAlloc;
+typedef DenseSlabAlloc<ClockBlock, 1 << 22, 1 << 10> ClockAlloc;
 typedef DenseSlabAllocCache ClockCache;
 
 // The clock that lives in sync variables (mutexes, atomics, etc).
@@ -65,10 +65,20 @@ class SyncClock {
   static const uptr kDirtyTids = 2;
 
   struct Dirty {
-    u64 epoch  : kClkBits;
-    u64 tid : 64 - kClkBits;  // kInvalidId if not active
+    u32 tid() const { return tid_ == kShortInvalidTid ? kInvalidTid : tid_; }
+    void set_tid(u32 tid) {
+      tid_ = tid == kInvalidTid ? kShortInvalidTid : tid;
+    }
+    u64 epoch : kClkBits;
+
+   private:
+    // Full kInvalidTid won't fit into Dirty::tid.
+    static const u64 kShortInvalidTid = (1ull << (64 - kClkBits)) - 1;
+    u64 tid_ : 64 - kClkBits;  // kInvalidId if not active
   };
 
+  static_assert(sizeof(Dirty) == 8, "Dirty is not 64bit");
+
   unsigned release_store_tid_;
   unsigned release_store_reused_;
   Dirty dirty_[kDirtyTids];
lib/tsan/tsan_defs.h
@@ -15,7 +15,7 @@
 
 #include "sanitizer_common/sanitizer_internal_defs.h"
 #include "sanitizer_common/sanitizer_libc.h"
-#include "tsan_stat.h"
+#include "sanitizer_common/sanitizer_mutex.h"
 #include "ubsan/ubsan_platform.h"
 
 // Setup defaults for compile definitions.
@@ -23,10 +23,6 @@
 # define TSAN_NO_HISTORY 0
 #endif
 
-#ifndef TSAN_COLLECT_STATS
-# define TSAN_COLLECT_STATS 0
-#endif
-
 #ifndef TSAN_CONTAINS_UBSAN
 # if CAN_SANITIZE_UB && !SANITIZER_GO
 #  define TSAN_CONTAINS_UBSAN 1
@@ -98,8 +94,6 @@ const bool kCollectHistory = false;
 const bool kCollectHistory = true;
 #endif
 
-const u16 kInvalidTid = kMaxTid + 1;
-
 // The following "build consistency" machinery ensures that all source files
 // are built in the same configuration. Inconsistent builds lead to
 // hard to debug crashes.
@@ -109,23 +103,12 @@ void build_consistency_debug();
 void build_consistency_release();
 #endif
 
-#if TSAN_COLLECT_STATS
-void build_consistency_stats();
-#else
-void build_consistency_nostats();
-#endif
-
 static inline void USED build_consistency() {
 #if SANITIZER_DEBUG
   build_consistency_debug();
 #else
   build_consistency_release();
 #endif
-#if TSAN_COLLECT_STATS
-  build_consistency_stats();
-#else
-  build_consistency_nostats();
-#endif
 }
 
 template<typename T>
@@ -190,6 +173,17 @@ enum ExternalTag : uptr {
   // as 16-bit values, see tsan_defs.h.
 };
 
+enum MutexType {
+  MutexTypeTrace = MutexLastCommon,
+  MutexTypeReport,
+  MutexTypeSyncVar,
+  MutexTypeAnnotations,
+  MutexTypeAtExit,
+  MutexTypeFired,
+  MutexTypeRacy,
+  MutexTypeGlobalProc,
+};
+
 }  // namespace __tsan
 
 #endif  // TSAN_DEFS_H
lib/tsan/tsan_dense_alloc.h
@@ -20,7 +20,6 @@
 
 #include "sanitizer_common/sanitizer_common.h"
 #include "tsan_defs.h"
-#include "tsan_mutex.h"
 
 namespace __tsan {
 
@@ -29,28 +28,40 @@ class DenseSlabAllocCache {
   typedef u32 IndexT;
   uptr pos;
   IndexT cache[kSize];
-  template<typename T, uptr kL1Size, uptr kL2Size> friend class DenseSlabAlloc;
+  template <typename, uptr, uptr, u64>
+  friend class DenseSlabAlloc;
 };
 
-template<typename T, uptr kL1Size, uptr kL2Size>
+template <typename T, uptr kL1Size, uptr kL2Size, u64 kReserved = 0>
 class DenseSlabAlloc {
  public:
   typedef DenseSlabAllocCache Cache;
   typedef typename Cache::IndexT IndexT;
 
-  explicit DenseSlabAlloc(const char *name) {
-    // Check that kL1Size and kL2Size are sane.
-    CHECK_EQ(kL1Size & (kL1Size - 1), 0);
-    CHECK_EQ(kL2Size & (kL2Size - 1), 0);
-    CHECK_GE(1ull << (sizeof(IndexT) * 8), kL1Size * kL2Size);
-    // Check that it makes sense to use the dense alloc.
-    CHECK_GE(sizeof(T), sizeof(IndexT));
-    internal_memset(map_, 0, sizeof(map_));
+  static_assert((kL1Size & (kL1Size - 1)) == 0,
+                "kL1Size must be a power-of-two");
+  static_assert((kL2Size & (kL2Size - 1)) == 0,
+                "kL2Size must be a power-of-two");
+  static_assert((kL1Size * kL2Size) <= (1ull << (sizeof(IndexT) * 8)),
+                "kL1Size/kL2Size are too large");
+  static_assert(((kL1Size * kL2Size - 1) & kReserved) == 0,
+                "reserved bits don't fit");
+  static_assert(sizeof(T) > sizeof(IndexT),
+                "it doesn't make sense to use dense alloc");
+
+  explicit DenseSlabAlloc(LinkerInitialized, const char *name) {
     freelist_ = 0;
     fillpos_ = 0;
     name_ = name;
   }
 
+  explicit DenseSlabAlloc(const char *name)
+      : DenseSlabAlloc(LINKER_INITIALIZED, name) {
+    // It can be very large.
+    // Don't page it in for linker initialized objects.
+    internal_memset(map_, 0, sizeof(map_));
+  }
+
   ~DenseSlabAlloc() {
     for (uptr i = 0; i < kL1Size; i++) {
       if (map_[i] != 0)
lib/tsan/tsan_external.cpp
@@ -11,6 +11,7 @@
 //===----------------------------------------------------------------------===//
 #include "tsan_rtl.h"
 #include "tsan_interceptors.h"
+#include "sanitizer_common/sanitizer_ptrauth.h"
 
 namespace __tsan {
 
@@ -57,13 +58,13 @@ uptr TagFromShadowStackFrame(uptr pc) {
 #if !SANITIZER_GO
 
 typedef void(*AccessFunc)(ThreadState *, uptr, uptr, int);
-void ExternalAccess(void *addr, void *caller_pc, void *tag, AccessFunc access) {
+void ExternalAccess(void *addr, uptr caller_pc, void *tag, AccessFunc access) {
   CHECK_LT(tag, atomic_load(&used_tags, memory_order_relaxed));
   ThreadState *thr = cur_thread();
-  if (caller_pc) FuncEntry(thr, (uptr)caller_pc);
+  if (caller_pc) FuncEntry(thr, caller_pc);
   InsertShadowStackFrameForTag(thr, (uptr)tag);
   bool in_ignored_lib;
-  if (!caller_pc || !libignore()->IsIgnored((uptr)caller_pc, &in_ignored_lib)) {
+  if (!caller_pc || !libignore()->IsIgnored(caller_pc, &in_ignored_lib)) {
     access(thr, CALLERPC, (uptr)addr, kSizeLog1);
   }
   FuncExit(thr);
@@ -110,12 +111,12 @@ void __tsan_external_assign_tag(void *addr, void *tag) {
 
 SANITIZER_INTERFACE_ATTRIBUTE
 void __tsan_external_read(void *addr, void *caller_pc, void *tag) {
-  ExternalAccess(addr, caller_pc, tag, MemoryRead);
+  ExternalAccess(addr, STRIP_PAC_PC(caller_pc), tag, MemoryRead);
 }
 
 SANITIZER_INTERFACE_ATTRIBUTE
 void __tsan_external_write(void *addr, void *caller_pc, void *tag) {
-  ExternalAccess(addr, caller_pc, tag, MemoryWrite);
+  ExternalAccess(addr, STRIP_PAC_PC(caller_pc), tag, MemoryWrite);
 }
 }  // extern "C"
 
lib/tsan/tsan_flags.cpp
@@ -87,7 +87,7 @@ void InitializeFlags(Flags *f, const char *env, const char *env_option_name) {
   // Let a frontend override.
   parser.ParseString(__tsan_default_options());
 #if TSAN_CONTAINS_UBSAN
-  const char *ubsan_default_options = __ubsan::MaybeCallUbsanDefaultOptions();
+  const char *ubsan_default_options = __ubsan_default_options();
   ubsan_parser.ParseString(ubsan_default_options);
 #endif
   // Override from command line.
lib/tsan/tsan_interceptors.h
@@ -22,7 +22,7 @@ class ScopedInterceptor {
 LibIgnore *libignore();
 
 #if !SANITIZER_GO
-INLINE bool in_symbolizer() {
+inline bool in_symbolizer() {
   cur_thread_init();
   return UNLIKELY(cur_thread()->in_symbolizer);
 }
@@ -30,14 +30,14 @@ INLINE bool in_symbolizer() {
 
 }  // namespace __tsan
 
-#define SCOPED_INTERCEPTOR_RAW(func, ...) \
-    cur_thread_init(); \
-    ThreadState *thr = cur_thread(); \
-    const uptr caller_pc = GET_CALLER_PC(); \
-    ScopedInterceptor si(thr, #func, caller_pc); \
-    const uptr pc = StackTrace::GetCurrentPc(); \
-    (void)pc; \
-/**/
+#define SCOPED_INTERCEPTOR_RAW(func, ...)      \
+  cur_thread_init();                           \
+  ThreadState *thr = cur_thread();             \
+  const uptr caller_pc = GET_CALLER_PC();      \
+  ScopedInterceptor si(thr, #func, caller_pc); \
+  const uptr pc = GET_CURRENT_PC();            \
+  (void)pc;                                    \
+  /**/
 
 #define SCOPED_TSAN_INTERCEPTOR(func, ...) \
     SCOPED_INTERCEPTOR_RAW(func, __VA_ARGS__); \
lib/tsan/tsan_interceptors_mac.cpp
@@ -44,8 +44,9 @@ namespace __tsan {
 // actually aliases of each other, and we cannot have different interceptors for
 // them, because they're actually the same function.  Thus, we have to stay
 // conservative and treat the non-barrier versions as mo_acq_rel.
-static const morder kMacOrderBarrier = mo_acq_rel;
-static const morder kMacOrderNonBarrier = mo_acq_rel;
+static constexpr morder kMacOrderBarrier = mo_acq_rel;
+static constexpr morder kMacOrderNonBarrier = mo_acq_rel;
+static constexpr morder kMacFailureOrder = mo_relaxed;
 
 #define OSATOMIC_INTERCEPTOR(return_t, t, tsan_t, f, tsan_atomic_f, mo) \
   TSAN_INTERCEPTOR(return_t, f, t x, volatile t *ptr) {                 \
@@ -110,7 +111,7 @@ OSATOMIC_INTERCEPTORS_BITWISE(OSAtomicXor, fetch_xor,
     SCOPED_TSAN_INTERCEPTOR(f, old_value, new_value, ptr);                  \
     return tsan_atomic_f##_compare_exchange_strong(                         \
         (volatile tsan_t *)ptr, (tsan_t *)&old_value, (tsan_t)new_value,    \
-        kMacOrderNonBarrier, kMacOrderNonBarrier);                          \
+        kMacOrderNonBarrier, kMacFailureOrder);                             \
   }                                                                         \
                                                                             \
   TSAN_INTERCEPTOR(bool, f##Barrier, t old_value, t new_value,              \
@@ -118,7 +119,7 @@ OSATOMIC_INTERCEPTORS_BITWISE(OSAtomicXor, fetch_xor,
     SCOPED_TSAN_INTERCEPTOR(f##Barrier, old_value, new_value, ptr);         \
     return tsan_atomic_f##_compare_exchange_strong(                         \
         (volatile tsan_t *)ptr, (tsan_t *)&old_value, (tsan_t)new_value,    \
-        kMacOrderBarrier, kMacOrderNonBarrier);                             \
+        kMacOrderBarrier, kMacFailureOrder);                                \
   }
 
 OSATOMIC_INTERCEPTORS_CAS(OSAtomicCompareAndSwapInt, __tsan_atomic32, a32, int)
@@ -438,6 +439,7 @@ struct fake_shared_weak_count {
   virtual void on_zero_shared() = 0;
   virtual void _unused_0x18() = 0;
   virtual void on_zero_shared_weak() = 0;
+  virtual ~fake_shared_weak_count() = 0;  // suppress -Wnon-virtual-dtor
 };
 }  // namespace
 
lib/tsan/tsan_interceptors_mach_vm.cpp
@@ -19,12 +19,11 @@
 
 namespace __tsan {
 
-static bool intersects_with_shadow(mach_vm_address_t *address,
+static bool intersects_with_shadow(mach_vm_address_t address,
                                    mach_vm_size_t size, int flags) {
   // VM_FLAGS_FIXED is 0x0, so we have to test for VM_FLAGS_ANYWHERE.
   if (flags & VM_FLAGS_ANYWHERE) return false;
-  uptr ptr = *address;
-  return !IsAppMem(ptr) || !IsAppMem(ptr + size - 1);
+  return !IsAppMem(address) || !IsAppMem(address + size - 1);
 }
 
 TSAN_INTERCEPTOR(kern_return_t, mach_vm_allocate, vm_map_t target,
@@ -32,12 +31,12 @@ TSAN_INTERCEPTOR(kern_return_t, mach_vm_allocate, vm_map_t target,
   SCOPED_TSAN_INTERCEPTOR(mach_vm_allocate, target, address, size, flags);
   if (target != mach_task_self())
     return REAL(mach_vm_allocate)(target, address, size, flags);
-  if (intersects_with_shadow(address, size, flags))
+  if (address && intersects_with_shadow(*address, size, flags))
     return KERN_NO_SPACE;
-  kern_return_t res = REAL(mach_vm_allocate)(target, address, size, flags);
-  if (res == KERN_SUCCESS)
+  kern_return_t kr = REAL(mach_vm_allocate)(target, address, size, flags);
+  if (kr == KERN_SUCCESS)
     MemoryRangeImitateWriteOrResetRange(thr, pc, *address, size);
-  return res;
+  return kr;
 }
 
 TSAN_INTERCEPTOR(kern_return_t, mach_vm_deallocate, vm_map_t target,
@@ -45,8 +44,10 @@ TSAN_INTERCEPTOR(kern_return_t, mach_vm_deallocate, vm_map_t target,
   SCOPED_TSAN_INTERCEPTOR(mach_vm_deallocate, target, address, size);
   if (target != mach_task_self())
     return REAL(mach_vm_deallocate)(target, address, size);
-  UnmapShadow(thr, address, size);
-  return REAL(mach_vm_deallocate)(target, address, size);
+  kern_return_t kr = REAL(mach_vm_deallocate)(target, address, size);
+  if (kr == KERN_SUCCESS && address)
+    UnmapShadow(thr, address, size);
+  return kr;
 }
 
 }  // namespace __tsan
lib/tsan/tsan_interceptors_posix.cpp
@@ -31,6 +31,8 @@
 #include "tsan_mman.h"
 #include "tsan_fd.h"
 
+#include <stdarg.h>
+
 using namespace __tsan;
 
 #if SANITIZER_FREEBSD || SANITIZER_MAC
@@ -52,10 +54,6 @@ using namespace __tsan;
 #define vfork __vfork14
 #endif
 
-#if SANITIZER_ANDROID
-#define mallopt(a, b)
-#endif
-
 #ifdef __mips__
 const int kSigCount = 129;
 #else
@@ -73,7 +71,8 @@ struct ucontext_t {
 };
 #endif
 
-#if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1
+#if defined(__x86_64__) || defined(__mips__) || SANITIZER_PPC64V1 || \
+    defined(__s390x__)
 #define PTHREAD_ABI_BASE  "GLIBC_2.3.2"
 #elif defined(__aarch64__) || SANITIZER_PPC64V2
 #define PTHREAD_ABI_BASE  "GLIBC_2.17"
@@ -83,6 +82,8 @@ extern "C" int pthread_attr_init(void *attr);
 extern "C" int pthread_attr_destroy(void *attr);
 DECLARE_REAL(int, pthread_attr_getdetachstate, void *, void *)
 extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
+extern "C" int pthread_atfork(void (*prepare)(void), void (*parent)(void),
+                              void (*child)(void));
 extern "C" int pthread_key_create(unsigned *key, void (*destructor)(void* v));
 extern "C" int pthread_setspecific(unsigned key, const void *v);
 DECLARE_REAL(int, pthread_mutexattr_gettype, void *, void *)
@@ -95,7 +96,7 @@ extern "C" void _exit(int status);
 extern "C" int fileno_unlocked(void *stream);
 extern "C" int dirfd(void *dirp);
 #endif
-#if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_NETBSD
+#if SANITIZER_GLIBC
 extern "C" int mallopt(int param, int value);
 #endif
 #if SANITIZER_NETBSD
@@ -135,6 +136,7 @@ const int PTHREAD_BARRIER_SERIAL_THREAD = -1;
 #endif
 const int MAP_FIXED = 0x10;
 typedef long long_t;
+typedef __sanitizer::u16 mode_t;
 
 // From /usr/include/unistd.h
 # define F_ULOCK 0      /* Unlock a previously locked region.  */
@@ -194,12 +196,10 @@ struct InterceptorContext {
   unsigned finalize_key;
 #endif
 
-  BlockingMutex atexit_mu;
+  Mutex atexit_mu;
   Vector<struct AtExitCtx *> AtExitStack;
 
-  InterceptorContext()
-      : libignore(LINKER_INITIALIZED), AtExitStack() {
-  }
+  InterceptorContext() : libignore(LINKER_INITIALIZED), atexit_mu(MutexTypeAtExit), AtExitStack() {}
 };
 
 static ALIGNED(64) char interceptor_placeholder[sizeof(InterceptorContext)];
@@ -265,7 +265,7 @@ ScopedInterceptor::~ScopedInterceptor() {
   if (!thr_->ignore_interceptors) {
     ProcessPendingSignals(thr_);
     FuncExit(thr_);
-    CheckNoLocks(thr_);
+    CheckedMutex::CheckNoLocks();
   }
 }
 
@@ -375,7 +375,7 @@ static void at_exit_wrapper() {
   AtExitCtx *ctx;
   {
     // Ensure thread-safety.
-    BlockingMutexLock l(&interceptor_ctx()->atexit_mu);
+    Lock l(&interceptor_ctx()->atexit_mu);
 
     // Pop AtExitCtx from the top of the stack of callback functions
     uptr element = interceptor_ctx()->AtExitStack.Size() - 1;
@@ -431,7 +431,10 @@ static int setup_at_exit_wrapper(ThreadState *thr, uptr pc, void(*f)(),
     // Store ctx in a local stack-like structure
 
     // Ensure thread-safety.
-    BlockingMutexLock l(&interceptor_ctx()->atexit_mu);
+    Lock l(&interceptor_ctx()->atexit_mu);
+    // __cxa_atexit calls calloc. If we don't ignore interceptors, we will fail
+    // due to atexit_mu held on exit from the calloc interceptor.
+    ScopedIgnoreInterceptors ignore;
 
     res = REAL(__cxa_atexit)((void (*)(void *a))at_exit_wrapper, 0, 0);
     // Push AtExitCtx on the top of the stack of callback functions
@@ -656,8 +659,11 @@ TSAN_INTERCEPTOR(void*, malloc, uptr size) {
   return p;
 }
 
+// In glibc<2.25, dynamic TLS blocks are allocated by __libc_memalign. Intercept
+// __libc_memalign so that (1) we can detect races (2) free will not be called
+// on libc internally allocated blocks.
 TSAN_INTERCEPTOR(void*, __libc_memalign, uptr align, uptr sz) {
-  SCOPED_TSAN_INTERCEPTOR(__libc_memalign, align, sz);
+  SCOPED_INTERCEPTOR_RAW(__libc_memalign, align, sz);
   return user_memalign(thr, pc, align, sz);
 }
 
@@ -770,6 +776,11 @@ static void *mmap_interceptor(ThreadState *thr, uptr pc, Mmap real_mmap,
   if (!fix_mmap_addr(&addr, sz, flags)) return MAP_FAILED;
   void *res = real_mmap(addr, sz, prot, flags, fd, off);
   if (res != MAP_FAILED) {
+    if (!IsAppMem((uptr)res) || !IsAppMem((uptr)res + sz - 1)) {
+      Report("ThreadSanitizer: mmap at bad address: addr=%p size=%p res=%p\n",
+             addr, (void*)sz, res);
+      Die();
+    }
     if (fd > 0) FdAccess(thr, pc, fd);
     MemoryRangeImitateWriteOrResetRange(thr, pc, (uptr)res, sz);
   }
@@ -1119,27 +1130,37 @@ static void *init_cond(void *c, bool force = false) {
   return (void*)cond;
 }
 
+namespace {
+
+template <class Fn>
 struct CondMutexUnlockCtx {
   ScopedInterceptor *si;
   ThreadState *thr;
   uptr pc;
   void *m;
+  void *c;
+  const Fn &fn;
+
+  int Cancel() const { return fn(); }
+  void Unlock() const;
 };
 
-static void cond_mutex_unlock(CondMutexUnlockCtx *arg) {
+template <class Fn>
+void CondMutexUnlockCtx<Fn>::Unlock() const {
   // pthread_cond_wait interceptor has enabled async signal delivery
   // (see BlockingCall below). Disable async signals since we are running
   // tsan code. Also ScopedInterceptor and BlockingCall destructors won't run
   // since the thread is cancelled, so we have to manually execute them
   // (the thread still can run some user code due to pthread_cleanup_push).
-  ThreadSignalContext *ctx = SigCtx(arg->thr);
+  ThreadSignalContext *ctx = SigCtx(thr);
   CHECK_EQ(atomic_load(&ctx->in_blocking_func, memory_order_relaxed), 1);
   atomic_store(&ctx->in_blocking_func, 0, memory_order_relaxed);
-  MutexPostLock(arg->thr, arg->pc, (uptr)arg->m, MutexFlagDoPreLockOnPostLock);
+  MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
   // Undo BlockingCall ctor effects.
-  arg->thr->ignore_interceptors--;
-  arg->si->~ScopedInterceptor();
+  thr->ignore_interceptors--;
+  si->~ScopedInterceptor();
 }
+}  // namespace
 
 INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
   void *cond = init_cond(c, true);
@@ -1148,20 +1169,24 @@ INTERCEPTOR(int, pthread_cond_init, void *c, void *a) {
   return REAL(pthread_cond_init)(cond, a);
 }
 
-static int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si,
-                     int (*fn)(void *c, void *m, void *abstime), void *c,
-                     void *m, void *t) {
+template <class Fn>
+int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si, const Fn &fn,
+              void *c, void *m) {
   MemoryAccessRange(thr, pc, (uptr)c, sizeof(uptr), false);
   MutexUnlock(thr, pc, (uptr)m);
-  CondMutexUnlockCtx arg = {si, thr, pc, m};
   int res = 0;
   // This ensures that we handle mutex lock even in case of pthread_cancel.
   // See test/tsan/cond_cancel.cpp.
   {
     // Enable signal delivery while the thread is blocked.
     BlockingCall bc(thr);
+    CondMutexUnlockCtx<Fn> arg = {si, thr, pc, m, c, fn};
     res = call_pthread_cancel_with_cleanup(
-        fn, c, m, t, (void (*)(void *arg))cond_mutex_unlock, &arg);
+        [](void *arg) -> int {
+          return ((const CondMutexUnlockCtx<Fn> *)arg)->Cancel();
+        },
+        [](void *arg) { ((const CondMutexUnlockCtx<Fn> *)arg)->Unlock(); },
+        &arg);
   }
   if (res == errno_EOWNERDEAD) MutexRepair(thr, pc, (uptr)m);
   MutexPostLock(thr, pc, (uptr)m, MutexFlagDoPreLockOnPostLock);
@@ -1171,25 +1196,46 @@ static int cond_wait(ThreadState *thr, uptr pc, ScopedInterceptor *si,
 INTERCEPTOR(int, pthread_cond_wait, void *c, void *m) {
   void *cond = init_cond(c);
   SCOPED_TSAN_INTERCEPTOR(pthread_cond_wait, cond, m);
-  return cond_wait(thr, pc, &si, (int (*)(void *c, void *m, void *abstime))REAL(
-                                     pthread_cond_wait),
-                   cond, m, 0);
+  return cond_wait(
+      thr, pc, &si, [=]() { return REAL(pthread_cond_wait)(cond, m); }, cond,
+      m);
 }
 
 INTERCEPTOR(int, pthread_cond_timedwait, void *c, void *m, void *abstime) {
   void *cond = init_cond(c);
   SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait, cond, m, abstime);
-  return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait), cond, m,
-                   abstime);
+  return cond_wait(
+      thr, pc, &si,
+      [=]() { return REAL(pthread_cond_timedwait)(cond, m, abstime); }, cond,
+      m);
 }
 
+#if SANITIZER_LINUX
+INTERCEPTOR(int, pthread_cond_clockwait, void *c, void *m,
+            __sanitizer_clockid_t clock, void *abstime) {
+  void *cond = init_cond(c);
+  SCOPED_TSAN_INTERCEPTOR(pthread_cond_clockwait, cond, m, clock, abstime);
+  return cond_wait(
+      thr, pc, &si,
+      [=]() { return REAL(pthread_cond_clockwait)(cond, m, clock, abstime); },
+      cond, m);
+}
+#define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT TSAN_INTERCEPT(pthread_cond_clockwait)
+#else
+#define TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT
+#endif
+
 #if SANITIZER_MAC
 INTERCEPTOR(int, pthread_cond_timedwait_relative_np, void *c, void *m,
             void *reltime) {
   void *cond = init_cond(c);
   SCOPED_TSAN_INTERCEPTOR(pthread_cond_timedwait_relative_np, cond, m, reltime);
-  return cond_wait(thr, pc, &si, REAL(pthread_cond_timedwait_relative_np), cond,
-                   m, reltime);
+  return cond_wait(
+      thr, pc, &si,
+      [=]() {
+        return REAL(pthread_cond_timedwait_relative_np)(cond, m, reltime);
+      },
+      cond, m);
 }
 #endif
 
@@ -1508,20 +1554,28 @@ TSAN_INTERCEPTOR(int, fstat64, int fd, void *buf) {
 #define TSAN_MAYBE_INTERCEPT_FSTAT64
 #endif
 
-TSAN_INTERCEPTOR(int, open, const char *name, int flags, int mode) {
-  SCOPED_TSAN_INTERCEPTOR(open, name, flags, mode);
+TSAN_INTERCEPTOR(int, open, const char *name, int oflag, ...) {
+  va_list ap;
+  va_start(ap, oflag);
+  mode_t mode = va_arg(ap, int);
+  va_end(ap);
+  SCOPED_TSAN_INTERCEPTOR(open, name, oflag, mode);
   READ_STRING(thr, pc, name, 0);
-  int fd = REAL(open)(name, flags, mode);
+  int fd = REAL(open)(name, oflag, mode);
   if (fd >= 0)
     FdFileCreate(thr, pc, fd);
   return fd;
 }
 
 #if SANITIZER_LINUX
-TSAN_INTERCEPTOR(int, open64, const char *name, int flags, int mode) {
-  SCOPED_TSAN_INTERCEPTOR(open64, name, flags, mode);
+TSAN_INTERCEPTOR(int, open64, const char *name, int oflag, ...) {
+  va_list ap;
+  va_start(ap, oflag);
+  mode_t mode = va_arg(ap, int);
+  va_end(ap);
+  SCOPED_TSAN_INTERCEPTOR(open64, name, oflag, mode);
   READ_STRING(thr, pc, name, 0);
-  int fd = REAL(open64)(name, flags, mode);
+  int fd = REAL(open64)(name, oflag, mode);
   if (fd >= 0)
     FdFileCreate(thr, pc, fd);
   return fd;
@@ -1926,7 +1980,8 @@ static void CallUserSignalHandler(ThreadState *thr, bool sync, bool acquire,
   // because in async signal processing case (when handler is called directly
   // from rtl_generic_sighandler) we have not yet received the reraised
   // signal; and it looks too fragile to intercept all ways to reraise a signal.
-  if (flags()->report_bugs && !sync && sig != SIGTERM && errno != 99) {
+  if (ShouldReport(thr, ReportTypeErrnoInSignal) && !sync && sig != SIGTERM &&
+      errno != 99) {
     VarSizeStackTrace stack;
     // StackTrace::GetNestInstructionPc(pc) is used because return address is
     // expected, OutputReport() will undo this.
@@ -2096,26 +2151,32 @@ TSAN_INTERCEPTOR(int, fork, int fake) {
   if (in_symbolizer())
     return REAL(fork)(fake);
   SCOPED_INTERCEPTOR_RAW(fork, fake);
+  return REAL(fork)(fake);
+}
+
+void atfork_prepare() {
+  if (in_symbolizer())
+    return;
+  ThreadState *thr = cur_thread();
+  const uptr pc = StackTrace::GetCurrentPc();
   ForkBefore(thr, pc);
-  int pid;
-  {
-    // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
-    // we'll assert in CheckNoLocks() unless we ignore interceptors.
-    ScopedIgnoreInterceptors ignore;
-    pid = REAL(fork)(fake);
-  }
-  if (pid == 0) {
-    // child
-    ForkChildAfter(thr, pc);
-    FdOnFork(thr, pc);
-  } else if (pid > 0) {
-    // parent
-    ForkParentAfter(thr, pc);
-  } else {
-    // error
-    ForkParentAfter(thr, pc);
-  }
-  return pid;
+}
+
+void atfork_parent() {
+  if (in_symbolizer())
+    return;
+  ThreadState *thr = cur_thread();
+  const uptr pc = StackTrace::GetCurrentPc();
+  ForkParentAfter(thr, pc);
+}
+
+void atfork_child() {
+  if (in_symbolizer())
+    return;
+  ThreadState *thr = cur_thread();
+  const uptr pc = StackTrace::GetCurrentPc();
+  ForkChildAfter(thr, pc);
+  FdOnFork(thr, pc);
 }
 
 TSAN_INTERCEPTOR(int, vfork, int fake) {
@@ -2211,11 +2272,14 @@ static void HandleRecvmsg(ThreadState *thr, uptr pc,
 #define NEED_TLS_GET_ADDR
 #endif
 #undef SANITIZER_INTERCEPT_TLS_GET_ADDR
+#define SANITIZER_INTERCEPT_TLS_GET_OFFSET 1
 #undef SANITIZER_INTERCEPT_PTHREAD_SIGMASK
 
 #define COMMON_INTERCEPT_FUNCTION(name) INTERCEPT_FUNCTION(name)
 #define COMMON_INTERCEPT_FUNCTION_VER(name, ver)                          \
   INTERCEPT_FUNCTION_VER(name, ver)
+#define COMMON_INTERCEPT_FUNCTION_VER_UNVERSIONED_FALLBACK(name, ver) \
+  (INTERCEPT_FUNCTION_VER(name, ver) || INTERCEPT_FUNCTION(name))
 
 #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size)                    \
   MemoryAccessRange(((TsanInterceptorContext *)ctx)->thr,                 \
@@ -2359,6 +2423,10 @@ int sigaction_impl(int sig, const __sanitizer_sigaction *act,
   // the signal handler through rtl_sigaction, very bad things will happen.
   // The handler will run synchronously and corrupt tsan per-thread state.
   SCOPED_INTERCEPTOR_RAW(sigaction, sig, act, old);
+  if (sig <= 0 || sig >= kSigCount) {
+    errno = errno_EINVAL;
+    return -1;
+  }
   __sanitizer_sigaction *sigactions = interceptor_ctx()->sigactions;
   __sanitizer_sigaction old_stored;
   if (old) internal_memcpy(&old_stored, &sigactions[sig], sizeof(old_stored));
@@ -2437,13 +2505,13 @@ static void syscall_access_range(uptr pc, uptr p, uptr s, bool write) {
   MemoryAccessRange(thr, pc, p, s, write);
 }
 
-static void syscall_acquire(uptr pc, uptr addr) {
+static USED void syscall_acquire(uptr pc, uptr addr) {
   TSAN_SYSCALL();
   Acquire(thr, pc, addr);
   DPrintf("syscall_acquire(%p)\n", addr);
 }
 
-static void syscall_release(uptr pc, uptr addr) {
+static USED void syscall_release(uptr pc, uptr addr) {
   TSAN_SYSCALL();
   DPrintf("syscall_release(%p)\n", addr);
   Release(thr, pc, addr);
@@ -2466,13 +2534,10 @@ static USED void syscall_fd_release(uptr pc, int fd) {
   FdRelease(thr, pc, fd);
 }
 
-static void syscall_pre_fork(uptr pc) {
-  TSAN_SYSCALL();
-  ForkBefore(thr, pc);
-}
+static void syscall_pre_fork(uptr pc) { ForkBefore(cur_thread(), pc); }
 
 static void syscall_post_fork(uptr pc, int pid) {
-  TSAN_SYSCALL();
+  ThreadState *thr = cur_thread();
   if (pid == 0) {
     // child
     ForkChildAfter(thr, pc);
@@ -2527,6 +2592,20 @@ static void syscall_post_fork(uptr pc, int pid) {
 #include "sanitizer_common/sanitizer_syscalls_netbsd.inc"
 
 #ifdef NEED_TLS_GET_ADDR
+
+static void handle_tls_addr(void *arg, void *res) {
+  ThreadState *thr = cur_thread();
+  if (!thr)
+    return;
+  DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr,
+                                        thr->tls_addr + thr->tls_size);
+  if (!dtv)
+    return;
+  // New DTLS block has been allocated.
+  MemoryResetRange(thr, 0, dtv->beg, dtv->size);
+}
+
+#if !SANITIZER_S390
 // Define own interceptor instead of sanitizer_common's for three reasons:
 // 1. It must not process pending signals.
 //    Signal handlers may contain MOVDQA instruction (see below).
@@ -2539,17 +2618,17 @@ static void syscall_post_fork(uptr pc, int pid) {
 // execute MOVDQA with stack addresses.
 TSAN_INTERCEPTOR(void *, __tls_get_addr, void *arg) {
   void *res = REAL(__tls_get_addr)(arg);
-  ThreadState *thr = cur_thread();
-  if (!thr)
-    return res;
-  DTLS::DTV *dtv = DTLS_on_tls_get_addr(arg, res, thr->tls_addr,
-                                        thr->tls_addr + thr->tls_size);
-  if (!dtv)
-    return res;
-  // New DTLS block has been allocated.
-  MemoryResetRange(thr, 0, dtv->beg, dtv->size);
+  handle_tls_addr(arg, res);
   return res;
 }
+#else // SANITIZER_S390
+TSAN_INTERCEPTOR(uptr, __tls_get_addr_internal, void *arg) {
+  uptr res = __tls_get_offset_wrapper(arg, REAL(__tls_get_offset));
+  char *tp = static_cast<char *>(__builtin_thread_pointer());
+  handle_tls_addr(arg, res + tp);
+  return res;
+}
+#endif
 #endif
 
 #if SANITIZER_NETBSD
@@ -2622,7 +2701,7 @@ void InitializeInterceptors() {
 #endif
 
   // Instruct libc malloc to consume less memory.
-#if SANITIZER_LINUX
+#if SANITIZER_GLIBC
   mallopt(1, 0);  // M_MXFAST
   mallopt(-3, 32*1024);  // M_MMAP_THRESHOLD
 #endif
@@ -2685,6 +2764,8 @@ void InitializeInterceptors() {
   TSAN_INTERCEPT_VER(pthread_cond_timedwait, PTHREAD_ABI_BASE);
   TSAN_INTERCEPT_VER(pthread_cond_destroy, PTHREAD_ABI_BASE);
 
+  TSAN_MAYBE_PTHREAD_COND_CLOCKWAIT;
+
   TSAN_INTERCEPT(pthread_mutex_init);
   TSAN_INTERCEPT(pthread_mutex_destroy);
   TSAN_INTERCEPT(pthread_mutex_trylock);
@@ -2770,7 +2851,12 @@ void InitializeInterceptors() {
   TSAN_INTERCEPT(_exit);
 
 #ifdef NEED_TLS_GET_ADDR
+#if !SANITIZER_S390
   TSAN_INTERCEPT(__tls_get_addr);
+#else
+  TSAN_INTERCEPT(__tls_get_addr_internal);
+  TSAN_INTERCEPT(__tls_get_offset);
+#endif
 #endif
 
   TSAN_MAYBE_INTERCEPT__LWP_EXIT;
@@ -2786,6 +2872,10 @@ void InitializeInterceptors() {
     Printf("ThreadSanitizer: failed to setup atexit callback\n");
     Die();
   }
+  if (pthread_atfork(atfork_prepare, atfork_parent, atfork_child)) {
+    Printf("ThreadSanitizer: failed to setup atfork callbacks\n");
+    Die();
+  }
 
 #if !SANITIZER_MAC && !SANITIZER_NETBSD && !SANITIZER_FREEBSD
   if (pthread_key_create(&interceptor_ctx()->finalize_key, &thread_finalize)) {
lib/tsan/tsan_interface.cpp
@@ -14,15 +14,12 @@
 #include "tsan_interface_ann.h"
 #include "tsan_rtl.h"
 #include "sanitizer_common/sanitizer_internal_defs.h"
+#include "sanitizer_common/sanitizer_ptrauth.h"
 
 #define CALLERPC ((uptr)__builtin_return_address(0))
 
 using namespace __tsan;
 
-typedef u16 uint16_t;
-typedef u32 uint32_t;
-typedef u64 uint64_t;
-
 void __tsan_init() {
   cur_thread_init();
   Initialize(cur_thread());
@@ -43,13 +40,13 @@ void __tsan_write16(void *addr) {
 }
 
 void __tsan_read16_pc(void *addr, void *pc) {
-  MemoryRead(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog8);
-  MemoryRead(cur_thread(), (uptr)pc, (uptr)addr + 8, kSizeLog8);
+  MemoryRead(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog8);
+  MemoryRead(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr + 8, kSizeLog8);
 }
 
 void __tsan_write16_pc(void *addr, void *pc) {
-  MemoryWrite(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog8);
-  MemoryWrite(cur_thread(), (uptr)pc, (uptr)addr + 8, kSizeLog8);
+  MemoryWrite(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog8);
+  MemoryWrite(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr + 8, kSizeLog8);
 }
 
 // __tsan_unaligned_read/write calls are emitted by compiler.
lib/tsan/tsan_interface.h
@@ -196,7 +196,8 @@ typedef unsigned short a16;
 typedef unsigned int       a32;
 typedef unsigned long long a64;
 #if !SANITIZER_GO && (defined(__SIZEOF_INT128__) \
-    || (__clang_major__ * 100 + __clang_minor__ >= 302)) && !defined(__mips64)
+    || (__clang_major__ * 100 + __clang_minor__ >= 302)) && \
+    !defined(__mips64) && !defined(__s390x__)
 __extension__ typedef __int128 a128;
 # define __TSAN_HAS_INT128 1
 #else
@@ -204,7 +205,7 @@ __extension__ typedef __int128 a128;
 #endif
 
 // Part of ABI, do not change.
-// https://github.com/llvm/llvm-project/blob/master/libcxx/include/atomic
+// https://github.com/llvm/llvm-project/blob/main/libcxx/include/atomic
 typedef enum {
   mo_relaxed,
   mo_consume,
@@ -415,6 +416,13 @@ void __tsan_go_atomic32_compare_exchange(ThreadState *thr, uptr cpc, uptr pc,
 SANITIZER_INTERFACE_ATTRIBUTE
 void __tsan_go_atomic64_compare_exchange(ThreadState *thr, uptr cpc, uptr pc,
                                          u8 *a);
+
+SANITIZER_INTERFACE_ATTRIBUTE
+void __tsan_on_initialize();
+
+SANITIZER_INTERFACE_ATTRIBUTE
+int __tsan_on_finalize(int failed);
+
 }  // extern "C"
 
 }  // namespace __tsan
lib/tsan/tsan_interface_ann.cpp
@@ -15,7 +15,6 @@
 #include "sanitizer_common/sanitizer_stacktrace.h"
 #include "sanitizer_common/sanitizer_vector.h"
 #include "tsan_interface_ann.h"
-#include "tsan_mutex.h"
 #include "tsan_report.h"
 #include "tsan_rtl.h"
 #include "tsan_mman.h"
@@ -38,7 +37,7 @@ class ScopedAnnotation {
 
   ~ScopedAnnotation() {
     FuncExit(thr_);
-    CheckNoLocks(thr_);
+    CheckedMutex::CheckNoLocks();
   }
  private:
   ThreadState *const thr_;
@@ -49,8 +48,6 @@ class ScopedAnnotation {
       return ret; \
     ThreadState *thr = cur_thread(); \
     const uptr caller_pc = (uptr)__builtin_return_address(0); \
-    StatInc(thr, StatAnnotation); \
-    StatInc(thr, Stat##typ); \
     ScopedAnnotation sa(thr, __func__, caller_pc); \
     const uptr pc = StackTrace::GetCurrentPc(); \
     (void)pc; \
@@ -77,9 +74,7 @@ struct DynamicAnnContext {
   ExpectRace expect;
   ExpectRace benign;
 
-  DynamicAnnContext()
-    : mtx(MutexTypeAnnotations, StatMtxAnnotations) {
-  }
+  DynamicAnnContext() : mtx(MutexTypeAnnotations) {}
 };
 
 static DynamicAnnContext *dyn_ann_ctx;
lib/tsan/tsan_interface_atomic.cpp
@@ -218,8 +218,9 @@ static a128 NoTsanAtomicLoad(const volatile a128 *a, morder mo) {
 }
 #endif
 
-template<typename T>
-static T AtomicLoad(ThreadState *thr, uptr pc, const volatile T *a, morder mo) {
+template <typename T>
+static T AtomicLoad(ThreadState *thr, uptr pc, const volatile T *a,
+                    morder mo) NO_THREAD_SAFETY_ANALYSIS {
   CHECK(IsLoadOrder(mo));
   // This fast-path is critical for performance.
   // Assume the access is atomic.
@@ -254,9 +255,9 @@ static void NoTsanAtomicStore(volatile a128 *a, a128 v, morder mo) {
 }
 #endif
 
-template<typename T>
+template <typename T>
 static void AtomicStore(ThreadState *thr, uptr pc, volatile T *a, T v,
-    morder mo) {
+                        morder mo) NO_THREAD_SAFETY_ANALYSIS {
   CHECK(IsStoreOrder(mo));
   MemoryWriteAtomic(thr, pc, (uptr)a, SizeLog<T>());
   // This fast-path is critical for performance.
@@ -277,8 +278,9 @@ static void AtomicStore(ThreadState *thr, uptr pc, volatile T *a, T v,
   s->mtx.Unlock();
 }
 
-template<typename T, T (*F)(volatile T *v, T op)>
-static T AtomicRMW(ThreadState *thr, uptr pc, volatile T *a, T v, morder mo) {
+template <typename T, T (*F)(volatile T *v, T op)>
+static T AtomicRMW(ThreadState *thr, uptr pc, volatile T *a, T v,
+                   morder mo) NO_THREAD_SAFETY_ANALYSIS {
   MemoryWriteAtomic(thr, pc, (uptr)a, SizeLog<T>());
   SyncVar *s = 0;
   if (mo != mo_relaxed) {
@@ -399,37 +401,48 @@ static T NoTsanAtomicCAS(volatile T *a, T c, T v, morder mo, morder fmo) {
   return c;
 }
 
-template<typename T>
-static bool AtomicCAS(ThreadState *thr, uptr pc,
-    volatile T *a, T *c, T v, morder mo, morder fmo) {
-  (void)fmo;  // Unused because llvm does not pass it yet.
+template <typename T>
+static bool AtomicCAS(ThreadState *thr, uptr pc, volatile T *a, T *c, T v, morder mo,
+                      morder fmo) NO_THREAD_SAFETY_ANALYSIS {
+  // 31.7.2.18: "The failure argument shall not be memory_order_release
+  // nor memory_order_acq_rel". LLVM (2021-05) fallbacks to Monotonic
+  // (mo_relaxed) when those are used.
+  CHECK(IsLoadOrder(fmo));
+
   MemoryWriteAtomic(thr, pc, (uptr)a, SizeLog<T>());
   SyncVar *s = 0;
-  bool write_lock = mo != mo_acquire && mo != mo_consume;
-  if (mo != mo_relaxed) {
+  bool write_lock = IsReleaseOrder(mo);
+
+  if (mo != mo_relaxed || fmo != mo_relaxed)
     s = ctx->metamap.GetOrCreateAndLock(thr, pc, (uptr)a, write_lock);
+
+  T cc = *c;
+  T pr = func_cas(a, cc, v);
+  bool success = pr == cc;
+  if (!success) {
+    *c = pr;
+    mo = fmo;
+  }
+
+  if (s) {
     thr->fast_state.IncrementEpoch();
     // Can't increment epoch w/o writing to the trace as well.
     TraceAddEvent(thr, thr->fast_state, EventTypeMop, 0);
-    if (IsAcqRelOrder(mo))
+
+    if (success && IsAcqRelOrder(mo))
       AcquireReleaseImpl(thr, pc, &s->clock);
-    else if (IsReleaseOrder(mo))
+    else if (success && IsReleaseOrder(mo))
       ReleaseImpl(thr, pc, &s->clock);
     else if (IsAcquireOrder(mo))
       AcquireImpl(thr, pc, &s->clock);
-  }
-  T cc = *c;
-  T pr = func_cas(a, cc, v);
-  if (s) {
+
     if (write_lock)
       s->mtx.Unlock();
     else
       s->mtx.ReadUnlock();
   }
-  if (pr == cc)
-    return true;
-  *c = pr;
-  return false;
+
+  return success;
 }
 
 template<typename T>
@@ -481,7 +494,6 @@ static morder convert_morder(morder mo) {
     const uptr callpc = (uptr)__builtin_return_address(0); \
     uptr pc = StackTrace::GetCurrentPc(); \
     mo = convert_morder(mo); \
-    AtomicStatInc(thr, sizeof(*a), mo, StatAtomic##func); \
     ScopedAtomic sa(thr, callpc, a, mo, __func__); \
     return Atomic##func(thr, pc, __VA_ARGS__); \
 /**/
@@ -502,22 +514,6 @@ class ScopedAtomic {
   ThreadState *thr_;
 };
 
-static void AtomicStatInc(ThreadState *thr, uptr size, morder mo, StatType t) {
-  StatInc(thr, StatAtomic);
-  StatInc(thr, t);
-  StatInc(thr, size == 1 ? StatAtomic1
-             : size == 2 ? StatAtomic2
-             : size == 4 ? StatAtomic4
-             : size == 8 ? StatAtomic8
-             :             StatAtomic16);
-  StatInc(thr, mo == mo_relaxed ? StatAtomicRelaxed
-             : mo == mo_consume ? StatAtomicConsume
-             : mo == mo_acquire ? StatAtomicAcquire
-             : mo == mo_release ? StatAtomicRelease
-             : mo == mo_acq_rel ? StatAtomicAcq_Rel
-             :                    StatAtomicSeq_Cst);
-}
-
 extern "C" {
 SANITIZER_INTERFACE_ATTRIBUTE
 a8 __tsan_atomic8_load(const volatile a8 *a, morder mo) {
lib/tsan/tsan_interface_inl.h
@@ -12,6 +12,7 @@
 
 #include "tsan_interface.h"
 #include "tsan_rtl.h"
+#include "sanitizer_common/sanitizer_ptrauth.h"
 
 #define CALLERPC ((uptr)__builtin_return_address(0))
 
@@ -50,35 +51,35 @@ void __tsan_write8(void *addr) {
 }
 
 void __tsan_read1_pc(void *addr, void *pc) {
-  MemoryRead(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog1);
+  MemoryRead(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog1);
 }
 
 void __tsan_read2_pc(void *addr, void *pc) {
-  MemoryRead(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog2);
+  MemoryRead(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog2);
 }
 
 void __tsan_read4_pc(void *addr, void *pc) {
-  MemoryRead(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog4);
+  MemoryRead(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog4);
 }
 
 void __tsan_read8_pc(void *addr, void *pc) {
-  MemoryRead(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog8);
+  MemoryRead(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog8);
 }
 
 void __tsan_write1_pc(void *addr, void *pc) {
-  MemoryWrite(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog1);
+  MemoryWrite(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog1);
 }
 
 void __tsan_write2_pc(void *addr, void *pc) {
-  MemoryWrite(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog2);
+  MemoryWrite(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog2);
 }
 
 void __tsan_write4_pc(void *addr, void *pc) {
-  MemoryWrite(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog4);
+  MemoryWrite(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog4);
 }
 
 void __tsan_write8_pc(void *addr, void *pc) {
-  MemoryWrite(cur_thread(), (uptr)pc, (uptr)addr, kSizeLog8);
+  MemoryWrite(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, kSizeLog8);
 }
 
 void __tsan_vptr_update(void **vptr_p, void *new_val) {
@@ -100,7 +101,7 @@ void __tsan_vptr_read(void **vptr_p) {
 }
 
 void __tsan_func_entry(void *pc) {
-  FuncEntry(cur_thread(), (uptr)pc);
+  FuncEntry(cur_thread(), STRIP_PAC_PC(pc));
 }
 
 void __tsan_func_exit() {
@@ -124,9 +125,9 @@ void __tsan_write_range(void *addr, uptr size) {
 }
 
 void __tsan_read_range_pc(void *addr, uptr size, void *pc) {
-  MemoryAccessRange(cur_thread(), (uptr)pc, (uptr)addr, size, false);
+  MemoryAccessRange(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, size, false);
 }
 
 void __tsan_write_range_pc(void *addr, uptr size, void *pc) {
-  MemoryAccessRange(cur_thread(), (uptr)pc, (uptr)addr, size, true);
+  MemoryAccessRange(cur_thread(), STRIP_PAC_PC(pc), (uptr)addr, size, true);
 }
lib/tsan/tsan_interface_java.cpp
@@ -12,7 +12,6 @@
 
 #include "tsan_interface_java.h"
 #include "tsan_rtl.h"
-#include "tsan_mutex.h"
 #include "sanitizer_common/sanitizer_internal_defs.h"
 #include "sanitizer_common/sanitizer_common.h"
 #include "sanitizer_common/sanitizer_placement_new.h"
lib/tsan/tsan_mman.cpp
@@ -70,10 +70,7 @@ struct GlobalProc {
   Mutex mtx;
   Processor *proc;
 
-  GlobalProc()
-      : mtx(MutexTypeGlobalProc, StatMtxGlobalProc)
-      , proc(ProcCreate()) {
-  }
+  GlobalProc() : mtx(MutexTypeGlobalProc), proc(ProcCreate()) {}
 };
 
 static char global_proc_placeholder[sizeof(GlobalProc)] ALIGNED(64);
@@ -145,7 +142,7 @@ void AllocatorPrintStats() {
 
 static void SignalUnsafeCall(ThreadState *thr, uptr pc) {
   if (atomic_load_relaxed(&thr->in_signal_handler) == 0 ||
-      !flags()->report_signal_unsafe)
+      !ShouldReport(thr, ReportTypeSignalUnsafe))
     return;
   VarSizeStackTrace stack;
   ObtainCurrentStack(thr, pc, &stack);
lib/tsan/tsan_mutex.cpp
@@ -1,289 +0,0 @@
-//===-- tsan_mutex.cpp ----------------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is a part of ThreadSanitizer (TSan), a race detector.
-//
-//===----------------------------------------------------------------------===//
-#include "sanitizer_common/sanitizer_libc.h"
-#include "tsan_mutex.h"
-#include "tsan_platform.h"
-#include "tsan_rtl.h"
-
-namespace __tsan {
-
-// Simple reader-writer spin-mutex. Optimized for not-so-contended case.
-// Readers have preference, can possibly starvate writers.
-
-// The table fixes what mutexes can be locked under what mutexes.
-// E.g. if the row for MutexTypeThreads contains MutexTypeReport,
-// then Report mutex can be locked while under Threads mutex.
-// The leaf mutexes can be locked under any other mutexes.
-// Recursive locking is not supported.
-#if SANITIZER_DEBUG && !SANITIZER_GO
-const MutexType MutexTypeLeaf = (MutexType)-1;
-static MutexType CanLockTab[MutexTypeCount][MutexTypeCount] = {
-  /*0  MutexTypeInvalid*/     {},
-  /*1  MutexTypeTrace*/       {MutexTypeLeaf},
-  /*2  MutexTypeThreads*/     {MutexTypeReport},
-  /*3  MutexTypeReport*/      {MutexTypeSyncVar,
-                               MutexTypeMBlock, MutexTypeJavaMBlock},
-  /*4  MutexTypeSyncVar*/     {MutexTypeDDetector},
-  /*5  MutexTypeSyncTab*/     {},  // unused
-  /*6  MutexTypeSlab*/        {MutexTypeLeaf},
-  /*7  MutexTypeAnnotations*/ {},
-  /*8  MutexTypeAtExit*/      {MutexTypeSyncVar},
-  /*9  MutexTypeMBlock*/      {MutexTypeSyncVar},
-  /*10 MutexTypeJavaMBlock*/  {MutexTypeSyncVar},
-  /*11 MutexTypeDDetector*/   {},
-  /*12 MutexTypeFired*/       {MutexTypeLeaf},
-  /*13 MutexTypeRacy*/        {MutexTypeLeaf},
-  /*14 MutexTypeGlobalProc*/  {},
-};
-
-static bool CanLockAdj[MutexTypeCount][MutexTypeCount];
-#endif
-
-void InitializeMutex() {
-#if SANITIZER_DEBUG && !SANITIZER_GO
-  // Build the "can lock" adjacency matrix.
-  // If [i][j]==true, then one can lock mutex j while under mutex i.
-  const int N = MutexTypeCount;
-  int cnt[N] = {};
-  bool leaf[N] = {};
-  for (int i = 1; i < N; i++) {
-    for (int j = 0; j < N; j++) {
-      MutexType z = CanLockTab[i][j];
-      if (z == MutexTypeInvalid)
-        continue;
-      if (z == MutexTypeLeaf) {
-        CHECK(!leaf[i]);
-        leaf[i] = true;
-        continue;
-      }
-      CHECK(!CanLockAdj[i][(int)z]);
-      CanLockAdj[i][(int)z] = true;
-      cnt[i]++;
-    }
-  }
-  for (int i = 0; i < N; i++) {
-    CHECK(!leaf[i] || cnt[i] == 0);
-  }
-  // Add leaf mutexes.
-  for (int i = 0; i < N; i++) {
-    if (!leaf[i])
-      continue;
-    for (int j = 0; j < N; j++) {
-      if (i == j || leaf[j] || j == MutexTypeInvalid)
-        continue;
-      CHECK(!CanLockAdj[j][i]);
-      CanLockAdj[j][i] = true;
-    }
-  }
-  // Build the transitive closure.
-  bool CanLockAdj2[MutexTypeCount][MutexTypeCount];
-  for (int i = 0; i < N; i++) {
-    for (int j = 0; j < N; j++) {
-      CanLockAdj2[i][j] = CanLockAdj[i][j];
-    }
-  }
-  for (int k = 0; k < N; k++) {
-    for (int i = 0; i < N; i++) {
-      for (int j = 0; j < N; j++) {
-        if (CanLockAdj2[i][k] && CanLockAdj2[k][j]) {
-          CanLockAdj2[i][j] = true;
-        }
-      }
-    }
-  }
-#if 0
-  Printf("Can lock graph:\n");
-  for (int i = 0; i < N; i++) {
-    for (int j = 0; j < N; j++) {
-      Printf("%d ", CanLockAdj[i][j]);
-    }
-    Printf("\n");
-  }
-  Printf("Can lock graph closure:\n");
-  for (int i = 0; i < N; i++) {
-    for (int j = 0; j < N; j++) {
-      Printf("%d ", CanLockAdj2[i][j]);
-    }
-    Printf("\n");
-  }
-#endif
-  // Verify that the graph is acyclic.
-  for (int i = 0; i < N; i++) {
-    if (CanLockAdj2[i][i]) {
-      Printf("Mutex %d participates in a cycle\n", i);
-      Die();
-    }
-  }
-#endif
-}
-
-InternalDeadlockDetector::InternalDeadlockDetector() {
-  // Rely on zero initialization because some mutexes can be locked before ctor.
-}
-
-#if SANITIZER_DEBUG && !SANITIZER_GO
-void InternalDeadlockDetector::Lock(MutexType t) {
-  // Printf("LOCK %d @%zu\n", t, seq_ + 1);
-  CHECK_GT(t, MutexTypeInvalid);
-  CHECK_LT(t, MutexTypeCount);
-  u64 max_seq = 0;
-  u64 max_idx = MutexTypeInvalid;
-  for (int i = 0; i != MutexTypeCount; i++) {
-    if (locked_[i] == 0)
-      continue;
-    CHECK_NE(locked_[i], max_seq);
-    if (max_seq < locked_[i]) {
-      max_seq = locked_[i];
-      max_idx = i;
-    }
-  }
-  locked_[t] = ++seq_;
-  if (max_idx == MutexTypeInvalid)
-    return;
-  // Printf("  last %d @%zu\n", max_idx, max_seq);
-  if (!CanLockAdj[max_idx][t]) {
-    Printf("ThreadSanitizer: internal deadlock detected\n");
-    Printf("ThreadSanitizer: can't lock %d while under %zu\n",
-               t, (uptr)max_idx);
-    CHECK(0);
-  }
-}
-
-void InternalDeadlockDetector::Unlock(MutexType t) {
-  // Printf("UNLO %d @%zu #%zu\n", t, seq_, locked_[t]);
-  CHECK(locked_[t]);
-  locked_[t] = 0;
-}
-
-void InternalDeadlockDetector::CheckNoLocks() {
-  for (int i = 0; i != MutexTypeCount; i++) {
-    CHECK_EQ(locked_[i], 0);
-  }
-}
-#endif
-
-void CheckNoLocks(ThreadState *thr) {
-#if SANITIZER_DEBUG && !SANITIZER_GO
-  thr->internal_deadlock_detector.CheckNoLocks();
-#endif
-}
-
-const uptr kUnlocked = 0;
-const uptr kWriteLock = 1;
-const uptr kReadLock = 2;
-
-class Backoff {
- public:
-  Backoff()
-    : iter_() {
-  }
-
-  bool Do() {
-    if (iter_++ < kActiveSpinIters)
-      proc_yield(kActiveSpinCnt);
-    else
-      internal_sched_yield();
-    return true;
-  }
-
-  u64 Contention() const {
-    u64 active = iter_ % kActiveSpinIters;
-    u64 passive = iter_ - active;
-    return active + 10 * passive;
-  }
-
- private:
-  int iter_;
-  static const int kActiveSpinIters = 10;
-  static const int kActiveSpinCnt = 20;
-};
-
-Mutex::Mutex(MutexType type, StatType stat_type) {
-  CHECK_GT(type, MutexTypeInvalid);
-  CHECK_LT(type, MutexTypeCount);
-#if SANITIZER_DEBUG
-  type_ = type;
-#endif
-#if TSAN_COLLECT_STATS
-  stat_type_ = stat_type;
-#endif
-  atomic_store(&state_, kUnlocked, memory_order_relaxed);
-}
-
-Mutex::~Mutex() {
-  CHECK_EQ(atomic_load(&state_, memory_order_relaxed), kUnlocked);
-}
-
-void Mutex::Lock() {
-#if SANITIZER_DEBUG && !SANITIZER_GO
-  cur_thread()->internal_deadlock_detector.Lock(type_);
-#endif
-  uptr cmp = kUnlocked;
-  if (atomic_compare_exchange_strong(&state_, &cmp, kWriteLock,
-                                     memory_order_acquire))
-    return;
-  for (Backoff backoff; backoff.Do();) {
-    if (atomic_load(&state_, memory_order_relaxed) == kUnlocked) {
-      cmp = kUnlocked;
-      if (atomic_compare_exchange_weak(&state_, &cmp, kWriteLock,
-                                       memory_order_acquire)) {
-#if TSAN_COLLECT_STATS && !SANITIZER_GO
-        StatInc(cur_thread(), stat_type_, backoff.Contention());
-#endif
-        return;
-      }
-    }
-  }
-}
-
-void Mutex::Unlock() {
-  uptr prev = atomic_fetch_sub(&state_, kWriteLock, memory_order_release);
-  (void)prev;
-  DCHECK_NE(prev & kWriteLock, 0);
-#if SANITIZER_DEBUG && !SANITIZER_GO
-  cur_thread()->internal_deadlock_detector.Unlock(type_);
-#endif
-}
-
-void Mutex::ReadLock() {
-#if SANITIZER_DEBUG && !SANITIZER_GO
-  cur_thread()->internal_deadlock_detector.Lock(type_);
-#endif
-  uptr prev = atomic_fetch_add(&state_, kReadLock, memory_order_acquire);
-  if ((prev & kWriteLock) == 0)
-    return;
-  for (Backoff backoff; backoff.Do();) {
-    prev = atomic_load(&state_, memory_order_acquire);
-    if ((prev & kWriteLock) == 0) {
-#if TSAN_COLLECT_STATS && !SANITIZER_GO
-      StatInc(cur_thread(), stat_type_, backoff.Contention());
-#endif
-      return;
-    }
-  }
-}
-
-void Mutex::ReadUnlock() {
-  uptr prev = atomic_fetch_sub(&state_, kReadLock, memory_order_release);
-  (void)prev;
-  DCHECK_EQ(prev & kWriteLock, 0);
-  DCHECK_GT(prev & ~kWriteLock, 0);
-#if SANITIZER_DEBUG && !SANITIZER_GO
-  cur_thread()->internal_deadlock_detector.Unlock(type_);
-#endif
-}
-
-void Mutex::CheckLocked() {
-  CHECK_NE(atomic_load(&state_, memory_order_relaxed), 0);
-}
-
-}  // namespace __tsan
lib/tsan/tsan_mutex.h
@@ -1,90 +0,0 @@
-//===-- tsan_mutex.h --------------------------------------------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is a part of ThreadSanitizer (TSan), a race detector.
-//
-//===----------------------------------------------------------------------===//
-#ifndef TSAN_MUTEX_H
-#define TSAN_MUTEX_H
-
-#include "sanitizer_common/sanitizer_atomic.h"
-#include "sanitizer_common/sanitizer_mutex.h"
-#include "tsan_defs.h"
-
-namespace __tsan {
-
-enum MutexType {
-  MutexTypeInvalid,
-  MutexTypeTrace,
-  MutexTypeThreads,
-  MutexTypeReport,
-  MutexTypeSyncVar,
-  MutexTypeSyncTab,
-  MutexTypeSlab,
-  MutexTypeAnnotations,
-  MutexTypeAtExit,
-  MutexTypeMBlock,
-  MutexTypeJavaMBlock,
-  MutexTypeDDetector,
-  MutexTypeFired,
-  MutexTypeRacy,
-  MutexTypeGlobalProc,
-
-  // This must be the last.
-  MutexTypeCount
-};
-
-class Mutex {
- public:
-  explicit Mutex(MutexType type, StatType stat_type);
-  ~Mutex();
-
-  void Lock();
-  void Unlock();
-
-  void ReadLock();
-  void ReadUnlock();
-
-  void CheckLocked();
-
- private:
-  atomic_uintptr_t state_;
-#if SANITIZER_DEBUG
-  MutexType type_;
-#endif
-#if TSAN_COLLECT_STATS
-  StatType stat_type_;
-#endif
-
-  Mutex(const Mutex&);
-  void operator = (const Mutex&);
-};
-
-typedef GenericScopedLock<Mutex> Lock;
-typedef GenericScopedReadLock<Mutex> ReadLock;
-
-class InternalDeadlockDetector {
- public:
-  InternalDeadlockDetector();
-  void Lock(MutexType t);
-  void Unlock(MutexType t);
-  void CheckNoLocks();
- private:
-  u64 seq_;
-  u64 locked_[MutexTypeCount];
-};
-
-void InitializeMutex();
-
-// Checks that the current thread does not hold any runtime locks
-// (e.g. when returning from an interceptor).
-void CheckNoLocks(ThreadState *thr);
-
-}  // namespace __tsan
-
-#endif  // TSAN_MUTEX_H
lib/tsan/tsan_platform.h
@@ -23,9 +23,21 @@
 
 namespace __tsan {
 
+#if defined(__x86_64__)
+#define HAS_48_BIT_ADDRESS_SPACE 1
+#elif SANITIZER_IOSSIM // arm64 iOS simulators (order of #if matters)
+#define HAS_48_BIT_ADDRESS_SPACE 1
+#elif SANITIZER_IOS // arm64 iOS devices (order of #if matters)
+#define HAS_48_BIT_ADDRESS_SPACE 0
+#elif SANITIZER_MAC // arm64 macOS (order of #if matters)
+#define HAS_48_BIT_ADDRESS_SPACE 1
+#else
+#define HAS_48_BIT_ADDRESS_SPACE 0
+#endif
+
 #if !SANITIZER_GO
 
-#if defined(__x86_64__)
+#if HAS_48_BIT_ADDRESS_SPACE
 /*
 C/C++ on linux/x86_64 and freebsd/x86_64
 0000 0000 1000 - 0080 0000 0000: main binary and/or MAP_32BIT mappings (512GB)
@@ -93,7 +105,7 @@ fe00 0000 00 - ff00 0000 00: heap                                        (4 GB)
 ff00 0000 00 - ff80 0000 00: -                                           (2 GB)
 ff80 0000 00 - ffff ffff ff: modules and main thread stack              (<2 GB)
 */
-struct Mapping {
+struct Mapping40 {
   static const uptr kMetaShadowBeg = 0x4000000000ull;
   static const uptr kMetaShadowEnd = 0x5000000000ull;
   static const uptr kTraceMemBeg   = 0xb000000000ull;
@@ -114,6 +126,7 @@ struct Mapping {
 };
 
 #define TSAN_MID_APP_RANGE 1
+#define TSAN_RUNTIME_VMA 1
 #elif defined(__aarch64__) && defined(__APPLE__)
 /*
 C/C++ on Darwin/iOS/ARM64 (36-bit VMA, 64 GB VM)
@@ -146,7 +159,7 @@ struct Mapping {
   static const uptr kVdsoBeg       = 0x7000000000000000ull;
 };
 
-#elif defined(__aarch64__)
+#elif defined(__aarch64__) && !defined(__APPLE__)
 // AArch64 supports multiple VMA which leads to multiple address transformation
 // functions.  To support these multiple VMAS transformations and mappings TSAN
 // runtime for AArch64 uses an external memory read (vmaSize) to select which
@@ -352,9 +365,41 @@ struct Mapping47 {
 
 // Indicates the runtime will define the memory regions at runtime.
 #define TSAN_RUNTIME_VMA 1
+#elif defined(__s390x__)
+/*
+C/C++ on linux/s390x
+While the kernel provides a 64-bit address space, we have to restrict ourselves
+to 48 bits due to how e.g. SyncVar::GetId() works.
+0000 0000 1000 - 0e00 0000 0000: binary, modules, stacks - 14 TiB
+0e00 0000 0000 - 4000 0000 0000: -
+4000 0000 0000 - 8000 0000 0000: shadow - 64TiB (4 * app)
+8000 0000 0000 - 9000 0000 0000: -
+9000 0000 0000 - 9800 0000 0000: metainfo - 8TiB (0.5 * app)
+9800 0000 0000 - a000 0000 0000: -
+a000 0000 0000 - b000 0000 0000: traces - 16TiB (max history * 128k threads)
+b000 0000 0000 - be00 0000 0000: -
+be00 0000 0000 - c000 0000 0000: heap - 2TiB (max supported by the allocator)
+*/
+struct Mapping {
+  static const uptr kMetaShadowBeg = 0x900000000000ull;
+  static const uptr kMetaShadowEnd = 0x980000000000ull;
+  static const uptr kTraceMemBeg   = 0xa00000000000ull;
+  static const uptr kTraceMemEnd   = 0xb00000000000ull;
+  static const uptr kShadowBeg     = 0x400000000000ull;
+  static const uptr kShadowEnd     = 0x800000000000ull;
+  static const uptr kHeapMemBeg    = 0xbe0000000000ull;
+  static const uptr kHeapMemEnd    = 0xc00000000000ull;
+  static const uptr kLoAppMemBeg   = 0x000000001000ull;
+  static const uptr kLoAppMemEnd   = 0x0e0000000000ull;
+  static const uptr kHiAppMemBeg   = 0xc00000004000ull;
+  static const uptr kHiAppMemEnd   = 0xc00000004000ull;
+  static const uptr kAppMemMsk     = 0xb00000000000ull;
+  static const uptr kAppMemXor     = 0x100000000000ull;
+  static const uptr kVdsoBeg       = 0xfffffffff000ull;
+};
 #endif
 
-#elif SANITIZER_GO && !SANITIZER_WINDOWS && defined(__x86_64__)
+#elif SANITIZER_GO && !SANITIZER_WINDOWS && HAS_48_BIT_ADDRESS_SPACE
 
 /* Go on linux, darwin and freebsd on x86_64
 0000 0000 1000 - 0000 1000 0000: executable
@@ -461,7 +506,7 @@ struct Mapping47 {
 
 #elif SANITIZER_GO && defined(__aarch64__)
 
-/* Go on linux/aarch64 (48-bit VMA)
+/* Go on linux/aarch64 (48-bit VMA) and darwin/aarch64 (47-bit VMA)
 0000 0000 1000 - 0000 1000 0000: executable
 0000 1000 0000 - 00c0 0000 0000: -
 00c0 0000 0000 - 00e0 0000 0000: heap
@@ -488,6 +533,55 @@ struct Mapping {
 // Indicates the runtime will define the memory regions at runtime.
 #define TSAN_RUNTIME_VMA 1
 
+#elif SANITIZER_GO && defined(__mips64)
+/*
+Go on linux/mips64 (47-bit VMA)
+0000 0000 1000 - 0000 1000 0000: executable
+0000 1000 0000 - 00c0 0000 0000: -
+00c0 0000 0000 - 00e0 0000 0000: heap
+00e0 0000 0000 - 2000 0000 0000: -
+2000 0000 0000 - 3000 0000 0000: shadow
+3000 0000 0000 - 3000 0000 0000: -
+3000 0000 0000 - 4000 0000 0000: metainfo (memory blocks and sync objects)
+4000 0000 0000 - 6000 0000 0000: -
+6000 0000 0000 - 6200 0000 0000: traces
+6200 0000 0000 - 8000 0000 0000: -
+*/
+struct Mapping47 {
+  static const uptr kMetaShadowBeg = 0x300000000000ull;
+  static const uptr kMetaShadowEnd = 0x400000000000ull;
+  static const uptr kTraceMemBeg = 0x600000000000ull;
+  static const uptr kTraceMemEnd = 0x620000000000ull;
+  static const uptr kShadowBeg = 0x200000000000ull;
+  static const uptr kShadowEnd = 0x300000000000ull;
+  static const uptr kAppMemBeg = 0x000000001000ull;
+  static const uptr kAppMemEnd = 0x00e000000000ull;
+};
+
+#define TSAN_RUNTIME_VMA 1
+
+#elif SANITIZER_GO && defined(__s390x__)
+/*
+Go on linux/s390x
+0000 0000 1000 - 1000 0000 0000: executable and heap - 16 TiB
+1000 0000 0000 - 4000 0000 0000: -
+4000 0000 0000 - 8000 0000 0000: shadow - 64TiB (4 * app)
+8000 0000 0000 - 9000 0000 0000: -
+9000 0000 0000 - 9800 0000 0000: metainfo - 8TiB (0.5 * app)
+9800 0000 0000 - a000 0000 0000: -
+a000 0000 0000 - b000 0000 0000: traces - 16TiB (max history * 128k threads)
+*/
+struct Mapping {
+  static const uptr kMetaShadowBeg = 0x900000000000ull;
+  static const uptr kMetaShadowEnd = 0x980000000000ull;
+  static const uptr kTraceMemBeg   = 0xa00000000000ull;
+  static const uptr kTraceMemEnd   = 0xb00000000000ull;
+  static const uptr kShadowBeg     = 0x400000000000ull;
+  static const uptr kShadowEnd     = 0x800000000000ull;
+  static const uptr kAppMemBeg     = 0x000000001000ull;
+  static const uptr kAppMemEnd     = 0x100000000000ull;
+};
+
 #else
 # error "Unknown platform"
 #endif
@@ -568,6 +662,16 @@ uptr MappingArchImpl(void) {
   }
   DCHECK(0);
   return 0;
+#elif defined(__mips64)
+  switch (vmaSize) {
+#if !SANITIZER_GO
+    case 40: return MappingImpl<Mapping40, Type>();
+#else
+    case 47: return MappingImpl<Mapping47, Type>();
+#endif
+  }
+  DCHECK(0);
+  return 0;
 #else
   return MappingImpl<Mapping, Type>();
 #endif
@@ -725,6 +829,16 @@ bool IsAppMem(uptr mem) {
   }
   DCHECK(0);
   return false;
+#elif defined(__mips64)
+  switch (vmaSize) {
+#if !SANITIZER_GO
+    case 40: return IsAppMemImpl<Mapping40>(mem);
+#else
+    case 47: return IsAppMemImpl<Mapping47>(mem);
+#endif
+  }
+  DCHECK(0);
+  return false;
 #else
   return IsAppMemImpl<Mapping>(mem);
 #endif
@@ -756,6 +870,16 @@ bool IsShadowMem(uptr mem) {
   }
   DCHECK(0);
   return false;
+#elif defined(__mips64)
+  switch (vmaSize) {
+#if !SANITIZER_GO
+    case 40: return IsShadowMemImpl<Mapping40>(mem);
+#else
+    case 47: return IsShadowMemImpl<Mapping47>(mem);
+#endif
+  }
+  DCHECK(0);
+  return false;
 #else
   return IsShadowMemImpl<Mapping>(mem);
 #endif
@@ -787,6 +911,16 @@ bool IsMetaMem(uptr mem) {
   }
   DCHECK(0);
   return false;
+#elif defined(__mips64)
+  switch (vmaSize) {
+#if !SANITIZER_GO
+    case 40: return IsMetaMemImpl<Mapping40>(mem);
+#else
+    case 47: return IsMetaMemImpl<Mapping47>(mem);
+#endif
+  }
+  DCHECK(0);
+  return false;
 #else
   return IsMetaMemImpl<Mapping>(mem);
 #endif
@@ -828,6 +962,16 @@ uptr MemToShadow(uptr x) {
   }
   DCHECK(0);
   return 0;
+#elif defined(__mips64)
+  switch (vmaSize) {
+#if !SANITIZER_GO
+    case 40: return MemToShadowImpl<Mapping40>(x);
+#else
+    case 47: return MemToShadowImpl<Mapping47>(x);
+#endif
+  }
+  DCHECK(0);
+  return 0;
 #else
   return MemToShadowImpl<Mapping>(x);
 #endif
@@ -871,6 +1015,16 @@ u32 *MemToMeta(uptr x) {
   }
   DCHECK(0);
   return 0;
+#elif defined(__mips64)
+  switch (vmaSize) {
+#if !SANITIZER_GO
+    case 40: return MemToMetaImpl<Mapping40>(x);
+#else
+    case 47: return MemToMetaImpl<Mapping47>(x);
+#endif
+  }
+  DCHECK(0);
+  return 0;
 #else
   return MemToMetaImpl<Mapping>(x);
 #endif
@@ -927,6 +1081,16 @@ uptr ShadowToMem(uptr s) {
   }
   DCHECK(0);
   return 0;
+#elif defined(__mips64)
+  switch (vmaSize) {
+#if !SANITIZER_GO
+    case 40: return ShadowToMemImpl<Mapping40>(s);
+#else
+    case 47: return ShadowToMemImpl<Mapping47>(s);
+#endif
+  }
+  DCHECK(0);
+  return 0;
 #else
   return ShadowToMemImpl<Mapping>(s);
 #endif
@@ -966,6 +1130,16 @@ uptr GetThreadTrace(int tid) {
   }
   DCHECK(0);
   return 0;
+#elif defined(__mips64)
+  switch (vmaSize) {
+#if !SANITIZER_GO
+    case 40: return GetThreadTraceImpl<Mapping40>(tid);
+#else
+    case 47: return GetThreadTraceImpl<Mapping47>(tid);
+#endif
+  }
+  DCHECK(0);
+  return 0;
 #else
   return GetThreadTraceImpl<Mapping>(tid);
 #endif
@@ -1000,6 +1174,16 @@ uptr GetThreadTraceHeader(int tid) {
   }
   DCHECK(0);
   return 0;
+#elif defined(__mips64)
+  switch (vmaSize) {
+#if !SANITIZER_GO
+    case 40: return GetThreadTraceHeaderImpl<Mapping40>(tid);
+#else
+    case 47: return GetThreadTraceHeaderImpl<Mapping47>(tid);
+#endif
+  }
+  DCHECK(0);
+  return 0;
 #else
   return GetThreadTraceHeaderImpl<Mapping>(tid);
 #endif
@@ -1016,9 +1200,8 @@ int ExtractRecvmsgFDs(void *msg, int *fds, int nfd);
 uptr ExtractLongJmpSp(uptr *env);
 void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size);
 
-int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
-    void *abstime), void *c, void *m, void *abstime,
-    void(*cleanup)(void *arg), void *arg);
+int call_pthread_cancel_with_cleanup(int (*fn)(void *arg),
+                                     void (*cleanup)(void *arg), void *arg);
 
 void DestroyThreadState();
 void PlatformCleanUpThreadState(ThreadState *thr);
lib/tsan/tsan_platform_linux.cpp
@@ -12,14 +12,12 @@
 //===----------------------------------------------------------------------===//
 
 #include "sanitizer_common/sanitizer_platform.h"
-#if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD || \
-    SANITIZER_OPENBSD
+#if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD
 
 #include "sanitizer_common/sanitizer_common.h"
 #include "sanitizer_common/sanitizer_libc.h"
 #include "sanitizer_common/sanitizer_linux.h"
 #include "sanitizer_common/sanitizer_platform_limits_netbsd.h"
-#include "sanitizer_common/sanitizer_platform_limits_openbsd.h"
 #include "sanitizer_common/sanitizer_platform_limits_posix.h"
 #include "sanitizer_common/sanitizer_posix.h"
 #include "sanitizer_common/sanitizer_procmaps.h"
@@ -252,6 +250,20 @@ void InitializePlatformEarly() {
     Die();
   }
 # endif
+#elif defined(__mips64)
+# if !SANITIZER_GO
+  if (vmaSize != 40) {
+    Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
+    Printf("FATAL: Found %zd - Supported 40\n", vmaSize);
+    Die();
+  }
+# else
+  if (vmaSize != 47) {
+    Printf("FATAL: ThreadSanitizer: unsupported VMA range\n");
+    Printf("FATAL: Found %zd - Supported 47\n", vmaSize);
+    Die();
+  }
+# endif
 #endif
 #endif
 }
@@ -379,22 +391,32 @@ static uptr UnmangleLongJmpSp(uptr mangled_sp) {
   return mangled_sp ^ xor_key;
 #elif defined(__mips__)
   return mangled_sp;
+#elif defined(__s390x__)
+  // tcbhead_t.stack_guard
+  uptr xor_key = ((uptr *)__builtin_thread_pointer())[5];
+  return mangled_sp ^ xor_key;
 #else
   #error "Unknown platform"
 #endif
 }
 
-#ifdef __powerpc__
+#if SANITIZER_NETBSD
+# ifdef __x86_64__
+#  define LONG_JMP_SP_ENV_SLOT 6
+# else
+#  error unsupported
+# endif
+#elif defined(__powerpc__)
 # define LONG_JMP_SP_ENV_SLOT 0
 #elif SANITIZER_FREEBSD
 # define LONG_JMP_SP_ENV_SLOT 2
-#elif SANITIZER_NETBSD
-# define LONG_JMP_SP_ENV_SLOT 6
 #elif SANITIZER_LINUX
 # ifdef __aarch64__
 #  define LONG_JMP_SP_ENV_SLOT 13
 # elif defined(__mips64)
 #  define LONG_JMP_SP_ENV_SLOT 1
+# elif defined(__s390x__)
+#  define LONG_JMP_SP_ENV_SLOT 9
 # else
 #  define LONG_JMP_SP_ENV_SLOT 6
 # endif
@@ -441,14 +463,13 @@ void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) {
 
 // Note: this function runs with async signals enabled,
 // so it must not touch any tsan state.
-int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
-    void *abstime), void *c, void *m, void *abstime,
-    void(*cleanup)(void *arg), void *arg) {
+int call_pthread_cancel_with_cleanup(int (*fn)(void *arg),
+                                     void (*cleanup)(void *arg), void *arg) {
   // pthread_cleanup_push/pop are hardcore macros mess.
   // We can't intercept nor call them w/o including pthread.h.
   int res;
   pthread_cleanup_push(cleanup, arg);
-  res = fn(c, m, abstime);
+  res = fn(arg);
   pthread_cleanup_pop(0);
   return res;
 }
@@ -482,7 +503,7 @@ ThreadState *cur_thread() {
         dead_thread_state->fast_state.SetIgnoreBit();
         dead_thread_state->ignore_interceptors = 1;
         dead_thread_state->is_dead = true;
-        *const_cast<int*>(&dead_thread_state->tid) = -1;
+        *const_cast<u32*>(&dead_thread_state->tid) = -1;
         CHECK_EQ(0, internal_mprotect(dead_thread_state, sizeof(ThreadState),
                                       PROT_READ));
       }
@@ -513,5 +534,4 @@ void cur_thread_finalize() {
 
 }  // namespace __tsan
 
-#endif  // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD ||
-        // SANITIZER_OPENBSD
+#endif  // SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD
lib/tsan/tsan_platform_mac.cpp
@@ -234,7 +234,7 @@ static void my_pthread_introspection_hook(unsigned int event, pthread_t thread,
 #endif
 
 void InitializePlatformEarly() {
-#if defined(__aarch64__)
+#if !SANITIZER_GO && !HAS_48_BIT_ADDRESS_SPACE
   uptr max_vm = GetMaxUserVirtualAddress() + 1;
   if (max_vm != Mapping::kHiAppMemEnd) {
     Printf("ThreadSanitizer: unsupported vm address limit %p, expected %p.\n",
@@ -306,14 +306,13 @@ void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) {
 #if !SANITIZER_GO
 // Note: this function runs with async signals enabled,
 // so it must not touch any tsan state.
-int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m,
-    void *abstime), void *c, void *m, void *abstime,
-    void(*cleanup)(void *arg), void *arg) {
+int call_pthread_cancel_with_cleanup(int (*fn)(void *arg),
+                                     void (*cleanup)(void *arg), void *arg) {
   // pthread_cleanup_push/pop are hardcore macros mess.
   // We can't intercept nor call them w/o including pthread.h.
   int res;
   pthread_cleanup_push(cleanup, arg);
-  res = fn(c, m, abstime);
+  res = fn(arg);
   pthread_cleanup_pop(0);
   return res;
 }
lib/tsan/tsan_platform_posix.cpp
@@ -29,10 +29,6 @@ static const char kShadowMemoryMappingHint[] =
     "HINT: if %s is not supported in your environment, you may set "
     "TSAN_OPTIONS=%s=0\n";
 
-static void NoHugePagesInShadow(uptr addr, uptr size) {
-  SetShadowRegionHugePageMode(addr, size);
-}
-
 static void DontDumpShadow(uptr addr, uptr size) {
   if (common_flags()->use_madv_dontdump)
     if (!DontDumpShadowMemory(addr, size)) {
@@ -46,7 +42,8 @@ static void DontDumpShadow(uptr addr, uptr size) {
 #if !SANITIZER_GO
 void InitializeShadowMemory() {
   // Map memory shadow.
-  if (!MmapFixedNoReserve(ShadowBeg(), ShadowEnd() - ShadowBeg(), "shadow")) {
+  if (!MmapFixedSuperNoReserve(ShadowBeg(), ShadowEnd() - ShadowBeg(),
+                               "shadow")) {
     Printf("FATAL: ThreadSanitizer can not mmap the shadow memory\n");
     Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
     Die();
@@ -55,43 +52,6 @@ void InitializeShadowMemory() {
   // Frequently a thread uses only a small part of stack and similarly
   // a program uses a small part of large mmap. On some programs
   // we see 20% memory usage reduction without huge pages for this range.
-  // FIXME: don't use constants here.
-#if defined(__x86_64__)
-  const uptr kMadviseRangeBeg  = 0x7f0000000000ull;
-  const uptr kMadviseRangeSize = 0x010000000000ull;
-#elif defined(__mips64)
-  const uptr kMadviseRangeBeg  = 0xff00000000ull;
-  const uptr kMadviseRangeSize = 0x0100000000ull;
-#elif defined(__aarch64__) && defined(__APPLE__)
-  uptr kMadviseRangeBeg = LoAppMemBeg();
-  uptr kMadviseRangeSize = LoAppMemEnd() - LoAppMemBeg();
-#elif defined(__aarch64__)
-  uptr kMadviseRangeBeg = 0;
-  uptr kMadviseRangeSize = 0;
-  if (vmaSize == 39) {
-    kMadviseRangeBeg  = 0x7d00000000ull;
-    kMadviseRangeSize = 0x0300000000ull;
-  } else if (vmaSize == 42) {
-    kMadviseRangeBeg  = 0x3f000000000ull;
-    kMadviseRangeSize = 0x01000000000ull;
-  } else {
-    DCHECK(0);
-  }
-#elif defined(__powerpc64__)
-  uptr kMadviseRangeBeg = 0;
-  uptr kMadviseRangeSize = 0;
-  if (vmaSize == 44) {
-    kMadviseRangeBeg  = 0x0f60000000ull;
-    kMadviseRangeSize = 0x0010000000ull;
-  } else if (vmaSize == 46) {
-    kMadviseRangeBeg  = 0x3f0000000000ull;
-    kMadviseRangeSize = 0x010000000000ull;
-  } else {
-    DCHECK(0);
-  }
-#endif
-  NoHugePagesInShadow(MemToShadow(kMadviseRangeBeg),
-                      kMadviseRangeSize * kShadowMultiplier);
   DontDumpShadow(ShadowBeg(), ShadowEnd() - ShadowBeg());
   DPrintf("memory shadow: %zx-%zx (%zuGB)\n",
       ShadowBeg(), ShadowEnd(),
@@ -100,12 +60,11 @@ void InitializeShadowMemory() {
   // Map meta shadow.
   const uptr meta = MetaShadowBeg();
   const uptr meta_size = MetaShadowEnd() - meta;
-  if (!MmapFixedNoReserve(meta, meta_size, "meta shadow")) {
+  if (!MmapFixedSuperNoReserve(meta, meta_size, "meta shadow")) {
     Printf("FATAL: ThreadSanitizer can not mmap the shadow memory\n");
     Printf("FATAL: Make sure to compile with -fPIE and to link with -pie.\n");
     Die();
   }
-  NoHugePagesInShadow(meta, meta_size);
   DontDumpShadow(meta, meta_size);
   DPrintf("meta shadow: %zx-%zx (%zuGB)\n",
       meta, meta + meta_size, meta_size >> 30);
@@ -113,11 +72,15 @@ void InitializeShadowMemory() {
   InitializeShadowMemoryPlatform();
 }
 
-static void ProtectRange(uptr beg, uptr end) {
+static bool TryProtectRange(uptr beg, uptr end) {
   CHECK_LE(beg, end);
   if (beg == end)
-    return;
-  if (beg != (uptr)MmapFixedNoAccess(beg, end - beg)) {
+    return true;
+  return beg == (uptr)MmapFixedNoAccess(beg, end - beg);
+}
+
+static void ProtectRange(uptr beg, uptr end) {
+  if (!TryProtectRange(beg, end)) {
     Printf("FATAL: ThreadSanitizer can not protect [%zx,%zx]\n", beg, end);
     Printf("FATAL: Make sure you are not using unlimited stack\n");
     Die();
@@ -140,7 +103,7 @@ void CheckAndProtect() {
     Die();
   }
 
-#if defined(__aarch64__) && defined(__APPLE__)
+#if defined(__aarch64__) && defined(__APPLE__) && !HAS_48_BIT_ADDRESS_SPACE
   ProtectRange(HeapMemEnd(), ShadowBeg());
   ProtectRange(ShadowEnd(), MetaShadowBeg());
   ProtectRange(MetaShadowEnd(), TraceMemBeg());
@@ -159,6 +122,16 @@ void CheckAndProtect() {
   ProtectRange(TraceMemEnd(), HeapMemBeg());
   ProtectRange(HeapEnd(), HiAppMemBeg());
 #endif
+
+#if defined(__s390x__)
+  // Protect the rest of the address space.
+  const uptr user_addr_max_l4 = 0x0020000000000000ull;
+  const uptr user_addr_max_l5 = 0xfffffffffffff000ull;
+  // All the maintained s390x kernels support at least 4-level page tables.
+  ProtectRange(HiAppMemEnd(), user_addr_max_l4);
+  // Older s390x kernels may not support 5-level page tables.
+  TryProtectRange(user_addr_max_l4, user_addr_max_l5);
+#endif
 }
 #endif
 
lib/tsan/tsan_report.cpp
@@ -69,7 +69,7 @@ ReportDesc::~ReportDesc() {
 
 const int kThreadBufSize = 32;
 const char *thread_name(char *buf, int tid) {
-  if (tid == 0)
+  if (tid == kMainTid)
     return "main thread";
   internal_snprintf(buf, kThreadBufSize, "thread T%d", tid);
   return buf;
@@ -127,8 +127,9 @@ void PrintStack(const ReportStack *ent) {
   }
   SymbolizedStack *frame = ent->frames;
   for (int i = 0; frame && frame->info.address; frame = frame->next, i++) {
-    InternalScopedString res(2 * GetPageSizeCached());
-    RenderFrame(&res, common_flags()->stack_trace_format, i, frame->info,
+    InternalScopedString res;
+    RenderFrame(&res, common_flags()->stack_trace_format, i,
+                frame->info.address, &frame->info,
                 common_flags()->symbolize_vs_style,
                 common_flags()->strip_path_prefix, kInterposedFunctionPrefix);
     Printf("%s\n", res.data());
@@ -249,7 +250,7 @@ static void PrintMutex(const ReportMutex *rm) {
 
 static void PrintThread(const ReportThread *rt) {
   Decorator d;
-  if (rt->id == 0)  // Little sense in describing the main thread.
+  if (rt->id == kMainTid)  // Little sense in describing the main thread.
     return;
   Printf("%s", d.ThreadDescription());
   Printf("  Thread T%d", rt->id);
@@ -385,14 +386,15 @@ void PrintReport(const ReportDesc *rep) {
       ReportErrorSummary(rep_typ_str, frame->info);
   }
 
-  if (common_flags()->print_module_map == 2) PrintModuleMap();
+  if (common_flags()->print_module_map == 2)
+    DumpProcessMap();
 
   Printf("==================\n");
 }
 
 #else  // #if !SANITIZER_GO
 
-const int kMainThreadId = 1;
+const u32 kMainGoroutineId = 1;
 
 void PrintStack(const ReportStack *ent) {
   if (ent == 0 || ent->frames == 0) {
@@ -413,7 +415,7 @@ static void PrintMop(const ReportMop *mop, bool first) {
   Printf("%s at %p by ",
       (first ? (mop->write ? "Write" : "Read")
              : (mop->write ? "Previous write" : "Previous read")), mop->addr);
-  if (mop->tid == kMainThreadId)
+  if (mop->tid == kMainGoroutineId)
     Printf("main goroutine:\n");
   else
     Printf("goroutine %d:\n", mop->tid);
@@ -426,7 +428,7 @@ static void PrintLocation(const ReportLocation *loc) {
     Printf("\n");
     Printf("Heap block of size %zu at %p allocated by ",
         loc->heap_chunk_size, loc->heap_chunk_start);
-    if (loc->tid == kMainThreadId)
+    if (loc->tid == kMainGoroutineId)
       Printf("main goroutine:\n");
     else
       Printf("goroutine %d:\n", loc->tid);
@@ -446,7 +448,7 @@ static void PrintLocation(const ReportLocation *loc) {
 }
 
 static void PrintThread(const ReportThread *rt) {
-  if (rt->id == kMainThreadId)
+  if (rt->id == kMainGoroutineId)
     return;
   Printf("\n");
   Printf("Goroutine %d (%s) created at:\n",
lib/tsan/tsan_rtl.cpp
@@ -11,17 +11,19 @@
 // Main file (entry points) for the TSan run-time.
 //===----------------------------------------------------------------------===//
 
+#include "tsan_rtl.h"
+
 #include "sanitizer_common/sanitizer_atomic.h"
 #include "sanitizer_common/sanitizer_common.h"
 #include "sanitizer_common/sanitizer_file.h"
 #include "sanitizer_common/sanitizer_libc.h"
-#include "sanitizer_common/sanitizer_stackdepot.h"
 #include "sanitizer_common/sanitizer_placement_new.h"
+#include "sanitizer_common/sanitizer_stackdepot.h"
 #include "sanitizer_common/sanitizer_symbolizer.h"
 #include "tsan_defs.h"
-#include "tsan_platform.h"
-#include "tsan_rtl.h"
+#include "tsan_interface.h"
 #include "tsan_mman.h"
+#include "tsan_platform.h"
 #include "tsan_suppressions.h"
 #include "tsan_symbolize.h"
 #include "ubsan/ubsan_init.h"
@@ -56,15 +58,26 @@ Context *ctx;
 bool OnFinalize(bool failed);
 void OnInitialize();
 #else
+#include <dlfcn.h>
 SANITIZER_WEAK_CXX_DEFAULT_IMPL
 bool OnFinalize(bool failed) {
+#if !SANITIZER_GO
+  if (auto *ptr = dlsym(RTLD_DEFAULT, "__tsan_on_finalize"))
+    return reinterpret_cast<decltype(&__tsan_on_finalize)>(ptr)(failed);
+#endif
   return failed;
 }
 SANITIZER_WEAK_CXX_DEFAULT_IMPL
-void OnInitialize() {}
+void OnInitialize() {
+#if !SANITIZER_GO
+  if (auto *ptr = dlsym(RTLD_DEFAULT, "__tsan_on_initialize")) {
+    return reinterpret_cast<decltype(&__tsan_on_initialize)>(ptr)();
+  }
+#endif
+}
 #endif
 
-static char thread_registry_placeholder[sizeof(ThreadRegistry)];
+static ALIGNED(64) char thread_registry_placeholder[sizeof(ThreadRegistry)];
 
 static ThreadContextBase *CreateThreadContext(u32 tid) {
   // Map thread trace when context is created.
@@ -77,12 +90,19 @@ static ThreadContextBase *CreateThreadContext(u32 tid) {
   new((void*)hdr) Trace();
   // We are going to use only a small part of the trace with the default
   // value of history_size. However, the constructor writes to the whole trace.
-  // Unmap the unused part.
+  // Release the unused part.
   uptr hdr_end = hdr + sizeof(Trace);
   hdr_end -= sizeof(TraceHeader) * (kTraceParts - TraceParts());
   hdr_end = RoundUp(hdr_end, GetPageSizeCached());
-  if (hdr_end < hdr + sizeof(Trace))
-    UnmapOrDie((void*)hdr_end, hdr + sizeof(Trace) - hdr_end);
+  if (hdr_end < hdr + sizeof(Trace)) {
+    ReleaseMemoryPagesToOS(hdr_end, hdr + sizeof(Trace));
+    uptr unused = hdr + sizeof(Trace) - hdr_end;
+    if (hdr_end != (uptr)MmapFixedNoAccess(hdr_end, unused)) {
+      Report("ThreadSanitizer: failed to mprotect(%p, %p)\n",
+          hdr_end, unused);
+      CHECK("unable to mprotect" && 0);
+    }
+  }
   void *mem = internal_alloc(MBlockThreadContex, sizeof(ThreadContext));
   return new(mem) ThreadContext(tid);
 }
@@ -94,42 +114,45 @@ static const u32 kThreadQuarantineSize = 64;
 #endif
 
 Context::Context()
-  : initialized()
-  , report_mtx(MutexTypeReport, StatMtxReport)
-  , nreported()
-  , nmissed_expected()
-  , thread_registry(new(thread_registry_placeholder) ThreadRegistry(
-      CreateThreadContext, kMaxTid, kThreadQuarantineSize, kMaxTidReuse))
-  , racy_mtx(MutexTypeRacy, StatMtxRacy)
-  , racy_stacks()
-  , racy_addresses()
-  , fired_suppressions_mtx(MutexTypeFired, StatMtxFired)
-  , clock_alloc("clock allocator") {
+    : initialized(),
+      report_mtx(MutexTypeReport),
+      nreported(),
+      nmissed_expected(),
+      thread_registry(new (thread_registry_placeholder) ThreadRegistry(
+          CreateThreadContext, kMaxTid, kThreadQuarantineSize, kMaxTidReuse)),
+      racy_mtx(MutexTypeRacy),
+      racy_stacks(),
+      racy_addresses(),
+      fired_suppressions_mtx(MutexTypeFired),
+      clock_alloc(LINKER_INITIALIZED, "clock allocator") {
   fired_suppressions.reserve(8);
 }
 
 // The objects are allocated in TLS, so one may rely on zero-initialization.
-ThreadState::ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
-                         unsigned reuse_count,
-                         uptr stk_addr, uptr stk_size,
+ThreadState::ThreadState(Context *ctx, u32 tid, int unique_id, u64 epoch,
+                         unsigned reuse_count, uptr stk_addr, uptr stk_size,
                          uptr tls_addr, uptr tls_size)
-  : fast_state(tid, epoch)
-  // Do not touch these, rely on zero initialization,
-  // they may be accessed before the ctor.
-  // , ignore_reads_and_writes()
-  // , ignore_interceptors()
-  , clock(tid, reuse_count)
+    : fast_state(tid, epoch)
+      // Do not touch these, rely on zero initialization,
+      // they may be accessed before the ctor.
+      // , ignore_reads_and_writes()
+      // , ignore_interceptors()
+      ,
+      clock(tid, reuse_count)
 #if !SANITIZER_GO
-  , jmp_bufs()
+      ,
+      jmp_bufs()
 #endif
-  , tid(tid)
-  , unique_id(unique_id)
-  , stk_addr(stk_addr)
-  , stk_size(stk_size)
-  , tls_addr(tls_addr)
-  , tls_size(tls_size)
+      ,
+      tid(tid),
+      unique_id(unique_id),
+      stk_addr(stk_addr),
+      stk_size(stk_size),
+      tls_addr(tls_addr),
+      tls_size(tls_size)
 #if !SANITIZER_GO
-  , last_sleep_clock(tid)
+      ,
+      last_sleep_clock(tid)
 #endif
 {
 }
@@ -160,12 +183,12 @@ static void *BackgroundThread(void *arg) {
     } else if (internal_strcmp(flags()->profile_memory, "stderr") == 0) {
       mprof_fd = 2;
     } else {
-      InternalScopedString filename(kMaxPathLength);
+      InternalScopedString filename;
       filename.append("%s.%d", flags()->profile_memory, (int)internal_getpid());
       fd_t fd = OpenFile(filename.data(), WrOnly);
       if (fd == kInvalidFd) {
         Printf("ThreadSanitizer: failed to open memory profile file '%s'\n",
-            &filename[0]);
+               filename.data());
       } else {
         mprof_fd = fd;
       }
@@ -256,7 +279,8 @@ void MapShadow(uptr addr, uptr size) {
   const uptr kPageSize = GetPageSizeCached();
   uptr shadow_begin = RoundDownTo((uptr)MemToShadow(addr), kPageSize);
   uptr shadow_end = RoundUpTo((uptr)MemToShadow(addr + size), kPageSize);
-  if (!MmapFixedNoReserve(shadow_begin, shadow_end - shadow_begin, "shadow"))
+  if (!MmapFixedSuperNoReserve(shadow_begin, shadow_end - shadow_begin,
+                               "shadow"))
     Die();
 
   // Meta shadow is 2:1, so tread carefully.
@@ -269,7 +293,8 @@ void MapShadow(uptr addr, uptr size) {
   if (!data_mapped) {
     // First call maps data+bss.
     data_mapped = true;
-    if (!MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow"))
+    if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
+                                 "meta shadow"))
       Die();
   } else {
     // Mapping continous heap.
@@ -280,7 +305,8 @@ void MapShadow(uptr addr, uptr size) {
       return;
     if (meta_begin < mapped_meta_end)
       meta_begin = mapped_meta_end;
-    if (!MmapFixedNoReserve(meta_begin, meta_end - meta_begin, "meta shadow"))
+    if (!MmapFixedSuperNoReserve(meta_begin, meta_end - meta_begin,
+                                 "meta shadow"))
       Die();
     mapped_meta_end = meta_end;
   }
@@ -293,7 +319,7 @@ void MapThreadTrace(uptr addr, uptr size, const char *name) {
   CHECK_GE(addr, TraceMemBeg());
   CHECK_LE(addr + size, TraceMemEnd());
   CHECK_EQ(addr, addr & ~((64 << 10) - 1));  // windows wants 64K alignment
-  if (!MmapFixedNoReserve(addr, size, name)) {
+  if (!MmapFixedSuperNoReserve(addr, size, name)) {
     Printf("FATAL: ThreadSanitizer can not mmap thread trace (%p/%p)\n",
         addr, size);
     Die();
@@ -348,6 +374,18 @@ static void TsanOnDeadlySignal(int signo, void *siginfo, void *context) {
 }
 #endif
 
+void CheckUnwind() {
+  // There is high probability that interceptors will check-fail as well,
+  // on the other hand there is no sense in processing interceptors
+  // since we are going to die soon.
+  ScopedIgnoreInterceptors ignore;
+#if !SANITIZER_GO
+  cur_thread()->ignore_sync++;
+  cur_thread()->ignore_reads_and_writes++;
+#endif
+  PrintCurrentStackSlow(StackTrace::GetCurrentPc());
+}
+
 void Initialize(ThreadState *thr) {
   // Thread safe because done before all threads exist.
   static bool is_initialized = false;
@@ -358,7 +396,7 @@ void Initialize(ThreadState *thr) {
   ScopedIgnoreInterceptors ignore;
   SanitizerToolName = "ThreadSanitizer";
   // Install tool-specific callbacks in sanitizer_common.
-  SetCheckFailedCallback(TsanCheckFailed);
+  SetCheckUnwindCallback(CheckUnwind);
 
   ctx = new(ctx_placeholder) Context;
   const char *env_name = SANITIZER_GO ? "GORACE" : "TSAN_OPTIONS";
@@ -384,7 +422,6 @@ void Initialize(ThreadState *thr) {
   InitializeInterceptors();
   CheckShadowMapping();
   InitializePlatform();
-  InitializeMutex();
   InitializeDynamicAnnotations();
 #if !SANITIZER_GO
   InitializeShadowMemory();
@@ -443,7 +480,8 @@ void MaybeSpawnBackgroundThread() {
 int Finalize(ThreadState *thr) {
   bool failed = false;
 
-  if (common_flags()->print_module_map == 1) PrintModuleMap();
+  if (common_flags()->print_module_map == 1)
+    DumpProcessMap();
 
   if (flags()->atexit_sleep_ms > 0 && ThreadCount(thr) > 1)
     SleepForMillis(flags()->atexit_sleep_ms);
@@ -483,35 +521,37 @@ int Finalize(ThreadState *thr) {
 
   failed = OnFinalize(failed);
 
-#if TSAN_COLLECT_STATS
-  StatAggregate(ctx->stat, thr->stat);
-  StatOutput(ctx->stat);
-#endif
-
   return failed ? common_flags()->exitcode : 0;
 }
 
 #if !SANITIZER_GO
-void ForkBefore(ThreadState *thr, uptr pc) {
+void ForkBefore(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS {
   ctx->thread_registry->Lock();
   ctx->report_mtx.Lock();
-  // Ignore memory accesses in the pthread_atfork callbacks.
-  // If any of them triggers a data race we will deadlock
-  // on the report_mtx.
-  // We could ignore interceptors and sync operations as well,
+  ScopedErrorReportLock::Lock();
+  // Suppress all reports in the pthread_atfork callbacks.
+  // Reports will deadlock on the report_mtx.
+  // We could ignore sync operations as well,
   // but so far it's unclear if it will do more good or harm.
   // Unnecessarily ignoring things can lead to false positives later.
-  ThreadIgnoreBegin(thr, pc);
+  thr->suppress_reports++;
+  // On OS X, REAL(fork) can call intercepted functions (OSSpinLockLock), and
+  // we'll assert in CheckNoLocks() unless we ignore interceptors.
+  thr->ignore_interceptors++;
 }
 
-void ForkParentAfter(ThreadState *thr, uptr pc) {
-  ThreadIgnoreEnd(thr, pc);  // Begin is in ForkBefore.
+void ForkParentAfter(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS {
+  thr->suppress_reports--;  // Enabled in ForkBefore.
+  thr->ignore_interceptors--;
+  ScopedErrorReportLock::Unlock();
   ctx->report_mtx.Unlock();
   ctx->thread_registry->Unlock();
 }
 
-void ForkChildAfter(ThreadState *thr, uptr pc) {
-  ThreadIgnoreEnd(thr, pc);  // Begin is in ForkBefore.
+void ForkChildAfter(ThreadState *thr, uptr pc) NO_THREAD_SAFETY_ANALYSIS {
+  thr->suppress_reports--;  // Enabled in ForkBefore.
+  thr->ignore_interceptors--;
+  ScopedErrorReportLock::Unlock();
   ctx->report_mtx.Unlock();
   ctx->thread_registry->Unlock();
 
@@ -650,9 +690,6 @@ ALWAYS_INLINE
 void MemoryAccessImpl1(ThreadState *thr, uptr addr,
     int kAccessSizeLog, bool kAccessIsWrite, bool kIsAtomic,
     u64 *shadow_mem, Shadow cur) {
-  StatInc(thr, StatMop);
-  StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
-  StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
 
   // This potentially can live in an MMX/SSE scratch register.
   // The required intrinsics are:
@@ -709,7 +746,6 @@ void MemoryAccessImpl1(ThreadState *thr, uptr addr,
     return;
   // choose a random candidate slot and replace it
   StoreShadow(shadow_mem + (cur.epoch() % kShadowCnt), store_word);
-  StatInc(thr, StatShadowReplace);
   return;
  RACE:
   HandleRace(thr, shadow_mem, cur, old);
@@ -848,19 +884,11 @@ void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
   if (!SANITIZER_GO && !kAccessIsWrite && *shadow_mem == kShadowRodata) {
     // Access to .rodata section, no races here.
     // Measurements show that it can be 10-20% of all memory accesses.
-    StatInc(thr, StatMop);
-    StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
-    StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
-    StatInc(thr, StatMopRodata);
     return;
   }
 
   FastState fast_state = thr->fast_state;
   if (UNLIKELY(fast_state.GetIgnoreBit())) {
-    StatInc(thr, StatMop);
-    StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
-    StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
-    StatInc(thr, StatMopIgnored);
     return;
   }
 
@@ -871,10 +899,6 @@ void MemoryAccess(ThreadState *thr, uptr pc, uptr addr,
 
   if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
       thr->fast_synch_epoch, kAccessIsWrite))) {
-    StatInc(thr, StatMop);
-    StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
-    StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
-    StatInc(thr, StatMopSame);
     return;
   }
 
@@ -896,10 +920,6 @@ void MemoryAccessImpl(ThreadState *thr, uptr addr,
     u64 *shadow_mem, Shadow cur) {
   if (LIKELY(ContainsSameAccess(shadow_mem, cur.raw(),
       thr->fast_synch_epoch, kAccessIsWrite))) {
-    StatInc(thr, StatMop);
-    StatInc(thr, kAccessIsWrite ? StatMopWrite : StatMopRead);
-    StatInc(thr, (StatType)(StatMop1 + kAccessSizeLog));
-    StatInc(thr, StatMopSame);
     return;
   }
 
@@ -956,8 +976,7 @@ static void MemoryRangeSet(ThreadState *thr, uptr pc, uptr addr, uptr size,
     // Reset middle part.
     u64 *p1 = p;
     p = RoundDown(end, kPageSize);
-    UnmapOrDie((void*)p1, (uptr)p - (uptr)p1);
-    if (!MmapFixedNoReserve((uptr)p1, (uptr)p - (uptr)p1))
+    if (!MmapFixedSuperNoReserve((uptr)p1, (uptr)p - (uptr)p1))
       Die();
     // Set the ending.
     while (p < end) {
@@ -1016,7 +1035,6 @@ void MemoryRangeImitateWriteOrResetRange(ThreadState *thr, uptr pc, uptr addr,
 
 ALWAYS_INLINE USED
 void FuncEntry(ThreadState *thr, uptr pc) {
-  StatInc(thr, StatFuncEnter);
   DPrintf2("#%d: FuncEntry %p\n", (int)thr->fast_state.tid(), (void*)pc);
   if (kCollectHistory) {
     thr->fast_state.IncrementEpoch();
@@ -1038,7 +1056,6 @@ void FuncEntry(ThreadState *thr, uptr pc) {
 
 ALWAYS_INLINE USED
 void FuncExit(ThreadState *thr) {
-  StatInc(thr, StatFuncExit);
   DPrintf2("#%d: FuncExit\n", (int)thr->fast_state.tid());
   if (kCollectHistory) {
     thr->fast_state.IncrementEpoch();
@@ -1113,15 +1130,30 @@ void build_consistency_debug() {}
 void build_consistency_release() {}
 #endif
 
-#if TSAN_COLLECT_STATS
-void build_consistency_stats() {}
-#else
-void build_consistency_nostats() {}
-#endif
-
 }  // namespace __tsan
 
+#if SANITIZER_CHECK_DEADLOCKS
+namespace __sanitizer {
+using namespace __tsan;
+MutexMeta mutex_meta[] = {
+    {MutexInvalid, "Invalid", {}},
+    {MutexThreadRegistry, "ThreadRegistry", {}},
+    {MutexTypeTrace, "Trace", {MutexLeaf}},
+    {MutexTypeReport, "Report", {MutexTypeSyncVar}},
+    {MutexTypeSyncVar, "SyncVar", {}},
+    {MutexTypeAnnotations, "Annotations", {}},
+    {MutexTypeAtExit, "AtExit", {MutexTypeSyncVar}},
+    {MutexTypeFired, "Fired", {MutexLeaf}},
+    {MutexTypeRacy, "Racy", {MutexLeaf}},
+    {MutexTypeGlobalProc, "GlobalProc", {}},
+    {},
+};
+
+void PrintMutexPC(uptr pc) { StackTrace(&pc, 1).Print(); }
+}  // namespace __sanitizer
+#endif
+
 #if !SANITIZER_GO
 // Must be included in this file to make sure everything is inlined.
-#include "tsan_interface_inl.h"
+#  include "tsan_interface_inl.h"
 #endif
lib/tsan/tsan_rtl.h
@@ -84,9 +84,6 @@ typedef Allocator::AllocatorCache AllocatorCache;
 Allocator *allocator();
 #endif
 
-void TsanCheckFailed(const char *file, int line, const char *cond,
-                     u64 v1, u64 v2);
-
 const u64 kShadowRodata = (u64)-1;  // .rodata shadow marker
 
 // FastState (from most significant bit):
@@ -403,10 +400,7 @@ struct ThreadState {
   Vector<JmpBuf> jmp_bufs;
   int ignore_interceptors;
 #endif
-#if TSAN_COLLECT_STATS
-  u64 stat[StatCnt];
-#endif
-  const int tid;
+  const u32 tid;
   const int unique_id;
   bool in_symbolizer;
   bool in_ignored_lib;
@@ -420,9 +414,6 @@ struct ThreadState {
   const uptr tls_size;
   ThreadContext *tctx;
 
-#if SANITIZER_DEBUG && !SANITIZER_GO
-  InternalDeadlockDetector internal_deadlock_detector;
-#endif
   DDLogicalThread *dd_lt;
 
   // Current wired Processor, or nullptr. Required to handle any events.
@@ -447,9 +438,8 @@ struct ThreadState {
 
   const ReportDesc *current_report;
 
-  explicit ThreadState(Context *ctx, int tid, int unique_id, u64 epoch,
-                       unsigned reuse_count,
-                       uptr stk_addr, uptr stk_size,
+  explicit ThreadState(Context *ctx, u32 tid, int unique_id, u64 epoch,
+                       unsigned reuse_count, uptr stk_addr, uptr stk_size,
                        uptr tls_addr, uptr tls_size);
 };
 
@@ -458,26 +448,26 @@ struct ThreadState {
 ThreadState *cur_thread();
 void set_cur_thread(ThreadState *thr);
 void cur_thread_finalize();
-INLINE void cur_thread_init() { }
+inline void cur_thread_init() { }
 #else
 __attribute__((tls_model("initial-exec")))
 extern THREADLOCAL char cur_thread_placeholder[];
-INLINE ThreadState *cur_thread() {
+inline ThreadState *cur_thread() {
   return reinterpret_cast<ThreadState *>(cur_thread_placeholder)->current;
 }
-INLINE void cur_thread_init() {
+inline void cur_thread_init() {
   ThreadState *thr = reinterpret_cast<ThreadState *>(cur_thread_placeholder);
   if (UNLIKELY(!thr->current))
     thr->current = thr;
 }
-INLINE void set_cur_thread(ThreadState *thr) {
+inline void set_cur_thread(ThreadState *thr) {
   reinterpret_cast<ThreadState *>(cur_thread_placeholder)->current = thr;
 }
-INLINE void cur_thread_finalize() { }
+inline void cur_thread_finalize() { }
 #endif  // SANITIZER_MAC || SANITIZER_ANDROID
 #endif  // SANITIZER_GO
 
-class ThreadContext : public ThreadContextBase {
+class ThreadContext final : public ThreadContextBase {
  public:
   explicit ThreadContext(int tid);
   ~ThreadContext();
@@ -554,7 +544,6 @@ struct Context {
 
   Flags flags;
 
-  u64 stat[StatCnt];
   u64 int_alloc_cnt[MBlockTypeCount];
   u64 int_alloc_siz[MBlockTypeCount];
 };
@@ -624,6 +613,7 @@ class ScopedReport : public ScopedReportBase {
   ScopedErrorReportLock lock_;
 };
 
+bool ShouldReport(ThreadState *thr, ReportType typ);
 ThreadContext *IsThreadStackOrTls(uptr addr, bool *is_stack);
 void RestoreStack(int tid, const u64 epoch, VarSizeStackTrace *stk,
                   MutexSet *mset, uptr *tag = nullptr);
@@ -661,22 +651,6 @@ void ObtainCurrentStack(ThreadState *thr, uptr toppc, StackTraceTy *stack,
   ObtainCurrentStack(thr, pc, &stack); \
   stack.ReverseOrder();
 
-#if TSAN_COLLECT_STATS
-void StatAggregate(u64 *dst, u64 *src);
-void StatOutput(u64 *stat);
-#endif
-
-void ALWAYS_INLINE StatInc(ThreadState *thr, StatType typ, u64 n = 1) {
-#if TSAN_COLLECT_STATS
-  thr->stat[typ] += n;
-#endif
-}
-void ALWAYS_INLINE StatSet(ThreadState *thr, StatType typ, u64 n) {
-#if TSAN_COLLECT_STATS
-  thr->stat[typ] = n;
-#endif
-}
-
 void MapShadow(uptr addr, uptr size);
 void MapThreadTrace(uptr addr, uptr size, const char *name);
 void DontNeedShadowFor(uptr addr, uptr size);
@@ -857,7 +831,6 @@ void ALWAYS_INLINE TraceAddEvent(ThreadState *thr, FastState fs,
   DCHECK_GE((int)typ, 0);
   DCHECK_LE((int)typ, 7);
   DCHECK_EQ(GetLsb(addr, kEventPCBits), addr);
-  StatInc(thr, StatEvents);
   u64 pos = fs.GetTracePos();
   if (UNLIKELY((pos % kTracePartSize) == 0)) {
 #if !SANITIZER_GO
lib/tsan/tsan_rtl_mutex.cpp
@@ -24,7 +24,7 @@ namespace __tsan {
 
 void ReportDeadlock(ThreadState *thr, uptr pc, DDReport *r);
 
-struct Callback : DDCallback {
+struct Callback final : public DDCallback {
   ThreadState *thr;
   uptr pc;
 
@@ -51,6 +51,8 @@ static void ReportMutexMisuse(ThreadState *thr, uptr pc, ReportType typ,
   // or false positives (e.g. unlock in a different thread).
   if (SANITIZER_GO)
     return;
+  if (!ShouldReport(thr, typ))
+    return;
   ThreadRegistryLock l(ctx->thread_registry);
   ScopedReport rep(typ);
   rep.AddMutex(mid);
@@ -61,9 +63,8 @@ static void ReportMutexMisuse(ThreadState *thr, uptr pc, ReportType typ,
   OutputReport(thr, rep);
 }
 
-void MutexCreate(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
+void MutexCreate(ThreadState *thr, uptr pc, uptr addr, u32 flagz) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexCreate %zx flagz=0x%x\n", thr->tid, addr, flagz);
-  StatInc(thr, StatMutexCreate);
   if (!(flagz & MutexFlagLinkerInit) && IsAppMem(addr)) {
     CHECK(!thr->is_freeing);
     thr->is_freeing = true;
@@ -77,9 +78,8 @@ void MutexCreate(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
   s->mtx.Unlock();
 }
 
-void MutexDestroy(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
+void MutexDestroy(ThreadState *thr, uptr pc, uptr addr, u32 flagz) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexDestroy %zx\n", thr->tid, addr);
-  StatInc(thr, StatMutexDestroy);
   SyncVar *s = ctx->metamap.GetIfExistsAndLock(addr, true);
   if (s == 0)
     return;
@@ -96,9 +96,8 @@ void MutexDestroy(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
     ctx->dd->MutexInit(&cb, &s->dd);
   }
   bool unlock_locked = false;
-  if (flags()->report_destroy_locked
-      && s->owner_tid != SyncVar::kInvalidTid
-      && !s->IsFlagSet(MutexFlagBroken)) {
+  if (flags()->report_destroy_locked && s->owner_tid != kInvalidTid &&
+      !s->IsFlagSet(MutexFlagBroken)) {
     s->SetFlags(MutexFlagBroken);
     unlock_locked = true;
   }
@@ -107,7 +106,7 @@ void MutexDestroy(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
   if (!unlock_locked)
     s->Reset(thr->proc());  // must not reset it before the report is printed
   s->mtx.Unlock();
-  if (unlock_locked) {
+  if (unlock_locked && ShouldReport(thr, ReportTypeMutexDestroyLocked)) {
     ThreadRegistryLock l(ctx->thread_registry);
     ScopedReport rep(ReportTypeMutexDestroyLocked);
     rep.AddMutex(mid);
@@ -139,7 +138,7 @@ void MutexDestroy(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
   // s will be destroyed and freed in MetaMap::FreeBlock.
 }
 
-void MutexPreLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
+void MutexPreLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexPreLock %zx flagz=0x%x\n", thr->tid, addr, flagz);
   if (!(flagz & MutexFlagTryLock) && common_flags()->detect_deadlocks) {
     SyncVar *s = ctx->metamap.GetOrCreateAndLock(thr, pc, addr, false);
@@ -155,7 +154,8 @@ void MutexPreLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
   }
 }
 
-void MutexPostLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz, int rec) {
+void MutexPostLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz,
+                   int rec) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexPostLock %zx flag=0x%x rec=%d\n",
       thr->tid, addr, flagz, rec);
   if (flagz & MutexFlagRecursiveLock)
@@ -169,7 +169,7 @@ void MutexPostLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz, int rec) {
   thr->fast_state.IncrementEpoch();
   TraceAddEvent(thr, thr->fast_state, EventTypeLock, s->GetId());
   bool report_double_lock = false;
-  if (s->owner_tid == SyncVar::kInvalidTid) {
+  if (s->owner_tid == kInvalidTid) {
     CHECK_EQ(s->recursion, 0);
     s->owner_tid = thr->tid;
     s->last_lock = thr->fast_state.raw();
@@ -182,11 +182,9 @@ void MutexPostLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz, int rec) {
   const bool first = s->recursion == 0;
   s->recursion += rec;
   if (first) {
-    StatInc(thr, StatMutexLock);
     AcquireImpl(thr, pc, &s->clock);
     AcquireImpl(thr, pc, &s->read_clock);
   } else if (!s->IsFlagSet(MutexFlagWriteReentrant)) {
-    StatInc(thr, StatMutexRecLock);
   }
   thr->mset.Add(s->GetId(), true, thr->fast_state.epoch());
   bool pre_lock = false;
@@ -210,7 +208,7 @@ void MutexPostLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz, int rec) {
   }
 }
 
-int MutexUnlock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
+int MutexUnlock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexUnlock %zx flagz=0x%x\n", thr->tid, addr, flagz);
   if (IsAppMem(addr))
     MemoryReadAtomic(thr, pc, addr, kSizeLog1);
@@ -228,11 +226,9 @@ int MutexUnlock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
     rec = (flagz & MutexFlagRecursiveUnlock) ? s->recursion : 1;
     s->recursion -= rec;
     if (s->recursion == 0) {
-      StatInc(thr, StatMutexUnlock);
-      s->owner_tid = SyncVar::kInvalidTid;
+      s->owner_tid = kInvalidTid;
       ReleaseStoreImpl(thr, pc, &s->clock);
     } else {
-      StatInc(thr, StatMutexRecUnlock);
     }
   }
   thr->mset.Del(s->GetId(), true);
@@ -253,7 +249,7 @@ int MutexUnlock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
   return rec;
 }
 
-void MutexPreReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
+void MutexPreReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexPreReadLock %zx flagz=0x%x\n", thr->tid, addr, flagz);
   if (!(flagz & MutexFlagTryLock) && common_flags()->detect_deadlocks) {
     SyncVar *s = ctx->metamap.GetOrCreateAndLock(thr, pc, addr, false);
@@ -265,9 +261,8 @@ void MutexPreReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
   }
 }
 
-void MutexPostReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
+void MutexPostReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexPostReadLock %zx flagz=0x%x\n", thr->tid, addr, flagz);
-  StatInc(thr, StatMutexReadLock);
   if (IsAppMem(addr))
     MemoryReadAtomic(thr, pc, addr, kSizeLog1);
   SyncVar *s = ctx->metamap.GetOrCreateAndLock(thr, pc, addr, false);
@@ -275,7 +270,7 @@ void MutexPostReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
   thr->fast_state.IncrementEpoch();
   TraceAddEvent(thr, thr->fast_state, EventTypeRLock, s->GetId());
   bool report_bad_lock = false;
-  if (s->owner_tid != SyncVar::kInvalidTid) {
+  if (s->owner_tid != kInvalidTid) {
     if (flags()->report_mutex_bugs && !s->IsFlagSet(MutexFlagBroken)) {
       s->SetFlags(MutexFlagBroken);
       report_bad_lock = true;
@@ -305,16 +300,15 @@ void MutexPostReadLock(ThreadState *thr, uptr pc, uptr addr, u32 flagz) {
   }
 }
 
-void MutexReadUnlock(ThreadState *thr, uptr pc, uptr addr) {
+void MutexReadUnlock(ThreadState *thr, uptr pc, uptr addr) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexReadUnlock %zx\n", thr->tid, addr);
-  StatInc(thr, StatMutexReadUnlock);
   if (IsAppMem(addr))
     MemoryReadAtomic(thr, pc, addr, kSizeLog1);
   SyncVar *s = ctx->metamap.GetOrCreateAndLock(thr, pc, addr, true);
   thr->fast_state.IncrementEpoch();
   TraceAddEvent(thr, thr->fast_state, EventTypeRUnlock, s->GetId());
   bool report_bad_unlock = false;
-  if (s->owner_tid != SyncVar::kInvalidTid) {
+  if (s->owner_tid != kInvalidTid) {
     if (flags()->report_mutex_bugs && !s->IsFlagSet(MutexFlagBroken)) {
       s->SetFlags(MutexFlagBroken);
       report_bad_unlock = true;
@@ -337,17 +331,16 @@ void MutexReadUnlock(ThreadState *thr, uptr pc, uptr addr) {
   }
 }
 
-void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr) {
+void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexReadOrWriteUnlock %zx\n", thr->tid, addr);
   if (IsAppMem(addr))
     MemoryReadAtomic(thr, pc, addr, kSizeLog1);
   SyncVar *s = ctx->metamap.GetOrCreateAndLock(thr, pc, addr, true);
   bool write = true;
   bool report_bad_unlock = false;
-  if (s->owner_tid == SyncVar::kInvalidTid) {
+  if (s->owner_tid == kInvalidTid) {
     // Seems to be read unlock.
     write = false;
-    StatInc(thr, StatMutexReadUnlock);
     thr->fast_state.IncrementEpoch();
     TraceAddEvent(thr, thr->fast_state, EventTypeRUnlock, s->GetId());
     ReleaseImpl(thr, pc, &s->read_clock);
@@ -358,11 +351,9 @@ void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr) {
     CHECK_GT(s->recursion, 0);
     s->recursion--;
     if (s->recursion == 0) {
-      StatInc(thr, StatMutexUnlock);
-      s->owner_tid = SyncVar::kInvalidTid;
+      s->owner_tid = kInvalidTid;
       ReleaseStoreImpl(thr, pc, &s->clock);
     } else {
-      StatInc(thr, StatMutexRecUnlock);
     }
   } else if (!s->IsFlagSet(MutexFlagBroken)) {
     s->SetFlags(MutexFlagBroken);
@@ -384,15 +375,15 @@ void MutexReadOrWriteUnlock(ThreadState *thr, uptr pc, uptr addr) {
   }
 }
 
-void MutexRepair(ThreadState *thr, uptr pc, uptr addr) {
+void MutexRepair(ThreadState *thr, uptr pc, uptr addr) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexRepair %zx\n", thr->tid, addr);
   SyncVar *s = ctx->metamap.GetOrCreateAndLock(thr, pc, addr, true);
-  s->owner_tid = SyncVar::kInvalidTid;
+  s->owner_tid = kInvalidTid;
   s->recursion = 0;
   s->mtx.Unlock();
 }
 
-void MutexInvalidAccess(ThreadState *thr, uptr pc, uptr addr) {
+void MutexInvalidAccess(ThreadState *thr, uptr pc, uptr addr) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: MutexInvalidAccess %zx\n", thr->tid, addr);
   SyncVar *s = ctx->metamap.GetOrCreateAndLock(thr, pc, addr, true);
   u64 mid = s->GetId();
@@ -400,7 +391,7 @@ void MutexInvalidAccess(ThreadState *thr, uptr pc, uptr addr) {
   ReportMutexMisuse(thr, pc, ReportTypeMutexInvalidAccess, addr, mid);
 }
 
-void Acquire(ThreadState *thr, uptr pc, uptr addr) {
+void Acquire(ThreadState *thr, uptr pc, uptr addr) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: Acquire %zx\n", thr->tid, addr);
   if (thr->ignore_sync)
     return;
@@ -431,7 +422,7 @@ void AcquireGlobal(ThreadState *thr, uptr pc) {
       UpdateClockCallback, thr);
 }
 
-void ReleaseStoreAcquire(ThreadState *thr, uptr pc, uptr addr) {
+void ReleaseStoreAcquire(ThreadState *thr, uptr pc, uptr addr) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: ReleaseStoreAcquire %zx\n", thr->tid, addr);
   if (thr->ignore_sync)
     return;
@@ -443,7 +434,7 @@ void ReleaseStoreAcquire(ThreadState *thr, uptr pc, uptr addr) {
   s->mtx.Unlock();
 }
 
-void Release(ThreadState *thr, uptr pc, uptr addr) {
+void Release(ThreadState *thr, uptr pc, uptr addr) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: Release %zx\n", thr->tid, addr);
   if (thr->ignore_sync)
     return;
@@ -455,7 +446,7 @@ void Release(ThreadState *thr, uptr pc, uptr addr) {
   s->mtx.Unlock();
 }
 
-void ReleaseStore(ThreadState *thr, uptr pc, uptr addr) {
+void ReleaseStore(ThreadState *thr, uptr pc, uptr addr) NO_THREAD_SAFETY_ANALYSIS {
   DPrintf("#%d: ReleaseStore %zx\n", thr->tid, addr);
   if (thr->ignore_sync)
     return;
@@ -493,7 +484,6 @@ void AcquireImpl(ThreadState *thr, uptr pc, SyncClock *c) {
     return;
   thr->clock.set(thr->fast_state.epoch());
   thr->clock.acquire(&thr->proc()->clock_cache, c);
-  StatInc(thr, StatSyncAcquire);
 }
 
 void ReleaseStoreAcquireImpl(ThreadState *thr, uptr pc, SyncClock *c) {
@@ -502,7 +492,6 @@ void ReleaseStoreAcquireImpl(ThreadState *thr, uptr pc, SyncClock *c) {
   thr->clock.set(thr->fast_state.epoch());
   thr->fast_synch_epoch = thr->fast_state.epoch();
   thr->clock.releaseStoreAcquire(&thr->proc()->clock_cache, c);
-  StatInc(thr, StatSyncReleaseStoreAcquire);
 }
 
 void ReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c) {
@@ -511,7 +500,6 @@ void ReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c) {
   thr->clock.set(thr->fast_state.epoch());
   thr->fast_synch_epoch = thr->fast_state.epoch();
   thr->clock.release(&thr->proc()->clock_cache, c);
-  StatInc(thr, StatSyncRelease);
 }
 
 void ReleaseStoreImpl(ThreadState *thr, uptr pc, SyncClock *c) {
@@ -520,7 +508,6 @@ void ReleaseStoreImpl(ThreadState *thr, uptr pc, SyncClock *c) {
   thr->clock.set(thr->fast_state.epoch());
   thr->fast_synch_epoch = thr->fast_state.epoch();
   thr->clock.ReleaseStore(&thr->proc()->clock_cache, c);
-  StatInc(thr, StatSyncRelease);
 }
 
 void AcquireReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c) {
@@ -529,12 +516,10 @@ void AcquireReleaseImpl(ThreadState *thr, uptr pc, SyncClock *c) {
   thr->clock.set(thr->fast_state.epoch());
   thr->fast_synch_epoch = thr->fast_state.epoch();
   thr->clock.acq_rel(&thr->proc()->clock_cache, c);
-  StatInc(thr, StatSyncAcquire);
-  StatInc(thr, StatSyncRelease);
 }
 
 void ReportDeadlock(ThreadState *thr, uptr pc, DDReport *r) {
-  if (r == 0)
+  if (r == 0 || !ShouldReport(thr, ReportTypeDeadlock))
     return;
   ThreadRegistryLock l(ctx->thread_registry);
   ScopedReport rep(ReportTypeDeadlock);
lib/tsan/tsan_rtl_report.cpp
@@ -31,23 +31,6 @@ using namespace __sanitizer;
 
 static ReportStack *SymbolizeStack(StackTrace trace);
 
-void TsanCheckFailed(const char *file, int line, const char *cond,
-                     u64 v1, u64 v2) {
-  // There is high probability that interceptors will check-fail as well,
-  // on the other hand there is no sense in processing interceptors
-  // since we are going to die soon.
-  ScopedIgnoreInterceptors ignore;
-#if !SANITIZER_GO
-  cur_thread()->ignore_sync++;
-  cur_thread()->ignore_reads_and_writes++;
-#endif
-  Printf("FATAL: ThreadSanitizer CHECK failed: "
-         "%s:%d \"%s\" (0x%zx, 0x%zx)\n",
-         file, line, cond, (uptr)v1, (uptr)v2);
-  PrintCurrentStackSlow(StackTrace::GetCurrentPc());
-  Die();
-}
-
 // Can be overriden by an application/test to intercept reports.
 #ifdef TSAN_EXTERNAL_HOOKS
 bool OnReport(const ReportDesc *rep, bool suppressed);
@@ -142,6 +125,34 @@ static ReportStack *SymbolizeStack(StackTrace trace) {
   return stack;
 }
 
+bool ShouldReport(ThreadState *thr, ReportType typ) {
+  // We set thr->suppress_reports in the fork context.
+  // Taking any locking in the fork context can lead to deadlocks.
+  // If any locks are already taken, it's too late to do this check.
+  CheckedMutex::CheckNoLocks();
+  // For the same reason check we didn't lock thread_registry yet.
+  if (SANITIZER_DEBUG)
+    ThreadRegistryLock l(ctx->thread_registry);
+  if (!flags()->report_bugs || thr->suppress_reports)
+    return false;
+  switch (typ) {
+    case ReportTypeSignalUnsafe:
+      return flags()->report_signal_unsafe;
+    case ReportTypeThreadLeak:
+#if !SANITIZER_GO
+      // It's impossible to join phantom threads
+      // in the child after fork.
+      if (ctx->after_multithreaded_fork)
+        return false;
+#endif
+      return flags()->report_thread_leaks;
+    case ReportTypeMutexDestroyLocked:
+      return flags()->report_destroy_locked;
+    default:
+      return true;
+  }
+}
+
 ScopedReportBase::ScopedReportBase(ReportType typ, uptr tag) {
   ctx->thread_registry->CheckLocked();
   void *mem = internal_alloc(MBlockReport, sizeof(ReportDesc));
@@ -274,7 +285,7 @@ void ScopedReportBase::AddMutex(const SyncVar *s) {
   rm->stack = SymbolizeStackId(s->creation_stack_id);
 }
 
-u64 ScopedReportBase::AddMutex(u64 id) {
+u64 ScopedReportBase::AddMutex(u64 id) NO_THREAD_SAFETY_ANALYSIS {
   u64 uid = 0;
   u64 mid = id;
   uptr addr = SyncVar::SplitId(id, &uid);
@@ -497,8 +508,10 @@ static bool HandleRacyAddress(ThreadState *thr, uptr addr_min, uptr addr_max) {
 }
 
 bool OutputReport(ThreadState *thr, const ScopedReport &srep) {
-  if (!flags()->report_bugs || thr->suppress_reports)
-    return false;
+  // These should have been checked in ShouldReport.
+  // It's too late to check them here, we have already taken locks.
+  CHECK(flags()->report_bugs);
+  CHECK(!thr->suppress_reports);
   atomic_store_relaxed(&ctx->last_symbolize_time_ns, NanoTime());
   const ReportDesc *rep = srep.GetReport();
   CHECK_EQ(thr->current_report, nullptr);
@@ -583,13 +596,13 @@ static bool RaceBetweenAtomicAndFree(ThreadState *thr) {
 }
 
 void ReportRace(ThreadState *thr) {
-  CheckNoLocks(thr);
+  CheckedMutex::CheckNoLocks();
 
   // Symbolizer makes lots of intercepted calls. If we try to process them,
   // at best it will cause deadlocks on internal mutexes.
   ScopedIgnoreInterceptors ignore;
 
-  if (!flags()->report_bugs)
+  if (!ShouldReport(thr, ReportTypeRace))
     return;
   if (!flags()->report_atomic_races && !RaceBetweenAtomicAndFree(thr))
     return;
@@ -706,9 +719,7 @@ void ReportRace(ThreadState *thr) {
   }
 #endif
 
-  if (!OutputReport(thr, rep))
-    return;
-
+  OutputReport(thr, rep);
 }
 
 void PrintCurrentStack(ThreadState *thr, uptr pc) {
@@ -724,8 +735,7 @@ void PrintCurrentStack(ThreadState *thr, uptr pc) {
 // However, this solution is not reliable enough, please see dvyukov's comment
 // http://reviews.llvm.org/D19148#406208
 // Also see PR27280 comment 2 and 3 for breaking examples and analysis.
-ALWAYS_INLINE
-void PrintCurrentStackSlow(uptr pc) {
+ALWAYS_INLINE USED void PrintCurrentStackSlow(uptr pc) {
 #if !SANITIZER_GO
   uptr bp = GET_CURRENT_FRAME();
   BufferedStackTrace *ptrace =
lib/tsan/tsan_rtl_thread.cpp
@@ -51,7 +51,7 @@ struct OnCreatedArgs {
 
 void ThreadContext::OnCreated(void *arg) {
   thr = 0;
-  if (tid == 0)
+  if (tid == kMainTid)
     return;
   OnCreatedArgs *args = static_cast<OnCreatedArgs *>(arg);
   if (!args->thr)  // GCD workers don't have a parent thread.
@@ -61,8 +61,6 @@ void ThreadContext::OnCreated(void *arg) {
   TraceAddEvent(args->thr, args->thr->fast_state, EventTypeMop, 0);
   ReleaseImpl(args->thr, 0, &sync);
   creation_stack_id = CurrentStackId(args->thr, args->pc);
-  if (reuse_count == 0)
-    StatInc(args->thr, StatThreadMaxTid);
 }
 
 void ThreadContext::OnReset() {
@@ -115,7 +113,6 @@ void ThreadContext::OnStarted(void *arg) {
 
   thr->fast_synch_epoch = epoch0;
   AcquireImpl(thr, 0, &sync);
-  StatInc(thr, StatSyncAcquire);
   sync.Reset(&thr->proc()->clock_cache);
   thr->is_inited = true;
   DPrintf("#%d: ThreadStart epoch=%zu stk_addr=%zx stk_size=%zx "
@@ -149,9 +146,6 @@ void ThreadContext::OnFinished() {
   PlatformCleanUpThreadState(thr);
 #endif
   thr->~ThreadState();
-#if TSAN_COLLECT_STATS
-  StatAggregate(ctx->stat, thr->stat);
-#endif
   thr = 0;
 }
 
@@ -179,7 +173,7 @@ static void MaybeReportThreadLeak(ThreadContextBase *tctx_base, void *arg) {
 
 #if !SANITIZER_GO
 static void ReportIgnoresEnabled(ThreadContext *tctx, IgnoreSet *set) {
-  if (tctx->tid == 0) {
+  if (tctx->tid == kMainTid) {
     Printf("ThreadSanitizer: main thread finished with ignores enabled\n");
   } else {
     Printf("ThreadSanitizer: thread T%d %s finished with ignores enabled,"
@@ -210,7 +204,7 @@ static void ThreadCheckIgnore(ThreadState *thr) {}
 void ThreadFinalize(ThreadState *thr) {
   ThreadCheckIgnore(thr);
 #if !SANITIZER_GO
-  if (!flags()->report_thread_leaks)
+  if (!ShouldReport(thr, ReportTypeThreadLeak))
     return;
   ThreadRegistryLock l(ctx->thread_registry);
   Vector<ThreadLeak> leaks;
@@ -232,13 +226,11 @@ int ThreadCount(ThreadState *thr) {
 }
 
 int ThreadCreate(ThreadState *thr, uptr pc, uptr uid, bool detached) {
-  StatInc(thr, StatThreadCreate);
   OnCreatedArgs args = { thr, pc };
   u32 parent_tid = thr ? thr->tid : kInvalidTid;  // No parent for GCD workers.
   int tid =
       ctx->thread_registry->CreateThread(uid, detached, parent_tid, &args);
   DPrintf("#%d: ThreadCreate tid=%d uid=%zu\n", parent_tid, tid, uid);
-  StatSet(thr, StatThreadMaxAlive, ctx->thread_registry->GetMaxAliveThreads());
   return tid;
 }
 
@@ -250,9 +242,10 @@ void ThreadStart(ThreadState *thr, int tid, tid_t os_id,
   uptr tls_size = 0;
 #if !SANITIZER_GO
   if (thread_type != ThreadType::Fiber)
-    GetThreadStackAndTls(tid == 0, &stk_addr, &stk_size, &tls_addr, &tls_size);
+    GetThreadStackAndTls(tid == kMainTid, &stk_addr, &stk_size, &tls_addr,
+                         &tls_size);
 
-  if (tid) {
+  if (tid != kMainTid) {
     if (stk_addr && stk_size)
       MemoryRangeImitateWrite(thr, /*pc=*/ 1, stk_addr, stk_size);
 
@@ -279,7 +272,6 @@ void ThreadStart(ThreadState *thr, int tid, tid_t os_id,
 
 void ThreadFinish(ThreadState *thr) {
   ThreadCheckIgnore(thr);
-  StatInc(thr, StatThreadFinish);
   if (thr->stk_addr && thr->stk_size)
     DontNeedShadowFor(thr->stk_addr, thr->stk_size);
   if (thr->tls_addr && thr->tls_size)
@@ -313,7 +305,7 @@ static bool ConsumeThreadByUid(ThreadContextBase *tctx, void *arg) {
 int ThreadConsumeTid(ThreadState *thr, uptr pc, uptr uid) {
   ConsumeThreadContext findCtx = {uid, nullptr};
   ctx->thread_registry->FindThread(ConsumeThreadByUid, &findCtx);
-  int tid = findCtx.tctx ? findCtx.tctx->tid : ThreadRegistry::kUnknownTid;
+  int tid = findCtx.tctx ? findCtx.tctx->tid : kInvalidTid;
   DPrintf("#%d: ThreadTid uid=%zu tid=%d\n", thr->tid, uid, tid);
   return tid;
 }
@@ -371,13 +363,10 @@ void MemoryAccessRange(ThreadState *thr, uptr pc, uptr addr,
   }
 #endif
 
-  StatInc(thr, StatMopRange);
-
   if (*shadow_mem == kShadowRodata) {
     DCHECK(!is_write);
     // Access to .rodata section, no races here.
     // Measurements show that it can be 10-20% of all memory accesses.
-    StatInc(thr, StatMopRangeRodata);
     return;
   }
 
lib/tsan/tsan_stack_trace.cpp
@@ -54,10 +54,8 @@ void __sanitizer::BufferedStackTrace::UnwindImpl(
     uptr pc, uptr bp, void *context, bool request_fast, u32 max_depth) {
   uptr top = 0;
   uptr bottom = 0;
-  if (StackTrace::WillUseFastUnwind(request_fast)) {
-    GetThreadStackTopAndBottom(false, &top, &bottom);
-    Unwind(max_depth, pc, bp, nullptr, top, bottom, true);
-  } else
-    Unwind(max_depth, pc, 0, context, 0, 0, false);
+  GetThreadStackTopAndBottom(false, &top, &bottom);
+  bool fast = StackTrace::WillUseFastUnwind(request_fast);
+  Unwind(max_depth, pc, bp, context, top, bottom, fast);
 }
 #endif  // SANITIZER_GO
lib/tsan/tsan_stat.cpp
@@ -1,186 +0,0 @@
-//===-- tsan_stat.cpp -----------------------------------------------------===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is a part of ThreadSanitizer (TSan), a race detector.
-//
-//===----------------------------------------------------------------------===//
-#include "tsan_stat.h"
-#include "tsan_rtl.h"
-
-namespace __tsan {
-
-#if TSAN_COLLECT_STATS
-
-void StatAggregate(u64 *dst, u64 *src) {
-  for (int i = 0; i < StatCnt; i++)
-    dst[i] += src[i];
-}
-
-void StatOutput(u64 *stat) {
-  stat[StatShadowNonZero] = stat[StatShadowProcessed] - stat[StatShadowZero];
-
-  static const char *name[StatCnt] = {};
-  name[StatMop]                          = "Memory accesses                   ";
-  name[StatMopRead]                      = "  Including reads                 ";
-  name[StatMopWrite]                     = "            writes                ";
-  name[StatMop1]                         = "  Including size 1                ";
-  name[StatMop2]                         = "            size 2                ";
-  name[StatMop4]                         = "            size 4                ";
-  name[StatMop8]                         = "            size 8                ";
-  name[StatMopSame]                      = "  Including same                  ";
-  name[StatMopIgnored]                   = "  Including ignored               ";
-  name[StatMopRange]                     = "  Including range                 ";
-  name[StatMopRodata]                    = "  Including .rodata               ";
-  name[StatMopRangeRodata]               = "  Including .rodata range         ";
-  name[StatShadowProcessed]              = "Shadow processed                  ";
-  name[StatShadowZero]                   = "  Including empty                 ";
-  name[StatShadowNonZero]                = "  Including non empty             ";
-  name[StatShadowSameSize]               = "  Including same size             ";
-  name[StatShadowIntersect]              = "            intersect             ";
-  name[StatShadowNotIntersect]           = "            not intersect         ";
-  name[StatShadowSameThread]             = "  Including same thread           ";
-  name[StatShadowAnotherThread]          = "            another thread        ";
-  name[StatShadowReplace]                = "  Including evicted               ";
-
-  name[StatFuncEnter]                    = "Function entries                  ";
-  name[StatFuncExit]                     = "Function exits                    ";
-  name[StatEvents]                       = "Events collected                  ";
-
-  name[StatThreadCreate]                 = "Total threads created             ";
-  name[StatThreadFinish]                 = "  threads finished                ";
-  name[StatThreadReuse]                  = "  threads reused                  ";
-  name[StatThreadMaxTid]                 = "  max tid                         ";
-  name[StatThreadMaxAlive]               = "  max alive threads               ";
-
-  name[StatMutexCreate]                  = "Mutexes created                   ";
-  name[StatMutexDestroy]                 = "  destroyed                       ";
-  name[StatMutexLock]                    = "  lock                            ";
-  name[StatMutexUnlock]                  = "  unlock                          ";
-  name[StatMutexRecLock]                 = "  recursive lock                  ";
-  name[StatMutexRecUnlock]               = "  recursive unlock                ";
-  name[StatMutexReadLock]                = "  read lock                       ";
-  name[StatMutexReadUnlock]              = "  read unlock                     ";
-
-  name[StatSyncCreated]                  = "Sync objects created              ";
-  name[StatSyncDestroyed]                = "             destroyed            ";
-  name[StatSyncAcquire]                  = "             acquired             ";
-  name[StatSyncRelease]                  = "             released             ";
-
-  name[StatClockAcquire]                 = "Clock acquire                     ";
-  name[StatClockAcquireEmpty]            = "  empty clock                     ";
-  name[StatClockAcquireFastRelease]      = "  fast from release-store         ";
-  name[StatClockAcquireFull]             = "  full (slow)                     ";
-  name[StatClockAcquiredSomething]       = "  acquired something              ";
-  name[StatClockRelease]                 = "Clock release                     ";
-  name[StatClockReleaseResize]           = "  resize                          ";
-  name[StatClockReleaseFast]             = "  fast                            ";
-  name[StatClockReleaseSlow]             = "  dirty overflow (slow)           ";
-  name[StatClockReleaseFull]             = "  full (slow)                     ";
-  name[StatClockReleaseAcquired]         = "  was acquired                    ";
-  name[StatClockReleaseClearTail]        = "  clear tail                      ";
-  name[StatClockStore]                   = "Clock release store               ";
-  name[StatClockStoreResize]             = "  resize                          ";
-  name[StatClockStoreFast]               = "  fast                            ";
-  name[StatClockStoreFull]               = "  slow                            ";
-  name[StatClockStoreTail]               = "  clear tail                      ";
-  name[StatClockAcquireRelease]          = "Clock acquire-release             ";
-
-  name[StatAtomic]                       = "Atomic operations                 ";
-  name[StatAtomicLoad]                   = "  Including load                  ";
-  name[StatAtomicStore]                  = "            store                 ";
-  name[StatAtomicExchange]               = "            exchange              ";
-  name[StatAtomicFetchAdd]               = "            fetch_add             ";
-  name[StatAtomicFetchSub]               = "            fetch_sub             ";
-  name[StatAtomicFetchAnd]               = "            fetch_and             ";
-  name[StatAtomicFetchOr]                = "            fetch_or              ";
-  name[StatAtomicFetchXor]               = "            fetch_xor             ";
-  name[StatAtomicFetchNand]              = "            fetch_nand            ";
-  name[StatAtomicCAS]                    = "            compare_exchange      ";
-  name[StatAtomicFence]                  = "            fence                 ";
-  name[StatAtomicRelaxed]                = "  Including relaxed               ";
-  name[StatAtomicConsume]                = "            consume               ";
-  name[StatAtomicAcquire]                = "            acquire               ";
-  name[StatAtomicRelease]                = "            release               ";
-  name[StatAtomicAcq_Rel]                = "            acq_rel               ";
-  name[StatAtomicSeq_Cst]                = "            seq_cst               ";
-  name[StatAtomic1]                      = "  Including size 1                ";
-  name[StatAtomic2]                      = "            size 2                ";
-  name[StatAtomic4]                      = "            size 4                ";
-  name[StatAtomic8]                      = "            size 8                ";
-  name[StatAtomic16]                     = "            size 16               ";
-
-  name[StatAnnotation]                   = "Dynamic annotations               ";
-  name[StatAnnotateHappensBefore]        = "  HappensBefore                   ";
-  name[StatAnnotateHappensAfter]         = "  HappensAfter                    ";
-  name[StatAnnotateCondVarSignal]        = "  CondVarSignal                   ";
-  name[StatAnnotateCondVarSignalAll]     = "  CondVarSignalAll                ";
-  name[StatAnnotateMutexIsNotPHB]        = "  MutexIsNotPHB                   ";
-  name[StatAnnotateCondVarWait]          = "  CondVarWait                     ";
-  name[StatAnnotateRWLockCreate]         = "  RWLockCreate                    ";
-  name[StatAnnotateRWLockCreateStatic]   = "  StatAnnotateRWLockCreateStatic  ";
-  name[StatAnnotateRWLockDestroy]        = "  RWLockDestroy                   ";
-  name[StatAnnotateRWLockAcquired]       = "  RWLockAcquired                  ";
-  name[StatAnnotateRWLockReleased]       = "  RWLockReleased                  ";
-  name[StatAnnotateTraceMemory]          = "  TraceMemory                     ";
-  name[StatAnnotateFlushState]           = "  FlushState                      ";
-  name[StatAnnotateNewMemory]            = "  NewMemory                       ";
-  name[StatAnnotateNoOp]                 = "  NoOp                            ";
-  name[StatAnnotateFlushExpectedRaces]   = "  FlushExpectedRaces              ";
-  name[StatAnnotateEnableRaceDetection]  = "  EnableRaceDetection             ";
-  name[StatAnnotateMutexIsUsedAsCondVar] = "  MutexIsUsedAsCondVar            ";
-  name[StatAnnotatePCQGet]               = "  PCQGet                          ";
-  name[StatAnnotatePCQPut]               = "  PCQPut                          ";
-  name[StatAnnotatePCQDestroy]           = "  PCQDestroy                      ";
-  name[StatAnnotatePCQCreate]            = "  PCQCreate                       ";
-  name[StatAnnotateExpectRace]           = "  ExpectRace                      ";
-  name[StatAnnotateBenignRaceSized]      = "  BenignRaceSized                 ";
-  name[StatAnnotateBenignRace]           = "  BenignRace                      ";
-  name[StatAnnotateIgnoreReadsBegin]     = "  IgnoreReadsBegin                ";
-  name[StatAnnotateIgnoreReadsEnd]       = "  IgnoreReadsEnd                  ";
-  name[StatAnnotateIgnoreWritesBegin]    = "  IgnoreWritesBegin               ";
-  name[StatAnnotateIgnoreWritesEnd]      = "  IgnoreWritesEnd                 ";
-  name[StatAnnotateIgnoreSyncBegin]      = "  IgnoreSyncBegin                 ";
-  name[StatAnnotateIgnoreSyncEnd]        = "  IgnoreSyncEnd                   ";
-  name[StatAnnotatePublishMemoryRange]   = "  PublishMemoryRange              ";
-  name[StatAnnotateUnpublishMemoryRange] = "  UnpublishMemoryRange            ";
-  name[StatAnnotateThreadName]           = "  ThreadName                      ";
-  name[Stat__tsan_mutex_create]          = "  __tsan_mutex_create             ";
-  name[Stat__tsan_mutex_destroy]         = "  __tsan_mutex_destroy            ";
-  name[Stat__tsan_mutex_pre_lock]        = "  __tsan_mutex_pre_lock           ";
-  name[Stat__tsan_mutex_post_lock]       = "  __tsan_mutex_post_lock          ";
-  name[Stat__tsan_mutex_pre_unlock]      = "  __tsan_mutex_pre_unlock         ";
-  name[Stat__tsan_mutex_post_unlock]     = "  __tsan_mutex_post_unlock        ";
-  name[Stat__tsan_mutex_pre_signal]      = "  __tsan_mutex_pre_signal         ";
-  name[Stat__tsan_mutex_post_signal]     = "  __tsan_mutex_post_signal        ";
-  name[Stat__tsan_mutex_pre_divert]      = "  __tsan_mutex_pre_divert         ";
-  name[Stat__tsan_mutex_post_divert]     = "  __tsan_mutex_post_divert        ";
-
-  name[StatMtxTotal]                     = "Contentionz                       ";
-  name[StatMtxTrace]                     = "  Trace                           ";
-  name[StatMtxThreads]                   = "  Threads                         ";
-  name[StatMtxReport]                    = "  Report                          ";
-  name[StatMtxSyncVar]                   = "  SyncVar                         ";
-  name[StatMtxSyncTab]                   = "  SyncTab                         ";
-  name[StatMtxSlab]                      = "  Slab                            ";
-  name[StatMtxAtExit]                    = "  Atexit                          ";
-  name[StatMtxAnnotations]               = "  Annotations                     ";
-  name[StatMtxMBlock]                    = "  MBlock                          ";
-  name[StatMtxDeadlockDetector]          = "  DeadlockDetector                ";
-  name[StatMtxFired]                     = "  FiredSuppressions               ";
-  name[StatMtxRacy]                      = "  RacyStacks                      ";
-  name[StatMtxFD]                        = "  FD                              ";
-  name[StatMtxGlobalProc]                = "  GlobalProc                      ";
-
-  Printf("Statistics:\n");
-  for (int i = 0; i < StatCnt; i++)
-    Printf("%s: %16zu\n", name[i], (uptr)stat[i]);
-}
-
-#endif
-
-}  // namespace __tsan
lib/tsan/tsan_stat.h
@@ -1,191 +0,0 @@
-//===-- tsan_stat.h ---------------------------------------------*- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===----------------------------------------------------------------------===//
-//
-// This file is a part of ThreadSanitizer (TSan), a race detector.
-//
-//===----------------------------------------------------------------------===//
-
-#ifndef TSAN_STAT_H
-#define TSAN_STAT_H
-
-namespace __tsan {
-
-enum StatType {
-  // Memory access processing related stuff.
-  StatMop,
-  StatMopRead,
-  StatMopWrite,
-  StatMop1,  // These must be consequtive.
-  StatMop2,
-  StatMop4,
-  StatMop8,
-  StatMopSame,
-  StatMopIgnored,
-  StatMopRange,
-  StatMopRodata,
-  StatMopRangeRodata,
-  StatShadowProcessed,
-  StatShadowZero,
-  StatShadowNonZero,  // Derived.
-  StatShadowSameSize,
-  StatShadowIntersect,
-  StatShadowNotIntersect,
-  StatShadowSameThread,
-  StatShadowAnotherThread,
-  StatShadowReplace,
-
-  // Func processing.
-  StatFuncEnter,
-  StatFuncExit,
-
-  // Trace processing.
-  StatEvents,
-
-  // Threads.
-  StatThreadCreate,
-  StatThreadFinish,
-  StatThreadReuse,
-  StatThreadMaxTid,
-  StatThreadMaxAlive,
-
-  // Mutexes.
-  StatMutexCreate,
-  StatMutexDestroy,
-  StatMutexLock,
-  StatMutexUnlock,
-  StatMutexRecLock,
-  StatMutexRecUnlock,
-  StatMutexReadLock,
-  StatMutexReadUnlock,
-
-  // Synchronization.
-  StatSyncCreated,
-  StatSyncDestroyed,
-  StatSyncAcquire,
-  StatSyncRelease,
-  StatSyncReleaseStoreAcquire,
-
-  // Clocks - acquire.
-  StatClockAcquire,
-  StatClockAcquireEmpty,
-  StatClockAcquireFastRelease,
-  StatClockAcquireFull,
-  StatClockAcquiredSomething,
-  // Clocks - release.
-  StatClockRelease,
-  StatClockReleaseResize,
-  StatClockReleaseFast,
-  StatClockReleaseSlow,
-  StatClockReleaseFull,
-  StatClockReleaseAcquired,
-  StatClockReleaseClearTail,
-  // Clocks - release store.
-  StatClockStore,
-  StatClockStoreResize,
-  StatClockStoreFast,
-  StatClockStoreFull,
-  StatClockStoreTail,
-  // Clocks - acquire-release.
-  StatClockAcquireRelease,
-
-  // Atomics.
-  StatAtomic,
-  StatAtomicLoad,
-  StatAtomicStore,
-  StatAtomicExchange,
-  StatAtomicFetchAdd,
-  StatAtomicFetchSub,
-  StatAtomicFetchAnd,
-  StatAtomicFetchOr,
-  StatAtomicFetchXor,
-  StatAtomicFetchNand,
-  StatAtomicCAS,
-  StatAtomicFence,
-  StatAtomicRelaxed,
-  StatAtomicConsume,
-  StatAtomicAcquire,
-  StatAtomicRelease,
-  StatAtomicAcq_Rel,
-  StatAtomicSeq_Cst,
-  StatAtomic1,
-  StatAtomic2,
-  StatAtomic4,
-  StatAtomic8,
-  StatAtomic16,
-
-  // Dynamic annotations.
-  StatAnnotation,
-  StatAnnotateHappensBefore,
-  StatAnnotateHappensAfter,
-  StatAnnotateCondVarSignal,
-  StatAnnotateCondVarSignalAll,
-  StatAnnotateMutexIsNotPHB,
-  StatAnnotateCondVarWait,
-  StatAnnotateRWLockCreate,
-  StatAnnotateRWLockCreateStatic,
-  StatAnnotateRWLockDestroy,
-  StatAnnotateRWLockAcquired,
-  StatAnnotateRWLockReleased,
-  StatAnnotateTraceMemory,
-  StatAnnotateFlushState,
-  StatAnnotateNewMemory,
-  StatAnnotateNoOp,
-  StatAnnotateFlushExpectedRaces,
-  StatAnnotateEnableRaceDetection,
-  StatAnnotateMutexIsUsedAsCondVar,
-  StatAnnotatePCQGet,
-  StatAnnotatePCQPut,
-  StatAnnotatePCQDestroy,
-  StatAnnotatePCQCreate,
-  StatAnnotateExpectRace,
-  StatAnnotateBenignRaceSized,
-  StatAnnotateBenignRace,
-  StatAnnotateIgnoreReadsBegin,
-  StatAnnotateIgnoreReadsEnd,
-  StatAnnotateIgnoreWritesBegin,
-  StatAnnotateIgnoreWritesEnd,
-  StatAnnotateIgnoreSyncBegin,
-  StatAnnotateIgnoreSyncEnd,
-  StatAnnotatePublishMemoryRange,
-  StatAnnotateUnpublishMemoryRange,
-  StatAnnotateThreadName,
-  Stat__tsan_mutex_create,
-  Stat__tsan_mutex_destroy,
-  Stat__tsan_mutex_pre_lock,
-  Stat__tsan_mutex_post_lock,
-  Stat__tsan_mutex_pre_unlock,
-  Stat__tsan_mutex_post_unlock,
-  Stat__tsan_mutex_pre_signal,
-  Stat__tsan_mutex_post_signal,
-  Stat__tsan_mutex_pre_divert,
-  Stat__tsan_mutex_post_divert,
-
-  // Internal mutex contentionz.
-  StatMtxTotal,
-  StatMtxTrace,
-  StatMtxThreads,
-  StatMtxReport,
-  StatMtxSyncVar,
-  StatMtxSyncTab,
-  StatMtxSlab,
-  StatMtxAnnotations,
-  StatMtxAtExit,
-  StatMtxMBlock,
-  StatMtxDeadlockDetector,
-  StatMtxFired,
-  StatMtxRacy,
-  StatMtxFD,
-  StatMtxGlobalProc,
-
-  // This must be the last.
-  StatCnt
-};
-
-}  // namespace __tsan
-
-#endif  // TSAN_STAT_H
lib/tsan/tsan_sync.cpp
@@ -18,10 +18,7 @@ namespace __tsan {
 
 void DDMutexInit(ThreadState *thr, uptr pc, SyncVar *s);
 
-SyncVar::SyncVar()
-    : mtx(MutexTypeSyncVar, StatMtxSyncVar) {
-  Reset(0);
-}
+SyncVar::SyncVar() : mtx(MutexTypeSyncVar) { Reset(0); }
 
 void SyncVar::Init(ThreadState *thr, uptr pc, uptr addr, u64 uid) {
   this->addr = addr;
@@ -53,8 +50,8 @@ void SyncVar::Reset(Processor *proc) {
 }
 
 MetaMap::MetaMap()
-    : block_alloc_("heap block allocator")
-    , sync_alloc_("sync allocator") {
+    : block_alloc_(LINKER_INITIALIZED, "heap block allocator"),
+      sync_alloc_(LINKER_INITIALIZED, "sync allocator") {
   atomic_store(&uid_gen_, 0, memory_order_relaxed);
 }
 
@@ -175,7 +172,7 @@ void MetaMap::ResetRange(Processor *proc, uptr p, uptr sz) {
   uptr metap = (uptr)MemToMeta(p0);
   uptr metasz = sz0 / kMetaRatio;
   UnmapOrDie((void*)metap, metasz);
-  if (!MmapFixedNoReserve(metap, metasz))
+  if (!MmapFixedSuperNoReserve(metap, metasz))
     Die();
 }
 
@@ -202,8 +199,8 @@ SyncVar* MetaMap::GetIfExistsAndLock(uptr addr, bool write_lock) {
   return GetAndLock(0, 0, addr, write_lock, false);
 }
 
-SyncVar* MetaMap::GetAndLock(ThreadState *thr, uptr pc,
-                             uptr addr, bool write_lock, bool create) {
+SyncVar *MetaMap::GetAndLock(ThreadState *thr, uptr pc, uptr addr, bool write_lock,
+                             bool create) NO_THREAD_SAFETY_ANALYSIS {
   u32 *meta = MemToMeta(addr);
   u32 idx0 = *meta;
   u32 myidx = 0;
lib/tsan/tsan_sync.h
@@ -17,7 +17,6 @@
 #include "sanitizer_common/sanitizer_deadlock_detector_interface.h"
 #include "tsan_defs.h"
 #include "tsan_clock.h"
-#include "tsan_mutex.h"
 #include "tsan_dense_alloc.h"
 
 namespace __tsan {
@@ -50,13 +49,11 @@ enum MutexFlags {
 struct SyncVar {
   SyncVar();
 
-  static const int kInvalidTid = -1;
-
   uptr addr;  // overwritten by DenseSlabAlloc freelist
   Mutex mtx;
   u64 uid;  // Globally unique id.
   u32 creation_stack_id;
-  int owner_tid;  // Set only by exclusive owners.
+  u32 owner_tid;  // Set only by exclusive owners.
   u64 last_lock;
   int recursion;
   atomic_uint32_t flags;
@@ -130,8 +127,8 @@ class MetaMap {
   static const u32 kFlagMask  = 3u << 30;
   static const u32 kFlagBlock = 1u << 30;
   static const u32 kFlagSync  = 2u << 30;
-  typedef DenseSlabAlloc<MBlock, 1<<16, 1<<12> BlockAlloc;
-  typedef DenseSlabAlloc<SyncVar, 1<<16, 1<<10> SyncAlloc;
+  typedef DenseSlabAlloc<MBlock, 1 << 18, 1 << 12, kFlagMask> BlockAlloc;
+  typedef DenseSlabAlloc<SyncVar, 1 << 20, 1 << 10, kFlagMask> SyncAlloc;
   BlockAlloc block_alloc_;
   SyncAlloc sync_alloc_;
   atomic_uint64_t uid_gen_;
lib/tsan/tsan_trace.h
@@ -13,7 +13,6 @@
 #define TSAN_TRACE_H
 
 #include "tsan_defs.h"
-#include "tsan_mutex.h"
 #include "tsan_stack_trace.h"
 #include "tsan_mutexset.h"
 
@@ -65,9 +64,7 @@ struct Trace {
   // CreateThreadContext.
   TraceHeader headers[kTraceParts];
 
-  Trace()
-    : mtx(MutexTypeTrace, StatMtxTrace) {
-  }
+  Trace() : mtx(MutexTypeTrace) {}
 };
 
 }  // namespace __tsan
lib/tsan/tsan_update_shadow_word_inl.h
@@ -13,12 +13,10 @@
 // produce sligtly less efficient code.
 //===----------------------------------------------------------------------===//
 do {
-  StatInc(thr, StatShadowProcessed);
   const unsigned kAccessSize = 1 << kAccessSizeLog;
   u64 *sp = &shadow_mem[idx];
   old = LoadShadow(sp);
   if (LIKELY(old.IsZero())) {
-    StatInc(thr, StatShadowZero);
     if (!stored) {
       StoreIfNotYetStored(sp, &store_word);
       stored = true;
@@ -27,17 +25,14 @@ do {
   }
   // is the memory access equal to the previous?
   if (LIKELY(Shadow::Addr0AndSizeAreEqual(cur, old))) {
-    StatInc(thr, StatShadowSameSize);
     // same thread?
     if (LIKELY(Shadow::TidsAreEqual(old, cur))) {
-      StatInc(thr, StatShadowSameThread);
       if (LIKELY(old.IsRWWeakerOrEqual(kAccessIsWrite, kIsAtomic))) {
         StoreIfNotYetStored(sp, &store_word);
         stored = true;
       }
       break;
     }
-    StatInc(thr, StatShadowAnotherThread);
     if (HappensBefore(old, thr)) {
       if (old.IsRWWeakerOrEqual(kAccessIsWrite, kIsAtomic)) {
         StoreIfNotYetStored(sp, &store_word);
@@ -51,12 +46,8 @@ do {
   }
   // Do the memory access intersect?
   if (Shadow::TwoRangesIntersect(old, cur, kAccessSize)) {
-    StatInc(thr, StatShadowIntersect);
-    if (Shadow::TidsAreEqual(old, cur)) {
-      StatInc(thr, StatShadowSameThread);
+    if (Shadow::TidsAreEqual(old, cur))
       break;
-    }
-    StatInc(thr, StatShadowAnotherThread);
     if (old.IsBothReadsOrAtomic(kAccessIsWrite, kIsAtomic))
       break;
     if (LIKELY(HappensBefore(old, thr)))
@@ -64,6 +55,5 @@ do {
     goto RACE;
   }
   // The accesses do not intersect.
-  StatInc(thr, StatShadowNotIntersect);
   break;
 } while (0);
src/Cache.zig
@@ -210,7 +210,7 @@ pub const Manifest = struct {
     pub fn addFile(self: *Manifest, file_path: []const u8, max_file_size: ?usize) !usize {
         assert(self.manifest_file == null);
 
-        try self.files.ensureCapacity(self.cache.gpa, self.files.items.len + 1);
+        try self.files.ensureUnusedCapacity(self.cache.gpa, 1);
         const resolved_path = try fs.path.resolve(self.cache.gpa, &[_][]const u8{file_path});
 
         const idx = self.files.items.len;
src/Compilation.zig
@@ -2666,7 +2666,7 @@ fn reportRetryableCObjectError(
 
     const c_obj_err_msg = try comp.gpa.create(CObject.ErrorMsg);
     errdefer comp.gpa.destroy(c_obj_err_msg);
-    const msg = try std.fmt.allocPrint(comp.gpa, "unable to build C object: {s}", .{@errorName(err)});
+    const msg = try std.fmt.allocPrint(comp.gpa, "{s}", .{@errorName(err)});
     errdefer comp.gpa.free(msg);
     c_obj_err_msg.* = .{
         .msg = msg,
@@ -2742,6 +2742,8 @@ fn updateCObject(comp: *Compilation, c_object: *CObject, c_obj_prog_node: *std.P
     const tracy = trace(@src());
     defer tracy.end();
 
+    log.debug("updating C object: {s}", .{c_object.src.src_path});
+
     if (c_object.clearStatus(comp.gpa)) {
         // There was previous failure.
         const lock = comp.mutex.acquire();
@@ -3271,7 +3273,7 @@ fn failCObjWithOwnedErrorMsg(
         defer lock.release();
         {
             errdefer err_msg.destroy(comp.gpa);
-            try comp.failed_c_objects.ensureCapacity(comp.gpa, comp.failed_c_objects.count() + 1);
+            try comp.failed_c_objects.ensureUnusedCapacity(comp.gpa, 1);
         }
         comp.failed_c_objects.putAssumeCapacityNoClobber(c_object, err_msg);
     }
src/libcxx.zig
@@ -45,6 +45,7 @@ const libcxx_files = [_][]const u8{
     "src/filesystem/directory_iterator.cpp",
     "src/filesystem/int128_builtins.cpp",
     "src/filesystem/operations.cpp",
+    "src/format.cpp",
     "src/functional.cpp",
     "src/future.cpp",
     "src/hash.cpp",
@@ -64,6 +65,7 @@ const libcxx_files = [_][]const u8{
     "src/stdexcept.cpp",
     "src/string.cpp",
     "src/strstream.cpp",
+    "src/support/ibm/xlocale_zos.cpp",
     "src/support/solaris/xlocale.cpp",
     "src/support/win32/locale_win32.cpp",
     "src/support/win32/support.cpp",
src/libtsan.zig
@@ -260,7 +260,6 @@ const tsan_sources = [_][]const u8{
     "tsan_malloc_mac.cpp",
     "tsan_md5.cpp",
     "tsan_mman.cpp",
-    "tsan_mutex.cpp",
     "tsan_mutexset.cpp",
     "tsan_preinit.cpp",
     "tsan_report.cpp",
@@ -270,7 +269,6 @@ const tsan_sources = [_][]const u8{
     "tsan_rtl_report.cpp",
     "tsan_rtl_thread.cpp",
     "tsan_stack_trace.cpp",
-    "tsan_stat.cpp",
     "tsan_suppressions.cpp",
     "tsan_symbolize.cpp",
     "tsan_sync.cpp",
@@ -295,14 +293,15 @@ const sanitizer_common_sources = [_][]const u8{
     "sanitizer_deadlock_detector2.cpp",
     "sanitizer_errno.cpp",
     "sanitizer_file.cpp",
-    "sanitizer_flags.cpp",
     "sanitizer_flag_parser.cpp",
+    "sanitizer_flags.cpp",
     "sanitizer_fuchsia.cpp",
     "sanitizer_libc.cpp",
     "sanitizer_libignore.cpp",
     "sanitizer_linux.cpp",
     "sanitizer_linux_s390.cpp",
     "sanitizer_mac.cpp",
+    "sanitizer_mutex.cpp",
     "sanitizer_netbsd.cpp",
     "sanitizer_openbsd.cpp",
     "sanitizer_persistent_allocator.cpp",
@@ -314,20 +313,19 @@ const sanitizer_common_sources = [_][]const u8{
     "sanitizer_platform_limits_solaris.cpp",
     "sanitizer_posix.cpp",
     "sanitizer_printf.cpp",
-    "sanitizer_procmaps_common.cpp",
     "sanitizer_procmaps_bsd.cpp",
+    "sanitizer_procmaps_common.cpp",
     "sanitizer_procmaps_fuchsia.cpp",
     "sanitizer_procmaps_linux.cpp",
     "sanitizer_procmaps_mac.cpp",
     "sanitizer_procmaps_solaris.cpp",
-    "sanitizer_rtems.cpp",
     "sanitizer_solaris.cpp",
     "sanitizer_stoptheworld_fuchsia.cpp",
     "sanitizer_stoptheworld_mac.cpp",
     "sanitizer_suppressions.cpp",
     "sanitizer_termination.cpp",
-    "sanitizer_tls_get_addr.cpp",
     "sanitizer_thread_registry.cpp",
+    "sanitizer_tls_get_addr.cpp",
     "sanitizer_type_traits.cpp",
     "sanitizer_win.cpp",
 };