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