LLVM 22.0.0git
STLExtras.h
Go to the documentation of this file.
1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file contains some templates that are useful if you are working with
11/// the STL at all.
12///
13/// No library is required when using these functions.
14///
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/ADL.h"
21#include "llvm/ADT/Hashing.h"
24#include "llvm/ADT/iterator.h"
26#include "llvm/Config/abi-breaking.h"
28#include <algorithm>
29#include <cassert>
30#include <cstddef>
31#include <cstdint>
32#include <cstdlib>
33#include <functional>
34#include <initializer_list>
35#include <iterator>
36#include <limits>
37#include <memory>
38#include <numeric>
39#include <optional>
40#include <tuple>
41#include <type_traits>
42#include <utility>
43
44#ifdef EXPENSIVE_CHECKS
45#include <random> // for std::mt19937
46#endif
47
48namespace llvm {
49
50//===----------------------------------------------------------------------===//
51// Extra additions to <type_traits>
52//===----------------------------------------------------------------------===//
53
54template <typename T> struct make_const_ptr {
55 using type = std::add_pointer_t<std::add_const_t<T>>;
56};
57
58template <typename T> struct make_const_ref {
59 using type = std::add_lvalue_reference_t<std::add_const_t<T>>;
60};
61
62/// This class provides various trait information about a callable object.
63/// * To access the number of arguments: Traits::num_args
64/// * To access the type of an argument: Traits::arg_t<Index>
65/// * To access the type of the result: Traits::result_t
66template <typename T, bool isClass = std::is_class<T>::value>
67struct function_traits : public function_traits<decltype(&T::operator())> {};
68
69/// Overload for class function types.
70template <typename ClassType, typename ReturnType, typename... Args>
71struct function_traits<ReturnType (ClassType::*)(Args...) const, false> {
72 /// The number of arguments to this function.
73 enum { num_args = sizeof...(Args) };
74
75 /// The result type of this function.
76 using result_t = ReturnType;
77
78 /// The type of an argument to this function.
79 template <size_t Index>
80 using arg_t = std::tuple_element_t<Index, std::tuple<Args...>>;
81};
82/// Overload for class function types.
83template <typename ClassType, typename ReturnType, typename... Args>
84struct function_traits<ReturnType (ClassType::*)(Args...), false>
85 : public function_traits<ReturnType (ClassType::*)(Args...) const> {};
86/// Overload for non-class function types.
87template <typename ReturnType, typename... Args>
88struct function_traits<ReturnType (*)(Args...), false> {
89 /// The number of arguments to this function.
90 enum { num_args = sizeof...(Args) };
91
92 /// The result type of this function.
93 using result_t = ReturnType;
94
95 /// The type of an argument to this function.
96 template <size_t i>
97 using arg_t = std::tuple_element_t<i, std::tuple<Args...>>;
98};
99template <typename ReturnType, typename... Args>
100struct function_traits<ReturnType (*const)(Args...), false>
101 : public function_traits<ReturnType (*)(Args...)> {};
102/// Overload for non-class function type references.
103template <typename ReturnType, typename... Args>
104struct function_traits<ReturnType (&)(Args...), false>
105 : public function_traits<ReturnType (*)(Args...)> {};
106
107/// traits class for checking whether type T is one of any of the given
108/// types in the variadic list.
109template <typename T, typename... Ts>
110using is_one_of = std::disjunction<std::is_same<T, Ts>...>;
111
112/// traits class for checking whether type T is a base class for all
113/// the given types in the variadic list.
114template <typename T, typename... Ts>
115using are_base_of = std::conjunction<std::is_base_of<T, Ts>...>;
116
117/// Determine if all types in Ts are distinct.
118///
119/// Useful to statically assert when Ts is intended to describe a non-multi set
120/// of types.
121///
122/// Expensive (currently quadratic in sizeof(Ts...)), and so should only be
123/// asserted once per instantiation of a type which requires it.
124template <typename... Ts> struct TypesAreDistinct;
125template <> struct TypesAreDistinct<> : std::true_type {};
126template <typename T, typename... Us>
127struct TypesAreDistinct<T, Us...>
128 : std::conjunction<std::negation<is_one_of<T, Us...>>,
129 TypesAreDistinct<Us...>> {};
130
131/// Find the first index where a type appears in a list of types.
132///
133/// FirstIndexOfType<T, Us...>::value is the first index of T in Us.
134///
135/// Typically only meaningful when it is otherwise statically known that the
136/// type pack has no duplicate types. This should be guaranteed explicitly with
137/// static_assert(TypesAreDistinct<Us...>::value).
138///
139/// It is a compile-time error to instantiate when T is not present in Us, i.e.
140/// if is_one_of<T, Us...>::value is false.
141template <typename T, typename... Us> struct FirstIndexOfType;
142template <typename T, typename U, typename... Us>
143struct FirstIndexOfType<T, U, Us...>
144 : std::integral_constant<size_t, 1 + FirstIndexOfType<T, Us...>::value> {};
145template <typename T, typename... Us>
146struct FirstIndexOfType<T, T, Us...> : std::integral_constant<size_t, 0> {};
147
148/// Find the type at a given index in a list of types.
149///
150/// TypeAtIndex<I, Ts...> is the type at index I in Ts.
151template <size_t I, typename... Ts>
152using TypeAtIndex = std::tuple_element_t<I, std::tuple<Ts...>>;
153
154/// Helper which adds two underlying types of enumeration type.
155/// Implicit conversion to a common type is accepted.
156template <typename EnumTy1, typename EnumTy2,
157 typename UT1 = std::enable_if_t<std::is_enum<EnumTy1>::value,
158 std::underlying_type_t<EnumTy1>>,
159 typename UT2 = std::enable_if_t<std::is_enum<EnumTy2>::value,
160 std::underlying_type_t<EnumTy2>>>
161constexpr auto addEnumValues(EnumTy1 LHS, EnumTy2 RHS) {
162 return static_cast<UT1>(LHS) + static_cast<UT2>(RHS);
163}
164
165//===----------------------------------------------------------------------===//
166// Extra additions to <iterator>
167//===----------------------------------------------------------------------===//
168
170
171/// Templated storage wrapper for a callable.
172///
173/// This class is consistently default constructible, copy / move
174/// constructible / assignable.
175///
176/// Supported callable types:
177/// - Function pointer
178/// - Function reference
179/// - Lambda
180/// - Function object
181template <typename T,
182 bool = std::is_function_v<std::remove_pointer_t<remove_cvref_t<T>>>>
183class Callable {
184 using value_type = std::remove_reference_t<T>;
185 using reference = value_type &;
186 using const_reference = value_type const &;
187
188 std::optional<value_type> Obj;
189
190 static_assert(!std::is_pointer_v<value_type>,
191 "Pointers to non-functions are not callable.");
192
193public:
194 Callable() = default;
195 Callable(T const &O) : Obj(std::in_place, O) {}
196
197 Callable(Callable const &Other) = default;
198 Callable(Callable &&Other) = default;
199
201 Obj = std::nullopt;
202 if (Other.Obj)
203 Obj.emplace(*Other.Obj);
204 return *this;
205 }
206
208 Obj = std::nullopt;
209 if (Other.Obj)
210 Obj.emplace(std::move(*Other.Obj));
211 return *this;
212 }
213
214 template <typename... Pn,
215 std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0>
216 decltype(auto) operator()(Pn &&...Params) {
217 return (*Obj)(std::forward<Pn>(Params)...);
218 }
219
220 template <typename... Pn,
221 std::enable_if_t<std::is_invocable_v<T const, Pn...>, int> = 0>
222 decltype(auto) operator()(Pn &&...Params) const {
223 return (*Obj)(std::forward<Pn>(Params)...);
224 }
225
226 bool valid() const { return Obj != std::nullopt; }
227 bool reset() { return Obj = std::nullopt; }
228
229 operator reference() { return *Obj; }
230 operator const_reference() const { return *Obj; }
231};
232
233// Function specialization. No need to waste extra space wrapping with a
234// std::optional.
235template <typename T> class Callable<T, true> {
236 static constexpr bool IsPtr = std::is_pointer_v<remove_cvref_t<T>>;
237
238 using StorageT = std::conditional_t<IsPtr, T, std::remove_reference_t<T> *>;
239 using CastT = std::conditional_t<IsPtr, T, T &>;
240
241private:
242 StorageT Func = nullptr;
243
244private:
245 template <typename In> static constexpr auto convertIn(In &&I) {
246 if constexpr (IsPtr) {
247 // Pointer... just echo it back.
248 return I;
249 } else {
250 // Must be a function reference. Return its address.
251 return &I;
252 }
253 }
254
255public:
256 Callable() = default;
257
258 // Construct from a function pointer or reference.
259 //
260 // Disable this constructor for references to 'Callable' so we don't violate
261 // the rule of 0.
262 template < // clang-format off
263 typename FnPtrOrRef,
264 std::enable_if_t<
265 !std::is_same_v<remove_cvref_t<FnPtrOrRef>, Callable>, int
266 > = 0
267 > // clang-format on
268 Callable(FnPtrOrRef &&F) : Func(convertIn(F)) {}
269
270 template <typename... Pn,
271 std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0>
272 decltype(auto) operator()(Pn &&...Params) const {
273 return Func(std::forward<Pn>(Params)...);
274 }
275
276 bool valid() const { return Func != nullptr; }
277 void reset() { Func = nullptr; }
278
279 operator T const &() const {
280 if constexpr (IsPtr) {
281 // T is a pointer... just echo it back.
282 return Func;
283 } else {
284 static_assert(std::is_reference_v<T>,
285 "Expected a reference to a function.");
286 // T is a function reference... dereference the stored pointer.
287 return *Func;
288 }
289 }
290};
291
292} // namespace callable_detail
293
294/// Returns true if the given container only contains a single element.
295template <typename ContainerTy> bool hasSingleElement(ContainerTy &&C) {
296 auto B = adl_begin(C);
297 auto E = adl_end(C);
298 return B != E && std::next(B) == E;
299}
300
301/// Asserts that the given container has a single element and returns that
302/// element.
303template <typename ContainerTy>
304decltype(auto) getSingleElement(ContainerTy &&C) {
305 assert(hasSingleElement(C) && "expected container with single element");
306 return *adl_begin(C);
307}
308
309/// Return a range covering \p RangeOrContainer with the first N elements
310/// excluded.
311template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N = 1) {
312 return make_range(std::next(adl_begin(RangeOrContainer), N),
313 adl_end(RangeOrContainer));
314}
315
316/// Return a range covering \p RangeOrContainer with the last N elements
317/// excluded.
318template <typename T> auto drop_end(T &&RangeOrContainer, size_t N = 1) {
319 return make_range(adl_begin(RangeOrContainer),
320 std::prev(adl_end(RangeOrContainer), N));
321}
322
323// mapped_iterator - This is a simple iterator adapter that causes a function to
324// be applied whenever operator* is invoked on the iterator.
325
326template <typename ItTy, typename FuncTy,
327 typename ReferenceTy =
328 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
330 : public iterator_adaptor_base<
331 mapped_iterator<ItTy, FuncTy>, ItTy,
332 typename std::iterator_traits<ItTy>::iterator_category,
333 std::remove_reference_t<ReferenceTy>,
334 typename std::iterator_traits<ItTy>::difference_type,
335 std::remove_reference_t<ReferenceTy> *, ReferenceTy> {
336public:
337 mapped_iterator() = default;
340
341 ItTy getCurrent() { return this->I; }
342
343 const FuncTy &getFunction() const { return F; }
344
345 ReferenceTy operator*() const { return F(*this->I); }
346
347private:
349};
350
351// map_iterator - Provide a convenient way to create mapped_iterators, just like
352// make_pair is useful for creating pairs...
353template <class ItTy, class FuncTy>
355 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
356}
357
358template <class ContainerTy, class FuncTy>
359auto map_range(ContainerTy &&C, FuncTy F) {
361}
362
363/// A base type of mapped iterator, that is useful for building derived
364/// iterators that do not need/want to store the map function (as in
365/// mapped_iterator). These iterators must simply provide a `mapElement` method
366/// that defines how to map a value of the iterator to the provided reference
367/// type.
368template <typename DerivedT, typename ItTy, typename ReferenceTy>
370 : public iterator_adaptor_base<
371 DerivedT, ItTy,
372 typename std::iterator_traits<ItTy>::iterator_category,
373 std::remove_reference_t<ReferenceTy>,
374 typename std::iterator_traits<ItTy>::difference_type,
375 std::remove_reference_t<ReferenceTy> *, ReferenceTy> {
376public:
378
381
382 ItTy getCurrent() { return this->I; }
383
384 ReferenceTy operator*() const {
385 return static_cast<const DerivedT &>(*this).mapElement(*this->I);
386 }
387};
388
389namespace detail {
390template <typename Range>
392 decltype(adl_rbegin(std::declval<Range &>()));
393
394template <typename Range>
395static constexpr bool HasFreeFunctionRBegin =
397} // namespace detail
398
399// Returns an iterator_range over the given container which iterates in reverse.
400// Does not mutate the container.
401template <typename ContainerTy> [[nodiscard]] auto reverse(ContainerTy &&C) {
403 return make_range(adl_rbegin(C), adl_rend(C));
404 else
405 return make_range(std::make_reverse_iterator(adl_end(C)),
406 std::make_reverse_iterator(adl_begin(C)));
407}
408
409/// An iterator adaptor that filters the elements of given inner iterators.
410///
411/// The predicate parameter should be a callable object that accepts the wrapped
412/// iterator's reference type and returns a bool. When incrementing or
413/// decrementing the iterator, it will call the predicate on each element and
414/// skip any where it returns false.
415///
416/// \code
417/// int A[] = { 1, 2, 3, 4 };
418/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
419/// // R contains { 1, 3 }.
420/// \endcode
421///
422/// Note: filter_iterator_base implements support for forward iteration.
423/// filter_iterator_impl exists to provide support for bidirectional iteration,
424/// conditional on whether the wrapped iterator supports it.
425template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
427 : public iterator_adaptor_base<
428 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
429 WrappedIteratorT,
430 std::common_type_t<IterTag,
431 typename std::iterator_traits<
432 WrappedIteratorT>::iterator_category>> {
433 using BaseT = typename filter_iterator_base::iterator_adaptor_base;
434
435protected:
438
440 while (this->I != End && !Pred(*this->I))
441 BaseT::operator++();
442 }
443
445
446 // Construct the iterator. The begin iterator needs to know where the end
447 // is, so that it can properly stop when it gets there. The end iterator only
448 // needs the predicate to support bidirectional iteration.
454
455public:
456 using BaseT::operator++;
457
459 BaseT::operator++();
461 return *this;
462 }
463
464 decltype(auto) operator*() const {
465 assert(BaseT::wrapped() != End && "Cannot dereference end iterator!");
466 return BaseT::operator*();
467 }
468
469 decltype(auto) operator->() const {
470 assert(BaseT::wrapped() != End && "Cannot dereference end iterator!");
471 return BaseT::operator->();
472 }
473};
474
475/// Specialization of filter_iterator_base for forward iteration only.
476template <typename WrappedIteratorT, typename PredicateT,
477 typename IterTag = std::forward_iterator_tag>
479 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
480public:
482
486};
487
488/// Specialization of filter_iterator_base for bidirectional iteration.
489template <typename WrappedIteratorT, typename PredicateT>
491 std::bidirectional_iterator_tag>
492 : public filter_iterator_base<WrappedIteratorT, PredicateT,
493 std::bidirectional_iterator_tag> {
494 using BaseT = typename filter_iterator_impl::filter_iterator_base;
495
496 void findPrevValid() {
497 while (!this->Pred(*this->I))
498 BaseT::operator--();
499 }
500
501public:
502 using BaseT::operator--;
503
505
509
511 BaseT::operator--();
512 findPrevValid();
513 return *this;
514 }
515};
516
517namespace detail {
518
519/// A type alias which is std::bidirectional_iterator_tag if the category of
520/// \p IterT derives from it, and std::forward_iterator_tag otherwise.
521template <typename IterT>
522using fwd_or_bidi_tag = std::conditional_t<
523 std::is_base_of_v<std::bidirectional_iterator_tag,
524 typename std::iterator_traits<IterT>::iterator_category>,
525 std::bidirectional_iterator_tag, std::forward_iterator_tag>;
526
527} // namespace detail
528
529/// Defines filter_iterator to a suitable specialization of
530/// filter_iterator_impl, based on the underlying iterator's category.
531template <typename WrappedIteratorT, typename PredicateT>
535
536/// Convenience function that takes a range of elements and a predicate,
537/// and return a new filter_iterator range.
538///
539/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
540/// lifetime of that temporary is not kept by the returned range object, and the
541/// temporary is going to be dropped on the floor after the make_iterator_range
542/// full expression that contains this function call.
543template <typename RangeT, typename PredicateT>
546 using FilterIteratorT =
548 auto B = adl_begin(Range);
549 auto E = adl_end(Range);
550 return make_range(FilterIteratorT(B, E, Pred), FilterIteratorT(E, E, Pred));
551}
552
553/// A pseudo-iterator adaptor that is designed to implement "early increment"
554/// style loops.
555///
556/// This is *not a normal iterator* and should almost never be used directly. It
557/// is intended primarily to be used with range based for loops and some range
558/// algorithms.
559///
560/// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
561/// somewhere between them. The constraints of these iterators are:
562///
563/// - On construction or after being incremented, it is comparable and
564/// dereferencable. It is *not* incrementable.
565/// - After being dereferenced, it is neither comparable nor dereferencable, it
566/// is only incrementable.
567///
568/// This means you can only dereference the iterator once, and you can only
569/// increment it once between dereferences.
570template <typename WrappedIteratorT>
572 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
573 WrappedIteratorT, std::input_iterator_tag> {
575
576 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
577
578protected:
579#if LLVM_ENABLE_ABI_BREAKING_CHECKS
580 bool IsEarlyIncremented = false;
581#endif
582
583public:
585
586 using BaseT::operator*;
587 decltype(*std::declval<WrappedIteratorT>()) operator*() {
588#if LLVM_ENABLE_ABI_BREAKING_CHECKS
589 assert(!IsEarlyIncremented && "Cannot dereference twice!");
590 IsEarlyIncremented = true;
591#endif
592 return *(this->I)++;
593 }
594
595 using BaseT::operator++;
597#if LLVM_ENABLE_ABI_BREAKING_CHECKS
598 assert(IsEarlyIncremented && "Cannot increment before dereferencing!");
599 IsEarlyIncremented = false;
600#endif
601 return *this;
602 }
603
606#if LLVM_ENABLE_ABI_BREAKING_CHECKS
607 assert(!LHS.IsEarlyIncremented && "Cannot compare after dereferencing!");
608#endif
609 return (const BaseT &)LHS == (const BaseT &)RHS;
610 }
611};
612
613/// Make a range that does early increment to allow mutation of the underlying
614/// range without disrupting iteration.
615///
616/// The underlying iterator will be incremented immediately after it is
617/// dereferenced, allowing deletion of the current node or insertion of nodes to
618/// not disrupt iteration provided they do not invalidate the *next* iterator --
619/// the current iterator can be invalidated.
620///
621/// This requires a very exact pattern of use that is only really suitable to
622/// range based for loops and other range algorithms that explicitly guarantee
623/// to dereference exactly once each element, and to increment exactly once each
624/// element.
625template <typename RangeT>
628 using EarlyIncIteratorT =
630 return make_range(EarlyIncIteratorT(adl_begin(Range)),
631 EarlyIncIteratorT(adl_end(Range)));
632}
633
634// Forward declarations required by zip_shortest/zip_equal/zip_first/zip_longest
635template <typename R, typename UnaryPredicate>
636bool all_of(R &&range, UnaryPredicate P);
637
638template <typename R, typename UnaryPredicate>
639bool any_of(R &&range, UnaryPredicate P);
640
641template <typename T> bool all_equal(std::initializer_list<T> Values);
642
643template <typename R> constexpr size_t range_size(R &&Range);
644
645namespace detail {
646
647using std::declval;
648
649// We have to alias this since inlining the actual type at the usage site
650// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
651template<typename... Iters> struct ZipTupleType {
652 using type = std::tuple<decltype(*declval<Iters>())...>;
653};
654
655template <typename ZipType, typename ReferenceTupleType, typename... Iters>
657 ZipType,
658 std::common_type_t<
659 std::bidirectional_iterator_tag,
660 typename std::iterator_traits<Iters>::iterator_category...>,
661 // ^ TODO: Implement random access methods.
662 ReferenceTupleType,
663 typename std::iterator_traits<
664 std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type,
665 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
666 // inner iterators have the same difference_type. It would fail if, for
667 // instance, the second field's difference_type were non-numeric while the
668 // first is.
669 ReferenceTupleType *, ReferenceTupleType>;
670
671template <typename ZipType, typename ReferenceTupleType, typename... Iters>
672struct zip_common : public zip_traits<ZipType, ReferenceTupleType, Iters...> {
673 using Base = zip_traits<ZipType, ReferenceTupleType, Iters...>;
674 using IndexSequence = std::index_sequence_for<Iters...>;
675 using value_type = typename Base::value_type;
676
677 std::tuple<Iters...> iterators;
678
679protected:
680 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
681 return value_type(*std::get<Ns>(iterators)...);
682 }
683
684 template <size_t... Ns> void tup_inc(std::index_sequence<Ns...>) {
685 (++std::get<Ns>(iterators), ...);
686 }
687
688 template <size_t... Ns> void tup_dec(std::index_sequence<Ns...>) {
689 (--std::get<Ns>(iterators), ...);
690 }
691
692 template <size_t... Ns>
693 bool test_all_equals(const zip_common &other,
694 std::index_sequence<Ns...>) const {
695 return ((std::get<Ns>(this->iterators) == std::get<Ns>(other.iterators)) &&
696 ...);
697 }
698
699public:
700 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
701
703
704 ZipType &operator++() {
706 return static_cast<ZipType &>(*this);
707 }
708
709 ZipType &operator--() {
710 static_assert(Base::IsBidirectional,
711 "All inner iterators must be at least bidirectional.");
713 return static_cast<ZipType &>(*this);
714 }
715
716 /// Return true if all the iterator are matching `other`'s iterators.
717 bool all_equals(zip_common &other) {
718 return test_all_equals(other, IndexSequence{});
719 }
720};
721
722template <typename... Iters>
723struct zip_first : zip_common<zip_first<Iters...>,
724 typename ZipTupleType<Iters...>::type, Iters...> {
725 using zip_common<zip_first, typename ZipTupleType<Iters...>::type,
726 Iters...>::zip_common;
727
728 bool operator==(const zip_first &other) const {
729 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
730 }
731};
732
733template <typename... Iters>
735 : zip_common<zip_shortest<Iters...>, typename ZipTupleType<Iters...>::type,
736 Iters...> {
737 using zip_common<zip_shortest, typename ZipTupleType<Iters...>::type,
738 Iters...>::zip_common;
739
740 bool operator==(const zip_shortest &other) const {
741 return any_iterator_equals(other, std::index_sequence_for<Iters...>{});
742 }
743
744private:
745 template <size_t... Ns>
746 bool any_iterator_equals(const zip_shortest &other,
747 std::index_sequence<Ns...>) const {
748 return ((std::get<Ns>(this->iterators) == std::get<Ns>(other.iterators)) ||
749 ...);
750 }
751};
752
753/// Helper to obtain the iterator types for the tuple storage within `zippy`.
754template <template <typename...> class ItType, typename TupleStorageType,
755 typename IndexSequence>
757
758/// Partial specialization for non-const tuple storage.
759template <template <typename...> class ItType, typename... Args,
760 std::size_t... Ns>
761struct ZippyIteratorTuple<ItType, std::tuple<Args...>,
762 std::index_sequence<Ns...>> {
763 using type = ItType<decltype(adl_begin(
764 std::get<Ns>(declval<std::tuple<Args...> &>())))...>;
765};
766
767/// Partial specialization for const tuple storage.
768template <template <typename...> class ItType, typename... Args,
769 std::size_t... Ns>
770struct ZippyIteratorTuple<ItType, const std::tuple<Args...>,
771 std::index_sequence<Ns...>> {
772 using type = ItType<decltype(adl_begin(
773 std::get<Ns>(declval<const std::tuple<Args...> &>())))...>;
774};
775
776template <template <typename...> class ItType, typename... Args> class zippy {
777private:
778 std::tuple<Args...> storage;
779 using IndexSequence = std::index_sequence_for<Args...>;
780
781public:
782 using iterator = typename ZippyIteratorTuple<ItType, decltype(storage),
783 IndexSequence>::type;
785 typename ZippyIteratorTuple<ItType, const decltype(storage),
786 IndexSequence>::type;
787 using iterator_category = typename iterator::iterator_category;
788 using value_type = typename iterator::value_type;
789 using difference_type = typename iterator::difference_type;
790 using pointer = typename iterator::pointer;
791 using reference = typename iterator::reference;
792 using const_reference = typename const_iterator::reference;
793
794 zippy(Args &&...args) : storage(std::forward<Args>(args)...) {}
795
796 const_iterator begin() const { return begin_impl(IndexSequence{}); }
797 iterator begin() { return begin_impl(IndexSequence{}); }
798 const_iterator end() const { return end_impl(IndexSequence{}); }
799 iterator end() { return end_impl(IndexSequence{}); }
800
801private:
802 template <size_t... Ns>
803 const_iterator begin_impl(std::index_sequence<Ns...>) const {
804 return const_iterator(adl_begin(std::get<Ns>(storage))...);
805 }
806 template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) {
807 return iterator(adl_begin(std::get<Ns>(storage))...);
808 }
809
810 template <size_t... Ns>
811 const_iterator end_impl(std::index_sequence<Ns...>) const {
812 return const_iterator(adl_end(std::get<Ns>(storage))...);
813 }
814 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) {
815 return iterator(adl_end(std::get<Ns>(storage))...);
816 }
817};
818
819} // end namespace detail
820
821/// zip iterator for two or more iteratable types. Iteration continues until the
822/// end of the *shortest* iteratee is reached.
823template <typename T, typename U, typename... Args>
824detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
825 Args &&...args) {
826 return detail::zippy<detail::zip_shortest, T, U, Args...>(
827 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
828}
829
830/// zip iterator that assumes that all iteratees have the same length.
831/// In builds with assertions on, this assumption is checked before the
832/// iteration starts.
833template <typename T, typename U, typename... Args>
834detail::zippy<detail::zip_first, T, U, Args...> zip_equal(T &&t, U &&u,
835 Args &&...args) {
837 "Iteratees do not have equal length");
838 return detail::zippy<detail::zip_first, T, U, Args...>(
839 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
840}
841
842/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
843/// be the shortest. Iteration continues until the end of the first iteratee is
844/// reached. In builds with assertions on, we check that the assumption about
845/// the first iteratee being the shortest holds.
846template <typename T, typename U, typename... Args>
847detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
848 Args &&...args) {
849 assert(range_size(t) <= std::min({range_size(u), range_size(args)...}) &&
850 "First iteratee is not the shortest");
851
852 return detail::zippy<detail::zip_first, T, U, Args...>(
853 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
854}
855
856namespace detail {
857template <typename Iter>
858Iter next_or_end(const Iter &I, const Iter &End) {
859 if (I == End)
860 return End;
861 return std::next(I);
862}
863
864template <typename Iter>
865auto deref_or_none(const Iter &I, const Iter &End) -> std::optional<
866 std::remove_const_t<std::remove_reference_t<decltype(*I)>>> {
867 if (I == End)
868 return std::nullopt;
869 return *I;
870}
871
872template <typename Iter> struct ZipLongestItemType {
873 using type = std::optional<std::remove_const_t<
874 std::remove_reference_t<decltype(*std::declval<Iter>())>>>;
875};
876
877template <typename... Iters> struct ZipLongestTupleType {
878 using type = std::tuple<typename ZipLongestItemType<Iters>::type...>;
879};
880
881template <typename... Iters>
883 : public iterator_facade_base<
884 zip_longest_iterator<Iters...>,
885 std::common_type_t<
886 std::forward_iterator_tag,
887 typename std::iterator_traits<Iters>::iterator_category...>,
888 typename ZipLongestTupleType<Iters...>::type,
889 typename std::iterator_traits<
890 std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type,
891 typename ZipLongestTupleType<Iters...>::type *,
892 typename ZipLongestTupleType<Iters...>::type> {
893public:
894 using value_type = typename ZipLongestTupleType<Iters...>::type;
895
896private:
897 std::tuple<Iters...> iterators;
898 std::tuple<Iters...> end_iterators;
899
900 template <size_t... Ns>
901 bool test(const zip_longest_iterator<Iters...> &other,
902 std::index_sequence<Ns...>) const {
903 return ((std::get<Ns>(this->iterators) != std::get<Ns>(other.iterators)) ||
904 ...);
905 }
906
907 template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const {
908 return value_type(
909 deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
910 }
911
912 template <size_t... Ns>
913 decltype(iterators) tup_inc(std::index_sequence<Ns...>) const {
914 return std::tuple<Iters...>(
915 next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...);
916 }
917
918public:
919 zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts)
920 : iterators(std::forward<Iters>(ts.first)...),
921 end_iterators(std::forward<Iters>(ts.second)...) {}
922
924 return deref(std::index_sequence_for<Iters...>{});
925 }
926
928 iterators = tup_inc(std::index_sequence_for<Iters...>{});
929 return *this;
930 }
931
933 return !test(other, std::index_sequence_for<Iters...>{});
934 }
935};
936
937template <typename... Args> class zip_longest_range {
938public:
939 using iterator =
944 using pointer = typename iterator::pointer;
946
947private:
948 std::tuple<Args...> ts;
949
950 template <size_t... Ns>
951 iterator begin_impl(std::index_sequence<Ns...>) const {
952 return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)),
953 adl_end(std::get<Ns>(ts)))...);
954 }
955
956 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
957 return iterator(std::make_pair(adl_end(std::get<Ns>(ts)),
958 adl_end(std::get<Ns>(ts)))...);
959 }
960
961public:
962 zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
963
964 iterator begin() const {
965 return begin_impl(std::index_sequence_for<Args...>{});
966 }
967 iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); }
968};
969} // namespace detail
970
971/// Iterate over two or more iterators at the same time. Iteration continues
972/// until all iterators reach the end. The std::optional only contains a value
973/// if the iterator has not reached the end.
974template <typename T, typename U, typename... Args>
975detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u,
976 Args &&... args) {
977 return detail::zip_longest_range<T, U, Args...>(
978 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
979}
980
981/// Iterator wrapper that concatenates sequences together.
982///
983/// This can concatenate different iterators, even with different types, into
984/// a single iterator provided the value types of all the concatenated
985/// iterators expose `reference` and `pointer` types that can be converted to
986/// `ValueT &` and `ValueT *` respectively. It doesn't support more
987/// interesting/customized pointer or reference types.
988///
989/// Currently this only supports forward or higher iterator categories as
990/// inputs and always exposes a forward iterator interface.
991template <typename ValueT, typename... IterTs>
993 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
994 std::forward_iterator_tag, ValueT> {
995 using BaseT = typename concat_iterator::iterator_facade_base;
996
997 static constexpr bool ReturnsByValue =
998 !(std::is_reference_v<decltype(*std::declval<IterTs>())> && ...);
999
1000 using reference_type =
1001 typename std::conditional_t<ReturnsByValue, ValueT, ValueT &>;
1002
1003 using handle_type =
1004 typename std::conditional_t<ReturnsByValue, std::optional<ValueT>,
1005 ValueT *>;
1006
1007 /// We store both the current and end iterators for each concatenated
1008 /// sequence in a tuple of pairs.
1009 ///
1010 /// Note that something like iterator_range seems nice at first here, but the
1011 /// range properties are of little benefit and end up getting in the way
1012 /// because we need to do mutation on the current iterators.
1013 std::tuple<IterTs...> Begins;
1014 std::tuple<IterTs...> Ends;
1015
1016 /// Attempts to increment a specific iterator.
1017 ///
1018 /// Returns true if it was able to increment the iterator. Returns false if
1019 /// the iterator is already at the end iterator.
1020 template <size_t Index> bool incrementHelper() {
1021 auto &Begin = std::get<Index>(Begins);
1022 auto &End = std::get<Index>(Ends);
1023 if (Begin == End)
1024 return false;
1025
1026 ++Begin;
1027 return true;
1028 }
1029
1030 /// Increments the first non-end iterator.
1031 ///
1032 /// It is an error to call this with all iterators at the end.
1033 template <size_t... Ns> void increment(std::index_sequence<Ns...>) {
1034 // Build a sequence of functions to increment each iterator if possible.
1035 bool (concat_iterator::*IncrementHelperFns[])() = {
1036 &concat_iterator::incrementHelper<Ns>...};
1037
1038 // Loop over them, and stop as soon as we succeed at incrementing one.
1039 for (auto &IncrementHelperFn : IncrementHelperFns)
1040 if ((this->*IncrementHelperFn)())
1041 return;
1042
1043 llvm_unreachable("Attempted to increment an end concat iterator!");
1044 }
1045
1046 /// Returns null if the specified iterator is at the end. Otherwise,
1047 /// dereferences the iterator and returns the address of the resulting
1048 /// reference.
1049 template <size_t Index> handle_type getHelper() const {
1050 auto &Begin = std::get<Index>(Begins);
1051 auto &End = std::get<Index>(Ends);
1052 if (Begin == End)
1053 return {};
1054
1055 if constexpr (ReturnsByValue)
1056 return *Begin;
1057 else
1058 return &*Begin;
1059 }
1060
1061 /// Finds the first non-end iterator, dereferences, and returns the resulting
1062 /// reference.
1063 ///
1064 /// It is an error to call this with all iterators at the end.
1065 template <size_t... Ns> reference_type get(std::index_sequence<Ns...>) const {
1066 // Build a sequence of functions to get from iterator if possible.
1067 handle_type (concat_iterator::*GetHelperFns[])()
1068 const = {&concat_iterator::getHelper<Ns>...};
1069
1070 // Loop over them, and return the first result we find.
1071 for (auto &GetHelperFn : GetHelperFns)
1072 if (auto P = (this->*GetHelperFn)())
1073 return *P;
1074
1075 llvm_unreachable("Attempted to get a pointer from an end concat iterator!");
1076 }
1077
1078public:
1079 /// Constructs an iterator from a sequence of ranges.
1080 ///
1081 /// We need the full range to know how to switch between each of the
1082 /// iterators.
1083 template <typename... RangeTs>
1084 explicit concat_iterator(RangeTs &&...Ranges)
1085 : Begins(adl_begin(Ranges)...), Ends(adl_end(Ranges)...) {}
1086
1087 using BaseT::operator++;
1088
1090 increment(std::index_sequence_for<IterTs...>());
1091 return *this;
1092 }
1093
1094 reference_type operator*() const {
1095 return get(std::index_sequence_for<IterTs...>());
1096 }
1097
1098 bool operator==(const concat_iterator &RHS) const {
1099 return Begins == RHS.Begins && Ends == RHS.Ends;
1100 }
1101};
1102
1103namespace detail {
1104
1105/// Helper to store a sequence of ranges being concatenated and access them.
1106///
1107/// This is designed to facilitate providing actual storage when temporaries
1108/// are passed into the constructor such that we can use it as part of range
1109/// based for loops.
1110template <typename ValueT, typename... RangeTs> class concat_range {
1111public:
1112 using iterator =
1113 concat_iterator<ValueT,
1114 decltype(adl_begin(std::declval<RangeTs &>()))...>;
1115
1116private:
1117 std::tuple<RangeTs...> Ranges;
1118
1119 template <size_t... Ns> iterator begin_impl(std::index_sequence<Ns...>) {
1120 return iterator(std::get<Ns>(Ranges)...);
1121 }
1122 template <size_t... Ns>
1123 iterator begin_impl(std::index_sequence<Ns...>) const {
1124 return iterator(std::get<Ns>(Ranges)...);
1125 }
1126 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) {
1127 return iterator(make_range(adl_end(std::get<Ns>(Ranges)),
1128 adl_end(std::get<Ns>(Ranges)))...);
1129 }
1130 template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const {
1131 return iterator(make_range(adl_end(std::get<Ns>(Ranges)),
1132 adl_end(std::get<Ns>(Ranges)))...);
1133 }
1134
1135public:
1136 concat_range(RangeTs &&... Ranges)
1137 : Ranges(std::forward<RangeTs>(Ranges)...) {}
1138
1140 return begin_impl(std::index_sequence_for<RangeTs...>{});
1141 }
1142 iterator begin() const {
1143 return begin_impl(std::index_sequence_for<RangeTs...>{});
1144 }
1146 return end_impl(std::index_sequence_for<RangeTs...>{});
1147 }
1148 iterator end() const {
1149 return end_impl(std::index_sequence_for<RangeTs...>{});
1150 }
1151};
1152
1153} // end namespace detail
1154
1155/// Returns a concatenated range across two or more ranges. Does not modify the
1156/// ranges.
1157///
1158/// The desired value type must be explicitly specified.
1159template <typename ValueT, typename... RangeTs>
1160[[nodiscard]] detail::concat_range<ValueT, RangeTs...>
1161concat(RangeTs &&...Ranges) {
1162 static_assert(sizeof...(RangeTs) > 1,
1163 "Need more than one range to concatenate!");
1164 return detail::concat_range<ValueT, RangeTs...>(
1165 std::forward<RangeTs>(Ranges)...);
1166}
1167
1168/// A utility class used to implement an iterator that contains some base object
1169/// and an index. The iterator moves the index but keeps the base constant.
1170template <typename DerivedT, typename BaseT, typename T,
1171 typename PointerT = T *, typename ReferenceT = T &>
1173 : public llvm::iterator_facade_base<DerivedT,
1174 std::random_access_iterator_tag, T,
1175 std::ptrdiff_t, PointerT, ReferenceT> {
1176public:
1178 assert(base == rhs.base && "incompatible iterators");
1179 return index - rhs.index;
1180 }
1181 bool operator==(const indexed_accessor_iterator &rhs) const {
1182 assert(base == rhs.base && "incompatible iterators");
1183 return index == rhs.index;
1184 }
1185 bool operator<(const indexed_accessor_iterator &rhs) const {
1186 assert(base == rhs.base && "incompatible iterators");
1187 return index < rhs.index;
1188 }
1189
1190 DerivedT &operator+=(ptrdiff_t offset) {
1191 this->index += offset;
1192 return static_cast<DerivedT &>(*this);
1193 }
1194 DerivedT &operator-=(ptrdiff_t offset) {
1195 this->index -= offset;
1196 return static_cast<DerivedT &>(*this);
1197 }
1198
1199 /// Returns the current index of the iterator.
1200 ptrdiff_t getIndex() const { return index; }
1201
1202 /// Returns the current base of the iterator.
1203 const BaseT &getBase() const { return base; }
1204
1205protected:
1208 BaseT base;
1210};
1211
1212namespace detail {
1213/// The class represents the base of a range of indexed_accessor_iterators. It
1214/// provides support for many different range functionalities, e.g.
1215/// drop_front/slice/etc.. Derived range classes must implement the following
1216/// static methods:
1217/// * ReferenceT dereference_iterator(const BaseT &base, ptrdiff_t index)
1218/// - Dereference an iterator pointing to the base object at the given
1219/// index.
1220/// * BaseT offset_base(const BaseT &base, ptrdiff_t index)
1221/// - Return a new base that is offset from the provide base by 'index'
1222/// elements.
1223template <typename DerivedT, typename BaseT, typename T,
1224 typename PointerT = T *, typename ReferenceT = T &>
1226public:
1228
1229 /// An iterator element of this range.
1230 class iterator : public indexed_accessor_iterator<iterator, BaseT, T,
1231 PointerT, ReferenceT> {
1232 public:
1233 // Index into this iterator, invoking a static method on the derived type.
1234 ReferenceT operator*() const {
1235 return DerivedT::dereference_iterator(this->getBase(), this->getIndex());
1236 }
1237
1238 private:
1239 iterator(BaseT owner, ptrdiff_t curIndex)
1240 : iterator::indexed_accessor_iterator(owner, curIndex) {}
1241
1242 /// Allow access to the constructor.
1243 friend indexed_accessor_range_base<DerivedT, BaseT, T, PointerT,
1244 ReferenceT>;
1245 };
1246
1248 : base(offset_base(begin.getBase(), begin.getIndex())),
1249 count(end.getIndex() - begin.getIndex()) {}
1254
1255 iterator begin() const { return iterator(base, 0); }
1256 iterator end() const { return iterator(base, count); }
1257 ReferenceT operator[](size_t Index) const {
1258 assert(Index < size() && "invalid index for value range");
1259 return DerivedT::dereference_iterator(base, static_cast<ptrdiff_t>(Index));
1260 }
1261 ReferenceT front() const {
1262 assert(!empty() && "expected non-empty range");
1263 return (*this)[0];
1264 }
1265 ReferenceT back() const {
1266 assert(!empty() && "expected non-empty range");
1267 return (*this)[size() - 1];
1268 }
1269
1270 /// Return the size of this range.
1271 size_t size() const { return count; }
1272
1273 /// Return if the range is empty.
1274 bool empty() const { return size() == 0; }
1275
1276 /// Drop the first N elements, and keep M elements.
1277 DerivedT slice(size_t n, size_t m) const {
1278 assert(n + m <= size() && "invalid size specifiers");
1279 return DerivedT(offset_base(base, n), m);
1280 }
1281
1282 /// Drop the first n elements.
1283 DerivedT drop_front(size_t n = 1) const {
1284 assert(size() >= n && "Dropping more elements than exist");
1285 return slice(n, size() - n);
1286 }
1287 /// Drop the last n elements.
1288 DerivedT drop_back(size_t n = 1) const {
1289 assert(size() >= n && "Dropping more elements than exist");
1290 return DerivedT(base, size() - n);
1291 }
1292
1293 /// Take the first n elements.
1294 DerivedT take_front(size_t n = 1) const {
1295 return n < size() ? drop_back(size() - n)
1296 : static_cast<const DerivedT &>(*this);
1297 }
1298
1299 /// Take the last n elements.
1300 DerivedT take_back(size_t n = 1) const {
1301 return n < size() ? drop_front(size() - n)
1302 : static_cast<const DerivedT &>(*this);
1303 }
1304
1305 /// Allow conversion to any type accepting an iterator_range.
1306 template <typename RangeT, typename = std::enable_if_t<std::is_constructible<
1308 operator RangeT() const {
1309 return RangeT(iterator_range<iterator>(*this));
1310 }
1311
1312 /// Returns the base of this range.
1313 const BaseT &getBase() const { return base; }
1314
1315private:
1316 /// Offset the given base by the given amount.
1317 static BaseT offset_base(const BaseT &base, size_t n) {
1318 return n == 0 ? base : DerivedT::offset_base(base, n);
1319 }
1320
1321protected:
1326
1327 /// The base that owns the provided range of values.
1328 BaseT base;
1329 /// The size from the owning range.
1331};
1332/// Compare this range with another.
1333/// FIXME: Make me a member function instead of friend when it works in C++20.
1334template <typename OtherT, typename DerivedT, typename BaseT, typename T,
1335 typename PointerT, typename ReferenceT>
1336bool operator==(const indexed_accessor_range_base<DerivedT, BaseT, T, PointerT,
1337 ReferenceT> &lhs,
1338 const OtherT &rhs) {
1339 return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
1340}
1341
1342template <typename OtherT, typename DerivedT, typename BaseT, typename T,
1343 typename PointerT, typename ReferenceT>
1344bool operator!=(const indexed_accessor_range_base<DerivedT, BaseT, T, PointerT,
1345 ReferenceT> &lhs,
1346 const OtherT &rhs) {
1347 return !(lhs == rhs);
1348}
1349} // end namespace detail
1350
1351/// This class provides an implementation of a range of
1352/// indexed_accessor_iterators where the base is not indexable. Ranges with
1353/// bases that are offsetable should derive from indexed_accessor_range_base
1354/// instead. Derived range classes are expected to implement the following
1355/// static method:
1356/// * ReferenceT dereference(const BaseT &base, ptrdiff_t index)
1357/// - Dereference an iterator pointing to a parent base at the given index.
1358template <typename DerivedT, typename BaseT, typename T,
1359 typename PointerT = T *, typename ReferenceT = T &>
1362 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT> {
1363public:
1366 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT>(
1367 std::make_pair(base, startIndex), count) {}
1369 DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT,
1371
1372 /// Returns the current base of the range.
1373 const BaseT &getBase() const { return this->base.first; }
1374
1375 /// Returns the current start index of the range.
1376 ptrdiff_t getStartIndex() const { return this->base.second; }
1377
1378 /// See `detail::indexed_accessor_range_base` for details.
1379 static std::pair<BaseT, ptrdiff_t>
1380 offset_base(const std::pair<BaseT, ptrdiff_t> &base, ptrdiff_t index) {
1381 // We encode the internal base as a pair of the derived base and a start
1382 // index into the derived base.
1383 return std::make_pair(base.first, base.second + index);
1384 }
1385 /// See `detail::indexed_accessor_range_base` for details.
1386 static ReferenceT
1387 dereference_iterator(const std::pair<BaseT, ptrdiff_t> &base,
1388 ptrdiff_t index) {
1389 return DerivedT::dereference(base.first, base.second + index);
1390 }
1391};
1392
1393namespace detail {
1394/// Return a reference to the first or second member of a reference. Otherwise,
1395/// return a copy of the member of a temporary.
1396///
1397/// When passing a range whose iterators return values instead of references,
1398/// the reference must be dropped from `decltype((elt.first))`, which will
1399/// always be a reference, to avoid returning a reference to a temporary.
1400template <typename EltTy, typename FirstTy> class first_or_second_type {
1401public:
1402 using type = std::conditional_t<std::is_reference<EltTy>::value, FirstTy,
1403 std::remove_reference_t<FirstTy>>;
1404};
1405} // end namespace detail
1406
1407/// Given a container of pairs, return a range over the first elements.
1408template <typename ContainerTy> auto make_first_range(ContainerTy &&c) {
1409 using EltTy = decltype(*adl_begin(c));
1410 return llvm::map_range(std::forward<ContainerTy>(c),
1411 [](EltTy elt) -> typename detail::first_or_second_type<
1412 EltTy, decltype((elt.first))>::type {
1413 return elt.first;
1414 });
1415}
1416
1417/// Given a container of pairs, return a range over the second elements.
1418template <typename ContainerTy> auto make_second_range(ContainerTy &&c) {
1419 using EltTy = decltype(*adl_begin(c));
1420 return llvm::map_range(
1421 std::forward<ContainerTy>(c),
1422 [](EltTy elt) ->
1423 typename detail::first_or_second_type<EltTy,
1424 decltype((elt.second))>::type {
1425 return elt.second;
1426 });
1427}
1428
1429//===----------------------------------------------------------------------===//
1430// Extra additions to <utility>
1431//===----------------------------------------------------------------------===//
1432
1433/// Function object to check whether the first component of a container
1434/// supported by std::get (like std::pair and std::tuple) compares less than the
1435/// first component of another container.
1437 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
1438 return std::less<>()(std::get<0>(lhs), std::get<0>(rhs));
1439 }
1440};
1441
1442/// Function object to check whether the second component of a container
1443/// supported by std::get (like std::pair and std::tuple) compares less than the
1444/// second component of another container.
1446 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
1447 return std::less<>()(std::get<1>(lhs), std::get<1>(rhs));
1448 }
1449};
1450
1451/// \brief Function object to apply a binary function to the first component of
1452/// a std::pair.
1453template<typename FuncTy>
1454struct on_first {
1455 FuncTy func;
1456
1457 template <typename T>
1458 decltype(auto) operator()(const T &lhs, const T &rhs) const {
1459 return func(lhs.first, rhs.first);
1460 }
1461};
1462
1463/// Utility type to build an inheritance chain that makes it easy to rank
1464/// overload candidates.
1465template <int N> struct rank : rank<N - 1> {};
1466template <> struct rank<0> {};
1467
1468namespace detail {
1469template <typename... Ts> struct Visitor;
1470
1471template <typename HeadT, typename... TailTs>
1472struct Visitor<HeadT, TailTs...> : remove_cvref_t<HeadT>, Visitor<TailTs...> {
1473 explicit constexpr Visitor(HeadT &&Head, TailTs &&...Tail)
1474 : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)),
1475 Visitor<TailTs...>(std::forward<TailTs>(Tail)...) {}
1476 using remove_cvref_t<HeadT>::operator();
1477 using Visitor<TailTs...>::operator();
1478};
1479
1480template <typename HeadT> struct Visitor<HeadT> : remove_cvref_t<HeadT> {
1481 explicit constexpr Visitor(HeadT &&Head)
1482 : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)) {}
1483 using remove_cvref_t<HeadT>::operator();
1484};
1485} // namespace detail
1486
1487/// Returns an opaquely-typed Callable object whose operator() overload set is
1488/// the sum of the operator() overload sets of each CallableT in CallableTs.
1489///
1490/// The type of the returned object derives from each CallableT in CallableTs.
1491/// The returned object is constructed by invoking the appropriate copy or move
1492/// constructor of each CallableT, as selected by overload resolution on the
1493/// corresponding argument to makeVisitor.
1494///
1495/// Example:
1496///
1497/// \code
1498/// auto visitor = makeVisitor([](auto) { return "unhandled type"; },
1499/// [](int i) { return "int"; },
1500/// [](std::string s) { return "str"; });
1501/// auto a = visitor(42); // `a` is now "int".
1502/// auto b = visitor("foo"); // `b` is now "str".
1503/// auto c = visitor(3.14f); // `c` is now "unhandled type".
1504/// \endcode
1505///
1506/// Example of making a visitor with a lambda which captures a move-only type:
1507///
1508/// \code
1509/// std::unique_ptr<FooHandler> FH = /* ... */;
1510/// auto visitor = makeVisitor(
1511/// [FH{std::move(FH)}](Foo F) { return FH->handle(F); },
1512/// [](int i) { return i; },
1513/// [](std::string s) { return atoi(s); });
1514/// \endcode
1515template <typename... CallableTs>
1516constexpr decltype(auto) makeVisitor(CallableTs &&...Callables) {
1517 return detail::Visitor<CallableTs...>(std::forward<CallableTs>(Callables)...);
1518}
1519
1520//===----------------------------------------------------------------------===//
1521// Extra additions to <algorithm>
1522//===----------------------------------------------------------------------===//
1523
1524// We have a copy here so that LLVM behaves the same when using different
1525// standard libraries.
1526template <class Iterator, class RNG>
1527void shuffle(Iterator first, Iterator last, RNG &&g) {
1528 // It would be better to use a std::uniform_int_distribution,
1529 // but that would be stdlib dependent.
1530 typedef
1531 typename std::iterator_traits<Iterator>::difference_type difference_type;
1532 for (auto size = last - first; size > 1; ++first, (void)--size) {
1533 difference_type offset = g() % size;
1534 // Avoid self-assignment due to incorrect assertions in libstdc++
1535 // containers (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85828).
1536 if (offset != difference_type(0))
1537 std::iter_swap(first, first + offset);
1538 }
1539}
1540
1541/// Adapt std::less<T> for array_pod_sort.
1542template<typename T>
1543inline int array_pod_sort_comparator(const void *P1, const void *P2) {
1544 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
1545 *reinterpret_cast<const T*>(P2)))
1546 return -1;
1547 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
1548 *reinterpret_cast<const T*>(P1)))
1549 return 1;
1550 return 0;
1551}
1552
1553/// get_array_pod_sort_comparator - This is an internal helper function used to
1554/// get type deduction of T right.
1555template<typename T>
1556inline int (*get_array_pod_sort_comparator(const T &))
1557 (const void*, const void*) {
1559}
1560
1561#ifdef EXPENSIVE_CHECKS
1562namespace detail {
1563
1564inline unsigned presortShuffleEntropy() {
1565 static unsigned Result(std::random_device{}());
1566 return Result;
1567}
1568
1569template <class IteratorTy>
1570inline void presortShuffle(IteratorTy Start, IteratorTy End) {
1571 std::mt19937 Generator(presortShuffleEntropy());
1572 llvm::shuffle(Start, End, Generator);
1573}
1574
1575} // end namespace detail
1576#endif
1577
1578/// array_pod_sort - This sorts an array with the specified start and end
1579/// extent. This is just like std::sort, except that it calls qsort instead of
1580/// using an inlined template. qsort is slightly slower than std::sort, but
1581/// most sorts are not performance critical in LLVM and std::sort has to be
1582/// template instantiated for each type, leading to significant measured code
1583/// bloat. This function should generally be used instead of std::sort where
1584/// possible.
1585///
1586/// This function assumes that you have simple POD-like types that can be
1587/// compared with std::less and can be moved with memcpy. If this isn't true,
1588/// you should use std::sort.
1589///
1590/// NOTE: If qsort_r were portable, we could allow a custom comparator and
1591/// default to std::less.
1592template<class IteratorTy>
1593inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
1594 // Don't inefficiently call qsort with one element or trigger undefined
1595 // behavior with an empty sequence.
1596 auto NElts = End - Start;
1597 if (NElts <= 1) return;
1598#ifdef EXPENSIVE_CHECKS
1599 detail::presortShuffle<IteratorTy>(Start, End);
1600#endif
1601 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
1602}
1603
1604template <class IteratorTy>
1605inline void array_pod_sort(
1606 IteratorTy Start, IteratorTy End,
1607 int (*Compare)(
1608 const typename std::iterator_traits<IteratorTy>::value_type *,
1609 const typename std::iterator_traits<IteratorTy>::value_type *)) {
1610 // Don't inefficiently call qsort with one element or trigger undefined
1611 // behavior with an empty sequence.
1612 auto NElts = End - Start;
1613 if (NElts <= 1) return;
1614#ifdef EXPENSIVE_CHECKS
1615 detail::presortShuffle<IteratorTy>(Start, End);
1616#endif
1617 qsort(&*Start, NElts, sizeof(*Start),
1618 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
1619}
1620
1621namespace detail {
1622template <typename T>
1623// We can use qsort if the iterator type is a pointer and the underlying value
1624// is trivially copyable.
1625using sort_trivially_copyable = std::conjunction<
1626 std::is_pointer<T>,
1627 std::is_trivially_copyable<typename std::iterator_traits<T>::value_type>>;
1628} // namespace detail
1629
1630// Provide wrappers to std::sort which shuffle the elements before sorting
1631// to help uncover non-deterministic behavior (PR35135).
1632template <typename IteratorTy>
1633inline void sort(IteratorTy Start, IteratorTy End) {
1635 // Forward trivially copyable types to array_pod_sort. This avoids a large
1636 // amount of code bloat for a minor performance hit.
1637 array_pod_sort(Start, End);
1638 } else {
1639#ifdef EXPENSIVE_CHECKS
1640 detail::presortShuffle<IteratorTy>(Start, End);
1641#endif
1642 std::sort(Start, End);
1643 }
1644}
1645
1646template <typename Container> inline void sort(Container &&C) {
1648}
1649
1650template <typename IteratorTy, typename Compare>
1651inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
1652#ifdef EXPENSIVE_CHECKS
1653 detail::presortShuffle<IteratorTy>(Start, End);
1654#endif
1655 std::sort(Start, End, Comp);
1656}
1657
1658template <typename Container, typename Compare>
1659inline void sort(Container &&C, Compare Comp) {
1660 llvm::sort(adl_begin(C), adl_end(C), Comp);
1661}
1662
1663/// Get the size of a range. This is a wrapper function around std::distance
1664/// which is only enabled when the operation is O(1).
1665template <typename R>
1666auto size(R &&Range,
1667 std::enable_if_t<
1668 std::is_base_of<std::random_access_iterator_tag,
1669 typename std::iterator_traits<decltype(
1670 Range.begin())>::iterator_category>::value,
1671 void> * = nullptr) {
1672 return std::distance(Range.begin(), Range.end());
1673}
1674
1675namespace detail {
1676template <typename Range>
1678 decltype(adl_size(std::declval<Range &>()));
1679
1680template <typename Range>
1681static constexpr bool HasFreeFunctionSize =
1683} // namespace detail
1684
1685/// Returns the size of the \p Range, i.e., the number of elements. This
1686/// implementation takes inspiration from `std::ranges::size` from C++20 and
1687/// delegates the size check to `adl_size` or `std::distance`, in this order of
1688/// preference. Unlike `llvm::size`, this function does *not* guarantee O(1)
1689/// running time, and is intended to be used in generic code that does not know
1690/// the exact range type.
1691template <typename R> constexpr size_t range_size(R &&Range) {
1692 if constexpr (detail::HasFreeFunctionSize<R>)
1693 return adl_size(Range);
1694 else
1695 return static_cast<size_t>(std::distance(adl_begin(Range), adl_end(Range)));
1696}
1697
1698/// Wrapper for std::accumulate.
1699template <typename R, typename E> auto accumulate(R &&Range, E &&Init) {
1700 return std::accumulate(adl_begin(Range), adl_end(Range),
1701 std::forward<E>(Init));
1702}
1703
1704/// Provide wrappers to std::for_each which take ranges instead of having to
1705/// pass begin/end explicitly.
1706template <typename R, typename UnaryFunction>
1707UnaryFunction for_each(R &&Range, UnaryFunction F) {
1708 return std::for_each(adl_begin(Range), adl_end(Range), F);
1709}
1710
1711/// Provide wrappers to std::all_of which take ranges instead of having to pass
1712/// begin/end explicitly.
1713template <typename R, typename UnaryPredicate>
1714bool all_of(R &&Range, UnaryPredicate P) {
1715 return std::all_of(adl_begin(Range), adl_end(Range), P);
1716}
1717
1718/// Provide wrappers to std::any_of which take ranges instead of having to pass
1719/// begin/end explicitly.
1720template <typename R, typename UnaryPredicate>
1721bool any_of(R &&Range, UnaryPredicate P) {
1722 return std::any_of(adl_begin(Range), adl_end(Range), P);
1723}
1724
1725/// Provide wrappers to std::none_of which take ranges instead of having to pass
1726/// begin/end explicitly.
1727template <typename R, typename UnaryPredicate>
1728bool none_of(R &&Range, UnaryPredicate P) {
1729 return std::none_of(adl_begin(Range), adl_end(Range), P);
1730}
1731
1732/// Provide wrappers to std::fill which take ranges instead of having to pass
1733/// begin/end explicitly.
1734template <typename R, typename T> void fill(R &&Range, T &&Value) {
1735 std::fill(adl_begin(Range), adl_end(Range), std::forward<T>(Value));
1736}
1737
1738/// Provide wrappers to std::find which take ranges instead of having to pass
1739/// begin/end explicitly.
1740template <typename R, typename T> auto find(R &&Range, const T &Val) {
1741 return std::find(adl_begin(Range), adl_end(Range), Val);
1742}
1743
1744/// Provide wrappers to std::find_if which take ranges instead of having to pass
1745/// begin/end explicitly.
1746template <typename R, typename UnaryPredicate>
1747auto find_if(R &&Range, UnaryPredicate P) {
1748 return std::find_if(adl_begin(Range), adl_end(Range), P);
1749}
1750
1751template <typename R, typename UnaryPredicate>
1752auto find_if_not(R &&Range, UnaryPredicate P) {
1753 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1754}
1755
1756/// Provide wrappers to std::remove_if which take ranges instead of having to
1757/// pass begin/end explicitly.
1758template <typename R, typename UnaryPredicate>
1759auto remove_if(R &&Range, UnaryPredicate P) {
1760 return std::remove_if(adl_begin(Range), adl_end(Range), P);
1761}
1762
1763/// Provide wrappers to std::copy_if which take ranges instead of having to
1764/// pass begin/end explicitly.
1765template <typename R, typename OutputIt, typename UnaryPredicate>
1766OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1767 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1768}
1769
1770/// Return the single value in \p Range that satisfies
1771/// \p P(<member of \p Range> *, AllowRepeats)->T * returning nullptr
1772/// when no values or multiple values were found.
1773/// When \p AllowRepeats is true, multiple values that compare equal
1774/// are allowed.
1775template <typename T, typename R, typename Predicate>
1776T *find_singleton(R &&Range, Predicate P, bool AllowRepeats = false) {
1777 T *RC = nullptr;
1778 for (auto &&A : Range) {
1779 if (T *PRC = P(A, AllowRepeats)) {
1780 if (RC) {
1781 if (!AllowRepeats || PRC != RC)
1782 return nullptr;
1783 } else {
1784 RC = PRC;
1785 }
1786 }
1787 }
1788 return RC;
1789}
1790
1791/// Return a pair consisting of the single value in \p Range that satisfies
1792/// \p P(<member of \p Range> *, AllowRepeats)->std::pair<T*, bool> returning
1793/// nullptr when no values or multiple values were found, and a bool indicating
1794/// whether multiple values were found to cause the nullptr.
1795/// When \p AllowRepeats is true, multiple values that compare equal are
1796/// allowed. The predicate \p P returns a pair<T *, bool> where T is the
1797/// singleton while the bool indicates whether multiples have already been
1798/// found. It is expected that first will be nullptr when second is true.
1799/// This allows using find_singleton_nested within the predicate \P.
1800template <typename T, typename R, typename Predicate>
1801std::pair<T *, bool> find_singleton_nested(R &&Range, Predicate P,
1802 bool AllowRepeats = false) {
1803 T *RC = nullptr;
1804 for (auto *A : Range) {
1805 std::pair<T *, bool> PRC = P(A, AllowRepeats);
1806 if (PRC.second) {
1807 assert(PRC.first == nullptr &&
1808 "Inconsistent return values in find_singleton_nested.");
1809 return PRC;
1810 }
1811 if (PRC.first) {
1812 if (RC) {
1813 if (!AllowRepeats || PRC.first != RC)
1814 return {nullptr, true};
1815 } else {
1816 RC = PRC.first;
1817 }
1818 }
1819 }
1820 return {RC, false};
1821}
1822
1823template <typename R, typename OutputIt>
1824OutputIt copy(R &&Range, OutputIt Out) {
1825 return std::copy(adl_begin(Range), adl_end(Range), Out);
1826}
1827
1828/// Provide wrappers to std::replace_copy_if which take ranges instead of having
1829/// to pass begin/end explicitly.
1830template <typename R, typename OutputIt, typename UnaryPredicate, typename T>
1831OutputIt replace_copy_if(R &&Range, OutputIt Out, UnaryPredicate P,
1832 const T &NewValue) {
1833 return std::replace_copy_if(adl_begin(Range), adl_end(Range), Out, P,
1834 NewValue);
1835}
1836
1837/// Provide wrappers to std::replace_copy which take ranges instead of having to
1838/// pass begin/end explicitly.
1839template <typename R, typename OutputIt, typename T>
1840OutputIt replace_copy(R &&Range, OutputIt Out, const T &OldValue,
1841 const T &NewValue) {
1842 return std::replace_copy(adl_begin(Range), adl_end(Range), Out, OldValue,
1843 NewValue);
1844}
1845
1846/// Provide wrappers to std::replace which take ranges instead of having to pass
1847/// begin/end explicitly.
1848template <typename R, typename T>
1849void replace(R &&Range, const T &OldValue, const T &NewValue) {
1850 std::replace(adl_begin(Range), adl_end(Range), OldValue, NewValue);
1851}
1852
1853/// Provide wrappers to std::move which take ranges instead of having to
1854/// pass begin/end explicitly.
1855template <typename R, typename OutputIt>
1856OutputIt move(R &&Range, OutputIt Out) {
1857 return std::move(adl_begin(Range), adl_end(Range), Out);
1858}
1859
1860namespace detail {
1861template <typename Range, typename Element>
1863 decltype(std::declval<Range &>().contains(std::declval<const Element &>()));
1864
1865template <typename Range, typename Element>
1866static constexpr bool HasMemberContains =
1868
1869template <typename Range, typename Element>
1871 decltype(std::declval<Range &>().find(std::declval<const Element &>()) !=
1872 std::declval<Range &>().end());
1873
1874template <typename Range, typename Element>
1875static constexpr bool HasMemberFind =
1877
1878} // namespace detail
1879
1880/// Returns true if \p Element is found in \p Range. Delegates the check to
1881/// either `.contains(Element)`, `.find(Element)`, or `std::find`, in this
1882/// order of preference. This is intended as the canonical way to check if an
1883/// element exists in a range in generic code or range type that does not
1884/// expose a `.contains(Element)` member.
1885template <typename R, typename E>
1886bool is_contained(R &&Range, const E &Element) {
1887 if constexpr (detail::HasMemberContains<R, E>)
1888 return Range.contains(Element);
1889 else if constexpr (detail::HasMemberFind<R, E>)
1890 return Range.find(Element) != Range.end();
1891 else
1892 return std::find(adl_begin(Range), adl_end(Range), Element) !=
1893 adl_end(Range);
1894}
1895
1896/// Returns true iff \p Element exists in \p Set. This overload takes \p Set as
1897/// an initializer list and is `constexpr`-friendly.
1898template <typename T, typename E>
1899constexpr bool is_contained(std::initializer_list<T> Set, const E &Element) {
1900 // TODO: Use std::find when we switch to C++20.
1901 for (const T &V : Set)
1902 if (V == Element)
1903 return true;
1904 return false;
1905}
1906
1907/// Wrapper function around std::is_sorted to check if elements in a range \p R
1908/// are sorted with respect to a comparator \p C.
1909template <typename R, typename Compare> bool is_sorted(R &&Range, Compare C) {
1910 return std::is_sorted(adl_begin(Range), adl_end(Range), C);
1911}
1912
1913/// Wrapper function around std::is_sorted to check if elements in a range \p R
1914/// are sorted in non-descending order.
1915template <typename R> bool is_sorted(R &&Range) {
1916 return std::is_sorted(adl_begin(Range), adl_end(Range));
1917}
1918
1919/// Provide wrappers to std::includes which take ranges instead of having to
1920/// pass begin/end explicitly.
1921/// This function checks if the sorted range \p R2 is a subsequence of the
1922/// sorted range \p R1. The ranges must be sorted in non-descending order.
1923template <typename R1, typename R2> bool includes(R1 &&Range1, R2 &&Range2) {
1924 assert(is_sorted(Range1) && "Range1 must be sorted in non-descending order");
1925 assert(is_sorted(Range2) && "Range2 must be sorted in non-descending order");
1926 return std::includes(adl_begin(Range1), adl_end(Range1), adl_begin(Range2),
1927 adl_end(Range2));
1928}
1929
1930/// This function checks if the sorted range \p R2 is a subsequence of the
1931/// sorted range \p R1. The ranges must be sorted with respect to a comparator
1932/// \p C.
1933template <typename R1, typename R2, typename Compare>
1934bool includes(R1 &&Range1, R2 &&Range2, Compare &&C) {
1935 assert(is_sorted(Range1, C) && "Range1 must be sorted with respect to C");
1936 assert(is_sorted(Range2, C) && "Range2 must be sorted with respect to C");
1937 return std::includes(adl_begin(Range1), adl_end(Range1), adl_begin(Range2),
1938 adl_end(Range2), std::forward<Compare>(C));
1939}
1940
1941/// Wrapper function around std::count to count the number of times an element
1942/// \p Element occurs in the given range \p Range.
1943template <typename R, typename E> auto count(R &&Range, const E &Element) {
1944 return std::count(adl_begin(Range), adl_end(Range), Element);
1945}
1946
1947/// Wrapper function around std::count_if to count the number of times an
1948/// element satisfying a given predicate occurs in a range.
1949template <typename R, typename UnaryPredicate>
1950auto count_if(R &&Range, UnaryPredicate P) {
1951 return std::count_if(adl_begin(Range), adl_end(Range), P);
1952}
1953
1954/// Wrapper function around std::transform to apply a function to a range and
1955/// store the result elsewhere.
1956template <typename R, typename OutputIt, typename UnaryFunction>
1957OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F) {
1958 return std::transform(adl_begin(Range), adl_end(Range), d_first, F);
1959}
1960
1961/// Provide wrappers to std::partition which take ranges instead of having to
1962/// pass begin/end explicitly.
1963template <typename R, typename UnaryPredicate>
1964auto partition(R &&Range, UnaryPredicate P) {
1965 return std::partition(adl_begin(Range), adl_end(Range), P);
1966}
1967
1968/// Provide wrappers to std::binary_search which take ranges instead of having
1969/// to pass begin/end explicitly.
1970template <typename R, typename T> auto binary_search(R &&Range, T &&Value) {
1971 return std::binary_search(adl_begin(Range), adl_end(Range),
1972 std::forward<T>(Value));
1973}
1974
1975template <typename R, typename T, typename Compare>
1976auto binary_search(R &&Range, T &&Value, Compare C) {
1977 return std::binary_search(adl_begin(Range), adl_end(Range),
1978 std::forward<T>(Value), C);
1979}
1980
1981/// Provide wrappers to std::lower_bound which take ranges instead of having to
1982/// pass begin/end explicitly.
1983template <typename R, typename T> auto lower_bound(R &&Range, T &&Value) {
1984 return std::lower_bound(adl_begin(Range), adl_end(Range),
1985 std::forward<T>(Value));
1986}
1987
1988template <typename R, typename T, typename Compare>
1989auto lower_bound(R &&Range, T &&Value, Compare C) {
1990 return std::lower_bound(adl_begin(Range), adl_end(Range),
1991 std::forward<T>(Value), C);
1992}
1993
1994/// Provide wrappers to std::upper_bound which take ranges instead of having to
1995/// pass begin/end explicitly.
1996template <typename R, typename T> auto upper_bound(R &&Range, T &&Value) {
1997 return std::upper_bound(adl_begin(Range), adl_end(Range),
1998 std::forward<T>(Value));
1999}
2000
2001template <typename R, typename T, typename Compare>
2002auto upper_bound(R &&Range, T &&Value, Compare C) {
2003 return std::upper_bound(adl_begin(Range), adl_end(Range),
2004 std::forward<T>(Value), C);
2005}
2006
2007/// Provide wrappers to std::min_element which take ranges instead of having to
2008/// pass begin/end explicitly.
2009template <typename R> auto min_element(R &&Range) {
2010 return std::min_element(adl_begin(Range), adl_end(Range));
2011}
2012
2013template <typename R, typename Compare> auto min_element(R &&Range, Compare C) {
2014 return std::min_element(adl_begin(Range), adl_end(Range), C);
2015}
2016
2017/// Provide wrappers to std::max_element which take ranges instead of having to
2018/// pass begin/end explicitly.
2019template <typename R> auto max_element(R &&Range) {
2020 return std::max_element(adl_begin(Range), adl_end(Range));
2021}
2022
2023template <typename R, typename Compare> auto max_element(R &&Range, Compare C) {
2024 return std::max_element(adl_begin(Range), adl_end(Range), C);
2025}
2026
2027/// Provide wrappers to std::mismatch which take ranges instead of having to
2028/// pass begin/end explicitly.
2029/// This function returns a pair of iterators for the first mismatching elements
2030/// from `R1` and `R2`. As an example, if:
2031///
2032/// R1 = [0, 1, 4, 6], R2 = [0, 1, 5, 6]
2033///
2034/// this function will return a pair of iterators, first pointing to R1[2] and
2035/// second pointing to R2[2].
2036template <typename R1, typename R2> auto mismatch(R1 &&Range1, R2 &&Range2) {
2037 return std::mismatch(adl_begin(Range1), adl_end(Range1), adl_begin(Range2),
2038 adl_end(Range2));
2039}
2040
2041template <typename R, typename IterTy>
2042auto uninitialized_copy(R &&Src, IterTy Dst) {
2043 return std::uninitialized_copy(adl_begin(Src), adl_end(Src), Dst);
2044}
2045
2046template <typename R>
2048 std::stable_sort(adl_begin(Range), adl_end(Range));
2049}
2050
2051template <typename R, typename Compare>
2052void stable_sort(R &&Range, Compare C) {
2053 std::stable_sort(adl_begin(Range), adl_end(Range), C);
2054}
2055
2056/// Binary search for the first iterator in a range where a predicate is false.
2057/// Requires that C is always true below some limit, and always false above it.
2058template <typename R, typename Predicate,
2059 typename Val = decltype(*adl_begin(std::declval<R>()))>
2061 return std::partition_point(adl_begin(Range), adl_end(Range), P);
2062}
2063
2064template<typename Range, typename Predicate>
2066 return std::unique(adl_begin(R), adl_end(R), P);
2067}
2068
2069/// Wrapper function around std::unique to allow calling unique on a
2070/// container without having to specify the begin/end iterators.
2071template <typename Range> auto unique(Range &&R) {
2072 return std::unique(adl_begin(R), adl_end(R));
2073}
2074
2075/// Wrapper function around std::equal to detect if pair-wise elements between
2076/// two ranges are the same.
2077template <typename L, typename R> bool equal(L &&LRange, R &&RRange) {
2078 return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange),
2079 adl_end(RRange));
2080}
2081
2082template <typename L, typename R, typename BinaryPredicate>
2083bool equal(L &&LRange, R &&RRange, BinaryPredicate P) {
2084 return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange),
2085 adl_end(RRange), P);
2086}
2087
2088/// Returns true if all elements in Range are equal or when the Range is empty.
2089template <typename R> bool all_equal(R &&Range) {
2090 auto Begin = adl_begin(Range);
2091 auto End = adl_end(Range);
2092 return Begin == End || std::equal(std::next(Begin), End, Begin);
2093}
2094
2095/// Returns true if all Values in the initializer lists are equal or the list
2096// is empty.
2097template <typename T> bool all_equal(std::initializer_list<T> Values) {
2098 return all_equal<std::initializer_list<T>>(std::move(Values));
2099}
2100
2101/// Provide a container algorithm similar to C++ Library Fundamentals v2's
2102/// `erase_if` which is equivalent to:
2103///
2104/// C.erase(remove_if(C, pred), C.end());
2105///
2106/// This version works for any container with an erase method call accepting
2107/// two iterators.
2108template <typename Container, typename UnaryPredicate>
2109void erase_if(Container &C, UnaryPredicate P) {
2110 C.erase(remove_if(C, P), C.end());
2111}
2112
2113/// Wrapper function to remove a value from a container:
2114///
2115/// C.erase(remove(C.begin(), C.end(), V), C.end());
2116template <typename Container, typename ValueType>
2117void erase(Container &C, ValueType V) {
2118 C.erase(std::remove(C.begin(), C.end(), V), C.end());
2119}
2120
2121/// Wrapper function to append range `R` to container `C`.
2122///
2123/// C.insert(C.end(), R.begin(), R.end());
2124template <typename Container, typename Range>
2125void append_range(Container &C, Range &&R) {
2126 C.insert(C.end(), adl_begin(R), adl_end(R));
2127}
2128
2129/// Appends all `Values` to container `C`.
2130template <typename Container, typename... Args>
2131void append_values(Container &C, Args &&...Values) {
2132 C.reserve(range_size(C) + sizeof...(Args));
2133 // Append all values one by one.
2134 ((void)C.insert(C.end(), std::forward<Args>(Values)), ...);
2135}
2136
2137/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
2138/// the range [ValIt, ValEnd) (which is not from the same container).
2139template <typename Container, typename RandomAccessIterator>
2140void replace(Container &Cont, typename Container::iterator ContIt,
2141 typename Container::iterator ContEnd, RandomAccessIterator ValIt,
2142 RandomAccessIterator ValEnd) {
2143 while (true) {
2144 if (ValIt == ValEnd) {
2145 Cont.erase(ContIt, ContEnd);
2146 return;
2147 }
2148 if (ContIt == ContEnd) {
2149 Cont.insert(ContIt, ValIt, ValEnd);
2150 return;
2151 }
2152 *ContIt = *ValIt;
2153 ++ContIt;
2154 ++ValIt;
2155 }
2156}
2157
2158/// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
2159/// the range R.
2160template <typename Container, typename Range = std::initializer_list<
2161 typename Container::value_type>>
2162void replace(Container &Cont, typename Container::iterator ContIt,
2163 typename Container::iterator ContEnd, Range &&R) {
2164 replace(Cont, ContIt, ContEnd, adl_begin(R), adl_end(R));
2165}
2166
2167/// An STL-style algorithm similar to std::for_each that applies a second
2168/// functor between every pair of elements.
2169///
2170/// This provides the control flow logic to, for example, print a
2171/// comma-separated list:
2172/// \code
2173/// interleave(names.begin(), names.end(),
2174/// [&](StringRef name) { os << name; },
2175/// [&] { os << ", "; });
2176/// \endcode
2177template <typename ForwardIterator, typename UnaryFunctor,
2178 typename NullaryFunctor,
2179 typename = std::enable_if_t<
2180 !std::is_constructible<StringRef, UnaryFunctor>::value &&
2181 !std::is_constructible<StringRef, NullaryFunctor>::value>>
2182inline void interleave(ForwardIterator begin, ForwardIterator end,
2183 UnaryFunctor each_fn, NullaryFunctor between_fn) {
2184 if (begin == end)
2185 return;
2186 each_fn(*begin);
2187 ++begin;
2188 for (; begin != end; ++begin) {
2189 between_fn();
2190 each_fn(*begin);
2191 }
2192}
2193
2194template <typename Container, typename UnaryFunctor, typename NullaryFunctor,
2195 typename = std::enable_if_t<
2196 !std::is_constructible<StringRef, UnaryFunctor>::value &&
2197 !std::is_constructible<StringRef, NullaryFunctor>::value>>
2198inline void interleave(const Container &c, UnaryFunctor each_fn,
2199 NullaryFunctor between_fn) {
2200 interleave(adl_begin(c), adl_end(c), each_fn, between_fn);
2201}
2202
2203/// Overload of interleave for the common case of string separator.
2204template <typename Container, typename UnaryFunctor, typename StreamT,
2206inline void interleave(const Container &c, StreamT &os, UnaryFunctor each_fn,
2207 const StringRef &separator) {
2208 interleave(adl_begin(c), adl_end(c), each_fn, [&] { os << separator; });
2209}
2210template <typename Container, typename StreamT,
2212inline void interleave(const Container &c, StreamT &os,
2213 const StringRef &separator) {
2214 interleave(
2215 c, os, [&](const T &a) { os << a; }, separator);
2216}
2217
2218template <typename Container, typename UnaryFunctor, typename StreamT,
2220inline void interleaveComma(const Container &c, StreamT &os,
2221 UnaryFunctor each_fn) {
2222 interleave(c, os, each_fn, ", ");
2223}
2224template <typename Container, typename StreamT,
2226inline void interleaveComma(const Container &c, StreamT &os) {
2227 interleaveComma(c, os, [&](const T &a) { os << a; });
2228}
2229
2230//===----------------------------------------------------------------------===//
2231// Extra additions to <memory>
2232//===----------------------------------------------------------------------===//
2233
2235 void operator()(void* v) {
2236 ::free(v);
2237 }
2238};
2239
2240template<typename First, typename Second>
2242 size_t operator()(const std::pair<First, Second> &P) const {
2243 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
2244 }
2245};
2246
2247/// Binary functor that adapts to any other binary functor after dereferencing
2248/// operands.
2249template <typename T> struct deref {
2251
2252 // Could be further improved to cope with non-derivable functors and
2253 // non-binary functors (should be a variadic template member function
2254 // operator()).
2255 template <typename A, typename B> auto operator()(A &lhs, B &rhs) const {
2256 assert(lhs);
2257 assert(rhs);
2258 return func(*lhs, *rhs);
2259 }
2260};
2261
2262namespace detail {
2263
2264/// Tuple-like type for `zip_enumerator` dereference.
2265template <typename... Refs> struct enumerator_result;
2266
2267template <typename... Iters>
2269
2270/// Zippy iterator that uses the second iterator for comparisons. For the
2271/// increment to be safe, the second range has to be the shortest.
2272/// Returns `enumerator_result` on dereference to provide `.index()` and
2273/// `.value()` member functions.
2274/// Note: Because the dereference operator returns `enumerator_result` as a
2275/// value instead of a reference and does not strictly conform to the C++17's
2276/// definition of forward iterator. However, it satisfies all the
2277/// forward_iterator requirements that the `zip_common` and `zippy` depend on
2278/// and fully conforms to the C++20 definition of forward iterator.
2279/// This is similar to `std::vector<bool>::iterator` that returns bit reference
2280/// wrappers on dereference.
2281template <typename... Iters>
2282struct zip_enumerator : zip_common<zip_enumerator<Iters...>,
2283 EnumeratorTupleType<Iters...>, Iters...> {
2284 static_assert(sizeof...(Iters) >= 2, "Expected at least two iteratees");
2285 using zip_common<zip_enumerator<Iters...>, EnumeratorTupleType<Iters...>,
2286 Iters...>::zip_common;
2287
2288 bool operator==(const zip_enumerator &Other) const {
2289 return std::get<1>(this->iterators) == std::get<1>(Other.iterators);
2290 }
2291};
2292
2293template <typename... Refs> struct enumerator_result<std::size_t, Refs...> {
2294 static constexpr std::size_t NumRefs = sizeof...(Refs);
2295 static_assert(NumRefs != 0);
2296 // `NumValues` includes the index.
2297 static constexpr std::size_t NumValues = NumRefs + 1;
2298
2299 // Tuple type whose element types are references for each `Ref`.
2300 using range_reference_tuple = std::tuple<Refs...>;
2301 // Tuple type who elements are references to all values, including both
2302 // the index and `Refs` reference types.
2303 using value_reference_tuple = std::tuple<std::size_t, Refs...>;
2304
2305 enumerator_result(std::size_t Index, Refs &&...Rs)
2306 : Idx(Index), Storage(std::forward<Refs>(Rs)...) {}
2307
2308 /// Returns the 0-based index of the current position within the original
2309 /// input range(s).
2310 std::size_t index() const { return Idx; }
2311
2312 /// Returns the value(s) for the current iterator. This does not include the
2313 /// index.
2314 decltype(auto) value() const {
2315 if constexpr (NumRefs == 1)
2316 return std::get<0>(Storage);
2317 else
2318 return Storage;
2319 }
2320
2321 /// Returns the value at index `I`. This case covers the index.
2322 template <std::size_t I, typename = std::enable_if_t<I == 0>>
2323 friend std::size_t get(const enumerator_result &Result) {
2324 return Result.Idx;
2325 }
2326
2327 /// Returns the value at index `I`. This case covers references to the
2328 /// iteratees.
2329 template <std::size_t I, typename = std::enable_if_t<I != 0>>
2330 friend decltype(auto) get(const enumerator_result &Result) {
2331 // Note: This is a separate function from the other `get`, instead of an
2332 // `if constexpr` case, to work around an MSVC 19.31.31XXX compiler
2333 // (Visual Studio 2022 17.1) return type deduction bug.
2334 return std::get<I - 1>(Result.Storage);
2335 }
2336
2337 template <typename... Ts>
2338 friend bool operator==(const enumerator_result &Result,
2339 const std::tuple<std::size_t, Ts...> &Other) {
2340 static_assert(NumRefs == sizeof...(Ts), "Size mismatch");
2341 if (Result.Idx != std::get<0>(Other))
2342 return false;
2343 return Result.is_value_equal(Other, std::make_index_sequence<NumRefs>{});
2344 }
2345
2346private:
2347 template <typename Tuple, std::size_t... Idx>
2348 bool is_value_equal(const Tuple &Other, std::index_sequence<Idx...>) const {
2349 return ((std::get<Idx>(Storage) == std::get<Idx + 1>(Other)) && ...);
2350 }
2351
2352 std::size_t Idx;
2353 // Make this tuple mutable to avoid casts that obfuscate const-correctness
2354 // issues. Const-correctness of references is taken care of by `zippy` that
2355 // defines const-non and const iterator types that will propagate down to
2356 // `enumerator_result`'s `Refs`.
2357 // Note that unlike the results of `zip*` functions, `enumerate`'s result are
2358 // supposed to be modifiable even when defined as
2359 // `const`.
2360 mutable range_reference_tuple Storage;
2361};
2362
2364 : llvm::iterator_facade_base<index_iterator,
2365 std::random_access_iterator_tag, std::size_t> {
2366 index_iterator(std::size_t Index) : Index(Index) {}
2367
2368 index_iterator &operator+=(std::ptrdiff_t N) {
2369 Index += N;
2370 return *this;
2371 }
2372
2373 index_iterator &operator-=(std::ptrdiff_t N) {
2374 Index -= N;
2375 return *this;
2376 }
2377
2378 std::ptrdiff_t operator-(const index_iterator &R) const {
2379 return Index - R.Index;
2380 }
2381
2382 // Note: This dereference operator returns a value instead of a reference
2383 // and does not strictly conform to the C++17's definition of forward
2384 // iterator. However, it satisfies all the forward_iterator requirements
2385 // that the `zip_common` depends on and fully conforms to the C++20
2386 // definition of forward iterator.
2387 std::size_t operator*() const { return Index; }
2388
2389 friend bool operator==(const index_iterator &Lhs, const index_iterator &Rhs) {
2390 return Lhs.Index == Rhs.Index;
2391 }
2392
2393 friend bool operator<(const index_iterator &Lhs, const index_iterator &Rhs) {
2394 return Lhs.Index < Rhs.Index;
2395 }
2396
2397private:
2398 std::size_t Index;
2399};
2400
2401/// Infinite stream of increasing 0-based `size_t` indices.
2403 index_iterator begin() const { return {0}; }
2405 // We approximate 'infinity' with the max size_t value, which should be good
2406 // enough to index over any container.
2407 return index_iterator{std::numeric_limits<std::size_t>::max()};
2408 }
2409};
2410
2411} // end namespace detail
2412
2413/// Increasing range of `size_t` indices.
2415 std::size_t Begin;
2416 std::size_t End;
2417
2418public:
2419 index_range(std::size_t Begin, std::size_t End) : Begin(Begin), End(End) {}
2420 detail::index_iterator begin() const { return {Begin}; }
2421 detail::index_iterator end() const { return {End}; }
2422};
2423
2424/// Given two or more input ranges, returns a new range whose values are
2425/// tuples (A, B, C, ...), such that A is the 0-based index of the item in the
2426/// sequence, and B, C, ..., are the values from the original input ranges. All
2427/// input ranges are required to have equal lengths. Note that the returned
2428/// iterator allows for the values (B, C, ...) to be modified. Example:
2429///
2430/// ```c++
2431/// std::vector<char> Letters = {'A', 'B', 'C', 'D'};
2432/// std::vector<int> Vals = {10, 11, 12, 13};
2433///
2434/// for (auto [Index, Letter, Value] : enumerate(Letters, Vals)) {
2435/// printf("Item %zu - %c: %d\n", Index, Letter, Value);
2436/// Value -= 10;
2437/// }
2438/// ```
2439///
2440/// Output:
2441/// Item 0 - A: 10
2442/// Item 1 - B: 11
2443/// Item 2 - C: 12
2444/// Item 3 - D: 13
2445///
2446/// or using an iterator:
2447/// ```c++
2448/// for (auto it : enumerate(Vals)) {
2449/// it.value() += 10;
2450/// printf("Item %zu: %d\n", it.index(), it.value());
2451/// }
2452/// ```
2453///
2454/// Output:
2455/// Item 0: 20
2456/// Item 1: 21
2457/// Item 2: 22
2458/// Item 3: 23
2459///
2460template <typename FirstRange, typename... RestRanges>
2461auto enumerate(FirstRange &&First, RestRanges &&...Rest) {
2462 if constexpr (sizeof...(Rest) != 0) {
2463#ifndef NDEBUG
2464 // Note: Create an array instead of an initializer list to work around an
2465 // Apple clang 14 compiler bug.
2466 size_t sizes[] = {range_size(First), range_size(Rest)...};
2467 assert(all_equal(sizes) && "Ranges have different length");
2468#endif
2469 }
2471 FirstRange, RestRanges...>;
2472 return enumerator(detail::index_stream{}, std::forward<FirstRange>(First),
2473 std::forward<RestRanges>(Rest)...);
2474}
2475
2476namespace detail {
2477
2478template <typename Predicate, typename... Args>
2480 auto z = zip(args...);
2481 auto it = z.begin();
2482 auto end = z.end();
2483 while (it != end) {
2484 if (!std::apply([&](auto &&...args) { return P(args...); }, *it))
2485 return false;
2486 ++it;
2487 }
2488 return it.all_equals(end);
2489}
2490
2491// Just an adaptor to switch the order of argument and have the predicate before
2492// the zipped inputs.
2493template <typename... ArgsThenPredicate, size_t... InputIndexes>
2495 std::tuple<ArgsThenPredicate...> argsThenPredicate,
2496 std::index_sequence<InputIndexes...>) {
2497 auto constexpr OutputIndex =
2498 std::tuple_size<decltype(argsThenPredicate)>::value - 1;
2499 return all_of_zip_predicate_first(std::get<OutputIndex>(argsThenPredicate),
2500 std::get<InputIndexes>(argsThenPredicate)...);
2501}
2502
2503} // end namespace detail
2504
2505/// Compare two zipped ranges using the provided predicate (as last argument).
2506/// Return true if all elements satisfy the predicate and false otherwise.
2507// Return false if the zipped iterator aren't all at end (size mismatch).
2508template <typename... ArgsAndPredicate>
2509bool all_of_zip(ArgsAndPredicate &&...argsAndPredicate) {
2511 std::forward_as_tuple(argsAndPredicate...),
2512 std::make_index_sequence<sizeof...(argsAndPredicate) - 1>{});
2513}
2514
2515/// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N)
2516/// time. Not meant for use with random-access iterators.
2517/// Can optionally take a predicate to filter lazily some items.
2518template <typename IterTy,
2519 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
2521 IterTy &&Begin, IterTy &&End, unsigned N,
2522 Pred &&ShouldBeCounted =
2523 [](const decltype(*std::declval<IterTy>()) &) { return true; },
2524 std::enable_if_t<
2525 !std::is_base_of<std::random_access_iterator_tag,
2526 typename std::iterator_traits<std::remove_reference_t<
2527 decltype(Begin)>>::iterator_category>::value,
2528 void> * = nullptr) {
2529 for (; N; ++Begin) {
2530 if (Begin == End)
2531 return false; // Too few.
2532 N -= ShouldBeCounted(*Begin);
2533 }
2534 for (; Begin != End; ++Begin)
2535 if (ShouldBeCounted(*Begin))
2536 return false; // Too many.
2537 return true;
2538}
2539
2540/// Return true if the sequence [Begin, End) has N or more items. Runs in O(N)
2541/// time. Not meant for use with random-access iterators.
2542/// Can optionally take a predicate to lazily filter some items.
2543template <typename IterTy,
2544 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
2546 IterTy &&Begin, IterTy &&End, unsigned N,
2547 Pred &&ShouldBeCounted =
2548 [](const decltype(*std::declval<IterTy>()) &) { return true; },
2549 std::enable_if_t<
2550 !std::is_base_of<std::random_access_iterator_tag,
2551 typename std::iterator_traits<std::remove_reference_t<
2552 decltype(Begin)>>::iterator_category>::value,
2553 void> * = nullptr) {
2554 for (; N; ++Begin) {
2555 if (Begin == End)
2556 return false; // Too few.
2557 N -= ShouldBeCounted(*Begin);
2558 }
2559 return true;
2560}
2561
2562/// Returns true if the sequence [Begin, End) has N or less items. Can
2563/// optionally take a predicate to lazily filter some items.
2564template <typename IterTy,
2565 typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)>
2567 IterTy &&Begin, IterTy &&End, unsigned N,
2568 Pred &&ShouldBeCounted = [](const decltype(*std::declval<IterTy>()) &) {
2569 return true;
2570 }) {
2571 assert(N != std::numeric_limits<unsigned>::max());
2572 return !hasNItemsOrMore(Begin, End, N + 1, ShouldBeCounted);
2573}
2574
2575/// Returns true if the given container has exactly N items
2576template <typename ContainerTy> bool hasNItems(ContainerTy &&C, unsigned N) {
2577 return hasNItems(adl_begin(C), adl_end(C), N);
2578}
2579
2580/// Returns true if the given container has N or more items
2581template <typename ContainerTy>
2582bool hasNItemsOrMore(ContainerTy &&C, unsigned N) {
2583 return hasNItemsOrMore(adl_begin(C), adl_end(C), N);
2584}
2585
2586/// Returns true if the given container has N or less items
2587template <typename ContainerTy>
2588bool hasNItemsOrLess(ContainerTy &&C, unsigned N) {
2589 return hasNItemsOrLess(adl_begin(C), adl_end(C), N);
2590}
2591
2592/// Returns a raw pointer that represents the same address as the argument.
2593///
2594/// This implementation can be removed once we move to C++20 where it's defined
2595/// as std::to_address().
2596///
2597/// The std::pointer_traits<>::to_address(p) variations of these overloads has
2598/// not been implemented.
2599template <class Ptr> auto to_address(const Ptr &P) { return P.operator->(); }
2600template <class T> constexpr T *to_address(T *P) { return P; }
2601
2602// Detect incomplete types, relying on the fact that their size is unknown.
2603namespace detail {
2604template <typename T> using has_sizeof = decltype(sizeof(T));
2605} // namespace detail
2606
2607/// Detects when type `T` is incomplete. This is true for forward declarations
2608/// and false for types with a full definition.
2609template <typename T>
2611
2612} // end namespace llvm
2613
2614namespace std {
2615template <typename... Refs>
2616struct tuple_size<llvm::detail::enumerator_result<Refs...>>
2617 : std::integral_constant<std::size_t, sizeof...(Refs)> {};
2618
2619template <std::size_t I, typename... Refs>
2620struct tuple_element<I, llvm::detail::enumerator_result<Refs...>>
2621 : std::tuple_element<I, std::tuple<Refs...>> {};
2622
2623template <std::size_t I, typename... Refs>
2624struct tuple_element<I, const llvm::detail::enumerator_result<Refs...>>
2625 : std::tuple_element<I, std::tuple<Refs...>> {};
2626
2627} // namespace std
2628
2629#endif // LLVM_ADT_STLEXTRAS_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
#define R2(n)
#define T
modulo schedule test
nvptx lower args
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
This file contains library features backported from future STL versions.
Value * RHS
Value * LHS
INLINE void g(uint32_t *state, size_t a, size_t b, size_t c, size_t d, uint32_t x, uint32_t y)
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
LLVM Value Representation.
Definition Value.h:75
decltype(auto) operator()(Pn &&...Params) const
Definition STLExtras.h:272
Templated storage wrapper for a callable.
Definition STLExtras.h:183
Callable & operator=(Callable &&Other)
Definition STLExtras.h:207
Callable(Callable const &Other)=default
Callable & operator=(Callable const &Other)
Definition STLExtras.h:200
Callable(Callable &&Other)=default
Iterator wrapper that concatenates sequences together.
Definition STLExtras.h:994
concat_iterator & operator++()
Definition STLExtras.h:1089
bool operator==(const concat_iterator &RHS) const
Definition STLExtras.h:1098
reference_type operator*() const
Definition STLExtras.h:1094
concat_iterator(RangeTs &&...Ranges)
Constructs an iterator from a sequence of ranges.
Definition STLExtras.h:1084
Helper to store a sequence of ranges being concatenated and access them.
Definition STLExtras.h:1110
concat_range(RangeTs &&... Ranges)
Definition STLExtras.h:1136
concat_iterator< ValueT, decltype(adl_begin(std::declval< RangeTs & >()))... > iterator
Definition STLExtras.h:1112
iterator begin() const
Definition STLExtras.h:1142
Return a reference to the first or second member of a reference.
Definition STLExtras.h:1400
std::conditional_t< std::is_reference< EltTy >::value, FirstTy, std::remove_reference_t< FirstTy > > type
Definition STLExtras.h:1402
An iterator element of this range.
Definition STLExtras.h:1231
The class represents the base of a range of indexed_accessor_iterators.
Definition STLExtras.h:1225
DerivedT slice(size_t n, size_t m) const
Drop the first N elements, and keep M elements.
Definition STLExtras.h:1277
size_t size() const
Return the size of this range.
Definition STLExtras.h:1271
bool empty() const
Return if the range is empty.
Definition STLExtras.h:1274
indexed_accessor_range_base & operator=(const indexed_accessor_range_base &)=default
DerivedT take_front(size_t n=1) const
Take the first n elements.
Definition STLExtras.h:1294
ReferenceT operator[](size_t Index) const
Definition STLExtras.h:1257
DerivedT drop_back(size_t n=1) const
Drop the last n elements.
Definition STLExtras.h:1288
indexed_accessor_range_base RangeBaseT
Definition STLExtras.h:1227
DerivedT take_back(size_t n=1) const
Take the last n elements.
Definition STLExtras.h:1300
DerivedT drop_front(size_t n=1) const
Drop the first n elements.
Definition STLExtras.h:1283
indexed_accessor_range_base(const indexed_accessor_range_base &)=default
indexed_accessor_range_base(BaseT base, ptrdiff_t count)
Definition STLExtras.h:1252
indexed_accessor_range_base(indexed_accessor_range_base &&)=default
indexed_accessor_range_base(iterator begin, iterator end)
Definition STLExtras.h:1247
ptrdiff_t count
The size from the owning range.
Definition STLExtras.h:1330
BaseT base
The base that owns the provided range of values.
Definition STLExtras.h:1328
indexed_accessor_range_base(const iterator_range< iterator > &range)
Definition STLExtras.h:1250
const BaseT & getBase() const
Returns the base of this range.
Definition STLExtras.h:1313
zip_longest_iterator(std::pair< Iters &&, Iters && >... ts)
Definition STLExtras.h:919
bool operator==(const zip_longest_iterator< Iters... > &other) const
Definition STLExtras.h:932
zip_longest_iterator< Iters... > & operator++()
Definition STLExtras.h:927
typename ZipLongestTupleType< Iters... >::type value_type
Definition STLExtras.h:894
typename iterator::iterator_category iterator_category
Definition STLExtras.h:941
typename iterator::pointer pointer
Definition STLExtras.h:944
typename iterator::difference_type difference_type
Definition STLExtras.h:943
zip_longest_iterator< decltype(adl_begin(std::declval< Args >()))... > iterator
Definition STLExtras.h:939
typename iterator::reference reference
Definition STLExtras.h:945
zip_longest_range(Args &&... ts_)
Definition STLExtras.h:962
typename iterator::value_type value_type
Definition STLExtras.h:942
typename ZippyIteratorTuple< ItType, decltype(storage), IndexSequence >::type iterator
Definition STLExtras.h:782
typename iterator::value_type value_type
Definition STLExtras.h:788
typename iterator::difference_type difference_type
Definition STLExtras.h:789
typename iterator::reference reference
Definition STLExtras.h:791
typename iterator::pointer pointer
Definition STLExtras.h:790
typename ZippyIteratorTuple< ItType, const decltype(storage), IndexSequence >::type const_iterator
Definition STLExtras.h:784
zippy(Args &&...args)
Definition STLExtras.h:794
typename const_iterator::reference const_reference
Definition STLExtras.h:792
const_iterator begin() const
Definition STLExtras.h:796
typename iterator::iterator_category iterator_category
Definition STLExtras.h:787
const_iterator end() const
Definition STLExtras.h:798
A pseudo-iterator adaptor that is designed to implement "early increment" style loops.
Definition STLExtras.h:573
friend bool operator==(const early_inc_iterator_impl &LHS, const early_inc_iterator_impl &RHS)
Definition STLExtras.h:604
early_inc_iterator_impl(WrappedIteratorT I)
Definition STLExtras.h:584
early_inc_iterator_impl & operator++()
Definition STLExtras.h:596
decltype(*std::declval< WrappedIteratorT >()) operator*()
Definition STLExtras.h:587
An iterator adaptor that filters the elements of given inner iterators.
Definition STLExtras.h:432
filter_iterator_base & operator++()
Definition STLExtras.h:458
WrappedIteratorT End
Definition STLExtras.h:436
filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
Definition STLExtras.h:449
filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
Definition STLExtras.h:506
Specialization of filter_iterator_base for forward iteration only.
Definition STLExtras.h:479
filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
Definition STLExtras.h:483
index_range(std::size_t Begin, std::size_t End)
Definition STLExtras.h:2419
detail::index_iterator begin() const
Definition STLExtras.h:2420
detail::index_iterator end() const
Definition STLExtras.h:2421
A utility class used to implement an iterator that contains some base object and an index.
Definition STLExtras.h:1175
DerivedT & operator+=(ptrdiff_t offset)
Definition STLExtras.h:1190
const BaseT & getBase() const
Returns the current base of the iterator.
Definition STLExtras.h:1203
bool operator==(const indexed_accessor_iterator &rhs) const
Definition STLExtras.h:1181
indexed_accessor_iterator(BaseT base, ptrdiff_t index)
Definition STLExtras.h:1206
DerivedT & operator-=(ptrdiff_t offset)
Definition STLExtras.h:1194
ptrdiff_t operator-(const indexed_accessor_iterator &rhs) const
Definition STLExtras.h:1177
bool operator<(const indexed_accessor_iterator &rhs) const
Definition STLExtras.h:1185
ptrdiff_t getIndex() const
Returns the current index of the iterator.
Definition STLExtras.h:1200
indexed_accessor_range(BaseT base, ptrdiff_t startIndex, ptrdiff_t count)
Definition STLExtras.h:1364
const BaseT & getBase() const
Returns the current base of the range.
Definition STLExtras.h:1373
ptrdiff_t getStartIndex() const
Returns the current start index of the range.
Definition STLExtras.h:1376
static ReferenceT dereference_iterator(const std::pair< BaseT, ptrdiff_t > &base, ptrdiff_t index)
See detail::indexed_accessor_range_base for details.
Definition STLExtras.h:1387
static std::pair< BaseT, ptrdiff_t > offset_base(const std::pair< BaseT, ptrdiff_t > &base, ptrdiff_t index)
See detail::indexed_accessor_range_base for details.
Definition STLExtras.h:1380
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
mapped_iterator_base BaseT
Definition STLExtras.h:377
ReferenceTy operator*() const
Definition STLExtras.h:384
const FuncTy & getFunction() const
Definition STLExtras.h:343
mapped_iterator(ItTy U, FuncTy F)
Definition STLExtras.h:338
ReferenceTy operator*() const
Definition STLExtras.h:345
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
decltype(adl_rbegin(std::declval< Range & >())) check_has_free_function_rbegin
Definition STLExtras.h:391
auto deref_or_none(const Iter &I, const Iter &End) -> std::optional< std::remove_const_t< std::remove_reference_t< decltype(*I)> > >
Definition STLExtras.h:865
enumerator_result< decltype(*declval< Iters >())... > EnumeratorTupleType
Definition STLExtras.h:2268
bool all_of_zip_predicate_first(Predicate &&P, Args &&...args)
Definition STLExtras.h:2479
const char unit< Period >::value[]
Definition Chrono.h:104
static constexpr bool HasMemberFind
Definition STLExtras.h:1875
static constexpr bool HasFreeFunctionRBegin
Definition STLExtras.h:395
decltype(adl_size(std::declval< Range & >())) check_has_free_function_size
Definition STLExtras.h:1677
bool operator!=(const DenseSetImpl< ValueT, MapTy, ValueInfoT > &LHS, const DenseSetImpl< ValueT, MapTy, ValueInfoT > &RHS)
Inequality comparison for DenseSet.
Definition DenseSet.h:248
static constexpr bool HasMemberContains
Definition STLExtras.h:1866
std::conditional_t< std::is_base_of_v< std::bidirectional_iterator_tag, typename std::iterator_traits< IterT >::iterator_category >, std::bidirectional_iterator_tag, std::forward_iterator_tag > fwd_or_bidi_tag
A type alias which is std::bidirectional_iterator_tag if the category of IterT derives from it,...
Definition STLExtras.h:522
bool all_of_zip_predicate_last(std::tuple< ArgsThenPredicate... > argsThenPredicate, std::index_sequence< InputIndexes... >)
Definition STLExtras.h:2494
decltype(std::declval< Range & >().contains(std::declval< const Element & >())) check_has_member_contains_t
Definition STLExtras.h:1862
decltype(sizeof(T)) has_sizeof
Definition STLExtras.h:2604
decltype(std::declval< Range & >().find(std::declval< const Element & >()) != std::declval< Range & >().end()) check_has_member_find_t
Definition STLExtras.h:1870
Iter next_or_end(const Iter &I, const Iter &End)
Definition STLExtras.h:858
iterator_facade_base< ZipType, std::common_type_t< std::bidirectional_iterator_tag, typename std::iterator_traits< Iters >::iterator_category... >, ReferenceTupleType, typename std::iterator_traits< std::tuple_element_t< 0, std::tuple< Iters... > > >::difference_type, ReferenceTupleType *, ReferenceTupleType > zip_traits
Definition STLExtras.h:656
static constexpr bool HasFreeFunctionSize
Definition STLExtras.h:1681
bool operator==(const DenseSetImpl< ValueT, MapTy, ValueInfoT > &LHS, const DenseSetImpl< ValueT, MapTy, ValueInfoT > &RHS)
Equality comparison for DenseSet.
Definition DenseSet.h:232
std::remove_reference_t< decltype(*adl_begin(std::declval< RangeT & >()))> ValueOfRange
Definition ADL.h:129
std::conjunction< std::is_pointer< T >, std::is_trivially_copyable< typename std::iterator_traits< T >::value_type > > sort_trivially_copyable
Definition STLExtras.h:1625
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:311
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:824
void stable_sort(R &&Range)
Definition STLExtras.h:2047
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1740
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1734
bool includes(R1 &&Range1, R2 &&Range2)
Provide wrappers to std::includes which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1923
auto min_element(R &&Range)
Provide wrappers to std::min_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2009
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1707
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1714
detail::zip_longest_range< T, U, Args... > zip_longest(T &&t, U &&u, Args &&... args)
Iterate over two or more iterators at the same time.
Definition STLExtras.h:975
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1666
int(*)(const void *, const void *) get_array_pod_sort_comparator(const T &)
get_array_pod_sort_comparator - This is an internal helper function used to get type deduction of T r...
Definition STLExtras.h:1556
constexpr bool is_incomplete_v
Detects when type T is incomplete.
Definition STLExtras.h:2610
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:834
constexpr auto adl_begin(RangeT &&range) -> decltype(adl_detail::begin_impl(std::forward< RangeT >(range)))
Returns the begin iterator to range using std::begin and function found through Argument-Dependent Lo...
Definition ADL.h:78
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2461
void interleave(ForwardIterator begin, ForwardIterator end, UnaryFunctor each_fn, NullaryFunctor between_fn)
An STL-style algorithm similar to std::for_each that applies a second functor between every pair of e...
Definition STLExtras.h:2182
auto accumulate(R &&Range, E &&Init)
Wrapper for std::accumulate.
Definition STLExtras.h:1699
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2060
int array_pod_sort_comparator(const void *P1, const void *P2)
Adapt std::less<T> for array_pod_sort.
Definition STLExtras.h:1543
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
mapped_iterator< ItTy, FuncTy > map_iterator(ItTy I, FuncTy F)
Definition STLExtras.h:354
decltype(auto) getSingleElement(ContainerTy &&C)
Asserts that the given container has a single element and returns that element.
Definition STLExtras.h:304
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2125
bool hasNItemsOrLess(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;})
Returns true if the sequence [Begin, End) has N or less items.
Definition STLExtras.h:2566
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2220
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:627
void shuffle(Iterator first, Iterator last, RNG &&g)
Definition STLExtras.h:1527
constexpr auto adl_end(RangeT &&range) -> decltype(adl_detail::end_impl(std::forward< RangeT >(range)))
Returns the end iterator to range using std::end and functions found through Argument-Dependent Looku...
Definition ADL.h:86
auto uninitialized_copy(R &&Src, IterTy Dst)
Definition STLExtras.h:2042
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2065
auto binary_search(R &&Range, T &&Value)
Provide wrappers to std::binary_search which take ranges instead of having to pass begin/end explicit...
Definition STLExtras.h:1970
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:1996
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1766
auto map_range(ContainerTy &&C, FuncTy F)
Definition STLExtras.h:359
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
Definition STLExtras.h:1161
constexpr auto adl_rbegin(RangeT &&range) -> decltype(adl_detail::rbegin_impl(std::forward< RangeT >(range)))
Returns the reverse-begin iterator to range using std::rbegin and function found through Argument-Dep...
Definition ADL.h:94
bool hasNItemsOrMore(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has N or more items.
Definition STLExtras.h:2545
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2117
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:1957
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1721
auto mismatch(R1 &&Range1, R2 &&Range2)
Provide wrappers to std::mismatch which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:2036
auto reverse(ContainerTy &&C)
Definition STLExtras.h:401
constexpr size_t range_size(R &&Range)
Returns the size of the Range, i.e., the number of elements.
Definition STLExtras.h:1691
detail::zippy< detail::zip_first, T, U, Args... > zip_first(T &&t, U &&u, Args &&...args)
zip iterator that, for the sake of efficiency, assumes the first iteratee to be the shortest.
Definition STLExtras.h:847
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1633
bool hasNItems(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;}, std::enable_if_t< !std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< std::remove_reference_t< decltype(Begin)> >::iterator_category >::value, void > *=nullptr)
Return true if the sequence [Begin, End) has exactly N items.
Definition STLExtras.h:2520
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1752
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1728
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1408
constexpr auto adl_size(RangeT &&range) -> decltype(adl_detail::size_impl(std::forward< RangeT >(range)))
Returns the size of range using std::size and functions found through Argument-Dependent Lookup (ADL)...
Definition ADL.h:118
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1909
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
Definition STLExtras.h:295
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:545
std::pair< T *, bool > find_singleton_nested(R &&Range, Predicate P, bool AllowRepeats=false)
Return a pair consisting of the single value in Range that satisfies P(<member of Range> ,...
Definition STLExtras.h:1801
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1776
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:318
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:71
auto remove_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1759
std::disjunction< std::is_same< T, Ts >... > is_one_of
traits class for checking whether type T is one of any of the given types in the variadic list.
Definition STLExtras.h:110
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:1983
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1849
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:1943
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2019
OutputIt replace_copy_if(R &&Range, OutputIt Out, UnaryPredicate P, const T &NewValue)
Provide wrappers to std::replace_copy_if which take ranges instead of having to pass begin/end explic...
Definition STLExtras.h:1831
auto to_address(const Ptr &P)
Returns a raw pointer that represents the same address as the argument.
Definition STLExtras.h:2599
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1824
auto partition(R &&Range, UnaryPredicate P)
Provide wrappers to std::partition which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1964
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1418
typename detail::detector< void, Op, Args... >::value_t is_detected
Detects if a given trait holds for some set of arguments 'Args'.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1856
OutputIt replace_copy(R &&Range, OutputIt Out, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace_copy which take ranges instead of having to pass begin/end explicitl...
Definition STLExtras.h:1840
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:1950
std::tuple_element_t< I, std::tuple< Ts... > > TypeAtIndex
Find the type at a given index in a list of types.
Definition STLExtras.h:152
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1747
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2109
constexpr auto adl_rend(RangeT &&range) -> decltype(adl_detail::rend_impl(std::forward< RangeT >(range)))
Returns the reverse-end iterator to range using std::rend and functions found through Argument-Depend...
Definition ADL.h:102
void append_values(Container &C, Args &&...Values)
Appends all Values to container C.
Definition STLExtras.h:2131
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1886
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2097
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1593
constexpr decltype(auto) makeVisitor(CallableTs &&...Callables)
Returns an opaquely-typed Callable object whose operator() overload set is the sum of the operator() ...
Definition STLExtras.h:1516
filter_iterator_impl< WrappedIteratorT, PredicateT, detail::fwd_or_bidi_tag< WrappedIteratorT > > filter_iterator
Defines filter_iterator to a suitable specialization of filter_iterator_impl, based on the underlying...
Definition STLExtras.h:532
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2077
std::conjunction< std::is_base_of< T, Ts >... > are_base_of
traits class for checking whether type T is a base class for all the given types in the variadic list...
Definition STLExtras.h:115
bool all_of_zip(ArgsAndPredicate &&...argsAndPredicate)
Compare two zipped ranges using the provided predicate (as last argument).
Definition STLExtras.h:2509
constexpr auto addEnumValues(EnumTy1 LHS, EnumTy2 RHS)
Helper which adds two underlying types of enumeration type.
Definition STLExtras.h:161
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:851
#define N
Find the first index where a type appears in a list of types.
Definition STLExtras.h:141
void operator()(void *v)
Definition STLExtras.h:2235
Determine if all types in Ts are distinct.
Definition STLExtras.h:124
Binary functor that adapts to any other binary functor after dereferencing operands.
Definition STLExtras.h:2249
auto operator()(A &lhs, B &rhs) const
Definition STLExtras.h:2255
constexpr Visitor(HeadT &&Head, TailTs &&...Tail)
Definition STLExtras.h:1473
constexpr Visitor(HeadT &&Head)
Definition STLExtras.h:1481
std::optional< std::remove_const_t< std::remove_reference_t< decltype(*std::declval< Iter >())> > > type
Definition STLExtras.h:873
std::tuple< typename ZipLongestItemType< Iters >::type... > type
Definition STLExtras.h:878
std::tuple< decltype(*declval< Iters >())... > type
Definition STLExtras.h:652
ItType< decltype(adl_begin( std::get< Ns >(declval< const std::tuple< Args... > & >())))... > type
Definition STLExtras.h:772
ItType< decltype(adl_begin( std::get< Ns >(declval< std::tuple< Args... > & >())))... > type
Definition STLExtras.h:763
Helper to obtain the iterator types for the tuple storage within zippy.
Definition STLExtras.h:756
decltype(auto) value() const
Returns the value(s) for the current iterator.
Definition STLExtras.h:2314
friend decltype(auto) get(const enumerator_result &Result)
Returns the value at index I.
Definition STLExtras.h:2330
std::tuple< std::size_t, Refs... > value_reference_tuple
Definition STLExtras.h:2303
friend bool operator==(const enumerator_result &Result, const std::tuple< std::size_t, Ts... > &Other)
Definition STLExtras.h:2338
std::size_t index() const
Returns the 0-based index of the current position within the original input range(s).
Definition STLExtras.h:2310
friend std::size_t get(const enumerator_result &Result)
Returns the value at index I. This case covers the index.
Definition STLExtras.h:2323
enumerator_result(std::size_t Index, Refs &&...Rs)
Definition STLExtras.h:2305
Tuple-like type for zip_enumerator dereference.
Definition STLExtras.h:2265
friend bool operator==(const index_iterator &Lhs, const index_iterator &Rhs)
Definition STLExtras.h:2389
std::ptrdiff_t operator-(const index_iterator &R) const
Definition STLExtras.h:2378
std::size_t operator*() const
Definition STLExtras.h:2387
friend bool operator<(const index_iterator &Lhs, const index_iterator &Rhs)
Definition STLExtras.h:2393
index_iterator & operator-=(std::ptrdiff_t N)
Definition STLExtras.h:2373
index_iterator & operator+=(std::ptrdiff_t N)
Definition STLExtras.h:2368
index_iterator(std::size_t Index)
Definition STLExtras.h:2366
Infinite stream of increasing 0-based size_t indices.
Definition STLExtras.h:2402
index_iterator begin() const
Definition STLExtras.h:2403
index_iterator end() const
Definition STLExtras.h:2404
zip_traits< ZipType, ReferenceTupleType, Iters... > Base
Definition STLExtras.h:673
std::index_sequence_for< Iters... > IndexSequence
Definition STLExtras.h:674
void tup_inc(std::index_sequence< Ns... >)
Definition STLExtras.h:684
zip_common(Iters &&... ts)
Definition STLExtras.h:700
bool test_all_equals(const zip_common &other, std::index_sequence< Ns... >) const
Definition STLExtras.h:693
std::tuple< Iters... > iterators
Definition STLExtras.h:677
value_type operator*() const
Definition STLExtras.h:702
typename Base::value_type value_type
Definition STLExtras.h:675
bool all_equals(zip_common &other)
Return true if all the iterator are matching other's iterators.
Definition STLExtras.h:717
void tup_dec(std::index_sequence< Ns... >)
Definition STLExtras.h:688
value_type deref(std::index_sequence< Ns... >) const
Definition STLExtras.h:680
Zippy iterator that uses the second iterator for comparisons.
Definition STLExtras.h:2283
bool operator==(const zip_enumerator &Other) const
Definition STLExtras.h:2288
bool operator==(const zip_first &other) const
Definition STLExtras.h:728
bool operator==(const zip_shortest &other) const
Definition STLExtras.h:740
std::tuple_element_t< Index, std::tuple< Args... > > arg_t
The type of an argument to this function.
Definition STLExtras.h:80
std::tuple_element_t< i, std::tuple< Args... > > arg_t
The type of an argument to this function.
Definition STLExtras.h:97
ReturnType result_t
The result type of this function.
Definition STLExtras.h:93
This class provides various trait information about a callable object.
Definition STLExtras.h:67
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1436
bool operator()(const T &lhs, const T &rhs) const
Definition STLExtras.h:1437
Function object to check whether the second component of a container supported by std::get (like std:...
Definition STLExtras.h:1445
bool operator()(const T &lhs, const T &rhs) const
Definition STLExtras.h:1446
std::add_pointer_t< std::add_const_t< T > > type
Definition STLExtras.h:55
std::add_lvalue_reference_t< std::add_const_t< T > > type
Definition STLExtras.h:59
Function object to apply a binary function to the first component of a std::pair.
Definition STLExtras.h:1454
size_t operator()(const std::pair< First, Second > &P) const
Definition STLExtras.h:2242
Utility type to build an inheritance chain that makes it easy to rank overload candidates.
Definition STLExtras.h:1465