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