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