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