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